Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(core): report one composition size in stage-size and timeline messages (#4496)
Miguel Ángel77b2260f2be5
diff --git a/packages/core/src/runtime/clipTree.test.ts b/packages/core/src/runtime/clipTree.test.tsindex dc0ec720cd..ba61438acc 100644--- a/packages/core/src/runtime/clipTree.test.ts+++ b/packages/core/src/runtime/clipTree.test.ts@@ -38,6 +38,17 @@ describe("createClipTree", () => {},);+ it("leaves out the explicit root when another composition comes first", () => {+ document.body.innerHTML = `+ <div data-composition-id="card" data-start="0" data-duration="3" id="card"></div>+ <div data-composition-id="main" data-root="true" data-start="0" data-duration="10" id="main">+ <div data-start="0" data-duration="5" id="clip"></div>+ </div>`;+ const ids = createClipTree(params).roots.map((node) => node.id);+ expect(ids).toContain("card");+ expect(ids).not.toContain("main");+ });+// Regression: id-less children (root index.html uses data-hf-id, not id) must// get their data-hf-id as the node id — not a synthetic `__clip-N` — so the// tree aligns with __clipManifest (which also keys on data-hf-id) and inlinediff --git a/packages/core/src/runtime/clipTree.ts b/packages/core/src/runtime/clipTree.tsindex 1e6dcae23f..f22c80e8e3 100644--- a/packages/core/src/runtime/clipTree.ts+++ b/packages/core/src/runtime/clipTree.ts@@ -17,6 +17,7 @@ import {resolveTimedImageDurationSeconds,} from "./playbackRate";import { isMediaElement } from "./domRealm";+import { findRootCompositionElement } from "./compositionDimension";export interface ClipNode {readonly id: string;@@ -118,7 +119,7 @@ export function createClipTree(params: {const { startResolver, timelineRegistry, rootDuration } = params;const elementToNode = new Map<Element, MutableClipNode>();- const root = document.querySelector("[data-composition-id]");+ const root = findRootCompositionElement();let ordinal = 0;for (const el of document.querySelectorAll("[data-start]")) {diff --git a/packages/core/src/runtime/compositionDimension.ts b/packages/core/src/runtime/compositionDimension.tsnew file mode 100644index 0000000000..5ade559768--- /dev/null+++ b/packages/core/src/runtime/compositionDimension.ts@@ -0,0 +1,22 @@+import { isHtmlElement } from "./domRealm";++/** A `data-width`/`data-height` length in CSS px as the stage lays it out, fractions kept. */+export function parseLayoutDimension(value: string | null | undefined): number | null {+ if (value == null || value.trim() === "") return null;+ const parsed = Number.parseFloat(value);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;+}++/** The size the runtime reports to its host: whole px, read with `parseInt` as the renderer does. */+export function parseCompositionDimension(value: string | null | undefined): number | null {+ if (value == null || value.trim() === "") return null;+ const parsed = Number.parseInt(value, 10);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;+}++export function findRootCompositionElement(): HTMLElement | null {+ const explicitRoot = document.querySelector('[data-composition-id][data-root="true"]');+ if (isHtmlElement(explicitRoot)) return explicitRoot;+ // The first composition in document order never sits inside another one.+ return document.querySelector<HTMLElement>("[data-composition-id]");+}diff --git a/packages/core/src/runtime/compositionLoader.test.ts b/packages/core/src/runtime/compositionLoader.test.tsindex dc7a476252..69f2654ccf 100644--- a/packages/core/src/runtime/compositionLoader.test.ts+++ b/packages/core/src/runtime/compositionLoader.test.ts@@ -109,6 +109,25 @@ describe("loadExternalCompositions", () => {).toBe(false);});+ it("sizes a flattened inner root from a px-suffixed or fractional size", async () => {+ const host = document.createElement("div");+ host.setAttribute("data-composition-src", "https://example.com/comp.html");+ host.setAttribute("data-composition-id", "scene-1");+ document.body.appendChild(host);+ const compositionHtml = `+ <html><body>+ <div data-composition-id="scene-1" data-width="1080px" data-height="540.5"><p>Hi</p></div>+ </body></html>+ `;+ vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));++ await loadExternalCompositions({ ...defaultParams });++ const flattened = host.querySelector("p")?.parentElement;+ expect(flattened?.style.width).toBe("1080px");+ expect(flattened?.style.height).toBe("540.5px");+ });+it("injects styles into document head", async () => {const host = document.createElement("div");host.setAttribute("data-composition-src", "https://example.com/comp.html");diff --git a/packages/core/src/runtime/compositionLoader.ts b/packages/core/src/runtime/compositionLoader.tsindex 0fa30800c1..45acf163db 100644--- a/packages/core/src/runtime/compositionLoader.ts+++ b/packages/core/src/runtime/compositionLoader.ts@@ -8,6 +8,7 @@ import {wrapScopedCompositionScript,} from "../compiler/compositionScoping";import { parseImportMap } from "../compiler/importMaps";+import { parseLayoutDimension } from "./compositionDimension";import { markFlattenedInnerRoot } from "./flattenedRoot";import {applyCssVariables,@@ -209,10 +210,10 @@ function stripExtractedCompositionAssets(node: ParentNode): void {function prepareFlattenedInnerRoot(innerRoot: HTMLElement): HTMLElement {const prepared = document.importNode(innerRoot, true) as HTMLElement;markFlattenedInnerRoot(prepared);- const w = prepared.getAttribute("data-width");- const h = prepared.getAttribute("data-height");- prepared.style.width = w ? `${w}px` : "100%";- prepared.style.height = h ? `${h}px` : "100%";+ const w = parseLayoutDimension(prepared.getAttribute("data-width"));+ const h = parseLayoutDimension(prepared.getAttribute("data-height"));+ prepared.style.width = w === null ? "100%" : `${w}px`;+ prepared.style.height = h === null ? "100%" : `${h}px`;return prepared;}diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.tsindex 2319c3b0da..fc73052c65 100644--- a/packages/core/src/runtime/init.test.ts+++ b/packages/core/src/runtime/init.test.ts@@ -416,6 +416,101 @@ describe("initSandboxRuntimeModular", () => {expect(innerTimeline._ease).toBeTypeOf("function");});+ it.each([+ ["1080px", "1920px", "1080x1920"],+ ["1080.5", "1920", "1080x1920"],+ ])(+ "reports one composition size in stage-size and timeline for %s x %s",+ (width, height, size) => {+ const outbound: Array<Record<string, unknown>> = [];+ vi.spyOn(window.parent, "postMessage").mockImplementation((message: unknown) => {+ if (typeof message === "object" && message !== null) {+ outbound.push(message as Record<string, unknown>);+ }+ });+ document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-duration="4" data-width="${width}" data-height="${height}"></div>`;+ window.__timelines = { main: createMockTimeline(4) };++ initSandboxRuntimeModular();++ const stageSizes = outbound+ .filter((m) => m.type === "stage-size")+ .map((m) => `${m.width}x${m.height}`);+ const timelineSizes = outbound+ .filter((m) => m.type === "timeline")+ .map((m) => `${m.compositionWidth}x${m.compositionHeight}`);+ expect(stageSizes.length).toBeGreaterThan(0);+ expect(timelineSizes.length).toBeGreaterThan(0);+ expect(new Set([...stageSizes, ...timelineSizes])).toEqual(new Set([size]));+ },+ );++ it.each([+ ["1080px", "1920px"],+ ["1080.5", "1920"],+ ])("lays the stage out at the authored size for %s x %s", (width, height) => {+ document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-duration="4" data-width="${width}" data-height="${height}"></div>`;+ window.__timelines = { main: createMockTimeline(4) };++ initSandboxRuntimeModular();++ const root = document.querySelector<HTMLElement>("[data-composition-id]")!;+ expect(root.style.width).toBe(`${parseFloat(width)}px`);+ expect(root.style.height).toBe("1920px");+ });++ it("keeps a subpixel size on a timed clip", () => {+ document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-duration="4" data-width="1920" data-height="1080"><div id="hairline" data-start="0" data-duration="4" data-width="0.5" data-height="0.5"></div></div>`;+ window.__timelines = { main: createMockTimeline(4) };++ initSandboxRuntimeModular();++ const clip = document.getElementById("hairline")!;+ expect(clip.style.width).toBe("0.5px");+ expect(clip.style.height).toBe("0.5px");+ });++ it("reports the explicit root's size when another composition comes first", () => {+ const outbound: Array<Record<string, unknown>> = [];+ vi.spyOn(window.parent, "postMessage").mockImplementation((message: unknown) => {+ if (typeof message === "object" && message !== null) {+ outbound.push(message as Record<string, unknown>);+ }+ });+ document.body.innerHTML = `<div data-composition-id="card" data-width="800px" data-height="600px"></div><div data-composition-id="main" data-root="true" data-duration="4" data-width="1920" data-height="1080"></div>`;+ window.__timelines = { main: createMockTimeline(4) };++ initSandboxRuntimeModular();++ const sizes = outbound+ .filter((m) => m.type === "stage-size" || m.type === "timeline")+ .map((m) =>+ m.type === "stage-size"+ ? `${m.width}x${m.height}`+ : `${m.compositionWidth}x${m.compositionHeight}`,+ );+ expect(sizes.length).toBeGreaterThan(1);+ expect(new Set(sizes)).toEqual(new Set(["1920x1080"]));+ const loaded = outbound.find((m) => m.event === "composition_loaded");+ expect(loaded?.properties).toMatchObject({ compositionId: "main" });+ });++ it("reports a collapsed stage for a px-suffixed root size", () => {+ const outbound: Array<Record<string, unknown>> = [];+ vi.spyOn(window.parent, "postMessage").mockImplementation((message: unknown) => {+ if (typeof message === "object" && message !== null) {+ outbound.push(message as Record<string, unknown>);+ }+ });+ document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-duration="4" data-width="1080px" data-height="1920px"></div>`;+ window.__timelines = { main: createMockTimeline(4) };++ initSandboxRuntimeModular();++ const collapsed = outbound.find((m) => m.code === "root_stage_layout_zero");+ expect(collapsed?.details).toMatchObject({ declaredWidth: 1080, declaredHeight: 1920 });+ });+it("isolates a failed keyframe ease repair and reports it without skipping siblings", () => {const outbound: Array<{ type?: string; event?: string }> = [];vi.spyOn(window.parent, "postMessage").mockImplementation((message: unknown) => {diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.tsindex 69adfc1197..2f3079e589 100644--- a/packages/core/src/runtime/init.ts+++ b/packages/core/src/runtime/init.ts@@ -38,6 +38,11 @@ import { createPickerModule } from "./picker";import { createRuntimePlayer, type RuntimePlayerTransport } from "./player";import { createRuntimeState } from "./state";import { collectRuntimeTimelinePayload, isRuntimeElementVisibleAt } from "./timeline";+import {+ findRootCompositionElement,+ parseCompositionDimension,+ parseLayoutDimension,+} from "./compositionDimension";import { resolveCompositionDuration } from "@hyperframes/parsers/composition-duration";import { createRuntimeStartTimeResolver } from "./startResolver";import { createClipTree } from "./clipTree";@@ -374,28 +379,12 @@ export function initSandboxRuntimeModular(): void {window.__timelines = window.__timelines || {};- // Resolve the root composition element with the same priority the rest of- // the runtime uses (explicit `data-root` marker first, then the topmost- // non-nested composition, then first in DOM order). Defined here so the- // array-normalization + data-start defaults below pick the same root the- // closure-based `resolveRootCompositionElement` does on multi-comp pages.- const findRootCompositionEl = (): HTMLElement | null => {- const explicitRoot = document.querySelector('[data-composition-id][data-root="true"]');- if (isHtmlElement(explicitRoot)) return explicitRoot;- const nodes = Array.from(document.querySelectorAll("[data-composition-id]")) as HTMLElement[];- return (- nodes.find((node) => !node.parentElement?.closest("[data-composition-id]")) ??- nodes[0] ??- null- );- };-// Agents often write `window.__timelines = [tl]` (array) instead of the// keyed-by-composition-id object the runtime expects. Normalize at init so// the rest of the pipeline can assume a Record<string, timeline>.if (Array.isArray(window.__timelines)) {const arr = window.__timelines as unknown[];- const rootId = findRootCompositionEl()?.getAttribute("data-composition-id") ?? "root";+ const rootId = findRootCompositionElement()?.getAttribute("data-composition-id") ?? "root";const normalized: Record<string, unknown> = {};if (arr.length === 1) {normalized[rootId] = arr[0];@@ -408,7 +397,7 @@ export function initSandboxRuntimeModular(): void {// Agents sometimes omit data-start on the root composition element. The// runtime skips timed-visibility for elements without it, making clips// invisible and timelines non-seekable. Default to 0 for the root.- const rootComp = findRootCompositionEl();+ const rootComp = findRootCompositionElement();if (rootComp && !rootComp.hasAttribute("data-start")) {rootComp.setAttribute("data-start", "0");}@@ -552,13 +541,11 @@ export function initSandboxRuntimeModular(): void {};const parseDimensionPx = (value: string | null): string | null => {- if (value == null || value.trim() === "") return null;- const parsed = Number.parseFloat(value);- if (!Number.isFinite(parsed) || parsed <= 0) return null;- return `${parsed}px`;+ const parsed = parseLayoutDimension(value);+ return parsed === null ? null : `${parsed}px`;};- const resolveRootCompositionElement = (): HTMLElement | null => findRootCompositionEl();+ const resolveRootCompositionElement = (): HTMLElement | null => findRootCompositionElement();const applyCompositionSizing = () => {const rootEl = resolveRootCompositionElement();@@ -579,7 +566,7 @@ export function initSandboxRuntimeModular(): void {// Mirror the SAME forced values onto documentElement/body (not a second// read of the root's own dimensions): once body's own size agrees with// the root it contains, `overflow: hidden` clips nothing that matters and- // the white-bar guard stays intact. `findRootCompositionEl` above returns+ // the white-bar guard stays intact. `findRootCompositionElement` returns// the outermost `[data-root="true"]` composition by convention, not by a// structural guarantee — this only ever affects a document whose author// marked a NESTED composition `data-root="true"` too, which nothing in@@ -1954,14 +1941,10 @@ export function initSandboxRuntimeModular(): void {return;}const rect = rootNode.getBoundingClientRect();- const declaredWidth = Number(rootNode.getAttribute("data-width"));- const declaredHeight = Number(rootNode.getAttribute("data-height"));+ const declaredWidth = parseLayoutDimension(rootNode.getAttribute("data-width"));+ const declaredHeight = parseLayoutDimension(rootNode.getAttribute("data-height"));const computedStyle = window.getComputedStyle(rootNode);- const hasDeclaredDimensions =- Number.isFinite(declaredWidth) &&- declaredWidth > 0 &&- Number.isFinite(declaredHeight) &&- declaredHeight > 0;+ const hasDeclaredDimensions = declaredWidth !== null && declaredHeight !== null;const looksCollapsed =rect.width <= 0 ||rect.height <= 0 ||@@ -2864,11 +2847,9 @@ export function initSandboxRuntimeModular(): void {// Post resolved stage size so the parent can scale the iframe containerconst stageSizeRootEl = resolveRootCompositionElement();if (stageSizeRootEl) {- const w = parseDimensionPx(stageSizeRootEl.getAttribute("data-width"));- const h = parseDimensionPx(stageSizeRootEl.getAttribute("data-height"));- const width = w ? parseInt(w, 10) : 0;- const height = h ? parseInt(h, 10) : 0;- if (width > 0 && height > 0) {+ const width = parseCompositionDimension(stageSizeRootEl.getAttribute("data-width"));+ const height = parseCompositionDimension(stageSizeRootEl.getAttribute("data-height"));+ if (width !== null && height !== null) {postRuntimeMessage({ source: "hf-preview", type: "stage-size", width, height });}}@@ -3257,8 +3238,7 @@ export function initSandboxRuntimeModular(): void {emitAnalyticsEvent("composition_loaded", {duration: player.getDuration(),- compositionId:- document.querySelector("[data-composition-id]")?.getAttribute("data-composition-id") ?? null,+ compositionId: findRootCompositionElement()?.getAttribute("data-composition-id") ?? null,});state.deterministicAdapters = [diff --git a/packages/core/src/runtime/timeline.test.ts b/packages/core/src/runtime/timeline.test.tsindex a783442128..99db25e8e1 100644--- a/packages/core/src/runtime/timeline.test.ts+++ b/packages/core/src/runtime/timeline.test.ts@@ -497,6 +497,29 @@ describe("collectRuntimeTimelinePayload", () => {expect(result.compositionHeight).toBe(2160);});+ it("reads a px-suffixed composition size the way the runtime lays it out", () => {+ const root = document.createElement("div");+ root.setAttribute("data-composition-id", "main");+ root.setAttribute("data-width", "1080px");+ root.setAttribute("data-height", "1920px");+ root.setAttribute("data-duration", "5");+ document.body.appendChild(root);++ const result = collectRuntimeTimelinePayload(defaultParams);+ expect(result.compositionWidth).toBe(1080);+ expect(result.compositionHeight).toBe(1920);+ });++ it("reads the size and duration of the explicit root when another composition comes first", () => {+ document.body.innerHTML = `<div data-composition-id="card" data-duration="3" data-width="800" data-height="600"></div><div data-composition-id="main" data-root="true" data-width="1920" data-height="1080"></div>`;+ (window as TimelineTestWindow).__timelines = { main: { duration: () => 7 } };++ const result = collectRuntimeTimelinePayload(defaultParams);+ expect(result.compositionWidth).toBe(1920);+ expect(result.compositionHeight).toBe(1080);+ expect(result.durationInFrames).toBe(210);+ });+it("defaults composition dimensions to 1920x1080", () => {const result = collectRuntimeTimelinePayload(defaultParams);expect(result.compositionWidth).toBe(1920);diff --git a/packages/core/src/runtime/timeline.ts b/packages/core/src/runtime/timeline.tsindex 89ccfccf55..e8022d83ea 100644--- a/packages/core/src/runtime/timeline.ts+++ b/packages/core/src/runtime/timeline.ts@@ -5,6 +5,7 @@ import type {RuntimeTimelineLike,} from "./types";import { stableClipId } from "./clipTree";+import { findRootCompositionElement, parseCompositionDimension } from "./compositionDimension";import {AUTHORED_DURATION_ATTR,AUTHORED_END_ATTR,@@ -316,7 +317,7 @@ export function collectRuntimeTimelinePayload(params: {};};- const root = document.querySelector("[data-composition-id]") as Element | null;+ const root = findRootCompositionElement();const compositionNodes = Array.from(document.querySelectorAll("[data-composition-id]"));const rootCompositionId = root?.getAttribute("data-composition-id") ?? null;const rootCompositionStart = root ? startResolver.resolveStartForElement(root, 0) : 0;@@ -705,7 +706,7 @@ export function collectRuntimeTimelinePayload(params: {durationInFrames,clips,scenes,- compositionWidth: parseNum(root?.getAttribute("data-width")) ?? 1920,- compositionHeight: parseNum(root?.getAttribute("data-height")) ?? 1080,+ compositionWidth: parseCompositionDimension(root?.getAttribute("data-width")) ?? 1920,+ compositionHeight: parseCompositionDimension(root?.getAttribute("data-height")) ?? 1080,};}