Skip to content

Commit 44b5836

Browse files
fix(core): composition scripts start after web fonts are ready, so renders repeat (#4980)
* fix(core): composition scripts start after web fonts are ready A scene script that measures text (offsetHeight, getBoundingClientRect) ran while the page parsed, often before its web font loaded, so it laid the scene out with fallback metrics. Renders of the same film differed run to run, and preview could differ from export. The compilers now give every body script a type the browser does not run (text/hf-after-fonts, or +module), through one helper in scriptRuns.ts called at the end of the bundler, the producer compile and the sub-composition preview. The Studio motion script is emitted the same way so it still runs after them. The runtime entry owns the wait: on DOMContentLoaded it forces a layout, waits for document.fonts.ready or FONT_WAIT_TIMEOUT_MS (5 s), then re-creates each script in its own place in parser order (classic in order, awaiting src loads; then module and defer scripts in insertion order), boots as before, and calls the DOMContentLoaded and load listeners the scripts added. On timeout the scripts run anyway and runtime_font_wait_timeout names the families still loading. Scene swaps and the composition loader use the same wait. * fix(core): a page whose runtime predates the font gate still runs its scripts A bundle can be served with a runtime loaded from HYPERFRAME_RUNTIME_URL. If that runtime is older than the font gate, nothing would run the deferred composition scripts and the film would be blank. Whenever the marking helper defers scripts, it also puts one small inline script first in the head. At DOMContentLoaded it runs the deferred scripts in parser order itself, without waiting for fonts and with a console warning, unless a runtime has claimed them. The gate's runtime claims them when it loads, before DOMContentLoaded, so the scripts run exactly once either way. * fix(studio-server): motion paths animate in Studio preview when gsap loads in the body The MotionPathPlugin tag Studio inserts after a body gsap script now carries that script's type, so the runtime runs it right after gsap once fonts are ready, instead of before gsap exists. * fix(cli): layout, motion-shot and validate wait for the composition scripts to run The three commands waited on the timeline registry, which exists as soon as the runtime file loads, or on a flat sleep. They now wait for the runtime's render-ready flag through one shared helper, keeping each command's timeout and proceeding as before when it passes. * fix(core): a script that wraps addEventListener keeps its wrapper after its scripts run While composition scripts run, the runtime patches addEventListener to hold load events that already passed. Putting the original back now happens only if the patch is still in place, so a library wrapper installed meanwhile survives. * docs: comments on script timing match scripts that wait for web fonts The early stub's flush and the player's iframe-load handler described page scripts as done by DOMContentLoaded and the runtime as ready before load. Composition scripts now wait for web fonts, so both can come later. Comment-only. * test(core): pin script order after an external script and the scene swap's font wait An inline composition script that follows an external one sees its global, and a scene swap runs the new scene's script only once web fonts are ready. * docs(producer): the early stub comment names what drains late font-gated work * fix(studio): motion paths add without a flash when gsap loads after web fonts Studio preloads MotionPathPlugin on iframe load. A body gsap now runs after web fonts, often after that load, so the preload retries once the runtime reports ready. * test(cli): pin the runtime wait before each command first samples the page * fix(studio): the motion path preload stops waiting once the preview runtime has booted A composition with no global gsap posts ready before the preload runs; the retry listener then never detached and kept each retired preview document alive. It now waits only while the runtime has not booted, and the tests pin the cleanup and the ready filter. * fix(studio): a preview frame that never boots is not kept alive by the motion path preload Only the latest preview waits for the ready message of its runtime; a newer load drops the older wait, so a crashed or missing composition frame can be collected. * style: comments added by the font gate move into names
1 parent 7f34649 commit 44b5836

29 files changed

Lines changed: 828 additions & 76 deletions

‎bun.lock‎

Lines changed: 13 additions & 13 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/cli/src/capture/captureCompositionFrame.test.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
22
import { tmpdir } from "node:os";
3-
import { join } from "node:path";
3+
import { dirname, join } from "node:path";
4+
import { fileURLToPath } from "node:url";
45
import { afterEach, describe, expect, it, vi } from "vitest";
56
import {
67
AUDIT_SEEK_OPTIONS,
@@ -14,6 +15,7 @@ import {
1415
resolveCropRegion,
1516
runFfmpegOnce,
1617
seekCompositionTimeline,
18+
waitForRuntimeReady,
1719
type CompositionSeekPage,
1820
} from "./captureCompositionFrame.js";
1921

@@ -48,6 +50,39 @@ afterEach(() => {
4850
vi.unstubAllGlobals();
4951
});
5052

53+
describe("waitForRuntimeReady", () => {
54+
it("waits for the runtime's render-ready flag and reports a timeout as not ready", async () => {
55+
const { waitForFunction } = fakeSeekPage();
56+
57+
await expect(waitForRuntimeReady({ waitForFunction }, 123)).resolves.toBe(true);
58+
expect(waitForFunction).toHaveBeenCalledWith(expect.any(Function), { timeout: 123 });
59+
const ready = waitForFunction.mock.calls[0]![0];
60+
vi.stubGlobal("window", { __timelines: {} });
61+
expect(ready()).toBe(false);
62+
vi.stubGlobal("window", { __timelines: {}, __renderReady: true });
63+
expect(ready()).toBe(true);
64+
65+
waitForFunction.mockRejectedValueOnce(new Error("Waiting failed: 1ms exceeded"));
66+
await expect(waitForRuntimeReady({ waitForFunction }, 1)).resolves.toBe(false);
67+
});
68+
69+
it("is what layout, motion-shot and validate wait on before they sample the page", () => {
70+
const commands = join(dirname(fileURLToPath(import.meta.url)), "../commands");
71+
const firstSample = {
72+
layout: "getCompositionDuration(page)",
73+
motionShot: "installSeekHelper(page)",
74+
validate: "auditClipDurations(page,",
75+
};
76+
for (const [name, sample] of Object.entries(firstSample)) {
77+
const source = readFileSync(join(commands, `${name}.ts`), "utf8");
78+
const wait = source.indexOf("await waitForRuntimeReady(page, ");
79+
expect(wait, name).toBeGreaterThan(-1);
80+
expect(source.indexOf(sample), name).toBeGreaterThan(wait);
81+
expect(source, name).not.toContain("__timelines?: unknown }).__timelines");
82+
}
83+
});
84+
});
85+
5186
describe("seekCompositionTimeline", () => {
5287
it("keeps the raced double-frame settle and adds a bounded font wait by default", async () => {
5388
const { page, evaluate, waitForFunction } = fakeSeekPage();

‎packages/cli/src/capture/captureCompositionFrame.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,14 +125,21 @@ function shaderTransitionsReadyInBrowser(): boolean {
125125
return shaderTransitionRegistryReady() ?? shaderLoadingOverlayReady();
126126
}
127127

128+
export function waitForRuntimeReady(
129+
page: Required<Pick<CompositionSeekPage, "waitForFunction">>,
130+
timeoutMs: number,
131+
): Promise<boolean> {
132+
return page
133+
.waitForFunction(compositionRuntimeReadyInBrowser, { timeout: timeoutMs })
134+
.then(() => true)
135+
.catch(() => false);
136+
}
137+
128138
async function waitForCompositionSettle(
129139
page: Page,
130140
options: OpenSettledCompositionPageOptions,
131141
): Promise<boolean> {
132-
const runtimeReady = await page
133-
.waitForFunction(compositionRuntimeReadyInBrowser, { timeout: options.renderReadyTimeoutMs })
134-
.then(() => true)
135-
.catch(() => false);
142+
const runtimeReady = await waitForRuntimeReady(page, options.renderReadyTimeoutMs);
136143

137144
if (!runtimeReady) {
138145
console.warn(

‎packages/cli/src/commands/layout.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
installPageFunctionGuard,
3535
seekCompositionTimeline,
3636
waitForCompositionFonts,
37+
waitForRuntimeReady,
3738
type SeekCompositionTimelineOptions,
3839
} from "../capture/captureCompositionFrame.js";
3940

@@ -237,11 +238,7 @@ async function runLayoutAudit(
237238
});
238239
await assertWebGpuAdapterAvailable(page, requiresWebGpu);
239240
await alignViewportToComposition(page, server.url);
240-
await page
241-
.waitForFunction(() => !!(window as unknown as { __timelines?: unknown }).__timelines, {
242-
timeout: opts.timeout,
243-
})
244-
.catch(() => {});
241+
await waitForRuntimeReady(page, opts.timeout);
245242
await waitForCompositionFonts(page, 750);
246243
await new Promise((resolveSettle) => setTimeout(resolveSettle, 250));
247244

‎packages/cli/src/commands/motionShot.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { mkdirSync, statSync, writeFileSync } from "node:fs";
1515
import { dirname, resolve } from "node:path";
1616
import { resolveDiagnosticNavigationTimeoutMs } from "../utils/renderArgs.js";
1717
import { resolveCompositionViewportFromHtml } from "../utils/compositionViewport.js";
18+
import { waitForRuntimeReady } from "../capture/captureCompositionFrame.js";
1819
import {
1920
assertWebGpuAdapterAvailable,
2021
compositionRequiresWebGpu,
@@ -415,11 +416,7 @@ async function openCompositionPage(
415416
await page.setViewport(size);
416417
await page.goto(url, { waitUntil: "domcontentloaded", timeout: navigationTimeout });
417418
await assertWebGpuAdapterAvailable(page, requiresWebGpu);
418-
await page
419-
.waitForFunction(() => !!(window as unknown as { __timelines?: unknown }).__timelines, {
420-
timeout: 10000,
421-
})
422-
.catch(() => {});
419+
await waitForRuntimeReady(page, 10000);
423420
await page
424421
.evaluate(async () => {
425422
const d = document as unknown as { fonts?: { ready?: Promise<unknown> } };

‎packages/cli/src/commands/validate.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
installPageFunctionGuard,
2121
resolveCliChromeGpuMode,
2222
seekCompositionTimeline,
23+
waitForRuntimeReady,
2324
} from "../capture/captureCompositionFrame.js";
2425

2526
const __filename = fileURLToPath(import.meta.url);
@@ -503,6 +504,7 @@ async function validateInBrowser(
503504
throw err;
504505
}
505506
await assertWebGpuAdapterAvailable(page, requiresWebGpu);
507+
await waitForRuntimeReady(page, opts.timeout ?? 3000);
506508
await new Promise((r) => setTimeout(r, opts.timeout ?? 3000));
507509

508510
for (const w of await auditClipDurations(page, analyzeClipMediaFit, opts.timeout ?? 3000)) {

‎packages/core/src/compiler/htmlBundler.test.ts‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { resetUnknownEnumWarnings } from "../runtime/getVariables";
1010
import { sanitizeCssValue } from "../runtime/applyVariableBindings";
1111
import { getHyperframeRuntimeScript } from "../generated/runtime-inline";
1212
import { ensureHfIds } from "../parsers/hfIds";
13+
import { AFTER_FONTS_SCRIPT_TYPE, AFTER_FONTS_SCRIPTS } from "./scriptRuns";
1314

1415
function makeTempProject(files: Record<string, string>): string {
1516
const dir = mkdtempSync(join(tmpdir(), "hf-bundler-test-"));
@@ -215,6 +216,33 @@ describe("bundleToSingleHtml", () => {
215216
expect(bundled).toContain('document.getElementById("scene")');
216217
});
217218

219+
it("defers the root's and every mounted composition's scripts until fonts, but not the runtime", async () => {
220+
const dir = makeTempProject({
221+
"index.html": `<!doctype html>
222+
<html><body>
223+
<div data-composition-id="main" data-width="320" data-height="180">
224+
<div data-composition-id="scene" data-composition-src="compositions/scene.html"></div>
225+
</div>
226+
<script>window.ROOT_SCRIPT = 1;</script>
227+
<script type="module">window.ROOT_MODULE = 1;</script>
228+
</body></html>`,
229+
"compositions/scene.html": `<template><div data-composition-id="scene" data-width="320" data-height="180">
230+
<script>window.SCENE_SCRIPT = 1;</script>
231+
</div></template>`,
232+
});
233+
234+
const { document } = parseHTML(await bundleToSingleHtml(dir));
235+
const deferred = [...document.querySelectorAll(AFTER_FONTS_SCRIPTS)].map(
236+
(el) => el.textContent,
237+
);
238+
for (const mark of ["SCENE_SCRIPT", "ROOT_SCRIPT", "ROOT_MODULE"]) {
239+
expect(deferred.some((text) => text?.includes(mark))).toBe(true);
240+
}
241+
expect([...document.querySelectorAll("body script")].length).toBe(deferred.length);
242+
const runtime = document.querySelector("script[data-hyperframes-preview-runtime]");
243+
expect(runtime?.getAttribute("type")).toBeNull();
244+
});
245+
218246
it("binds a mounted composition's scripts to its own file for __hyperframes.assetUrl", async () => {
219247
const dir = makeTempProject({
220248
"index.html": `<!doctype html>
@@ -257,8 +285,13 @@ describe("bundleToSingleHtml", () => {
257285

258286
const { document } = parseHTML(await bundleToSingleHtml(dir));
259287
const importMaps = [...document.querySelectorAll('script[type="importmap"]')];
260-
const modules = [...document.querySelectorAll('script[type="module"]')];
261-
const classic = [...document.querySelectorAll("script:not([type])")].map((s) => s.textContent);
288+
// Deferred until fonts: the runtime runs each as the type its marker names.
289+
const modules = [
290+
...document.querySelectorAll(`script[type="${AFTER_FONTS_SCRIPT_TYPE}+module"]`),
291+
];
292+
const classic = [...document.querySelectorAll(`script[type="${AFTER_FONTS_SCRIPT_TYPE}"]`)].map(
293+
(s) => s.textContent,
294+
);
262295

263296
expect(importMaps).toHaveLength(1);
264297
expect(JSON.parse(importMaps[0]!.textContent || "")).toEqual({
@@ -599,7 +632,9 @@ describe("bundleToSingleHtml", () => {
599632

600633
const bundled = await bundleToSingleHtml(dir);
601634

602-
expect(bundled).toMatch(/<script\b[^>]*\btype="module"[^>]*\bsrc="\.\/module\.js"/);
635+
expect(bundled).toMatch(
636+
/<script\b[^>]*\btype="text\/hf-after-fonts\+module"[^>]*\bsrc="\.\/module\.js"/,
637+
);
603638
expect(bundled).not.toContain('import { value } from "./value.js"');
604639
});
605640

‎packages/core/src/compiler/htmlBundler.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {
22
compositionStyle,
33
cssStyleMergeKey,
4+
deferScriptsUntilFonts,
45
UNCONDITIONAL_CSS_KEY,
56
headStyleRuns,
67
inlineScriptRuns,
@@ -1293,6 +1294,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
12931294
enforceCompositionPixelSizing(document);
12941295
autoHealMissingCompositionIds(document);
12951296
coalesceHeadStylesAndBodyScripts(document);
1297+
deferScriptsUntilFonts(document, (el) => el.hasAttribute(RUNTIME_BOOTSTRAP_ATTR));
12961298
injectTextRenderingRule(document);
12971299

12981300
// Inline textual assets

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,10 @@ export { addScenePartsManifest } from "./scenePartsManifest";
6161

6262
// Script ordering shared by the bundler and the producer coalescers
6363
export {
64+
AFTER_FONTS_SCRIPT_TYPE,
6465
compositionStyle,
6566
cssStyleMergeKey,
67+
deferScriptsUntilFonts,
6668
headStyleRuns,
6769
inlineScriptRuns,
6870
styleElementsFor,

0 commit comments

Comments
 (0)