Skip to content

Commit 0285a71

Browse files
feat(core): expose pretext text measurement on window.__hyperframes (#3302)
## What Exposes the `pretext` text-measurement API on `window.__hyperframes`, so the API our agent-facing docs already describe actually exists. Adds `pretext.prepare`, `.layout`, `.prepareWithSegments`, `.measureLineStats`, `.measureNaturalWidth`. ## Why `skills/hyperframes-core/references/determinism-rules.md` is required reading for any agent authoring a composition. Line 59 tells them to call `window.__hyperframes.pretext.prepare(text, font)` then `pretext.layout(prepared, maxWidth, lineHeight)` for text measurement without a DOM reflow. That object did not exist. The runtime exposed exactly `fitTextFontSize` and `getVariables`. Any composition following the documented recipe threw at runtime. Deleting the doc line was the smaller change, but reflow-free measurement is genuinely the right tool for sizing text per frame, and `fitTextFontSize` is already built on it. Making the docs true is the better fix. ## How - New `packages/core/src/text/pretext.ts` assembles the exposed surface in one place, with the include/exclude rationale next to it. - `entry.ts` attaches it alongside the existing helpers. Sub-compositions inherit it for free: the scoping shim builds its scoped variant with `Object.assign({}, base, { getVariables })`, so anything added to the base object is carried through. Two deliberate decisions: **Wider than the doc named.** `layout()` returns only `{ lineCount, height }`. The doc's own "shrinkwrap containers" use case needs a width, which is impossible with just `prepare` + `layout`. `measureNaturalWidth` and `measureLineStats` make that claim achievable; `prepareWithSegments` is their required input. **`clearCache` and `setLocale` withheld.** Both mutate state shared across compositions. Exposing them would let one composition change how a later one measures, making a render depend on what ran before it. **Doc correction.** The reference called this "pure arithmetic, ~0.0002 ms per call". Not quite: `prepare` measures fonts through a canvas and throws outside a browser. Only the steps after a prepared string are arithmetic. Reworded, and documented the width helpers and the omissions. ## Trade-off The runtime bundle grows **4,903 bytes (+1.30%)**, from 377,865 to 382,768. That ships inline in every composition. Measured by building the artifact with and without the change. ## Test plan - [x] Unit tests added/updated - [x] Manual testing performed - [x] Documentation updated (if applicable) `packages/core/src/text/pretext.test.ts` guards the shape of the published surface: the two documented names exist, the width helpers exist, and the two stateful functions are absent. Behaviour is deliberately not asserted there. `prepare` needs a canvas, and mocking it (as `fitTextFontSize.test.ts` must) would assert nothing real. Real behaviour was verified by rendering a composition that calls the documented API: ``` lines=2 height=216 naturalWidth=1785 ``` Self-consistent: natural width 1785 exceeds the 1600 container so it wraps to 2 lines, and 2 x 108 line-height is exactly the reported 216. The frame was inspected visually. Also run: - `packages/core` full suite from the package root: **903 passed, 46 files** - `tsc --noEmit` and `tsc --noEmit -p tsconfig.runtime.json`: clean - `oxlint` / `oxfmt`: clean ## Follow-ups (not in this PR) An audit of the wider attribute surface found several more doc/runtime mismatches, including `data-gpu-mode` documented as an HTML attribute when it is a config field, and `data-no-timeline` being real, load-bearing, and absent from the table agents read. Those are separate changes.
1 parent 5e36f7a commit 0285a71

7 files changed

Lines changed: 152 additions & 2 deletions

File tree

‎packages/core/scripts/test-hyperframe-runtime-contract.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,66 @@ for (const snippet of requiredSnippets) {
2727
assert(runtimeSource.includes(snippet), `Runtime contract snippet missing: ${snippet}`);
2828
}
2929

30+
// Snippet checks cannot prove what `window.__hyperframes` ends up carrying.
31+
// A name can reach the bundle through an unrelated import: `fitTextFontSize.ts`
32+
// imports `prepare`/`layout` from `@chenglou/pretext`, so grepping for
33+
// "pretext" stays green even if the attachment in entry.ts is deleted. Run the
34+
// runtime and read the object back instead.
35+
const { JSDOM } = await import("jsdom");
36+
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
37+
runScripts: "outside-only",
38+
});
39+
// The runtime's DOMContentLoaded path calls requestAnimationFrame. jsdom only
40+
// provides it under `pretendToBeVisual`, which also starts a frame loop that
41+
// keeps the process alive, so stub it instead. The stub never fires: we are
42+
// asserting what the runtime attaches at evaluation time, not what it animates.
43+
Object.defineProperty(dom.window, "requestAnimationFrame", {
44+
value: () => 0,
45+
configurable: true,
46+
});
47+
Object.defineProperty(dom.window, "cancelAnimationFrame", {
48+
value: () => {},
49+
configurable: true,
50+
});
51+
dom.window.eval(runtimeSource);
52+
53+
const hyperframes = (dom.window as unknown as { __hyperframes?: Record<string, unknown> })
54+
.__hyperframes;
55+
assert(hyperframes, "Runtime did not attach window.__hyperframes");
56+
57+
// Each of these is an API the agent-facing docs tell composition authors to
58+
// call. If one stops being attached, every composition written against the
59+
// docs throws at render time, which no other check would catch.
60+
const requiredHelpers = ["fitTextFontSize", "getVariables"];
61+
for (const helper of requiredHelpers) {
62+
assert(
63+
typeof hyperframes[helper] === "function",
64+
`window.__hyperframes.${helper} is not attached`,
65+
);
66+
}
67+
68+
const pretext = hyperframes.pretext as Record<string, unknown> | undefined;
69+
assert(pretext, "window.__hyperframes.pretext is not attached");
70+
const requiredPretextFns = [
71+
"prepare",
72+
"layout",
73+
"prepareWithSegments",
74+
"measureLineStats",
75+
"measureNaturalWidth",
76+
];
77+
for (const fn of requiredPretextFns) {
78+
assert(typeof pretext[fn] === "function", `window.__hyperframes.pretext.${fn} is not attached`);
79+
}
80+
81+
// clearCache/setLocale mutate state shared across compositions. Keeping them
82+
// off the surface is a deliberate determinism choice, so assert it holds.
83+
for (const forbidden of ["clearCache", "setLocale"]) {
84+
assert(
85+
!(forbidden in pretext),
86+
`window.__hyperframes.pretext.${forbidden} must not be exposed (mutates shared state)`,
87+
);
88+
}
89+
3090
const scriptDir = resolve(fileURLToPath(new URL(".", import.meta.url)));
3191
const manifestPath = resolve(scriptDir, "../dist/hyperframe.manifest.json");
3292
try {

‎packages/core/src/runtime/entry.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import { initSandboxRuntimeModular } from "./init";
22
import { installAuthoredOpacityCapture } from "./colorGrading";
33
import { fitTextFontSize } from "../text/fitTextFontSize";
4+
import { pretext } from "../text/pretext";
45
import { getVariables } from "./getVariables";
56

67
type HyperframeWindow = Window & {
78
__hyperframeRuntimeBootstrapped?: boolean;
89
__hyperframes?: {
910
fitTextFontSize: typeof fitTextFontSize;
1011
getVariables: typeof getVariables;
12+
pretext: typeof pretext;
1113
};
1214
};
1315

@@ -26,6 +28,7 @@ installAuthoredOpacityCapture();
2628
(window as HyperframeWindow).__hyperframes = {
2729
fitTextFontSize,
2830
getVariables,
31+
pretext,
2932
};
3033

3134
function bootstrapHyperframeRuntime(): void {

‎packages/core/src/text/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export { fitTextFontSize } from "./fitTextFontSize.js";
22
export type { FitTextOptions, FitTextResult } from "./fitTextFontSize.js";
3+
export { pretext } from "./pretext.js";
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { describe, it, expect } from "vitest";
2+
3+
import { pretext } from "./pretext.js";
4+
5+
// Behavior is not asserted here on purpose. `prepare` measures fonts through a
6+
// canvas, which Node does not have, so the real measuring is covered by the
7+
// browser check in `packages/cli` rather than mocked into meaninglessness here.
8+
// What this file guards is the shape of the published surface.
9+
describe("pretext runtime surface", () => {
10+
it("exposes the documented prepare and layout functions", () => {
11+
// The skill file agents are required to read documents
12+
// `window.__hyperframes.pretext.prepare(...)` / `.layout(...)`. If either
13+
// name disappears, every composition written against that doc throws.
14+
expect(typeof pretext.prepare).toBe("function");
15+
expect(typeof pretext.layout).toBe("function");
16+
});
17+
18+
it("exposes the width helpers the documented shrinkwrap case needs", () => {
19+
// `layout` returns only { lineCount, height }. Width has to come from
20+
// these, so without them "shrinkwrap containers" is not actually doable.
21+
expect(typeof pretext.prepareWithSegments).toBe("function");
22+
expect(typeof pretext.measureLineStats).toBe("function");
23+
expect(typeof pretext.measureNaturalWidth).toBe("function");
24+
});
25+
26+
it("does not expose the globally-stateful functions", () => {
27+
// clearCache/setLocale mutate state shared across compositions, which
28+
// would make a render depend on what ran before it.
29+
expect("clearCache" in pretext).toBe(false);
30+
expect("setLocale" in pretext).toBe(false);
31+
});
32+
});

‎packages/core/src/text/pretext.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import {
2+
layout,
3+
measureLineStats,
4+
measureNaturalWidth,
5+
prepare,
6+
prepareWithSegments,
7+
} from "@chenglou/pretext";
8+
9+
/**
10+
* The text measurement surface exposed to compositions as
11+
* `window.__hyperframes.pretext`.
12+
*
13+
* Measuring text by writing it into the DOM and reading it back forces a
14+
* reflow, which is both slow per frame and a determinism risk (the value
15+
* depends on when you read it). These measure off a canvas instead, so a
16+
* composition can size a container, pick a font size, or decide a line break
17+
* at any frame without disturbing layout. `fitTextFontSize` is itself built on
18+
* `prepare` + `layout`.
19+
*
20+
* Note the split, because it decides where you call these: `prepare` (and
21+
* `prepareWithSegments`) does the real font measurement and needs a canvas, so
22+
* it only works in a browser, not in Node. Everything downstream of a prepared
23+
* string is arithmetic and is cheap enough to run per frame.
24+
*
25+
* Deliberately omitted from this surface:
26+
* - `clearCache` and `setLocale` mutate process-global state. A composition
27+
* calling either would change how *other* compositions measure, which breaks
28+
* the guarantee that the same file renders the same video every time.
29+
* Withholding `clearCache` does not strand memory: the cache is keyed by
30+
* (segment, font) where segments come from `Intl.Segmenter` at word
31+
* granularity, so it grows with the number of distinct *words* a composition
32+
* renders, not with frames. A counter or typewriter re-measuring every frame
33+
* reuses the same entries. Only genuinely new words allocate, which bounds it
34+
* at a composition's vocabulary.
35+
* - The incremental cursor API (`layoutNextLine`, `walkLineRanges`, and
36+
* friends) has no caller yet. Add it when something needs it.
37+
*
38+
* @see packages/core/src/runtime/entry.ts for where this is attached.
39+
*/
40+
export const pretext = {
41+
/** Measure a string for a CSS font (e.g. `"700 48px Inter"`). */
42+
prepare,
43+
/** Line count and total height for a prepared string at a given width. */
44+
layout,
45+
/** Like `prepare`, but retains segments so widths can be measured. */
46+
prepareWithSegments,
47+
/** Line count plus `maxLineWidth` — the widest rendered line. */
48+
measureLineStats,
49+
/** Width the string would occupy on a single unwrapped line. */
50+
measureNaturalWidth,
51+
} as const;

‎skills-manifest.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
"files": 11
3535
},
3636
"hyperframes-core": {
37-
"hash": "e9daaccaed05b8b4",
37+
"hash": "4ca81d4092effc62",
3838
"files": 19
3939
},
4040
"hyperframes-creative": {

‎skills/hyperframes-core/references/determinism-rules.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,10 @@ Build the visible end-state in static HTML and CSS first, then animate from/to t
5656
- Use `position: absolute` for layers and decorative elements, not as the default content-layout strategy.
5757
- Prefer transforms and opacity for animation.
5858
- Keep text inside its intended container. For dynamic text, use `max-width`, wrapping, or `window.__hyperframes.fitTextFontSize(text, { maxWidth, fontFamily, fontWeight })`.
59-
- For text measurement without DOM reflow, use `window.__hyperframes.pretext`: `pretext.prepare(text, font)` then `pretext.layout(prepared, maxWidth, lineHeight)`. Pure arithmetic, ~0.0002 ms per call — safe for per-frame text reflow, shrinkwrap containers, and computing layout before render. `fitTextFontSize` is built on it.
59+
- For text measurement without DOM reflow, use `window.__hyperframes.pretext`. Measure off a canvas instead of writing into the page and reading it back, so nothing reflows: `pretext.prepare(text, font)` then `pretext.layout(prepared, maxWidth, lineHeight)` → `{ lineCount, height }`. `prepare` does the font measurement; everything downstream of a prepared string is arithmetic and cheap enough to run per frame. `fitTextFontSize` is built on it.
60+
- `layout` gives you height, not width. To size a container to its text (shrinkwrap), use `pretext.prepareWithSegments(text, font)` and then `pretext.measureNaturalWidth(prepared)` for the single-line width, or `pretext.measureLineStats(prepared, maxWidth)` for `{ lineCount, maxLineWidth }`.
61+
- `font` is a CSS font shorthand string, e.g. `"700 90px Inter"`.
62+
- `clearCache` and `setLocale` are deliberately not exposed: they mutate state shared across compositions, which would make a render depend on what ran before it.
6063
- **Do not** use `<br>` in body text. Forced breaks ignore the actual rendered font width and produce an extra break when the line already wraps naturally, causing overlap. Let text wrap via `max-width`. Exception: short display titles where each word is deliberately on its own line.
6164
- **Transformed elements must be block-level + sized.** `transform`/`scaleX`/`scaleY` is a no-op on an inline `<span>`, and scaling an auto-width (0px) element shows nothing → invisible bars/fills. Give them `display: block`/`inline-block`/flex-item **and** a real `width`/`height` (e.g. `width: 100%` inside a sized parent). _(Silent — automated gates may miss it.)_
6265
- **Absolutely-positioned decoratives that pulse or overshoot** (`yoyo` scale, `back.out`) need clearance at their **peak** size and must not straddle an `overflow: hidden` edge — else they overlap a neighbor or get clipped. Position for the largest frame, not the resting one. _(silent.)_

0 commit comments

Comments
 (0)