Skip to content

Commit c38e9f3

Browse files
fix(core): a composition mounted twice keeps each mount's own timeline (#5729)
1 parent 35b17c3 commit c38e9f3

11 files changed

Lines changed: 174 additions & 21 deletions

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,3 +309,11 @@ export function enumerateNestedCompositionHosts<TElement extends AssemblyAttribu
309309

310310
return { hosts, skipped };
311311
}
312+
313+
/** A mount sharing the page root's id counts as a repeat, so it is numbered instead of taking the root's timeline. */
314+
export function countPageRoot(counts: Map<string, number>, hosts: readonly Element[]): void {
315+
const root = hosts[0]?.ownerDocument.querySelector("[data-composition-id]");
316+
const rootId = root && !hosts.includes(root) ? root.getAttribute("data-composition-id") : null;
317+
const mounts = rootId ? counts.get(rootId) : undefined;
318+
if (rootId && mounts) counts.set(rootId, mounts + 1);
319+
}

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,45 @@ describe("composition scoping", () => {
4343
}
4444
});
4545

46+
it("never replaces another mount's timeline under the scene's own id", () => {
47+
const { document } = parseHTML("<main></main>");
48+
const fakeWindow = { document, __timelines: {} as Record<string, unknown>, readBack: "" };
49+
const run = (runtimeId: string, timeline: string) =>
50+
new Function(
51+
"window",
52+
wrapScopedCompositionScript(
53+
`window.__timelines.scene = ${JSON.stringify(timeline)};
54+
window.readBack = window.__timelines.scene;`,
55+
"scene",
56+
undefined,
57+
undefined,
58+
runtimeId,
59+
),
60+
)(fakeWindow);
61+
62+
run("scene", "first half");
63+
run("scene-split", "second half");
64+
expect(fakeWindow.__timelines).toEqual({ scene: "first half", "scene-split": "second half" });
65+
expect(fakeWindow.readBack).toBe("second half");
66+
67+
// A mount that owns the scene's id keeps it when its script runs again.
68+
const lone = { document, __timelines: {} as Record<string, unknown> };
69+
const runLone = (timeline: string) =>
70+
new Function(
71+
"window",
72+
wrapScopedCompositionScript(
73+
`window.__timelines.scene = ${JSON.stringify(timeline)};`,
74+
"scene",
75+
undefined,
76+
undefined,
77+
"intro",
78+
),
79+
)(lone);
80+
runLone("v1");
81+
runLone("v2");
82+
expect(lone.__timelines).toEqual({ scene: "v2", intro: "v2" });
83+
});
84+
4685
it("scopes regular selectors while preserving global at-rules", () => {
4786
const scoped = scopeCssToComposition(
4887
`

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

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -415,22 +415,24 @@ export function wrapScopedCompositionScript(
415415
if (prop !== __hfCompId) {
416416
return Reflect.get(target, prop, target);
417417
}
418-
var authoredValue = Reflect.get(target, prop, target);
419-
return authoredValue === undefined
420-
? Reflect.get(target, __hfTimelineCompId, target)
421-
: authoredValue;
418+
var runtimeValue = Reflect.get(target, __hfTimelineCompId, target);
419+
return runtimeValue === undefined ? Reflect.get(target, prop, target) : runtimeValue;
422420
},
423421
set: function(target, prop, value, receiver) {
424422
if (prop !== __hfCompId) {
425423
return Reflect.set(target, prop, value, target);
426424
}
427425
// The authored node remains in the compiled DOM when its local id
428426
// differs from the runtime mount id, so readiness legitimately sees
429-
// both compositions. Publish the same timeline under both identities
430-
// instead of replacing one with the other.
431-
var authoredSet = Reflect.set(target, __hfCompId, value, target);
427+
// both compositions. Publish the same timeline under both identities,
428+
// unless another mount of the same file already owns the authored one.
429+
var authoredValue = Reflect.get(target, __hfCompId, target);
430+
var ownsAuthored =
431+
authoredValue === undefined ||
432+
authoredValue === Reflect.get(target, __hfTimelineCompId, target);
432433
var runtimeSet = Reflect.set(target, __hfTimelineCompId, value, target);
433-
return authoredSet && runtimeSet;
434+
if (!ownsAuthored) return runtimeSet;
435+
return Reflect.set(target, __hfCompId, value, target) && runtimeSet;
434436
},
435437
});
436438
}

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1080,6 +1080,30 @@ describe("bundleToSingleHtml", () => {
10801080
expect(bundled).toContain('var __hfTimelineCompId = "scene__hf2"');
10811081
});
10821082

1083+
it("gives a mount that shares the page root's id its own runtime id", async () => {
1084+
const cliRoot = (title: string) =>
1085+
`<div id="root" data-composition-id="main" data-width="1920" data-height="1080"><h1>${title}</h1>`;
1086+
const dir = makeTempProject({
1087+
"index.html": `<!doctype html>
1088+
<html><head></head><body>
1089+
${cliRoot("Host")}
1090+
<div id="main_2" data-composition-id="main" data-composition-src="compositions/scene.html"></div>
1091+
</div>
1092+
<script>window.__timelines={};</script>
1093+
</body></html>`,
1094+
"compositions/scene.html": `<!doctype html><html><body>${cliRoot("Scene")}</div>
1095+
<script>window.__timelines["main"] = "scene";</script>
1096+
</body></html>`,
1097+
});
1098+
1099+
const bundled = await bundleToSingleHtml(dir);
1100+
const host = parseHTML(bundled).document.querySelector("#main_2");
1101+
1102+
expect(host?.getAttribute("data-composition-id")).toBe("main__hf1");
1103+
expect(host?.getAttribute("data-hf-original-composition-id")).toBe("main");
1104+
expect(bundled).toContain('var __hfTimelineCompId = "main__hf1"');
1105+
});
1106+
10831107
it("uniquifies duplicate sub-compositions across inline-template and external hosts", async () => {
10841108
const dir = makeTempProject({
10851109
"index.html": `<!doctype html>

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
type CompositionStyle,
1212
} from "./scriptRuns";
1313
import {
14+
countPageRoot,
1415
executableScripts,
1516
isJavaScriptType,
1617
planCompositionAssembly,
@@ -553,6 +554,7 @@ function countBundledAuthoredCompositionIds(hosts: Element[]): Map<string, numbe
553554
if (!authoredCompositionId) continue;
554555
counts.set(authoredCompositionId, (counts.get(authoredCompositionId) || 0) + 1);
555556
}
557+
countPageRoot(counts, hosts);
556558
return counts;
557559
}
558560

‎packages/core/src/runtime/compositionLoader.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -697,6 +697,30 @@ describe("loadCompositions external hosts", () => {
697697
expect(hostB.querySelector('[data-hf-authored-id="scene-root"]')).toBeTruthy();
698698
});
699699

700+
it("gives a mount that shares the page root's id its own runtime id", async () => {
701+
const root = document.createElement("div");
702+
root.setAttribute("data-composition-id", "main");
703+
document.body.appendChild(root);
704+
const host = document.createElement("div");
705+
host.setAttribute("data-composition-src", "https://example.com/scene.html");
706+
host.setAttribute("data-composition-id", "main");
707+
root.appendChild(host);
708+
vi.spyOn(globalThis, "fetch").mockImplementation(
709+
async () =>
710+
new Response(
711+
`<html><body><div data-composition-id="main" data-width="1920" data-height="1080"><h1>Scene</h1></div></body></html>`,
712+
{ status: 200 },
713+
),
714+
);
715+
716+
await loadFixture();
717+
718+
expect(root.getAttribute("data-composition-id")).toBe("main");
719+
expect(host.getAttribute("data-composition-id")).toBe("main__hf1");
720+
expect(host.getAttribute("data-hf-original-composition-id")).toBe("main");
721+
expect(host.querySelector("h1")?.textContent).toBe("Scene");
722+
});
723+
700724
it("normalizes a runtime composition id back to the authored id when only one host remains", async () => {
701725
const hostA = document.createElement("div");
702726
hostA.setAttribute("data-composition-src", "https://example.com/scene.html");

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
refreshSvgSelectorAliases,
55
} from "../compiler/svgSelectorAliases";
66
import {
7+
countPageRoot,
78
planCompositionAssembly,
89
extractedCompositionAssets,
910
} from "../compiler/compositionAssembly";
@@ -300,6 +301,7 @@ function countAuthoredCompositionIds(hosts: Element[]): Map<string, number> {
300301
if (!compId) continue;
301302
hostCountsByCompositionId.set(compId, (hostCountsByCompositionId.get(compId) || 0) + 1);
302303
}
304+
countPageRoot(hostCountsByCompositionId, hosts);
303305
return hostCountsByCompositionId;
304306
}
305307

‎packages/studio-server/src/helpers/compositionInsertion.test.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,31 @@ describe("insertCompositionIntoSource", () => {
9797
);
9898

9999
expect(result.hostId).toBe("headline_2");
100-
expect(new Set(ids).size).toBe(ids.length);
100+
expect(ids).toEqual(["main", "headline", "headline"]);
101+
});
102+
103+
it("mounts a project whose root shares the parent root's id under its own host id", () => {
104+
const dir = project();
105+
const cliRoot = (title: string) => `<!doctype html><html><body>
106+
<div id="root" data-composition-id="main" data-width="1920" data-height="1080" data-duration="6">${title}</div>
107+
</body></html>`;
108+
writeFileSync(join(dir, "index.html"), cliRoot("Host"));
109+
writeFileSync(join(dir, "scene.html"), cliRoot("Scene"));
110+
111+
const result = insertCompositionIntoSource({
112+
projectDir: dir,
113+
targetPath: "index.html",
114+
sourcePath: "scene.html",
115+
parentSource: cliRoot("Host"),
116+
start: 0,
117+
desiredTrack: 0,
118+
});
119+
const host = parseHTML(result.html).document.querySelector("[data-composition-src]");
120+
121+
expect(result.hostId).not.toBe("main");
122+
expect(result.hostId).not.toBe("root");
123+
expect(host?.id).toBe(result.hostId);
124+
expect(host?.getAttribute("data-composition-id")).toBe("main");
101125
});
102126

