Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(core): a composition mounted twice keeps each mount's own timeline (#5729)
Miguel Ángelc38e9f350b4d
diff --git a/packages/core/src/compiler/compositionAssembly.ts b/packages/core/src/compiler/compositionAssembly.tsindex 97198ecb39..9207bfb492 100644--- a/packages/core/src/compiler/compositionAssembly.ts+++ b/packages/core/src/compiler/compositionAssembly.ts@@ -309,3 +309,11 @@ export function enumerateNestedCompositionHosts<TElement extends AssemblyAttribureturn { hosts, skipped };}++/** A mount sharing the page root's id counts as a repeat, so it is numbered instead of taking the root's timeline. */+export function countPageRoot(counts: Map<string, number>, hosts: readonly Element[]): void {+ const root = hosts[0]?.ownerDocument.querySelector("[data-composition-id]");+ const rootId = root && !hosts.includes(root) ? root.getAttribute("data-composition-id") : null;+ const mounts = rootId ? counts.get(rootId) : undefined;+ if (rootId && mounts) counts.set(rootId, mounts + 1);+}diff --git a/packages/core/src/compiler/compositionScoping.test.ts b/packages/core/src/compiler/compositionScoping.test.tsindex dbca7a6916..559d11c5e4 100644--- a/packages/core/src/compiler/compositionScoping.test.ts+++ b/packages/core/src/compiler/compositionScoping.test.ts@@ -43,6 +43,45 @@ describe("composition scoping", () => {}});+ it("never replaces another mount's timeline under the scene's own id", () => {+ const { document } = parseHTML("<main></main>");+ const fakeWindow = { document, __timelines: {} as Record<string, unknown>, readBack: "" };+ const run = (runtimeId: string, timeline: string) =>+ new Function(+ "window",+ wrapScopedCompositionScript(+ `window.__timelines.scene = ${JSON.stringify(timeline)};+ window.readBack = window.__timelines.scene;`,+ "scene",+ undefined,+ undefined,+ runtimeId,+ ),+ )(fakeWindow);++ run("scene", "first half");+ run("scene-split", "second half");+ expect(fakeWindow.__timelines).toEqual({ scene: "first half", "scene-split": "second half" });+ expect(fakeWindow.readBack).toBe("second half");++ // A mount that owns the scene's id keeps it when its script runs again.+ const lone = { document, __timelines: {} as Record<string, unknown> };+ const runLone = (timeline: string) =>+ new Function(+ "window",+ wrapScopedCompositionScript(+ `window.__timelines.scene = ${JSON.stringify(timeline)};`,+ "scene",+ undefined,+ undefined,+ "intro",+ ),+ )(lone);+ runLone("v1");+ runLone("v2");+ expect(lone.__timelines).toEqual({ scene: "v2", intro: "v2" });+ });+it("scopes regular selectors while preserving global at-rules", () => {const scoped = scopeCssToComposition(`diff --git a/packages/core/src/compiler/compositionScoping.ts b/packages/core/src/compiler/compositionScoping.tsindex 703a6e5aaa..27f868a0ae 100644--- a/packages/core/src/compiler/compositionScoping.ts+++ b/packages/core/src/compiler/compositionScoping.ts@@ -415,10 +415,8 @@ export function wrapScopedCompositionScript(if (prop !== __hfCompId) {return Reflect.get(target, prop, target);}- var authoredValue = Reflect.get(target, prop, target);- return authoredValue === undefined- ? Reflect.get(target, __hfTimelineCompId, target)- : authoredValue;+ var runtimeValue = Reflect.get(target, __hfTimelineCompId, target);+ return runtimeValue === undefined ? Reflect.get(target, prop, target) : runtimeValue;},set: function(target, prop, value, receiver) {if (prop !== __hfCompId) {@@ -426,11 +424,15 @@ export function wrapScopedCompositionScript(}// The authored node remains in the compiled DOM when its local id// differs from the runtime mount id, so readiness legitimately sees- // both compositions. Publish the same timeline under both identities- // instead of replacing one with the other.- var authoredSet = Reflect.set(target, __hfCompId, value, target);+ // both compositions. Publish the same timeline under both identities,+ // unless another mount of the same file already owns the authored one.+ var authoredValue = Reflect.get(target, __hfCompId, target);+ var ownsAuthored =+ authoredValue === undefined ||+ authoredValue === Reflect.get(target, __hfTimelineCompId, target);var runtimeSet = Reflect.set(target, __hfTimelineCompId, value, target);- return authoredSet && runtimeSet;+ if (!ownsAuthored) return runtimeSet;+ return Reflect.set(target, __hfCompId, value, target) && runtimeSet;},});}diff --git a/packages/core/src/compiler/htmlBundler.test.ts b/packages/core/src/compiler/htmlBundler.test.tsindex ec2795986c..a511cc885a 100644--- a/packages/core/src/compiler/htmlBundler.test.ts+++ b/packages/core/src/compiler/htmlBundler.test.ts@@ -1080,6 +1080,30 @@ describe("bundleToSingleHtml", () => {expect(bundled).toContain('var __hfTimelineCompId = "scene__hf2"');});+ it("gives a mount that shares the page root's id its own runtime id", async () => {+ const cliRoot = (title: string) =>+ `<div id="root" data-composition-id="main" data-width="1920" data-height="1080"><h1>${title}</h1>`;+ const dir = makeTempProject({+ "index.html": `<!doctype html>+<html><head></head><body>+ ${cliRoot("Host")}+ <div id="main_2" data-composition-id="main" data-composition-src="compositions/scene.html"></div>+ </div>+ <script>window.__timelines={};</script>+</body></html>`,+ "compositions/scene.html": `<!doctype html><html><body>${cliRoot("Scene")}</div>+ <script>window.__timelines["main"] = "scene";</script>+</body></html>`,+ });++ const bundled = await bundleToSingleHtml(dir);+ const host = parseHTML(bundled).document.querySelector("#main_2");++ expect(host?.getAttribute("data-composition-id")).toBe("main__hf1");+ expect(host?.getAttribute("data-hf-original-composition-id")).toBe("main");+ expect(bundled).toContain('var __hfTimelineCompId = "main__hf1"');+ });+it("uniquifies duplicate sub-compositions across inline-template and external hosts", async () => {const dir = makeTempProject({"index.html": `<!doctype html>diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.tsindex 6dc5e357a9..7f385202bc 100644--- a/packages/core/src/compiler/htmlBundler.ts+++ b/packages/core/src/compiler/htmlBundler.ts@@ -11,6 +11,7 @@ import {type CompositionStyle,} from "./scriptRuns";import {+ countPageRoot,executableScripts,isJavaScriptType,planCompositionAssembly,@@ -553,6 +554,7 @@ function countBundledAuthoredCompositionIds(hosts: Element[]): Map<string, numbeif (!authoredCompositionId) continue;counts.set(authoredCompositionId, (counts.get(authoredCompositionId) || 0) + 1);}+ countPageRoot(counts, hosts);return counts;}diff --git a/packages/core/src/runtime/compositionLoader.test.ts b/packages/core/src/runtime/compositionLoader.test.tsindex 325bfa1135..c65b719a16 100644--- a/packages/core/src/runtime/compositionLoader.test.ts+++ b/packages/core/src/runtime/compositionLoader.test.ts@@ -697,6 +697,30 @@ describe("loadCompositions external hosts", () => {expect(hostB.querySelector('[data-hf-authored-id="scene-root"]')).toBeTruthy();});+ it("gives a mount that shares the page root's id its own runtime id", async () => {+ const root = document.createElement("div");+ root.setAttribute("data-composition-id", "main");+ document.body.appendChild(root);+ const host = document.createElement("div");+ host.setAttribute("data-composition-src", "https://example.com/scene.html");+ host.setAttribute("data-composition-id", "main");+ root.appendChild(host);+ vi.spyOn(globalThis, "fetch").mockImplementation(+ async () =>+ new Response(+ `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"><h1>Scene</h1></div></body></html>`,+ { status: 200 },+ ),+ );++ await loadFixture();++ expect(root.getAttribute("data-composition-id")).toBe("main");+ expect(host.getAttribute("data-composition-id")).toBe("main__hf1");+ expect(host.getAttribute("data-hf-original-composition-id")).toBe("main");+ expect(host.querySelector("h1")?.textContent).toBe("Scene");+ });+it("normalizes a runtime composition id back to the authored id when only one host remains", async () => {const hostA = document.createElement("div");hostA.setAttribute("data-composition-src", "https://example.com/scene.html");diff --git a/packages/core/src/runtime/compositionLoader.ts b/packages/core/src/runtime/compositionLoader.tsindex 3e83a8e219..319ae435fb 100644--- a/packages/core/src/runtime/compositionLoader.ts+++ b/packages/core/src/runtime/compositionLoader.ts@@ -4,6 +4,7 @@ import {refreshSvgSelectorAliases,} from "../compiler/svgSelectorAliases";import {+ countPageRoot,planCompositionAssembly,extractedCompositionAssets,} from "../compiler/compositionAssembly";@@ -300,6 +301,7 @@ function countAuthoredCompositionIds(hosts: Element[]): Map<string, number> {if (!compId) continue;hostCountsByCompositionId.set(compId, (hostCountsByCompositionId.get(compId) || 0) + 1);}+ countPageRoot(hostCountsByCompositionId, hosts);return hostCountsByCompositionId;}diff --git a/packages/studio-server/src/helpers/compositionInsertion.test.ts b/packages/studio-server/src/helpers/compositionInsertion.test.tsindex 69a1aa582f..b1666bfcb9 100644--- a/packages/studio-server/src/helpers/compositionInsertion.test.ts+++ b/packages/studio-server/src/helpers/compositionInsertion.test.ts@@ -97,7 +97,31 @@ describe("insertCompositionIntoSource", () => {);expect(result.hostId).toBe("headline_2");- expect(new Set(ids).size).toBe(ids.length);+ expect(ids).toEqual(["main", "headline", "headline"]);+ });++ it("mounts a project whose root shares the parent root's id under its own host id", () => {+ const dir = project();+ const cliRoot = (title: string) => `<!doctype html><html><body>+ <div id="root" data-composition-id="main" data-width="1920" data-height="1080" data-duration="6">${title}</div>+ </body></html>`;+ writeFileSync(join(dir, "index.html"), cliRoot("Host"));+ writeFileSync(join(dir, "scene.html"), cliRoot("Scene"));++ const result = insertCompositionIntoSource({+ projectDir: dir,+ targetPath: "index.html",+ sourcePath: "scene.html",+ parentSource: cliRoot("Host"),+ start: 0,+ desiredTrack: 0,+ });+ const host = parseHTML(result.html).document.querySelector("[data-composition-src]");++ expect(result.hostId).not.toBe("main");+ expect(result.hostId).not.toBe("root");+ expect(host?.id).toBe(result.hostId);+ expect(host?.getAttribute("data-composition-id")).toBe("main");});it("ignores nested composition internals when resolving a parent track collision", () => {diff --git a/packages/studio-server/src/helpers/compositionInsertion.ts b/packages/studio-server/src/helpers/compositionInsertion.tsindex 6d60c74863..5ece43dae7 100644--- a/packages/studio-server/src/helpers/compositionInsertion.ts+++ b/packages/studio-server/src/helpers/compositionInsertion.ts@@ -153,8 +153,8 @@ function resolveTrack(function uniqueHostId(root: Element, base: string): string {const ids = new Set([- ...descendants(root, "[id]").map((element) => element.id),- ...descendants(root, "[data-composition-id]").flatMap((element) => {+ ...[root, ...descendants(root, "[id]")].map((element) => element.id),+ ...[root, ...descendants(root, "[data-composition-id]")].flatMap((element) => {const id = element.getAttribute("data-composition-id");return id ? [id] : [];}),@@ -192,8 +192,9 @@ export function insertCompositionIntoSource(input: {const height = positiveAttribute(sourceComposition, "data-height");const { document, root } = compositionRoot(input.parentSource);const parentDuration = positiveAttribute(root, "data-duration", "data-composition-duration");+ const sourceCompositionId = sourceComposition.getAttribute("data-composition-id") ?? "";const base =- (sourceComposition.getAttribute("data-composition-id") ?? "composition")+ (sourceCompositionId || "composition").replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "composition";const hostId = uniqueHostId(root, base);@@ -216,7 +217,8 @@ export function insertCompositionIntoSource(input: {host.id = hostId;host.className = "clip";host.setAttribute("data-hf-id", `hf-${randomUUID()}`);- host.setAttribute("data-composition-id", hostId);+ const mountedRootId = sourceCompositionId || hostId;+ host.setAttribute("data-composition-id", mountedRootId);host.setAttribute("data-composition-src", relativeSourcePath(targetAbs, sourceAbs));host.setAttribute("data-start", String(Math.round(input.start * 100) / 100));host.setAttribute("data-duration", String(duration));diff --git a/packages/studio-server/src/helpers/sourceMutation.ts b/packages/studio-server/src/helpers/sourceMutation.tsindex 6f6dc1a118..4cda4cf4b9 100644--- a/packages/studio-server/src/helpers/sourceMutation.ts+++ b/packages/studio-server/src/helpers/sourceMutation.ts@@ -173,9 +173,20 @@ export function isHTMLElement(el: Node): el is HTMLElement {return HTMLEl ? el instanceof HTMLEl : el.nodeType === 1 && "style" in el;}+// A mount's id names the root it mounts; the runtime numbers repeated mounts (id__hf1, id__hf2).+function mountsComposition(document: Document, host: Element, compositionId: string): boolean {+ if (host.hasAttribute("data-composition-src")) return true;+ return (+ host.children.length === 0 &&+ querySelectorAllWithTemplates(document, "template").some(+ (template) => template.id === `${compositionId}-template`,+ )+ );+}+export function dedupeClonedCompositionId(document: Document, clone: Element): void {const compositionId = clone.getAttribute("data-composition-id");- if (!compositionId) return;+ if (!compositionId || mountsComposition(document, clone, compositionId)) return;const usedCompositionIds = new Set(querySelectorAllWithTemplates(document, "[data-composition-id]").map((node) =>node.getAttribute("data-composition-id"),diff --git a/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts b/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.tsindex 896bd488b3..902a2d5e5f 100644--- a/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts+++ b/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts@@ -87,7 +87,7 @@ describe("splitElementInHtml", () => {expect(result.html).toMatch(/id="box-split"[^>]*class="clip"/);});- it("gives a split composition host a unique composition id", () => {+ it("keeps every half of a split composition mount on the root it mounts", () => {const composition = source.replace('id="box" class="clip"','id="box" class="clip" data-composition-id="headline" data-composition-src="headline.html"',@@ -97,13 +97,28 @@ describe("splitElementInHtml", () => {const second = splitElementInHtml(first.html, { id: "box-split" }, 4, "box-split-2");const { document } = parseHTML(second.html);- const compositionIds = Array.from(- document.querySelectorAll("[data-composition-id]"),- (element) => element.getAttribute("data-composition-id"),+ const mounts = Array.from(document.querySelectorAll("[data-composition-src]"));+ expect(mounts.map((element) => element.getAttribute("data-composition-id"))).toEqual([+ "headline",+ "headline",+ "headline",+ ]);+ expect(new Set(mounts.map((element) => element.id)).size).toBe(3);+ });++ it("keeps a split inline-template mount on its template", () => {+ const composition = source+ .replace('id="box" class="clip"', 'id="box" class="clip" data-composition-id="headline"')+ .replace(+ "</body>",+ '<template id="headline-template"><div data-composition-id="headline"></div></template></body>',+ );++ const result = splitElementInHtml(composition, { id: "box" }, 3, "box-split");++ expect(result.html).toMatch(+ /id="box-split"[^>]*data-composition-id="headline"|data-composition-id="headline"[^>]*id="box-split"/,);- expect(compositionIds).toHaveLength(4);- expect(new Set(compositionIds)).toHaveLength(4);- expect(compositionIds).toEqual(expect.arrayContaining(["root", "headline", "headline-split"]));});it("returns matched false for out-of-range split time", () => {