Skip to content

Commit bfe2db3

Browse files
committed
fix(core): two scenes drawing SVGs with the same ids each show their own
1 parent b7d72c9 commit bfe2db3

6 files changed

Lines changed: 186 additions & 2 deletions

File tree

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2+
import { tmpdir } from "node:os";
3+
import { join } from "node:path";
4+
import sharp from "sharp";
5+
import { afterAll, expect, it, vi } from "vitest";
6+
import snapshotCommand from "./snapshot.js";
7+
8+
const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-scene-svg-ids-"));
9+
10+
afterAll(() => rmSync(dir, { recursive: true, force: true }));
11+
12+
// Two scenes drawn with the same SVG ids; the corner piece fills from a gradient both share at page level.
13+
const portrait = (
14+
color: string,
15+
) => `<svg viewBox="0 0 160 90" width="160" height="90" style="position:absolute;inset:0">
16+
<defs><linearGradient id="skin"><stop offset="0" stop-color="${color}"/><stop offset="1" stop-color="${color}"/></linearGradient>
17+
<clipPath id="face"><circle cx="80" cy="45" r="40"/></clipPath>
18+
<symbol id="portrait" viewBox="0 0 160 90"><rect width="160" height="90" fill="${color}"/></symbol></defs>
19+
<rect width="160" height="90" fill="url(#skin)" clip-path="url(#face)"/>
20+
<use href="#portrait" x="0" y="0" width="40" height="20"/>
21+
<rect x="140" y="70" width="20" height="20" fill="url(#page)"/>
22+
</svg>`;
23+
writeFileSync(
24+
join(dir, "index.html"),
25+
`<!doctype html><html><body style="margin:0;background:#000">
26+
<svg width="0" height="0" style="position:absolute"><linearGradient id="page"><stop offset="0" stop-color="#0f0"/><stop offset="1" stop-color="#0f0"/></linearGradient></svg>
27+
<div id="root" data-composition-id="main" data-start="0" data-duration="20" data-width="160" data-height="90" style="position:relative;width:160px;height:90px;background:#000">
28+
<div data-start="0" data-duration="10" data-track-index="0" style="position:absolute;inset:0">${portrait("#f00")}</div>
29+
<div data-start="10" data-duration="10" data-track-index="0" style="position:absolute;inset:0">${portrait("#00f")}</div>
30+
</div>
31+
<script>
32+
window.__timelines = window.__timelines || {};
33+
window.__timelines["main"] = { pause() {}, time() { return 0; }, duration() { return 20; }, seek() {} };
34+
</script></body></html>`,
35+
);
36+
37+
const colourAt = async (path: string, x: number, y: number) => {
38+
const { data, info } = await sharp(path).raw().toBuffer({ resolveWithObject: true });
39+
const at = (y * info.width + x) * info.channels;
40+
const [r, g, b] = [data[at]!, data[at + 1]!, data[at + 2]!];
41+
return r > 200 ? "red" : b > 200 ? "blue" : g > 200 ? "green" : "none";
42+
};
43+
44+
// fails without the fix: at 14 s the second scene's face painted nothing and its corner showed the first's red.
45+
it("shows each scene's own SVG portrait when two scenes reuse the same ids", async () => {
46+
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
47+
vi.spyOn(console, "error").mockImplementation(() => undefined);
48+
vi.spyOn(console, "warn").mockImplementation(() => undefined);
49+
try {
50+
await snapshotCommand.run?.({
51+
args: {
52+
dir,
53+
at: "4,14",
54+
end: false,
55+
json: true,
56+
output: join(dir, "out"),
57+
describe: "false",
58+
"browser-gpu": false,
59+
},
60+
} as never);
61+
const { frames } = JSON.parse(String(log.mock.calls.at(-1)?.[0])) as {
62+
frames: { path: string; time: number }[];
63+
};
64+
const seen = await Promise.all(
65+
frames.map(async ({ path, time }) => [
66+
time,
67+
await colourAt(path, 80, 45),
68+
await colourAt(path, 10, 5),
69+
await colourAt(path, 150, 80),
70+
]),
71+
);
72+
expect(seen).toEqual([
73+
[4, "red", "red", "green"],
74+
[14, "blue", "blue", "green"],
75+
]);
76+
} finally {
77+
vi.restoreAllMocks();
78+
}
79+
}, 120_000);

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

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -949,6 +949,58 @@ describe("inlineSubCompositions – #3490 nested SVG id collisions", () => {
949949
});
950950
});
951951