103127
it("ignores nested composition internals when resolving a parent track collision", () => {

‎packages/studio-server/src/helpers/compositionInsertion.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,8 +153,8 @@ function resolveTrack(
153153

154154
function uniqueHostId(root: Element, base: string): string {
155155
const ids = new Set([
156-
...descendants(root, "[id]").map((element) => element.id),
157-
...descendants(root, "[data-composition-id]").flatMap((element) => {
156+
...[root, ...descendants(root, "[id]")].map((element) => element.id),
157+
...[root, ...descendants(root, "[data-composition-id]")].flatMap((element) => {
158158
const id = element.getAttribute("data-composition-id");
159159
return id ? [id] : [];
160160
}),
@@ -192,8 +192,9 @@ export function insertCompositionIntoSource(input: {
192192
const height = positiveAttribute(sourceComposition, "data-height");
193193
const { document, root } = compositionRoot(input.parentSource);
194194
const parentDuration = positiveAttribute(root, "data-duration", "data-composition-duration");
195+
const sourceCompositionId = sourceComposition.getAttribute("data-composition-id") ?? "";
195196
const base =
196-
(sourceComposition.getAttribute("data-composition-id") ?? "composition")
197+
(sourceCompositionId || "composition")
197198
.replace(/[^a-zA-Z0-9_-]+/g, "-")
198199
.replace(/^-+|-+$/g, "") || "composition";
199200
const hostId = uniqueHostId(root, base);
@@ -216,7 +217,8 @@ export function insertCompositionIntoSource(input: {
216217
host.id = hostId;
217218
host.className = "clip";
218219
host.setAttribute("data-hf-id", `hf-${randomUUID()}`);
219-
host.setAttribute("data-composition-id", hostId);
220+
const mountedRootId = sourceCompositionId || hostId;
221+
host.setAttribute("data-composition-id", mountedRootId);
220222
host.setAttribute("data-composition-src", relativeSourcePath(targetAbs, sourceAbs));
221223
host.setAttribute("data-start", String(Math.round(input.start * 100) / 100));
222224
host.setAttribute("data-duration", String(duration));

‎packages/studio-server/src/helpers/sourceMutation.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,9 +173,20 @@ export function isHTMLElement(el: Node): el is HTMLElement {
173173
return HTMLEl ? el instanceof HTMLEl : el.nodeType === 1 && "style" in el;
174174
}
175175

176+
// A mount's id names the root it mounts; the runtime numbers repeated mounts (id__hf1, id__hf2).
177+
function mountsComposition(document: Document, host: Element, compositionId: string): boolean {
178+
if (host.hasAttribute("data-composition-src")) return true;
179+
return (
180+
host.children.length === 0 &&
181+
querySelectorAllWithTemplates(document, "template").some(
182+
(template) => template.id === `${compositionId}-template`,
183+
)
184+
);
185+
}
186+
176187
export function dedupeClonedCompositionId(document: Document, clone: Element): void {
177188
const compositionId = clone.getAttribute("data-composition-id");
178-
if (!compositionId) return;
189+
if (!compositionId || mountsComposition(document, clone, compositionId)) return;
179190
const usedCompositionIds = new Set(
180191
querySelectorAllWithTemplates(document, "[data-composition-id]").map((node) =>
181192
node.getAttribute("data-composition-id"),

0 commit comments

Comments
 (0)