fix(core): two scenes drawing SVGs with the same ids each show their own (#7251)

* fix(core): two scenes drawing SVGs with the same ids each show their own

* fix(core): the runtime's scene scopes typecheck as mounted scopes
This commit is contained in:
Miguel Ángel
2026-11-05 17:20:51 +00:00
committed by GitHub
parent f98218a224
commit b108f85120
6 changed files with 186 additions and 2 deletions
@@ -0,0 +1,79 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import sharp from "sharp";
import { afterAll, expect, it, vi } from "vitest";
import snapshotCommand from "./snapshot.js";
const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-scene-svg-ids-"));
afterAll(() => rmSync(dir, { recursive: true, force: true }));
// Two scenes drawn with the same SVG ids; the corner piece fills from a gradient both share at page level.
const portrait = (
color: string,
) => `<svg viewBox="0 0 160 90" width="160" height="90" style="position:absolute;inset:0">
<defs><linearGradient id="skin"><stop offset="0" stop-color="${color}"/><stop offset="1" stop-color="${color}"/></linearGradient>
<clipPath id="face"><circle cx="80" cy="45" r="40"/></clipPath>
<symbol id="portrait" viewBox="0 0 160 90"><rect width="160" height="90" fill="${color}"/></symbol></defs>
<rect width="160" height="90" fill="url(#skin)" clip-path="url(#face)"/>
<use href="#portrait" x="0" y="0" width="40" height="20"/>
<rect x="140" y="70" width="20" height="20" fill="url(#page)"/>
</svg>`;
writeFileSync(
join(dir, "index.html"),
`<!doctype html><html><body style="margin:0;background:#000">
<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>
<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">
<div data-start="0" data-duration="10" data-track-index="0" style="position:absolute;inset:0">${portrait("#f00")}</div>
<div data-start="10" data-duration="10" data-track-index="0" style="position:absolute;inset:0">${portrait("#00f")}</div>
</div>
<script>
window.__timelines = window.__timelines || {};
window.__timelines["main"] = { pause() {}, time() { return 0; }, duration() { return 20; }, seek() {} };
</script></body></html>`,
);
const colourAt = async (path: string, x: number, y: number) => {
const { data, info } = await sharp(path).raw().toBuffer({ resolveWithObject: true });
const at = (y * info.width + x) * info.channels;
const [r, g, b] = [data[at]!, data[at + 1]!, data[at + 2]!];
return r > 200 ? "red" : b > 200 ? "blue" : g > 200 ? "green" : "none";
};
// fails without the fix: at 14 s the second scene's face painted nothing and its corner showed the first's red.
it("shows each scene's own SVG portrait when two scenes reuse the same ids", async () => {
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.spyOn(console, "warn").mockImplementation(() => undefined);
try {
await snapshotCommand.run?.({
args: {
dir,
at: "4,14",
end: false,
json: true,
output: join(dir, "out"),
describe: "false",
"browser-gpu": false,
},
} as never);
const { frames } = JSON.parse(String(log.mock.calls.at(-1)?.[0])) as {
frames: { path: string; time: number }[];
};
const seen = await Promise.all(
frames.map(async ({ path, time }) => [
time,
await colourAt(path, 80, 45),
await colourAt(path, 10, 5),
await colourAt(path, 150, 80),
]),
);
expect(seen).toEqual([
[4, "red", "red", "green"],
[14, "blue", "blue", "green"],
]);
} finally {
vi.restoreAllMocks();
}
}, 120_000);
@@ -949,6 +949,58 @@ describe("inlineSubCompositions – #3490 nested SVG id collisions", () => {
});
});
describe("inlineSubCompositions – SVG ids in top-level scene clips", () => {
const portrait = (color: string) =>
`<svg><defs><linearGradient id="skin"><stop stop-color="${color}"/></linearGradient>` +
`<symbol id="portrait"><rect fill="${color}"/></symbol></defs>` +
`<rect class="face" fill="url(#skin)" clip-path="url(#shared)"/><use class="piece" href="#portrait"/></svg>`;
const compile = (clips: string) => {
const { document } = parseHTML(`<!DOCTYPE html><html><body>
<svg width="0" height="0"><clipPath id="shared"><circle r="40"/></clipPath></svg>
<div data-composition-id="main" data-start="0" data-duration="20">${clips}</div></body></html>`);
inlineSubCompositions(document, [], {
resolveHtml: () => null,
parseHtml: (html) => parseHTML(html).document,
hostIdentityMap: assignTestRuntimeCompositionIds([]),
});
return document;
};
// The first element with an id is what the browser resolves `url(#id)` and `href="#id"` to.
const resolved = (document: Document, value: string | null) =>
document.getElementById(value!.replace(/^url\(#|\)$|^#/g, ""));
// fails without the fix: the second scene's gradient and <use> resolved to the first scene's portrait.
it("gives each scene clip its own portrait when two scenes reuse the same SVG ids", () => {
const document = compile(
`<div class="scene" data-start="0" data-duration="10">${portrait("red")}</div>` +
`<div class="scene" data-start="10" data-duration="10">${portrait("blue")}</div>`,
);
const [first, second] = [...document.querySelectorAll(".scene")];
for (const scene of [first!, second!]) {
expect(
scene.contains(resolved(document, scene.querySelector(".face")!.getAttribute("fill"))),
).toBe(true);
expect(
scene.contains(resolved(document, scene.querySelector(".piece")!.getAttribute("href"))),
).toBe(true);
}
expect(first!.querySelector("linearGradient")!.id).toBe("skin");
expect(first!.querySelector("symbol")!.id).toBe("portrait");
});
it("leaves a page-level definition the scenes share where it is", () => {
const document = compile(
`<div class="scene" data-start="0" data-duration="10">${portrait("red")}</div>` +
`<div class="scene" data-start="10" data-duration="10">${portrait("blue")}</div>`,
);
const shared = document.getElementById("shared")!;
expect(shared.closest(".scene")).toBeNull();
for (const face of document.querySelectorAll(".face")) {
expect(face.getAttribute("clip-path")).toBe("url(#shared)");
}
});
});
describe("inlineSubCompositions – renamed SVG ids stay reachable from author scripts", () => {
// These tests execute the compiled, scoped scripts inside a real jsdom
// window built from the assembled document — the same thing the browser
@@ -35,6 +35,7 @@ import {
} from "./compositionScoping";
import {
namespaceCollidingSvgIds,
sceneClipRoots,
rewriteSvgIdReferencesInCss,
type SvgIdScope,
} from "./svgIdNamespacing";
@@ -778,6 +779,8 @@ export function inlineSubCompositions(
// `<style>` text gets the same substitution its DOM just received. See
// svgIdNamespacing.ts for why this is a rename, unlike the sibling
// getElementById/media-id fixes.
const hostRoots = svgIdScopes.map(({ root }) => root);
const clips = sceneClipRoots(document, hostRoots);
const svgIdMaps = namespaceCollidingSvgIds(document, [
...svgIdScopes.map(({ root, namespace, exclude, styleStart, styleEnd }) => ({
root,
@@ -789,9 +792,14 @@ export function inlineSubCompositions(
root: document.documentElement,
namespace: "",
referenceTarget: "document",
exclude: svgIdScopes.map(({ root }) => root),
exclude: [...hostRoots, ...clips],
cssTexts: rootStyles.map((style) => style.textContent ?? ""),
},
...clips.map((root, index) => ({
root,
namespace: `clip-${index}`,
exclude: hostRoots.filter((host) => root.contains(host)),
})),
]);
svgIdMaps.slice(0, svgIdScopes.length).forEach((idMap, index) => {
const { styleStart, styleEnd } = svgIdScopes[index]!;
@@ -414,6 +414,20 @@ function applyRenames(resolved: ResolvedScope, idMap: ReadonlyMap<string, string
}
}
const CLIP_SELECTOR = "[data-start]:not([data-composition-id]):not([data-composition-src])";
/** The outermost timed clips holding an `<svg>` outside every composition host. Each is its own id scope, as an
* inlined composition is, so two scenes drawn with the same ids each resolve their own `url(#id)` and `href`. */
export function sceneClipRoots(document: SvgIdQueryable, hosts: readonly Element[]): Element[] {
return [...document.querySelectorAll(CLIP_SELECTOR)].filter(
(clip) =>
!clip.parentElement?.closest(CLIP_SELECTOR) &&
!!clip.parentElement?.closest("[data-composition-id]") &&
!isExcluded(clip, hosts) &&
!!clip.querySelector("svg"),
);
}
/**
* Rename every colliding, natively-referenced SVG id across the inlined
* composition instances in `scopes` and rewrite each instance's attribute
@@ -1918,4 +1918,23 @@ describe("namespaceMountedSvgIds", () => {
const outerClip = clipTarget(outerG);
expect(host("outer").contains(outerClip) && !inner.contains(outerClip)).toBe(true);
});
// fails without the fix: the second scene's clip-path resolved to the first scene's clipPath.
it("resolves each top-level scene clip to its own clipPath, and a shared page-level one for both", async () => {
const scene = (start: number) =>
`<div class="scene" data-start="${start}" data-duration="10">${CLIPPED("c")}` +
`<svg><rect class="shared" clip-path="url(#page)"/></svg></div>`;
await mountAll(
{},
`<svg><clipPath id="page"><rect width="1" height="1"/></clipPath></svg>` +
`<div data-composition-id="main" data-start="0">${scene(0)}${scene(10)}</div>`,
);
const scenes = [...document.querySelectorAll(".scene")];
for (const each of scenes)
expect(each.contains(clipTarget(each.querySelector("g")))).toBe(true);
expect(scenes[0]!.querySelector("clipPath")!.id).toBe("c");
for (const rect of document.querySelectorAll(".shared"))
expect(clipTarget(rect)).toBe(document.getElementById("page"));
});
});
+13 -1
View File
@@ -17,6 +17,7 @@ import { parseImportMap } from "../compiler/importMaps";
import { hasSameLink } from "../compiler/scriptRuns";
import {
namespaceCollidingSvgIds,
sceneClipRoots,
rewriteSvgIdReferencesInCss,
} from "../compiler/svgIdNamespacing";
import { waitForFonts } from "./afterFonts";
@@ -888,9 +889,20 @@ export async function loadCompositions(params: LoadCompositionsParams): Promise<
/** Reuse one finalization set across authored mounting and initial-script discovery. */
function namespaceMountedSvgIds(
mounted: readonly MountedSvgScope[],
composed: readonly MountedSvgScope[],
finalizedIds: Set<Element>,
): void {
const hosts = composed
.filter((scope) => scope.referenceTarget !== "document")
.map(({ host }) => host);
const mounted: MountedSvgScope[] = [
...composed,
...sceneClipRoots(document, hosts).map((host, index) => ({
host,
namespace: `clip-${index}`,
styles: [],
})),
];
for (const { styles } of mounted) {
for (const style of styles) {
const current = style.element.textContent ?? "";