952+
describe("inlineSubCompositions – SVG ids in top-level scene clips", () => {
953+
const portrait = (color: string) =>
954+
`<svg><defs><linearGradient id="skin"><stop stop-color="${color}"/></linearGradient>` +
955+
`<symbol id="portrait"><rect fill="${color}"/></symbol></defs>` +
956+
`<rect class="face" fill="url(#skin)" clip-path="url(#shared)"/><use class="piece" href="#portrait"/></svg>`;
957+
const compile = (clips: string) => {
958+
const { document } = parseHTML(`<!DOCTYPE html><html><body>
959+
<svg width="0" height="0"><clipPath id="shared"><circle r="40"/></clipPath></svg>
960+
<div data-composition-id="main" data-start="0" data-duration="20">${clips}</div></body></html>`);
961+
inlineSubCompositions(document, [], {
962+
resolveHtml: () => null,
963+
parseHtml: (html) => parseHTML(html).document,
964+
hostIdentityMap: assignTestRuntimeCompositionIds([]),
965+
});
966+
return document;
967+
};
968+
// The first element with an id is what the browser resolves `url(#id)` and `href="#id"` to.
969+
const resolved = (document: Document, value: string | null) =>
970+
document.getElementById(value!.replace(/^url\(#|\)$|^#/g, ""));
971+
972+
// fails without the fix: the second scene's gradient and <use> resolved to the first scene's portrait.
973+
it("gives each scene clip its own portrait when two scenes reuse the same SVG ids", () => {
974+
const document = compile(
975+
`<div class="scene" data-start="0" data-duration="10">${portrait("red")}</div>` +
976+
`<div class="scene" data-start="10" data-duration="10">${portrait("blue")}</div>`,
977+
);
978+
const [first, second] = [...document.querySelectorAll(".scene")];
979+
for (const scene of [first!, second!]) {
980+
expect(
981+
scene.contains(resolved(document, scene.querySelector(".face")!.getAttribute("fill"))),
982+
).toBe(true);
983+
expect(
984+
scene.contains(resolved(document, scene.querySelector(".piece")!.getAttribute("href"))),
985+
).toBe(true);
986+
}
987+
expect(first!.querySelector("linearGradient")!.id).toBe("skin");
988+
expect(first!.querySelector("symbol")!.id).toBe("portrait");
989+
});
990+
991+
it("leaves a page-level definition the scenes share where it is", () => {
992+
const document = compile(
993+
`<div class="scene" data-start="0" data-duration="10">${portrait("red")}</div>` +
994+
`<div class="scene" data-start="10" data-duration="10">${portrait("blue")}</div>`,
995+
);
996+
const shared = document.getElementById("shared")!;
997+
expect(shared.closest(".scene")).toBeNull();
998+
for (const face of document.querySelectorAll(".face")) {
999+
expect(face.getAttribute("clip-path")).toBe("url(#shared)");
1000+
}
1001+
});
1002+
});
1003+
9521004
describe("inlineSubCompositions – renamed SVG ids stay reachable from author scripts", () => {
9531005
// These tests execute the compiled, scoped scripts inside a real jsdom
9541006
// window built from the assembled document — the same thing the browser

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
} from "./compositionScoping";
3636
import {
3737
namespaceCollidingSvgIds,
38+
sceneClipRoots,
3839
rewriteSvgIdReferencesInCss,
3940
type SvgIdScope,
4041
} from "./svgIdNamespacing";
@@ -778,6 +779,8 @@ export function inlineSubCompositions(
778779
// `<style>` text gets the same substitution its DOM just received. See
779780
// svgIdNamespacing.ts for why this is a rename, unlike the sibling
780781
// getElementById/media-id fixes.
782+
const hostRoots = svgIdScopes.map(({ root }) => root);
783+
const clips = sceneClipRoots(document, hostRoots);
781784
const svgIdMaps = namespaceCollidingSvgIds(document, [
782785
...svgIdScopes.map(({ root, namespace, exclude, styleStart, styleEnd }) => ({
783786
root,
@@ -789,9 +792,14 @@ export function inlineSubCompositions(
789792
root: document.documentElement,
790793
namespace: "",
791794
referenceTarget: "document",
792-
exclude: svgIdScopes.map(({ root }) => root),
795+
exclude: [...hostRoots, ...clips],
793796
cssTexts: rootStyles.map((style) => style.textContent ?? ""),
794797
},
798+
...clips.map((root, index) => ({
799+
root,
800+
namespace: `clip-${index}`,
801+
exclude: hostRoots.filter((host) => root.contains(host)),
802+
})),
795803
]);
796804
svgIdMaps.slice(0, svgIdScopes.length).forEach((idMap, index) => {
797805
const { styleStart, styleEnd } = svgIdScopes[index]!;

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,20 @@ function applyRenames(resolved: ResolvedScope, idMap: ReadonlyMap<string, string
414414
}
415415
}
416416

417+
const CLIP_SELECTOR = "[data-start]:not([data-composition-id]):not([data-composition-src])";
418+
419+
/** The outermost timed clips holding an `<svg>` outside every composition host. Each is its own id scope, as an
420+
* inlined composition is, so two scenes drawn with the same ids each resolve their own `url(#id)` and `href`. */
421+
export function sceneClipRoots(document: SvgIdQueryable, hosts: readonly Element[]): Element[] {
422+
return [...document.querySelectorAll(CLIP_SELECTOR)].filter(
423+
(clip) =>
424+
!clip.parentElement?.closest(CLIP_SELECTOR) &&
425+
!!clip.parentElement?.closest("[data-composition-id]") &&
426+
!isExcluded(clip, hosts) &&
427+
!!clip.querySelector("svg"),
428+
);
429+
}
430+
417431
/**
418432
* Rename every colliding, natively-referenced SVG id across the inlined
419433
* composition instances in `scopes` and rewrite each instance's attribute

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1918,4 +1918,23 @@ describe("namespaceMountedSvgIds", () => {
19181918
const outerClip = clipTarget(outerG);
19191919
expect(host("outer").contains(outerClip) && !inner.contains(outerClip)).toBe(true);
19201920
});
1921+
1922+
// fails without the fix: the second scene's clip-path resolved to the first scene's clipPath.
1923+
it("resolves each top-level scene clip to its own clipPath, and a shared page-level one for both", async () => {
1924+
const scene = (start: number) =>
1925+
`<div class="scene" data-start="${start}" data-duration="10">${CLIPPED("c")}` +
1926+
`<svg><rect class="shared" clip-path="url(#page)"/></svg></div>`;
1927+
await mountAll(
1928+
{},
1929+
`<svg><clipPath id="page"><rect width="1" height="1"/></clipPath></svg>` +
1930+
`<div data-composition-id="main" data-start="0">${scene(0)}${scene(10)}</div>`,
1931+
);
1932+
1933+
const scenes = [...document.querySelectorAll(".scene")];
1934+
for (const each of scenes)
1935+
expect(each.contains(clipTarget(each.querySelector("g")))).toBe(true);
1936+
expect(scenes[0]!.querySelector("clipPath")!.id).toBe("c");
1937+
for (const rect of document.querySelectorAll(".shared"))
1938+
expect(clipTarget(rect)).toBe(document.getElementById("page"));
1939+
});
19211940
});

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

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { parseImportMap } from "../compiler/importMaps";
1717
import { hasSameLink } from "../compiler/scriptRuns";
1818
import {
1919
namespaceCollidingSvgIds,
20+
sceneClipRoots,
2021
rewriteSvgIdReferencesInCss,
2122
} from "../compiler/svgIdNamespacing";
2223
import { waitForFonts } from "./afterFonts";
@@ -888,9 +889,20 @@ export async function loadCompositions(params: LoadCompositionsParams): Promise<
888889

889890
/** Reuse one finalization set across authored mounting and initial-script discovery. */
890891
function namespaceMountedSvgIds(
891-
mounted: readonly MountedSvgScope[],
892+
composed: readonly MountedSvgScope[],
892893
finalizedIds: Set<Element>,
893894
): void {
895+
const hosts = composed
896+
.filter((scope) => scope.referenceTarget !== "document")
897+
.map(({ host }) => host);
898+
const mounted = [
899+
...composed,
900+
...sceneClipRoots(document, hosts).map((host, index) => ({
901+
host,
902+
namespace: `clip-${index}`,
903+
styles: [],
904+
})),
905+
];
894906
for (const { styles } of mounted) {
895907
for (const style of styles) {
896908
const current = style.element.textContent ?? "";

0 commit comments

Comments
 (0)