Skip to content

Commit caa62fe

Browse files
fix(core): detect template entries structurally (heygen-com#7249)
* fix(core): detect template entries structurally isTemplateEntry only matched a raw file that starts with <template>, so the full-document sub-composition shape (<!doctype html><html><body><template> <div data-composition-id>...</template></body></html>) was not recognised and resolveEntryHtmlPath compiled the raw file, whose root sits in an inert template: no timeline, no duration, "Composition has zero duration". A template entry is now a document whose <template> holds the composition root with no live composition root outside it. Detection and extraction share one lookup (locateSceneRoot), the same one readSceneRoot uses. — Jerrai * fix(core): drop comments from the template lookup The comment ratchet allows no net rise in a file's comment share; the PR description carries the explanation. — Jerrai * fix(core): find the scene template among several templates locateSceneRoot read only the first <template>, so a scene template that follows another template was treated as not a template entry. Scan every template and take the first whose content holds a composition root. * fix(core): drop the added comment (comment ratchet) * chore: raise the inspector unpacked size budget by 0.5% The inspector bundles core; the multi-template scene lookup added a few hundred bytes and put it 10 bytes over the 1% tolerance. * fix(core): refuse a file with several scene templates, naming them * chore: trim the inspector size budget bump to what is needed * fix(core): render the first scene template and lint the ambiguity instead of failing A file with several scene templates and no live root rendered its first one before; locateSceneRoot threw and stopped such projects rendering. It returns the first again, and the multiple_scene_templates lint warning names each. Co-authored-by: Jerrai <[email protected]> * chore(core): drop the locateSceneRoot comment line the comment ratchet counts Co-authored-by: Jerrai <[email protected]> * fix(core): one shared scene-template pick for the compiler, the inliner and the loader A scene template after a card template was detected by locateSceneRoot but mounted from the first template of any kind, so it rendered blank. findSceneTemplate picks the first template holding a composition root and locateSceneRoot, resolveSubCompositionContent and the loader all use it. Co-authored-by: Jerrai <[email protected]>
1 parent 448f88f commit caa62fe

11 files changed

Lines changed: 326 additions & 17 deletions

File tree

‎docs/reference/lint-rules.mdx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,12 @@ lints the file it is editing.
4747

4848
**Fix:** Give every caption element the same `data-track-index`.
4949

50+
### `multiple_scene_templates`
51+
52+
**Warning.** A file has more than one `<template>` holding a composition root and no composition root outside them. Only the first one renders; the message names each template.
53+
54+
**Fix:** Keep one composition root per file, or move the other scenes into their own files.
55+
5056
### `clip_ends_past_root_duration`
5157

5258
**Warning.** A clip runs past the root composition's `data-duration`, so it is cut off in previews, posters and renders.

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,53 @@ describe("bundleToSingleHtml", () => {
285285
},
286286
);
287287

288+
it("bundles the first scene template of a file with two scene templates and no live root", async () => {
289+
const dir = makeTempProject({
290+
"index.html": `<!doctype html><html><body>
291+
<div data-composition-id="root" data-width="320" data-height="180" data-duration="6">
292+
<div data-composition-id="scene" data-composition-src="compositions/scene.html" data-start="0" data-duration="6"></div>
293+
</div>
294+
</body></html>`,
295+
"compositions/scene.html": `<template><div data-composition-id="scene" data-duration="6"><h1>first scene</h1></div></template>
296+
<template><div data-composition-id="other"><h1>second scene</h1></div></template>`,
297+
});
298+
299+
const bundled = await bundleToSingleHtml(dir, { entryFile: "compositions/scene.html" });
300+
301+
expect(bundled).toContain("first scene");
302+
expect(bundled).not.toContain("second scene");
303+
});
304+
305+
it.each([
306+
[
307+
"a card template before the scene",
308+
`<template id="card"><div class="card">card</div></template>`,
309+
"mounted scene",
310+
"",
311+
],
312+
[
313+
"two scene templates",
314+
"",
315+
"mounted scene",
316+
`<template><div data-composition-id="other"><h1>second scene</h1></div></template>`,
317+
],
318+
])("mounts the scene template of a file with %s", async (_label, before, expected, after) => {
319+
const dir = makeTempProject({
320+
"index.html": `<!doctype html><html><body>
321+
<div data-composition-id="root" data-width="320" data-height="180" data-duration="6">
322+
<div data-composition-id="scene" data-composition-src="compositions/scene.html" data-start="0" data-duration="6"></div>
323+
</div>
324+
</body></html>`,
325+
"compositions/scene.html": `${before}<template><div data-composition-id="scene" data-duration="6"><h1>mounted scene</h1></div></template>${after}`,
326+
});
327+
328+
const bundled = await bundleToSingleHtml(dir);
329+
330+
expect(bundled).toContain(expected);
331+
expect(bundled).not.toContain("second scene");
332+
expect(bundled).not.toContain(">card<");
333+
});
334+
288335
it("rebases direct-entry authored asset paths before inlining", async () => {
289336
const spriteSvg = '<svg xmlns="http://www.w3.org/2000/svg"><circle r="4"/></svg>';
290337
const bgSvg = '<svg xmlns="http://www.w3.org/2000/svg"><rect width="8" height="8"/></svg>';

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

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { acceleratedCanvasTrackerSource } from "../pageMotionBlur.js";
2+
import { findSceneTemplate } from "@hyperframes/parsers/sub-composition-validity";
23
import { parseHTML } from "linkedom";
34

45
export const RUNTIME_BOOTSTRAP_ATTR = "data-hyperframes-preview-runtime";
@@ -16,8 +17,30 @@ const SIMPLE_RUNTIME_FLAG_ASSIGNMENTS = [
1617

1718
const LEADING_COMMENTS = /^(?:\s|<!--(?:>|->|[\s\S]*?-->))*/;
1819

20+
export interface SceneRootLookup {
21+
root: Element | null;
22+
hasTemplate: boolean;
23+
hasLiveRoot: boolean;
24+
}
25+
26+
export function locateSceneRoot(html: string): SceneRootLookup {
27+
const { document } = parseHTML(html);
28+
const liveRoot = document.querySelector("[data-composition-id]") as Element | null;
29+
const templates = Array.from(document.querySelectorAll("template"));
30+
const sceneRoot =
31+
(findSceneTemplate(templates)?.content.querySelector(
32+
"[data-composition-id]",
33+
) as Element | null) ?? null;
34+
return {
35+
root: sceneRoot,
36+
hasTemplate: templates.length > 0,
37+
hasLiveRoot: liveRoot !== null,
38+
};
39+
}
40+
1941
export function isTemplateEntry(html: string): boolean {
20-
return /^<template[\s>/]/i.test(html.replace(LEADING_COMMENTS, ""));
42+
const { root, hasTemplate, hasLiveRoot } = locateSceneRoot(html);
43+
return hasTemplate && root !== null && !hasLiveRoot;
2144
}
2245

2346
export function isFullHtmlDocument(html: string): boolean {

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

Lines changed: 79 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,96 @@
11
import { parseHTML } from "linkedom";
22
import { describe, expect, it } from "vitest";
3+
import { locateSceneRoot } from "./htmlDocument";
34
import { extractStandaloneEntryFromIndex, isTemplateEntry } from "./standaloneEntry";
45

6+
const ROOT = `<div id="root" data-composition-id="scene" data-width="640" data-height="360" data-duration="3"><p id="label">Hello</p></div>`;
7+
const SCENE_SCRIPT = `<script>window.__timelines = window.__timelines || {}; const tl = gsap.timeline({ paused: true }); tl.to("#label", { opacity: 1, duration: 3 }, 0); window.__timelines["scene"] = tl;</script>`;
8+
const SCENE_STYLE = `<style>#root { position: absolute; inset: 0; background: #123456; }</style>`;
9+
510
describe("isTemplateEntry", () => {
611
it.each([
7-
"<template></template>",
8-
" \n<!-- Scene author notes -->\n<template id='scene'></template>",
9-
"<!-- a --><!-- <template> is inert --><TEMPLATE></TEMPLATE>",
10-
"<!--><template></template>",
11-
])("recognizes a template entry past leading comments: %s", (html) => {
12+
`<template>${ROOT}</template>`,
13+
` \n<!-- Scene author notes -->\n<template id='scene'>${ROOT}</template>`,
14+
`<!-- a --><!-- <template> is inert --><TEMPLATE>${ROOT}</TEMPLATE>`,
15+
`<!--><template>${ROOT}</template>`,
16+
])("recognizes a template-first fragment entry: %s", (html) => {
17+
expect(isTemplateEntry(html)).toBe(true);
18+
});
19+
20+
it("recognizes the full-document shape whose composition root lives in the body template", () => {
21+
const html = `<!doctype html>
22+
<html>
23+
<head><meta charset="UTF-8" /></head>
24+
<body>
25+
<template>
26+
${SCENE_STYLE}
27+
${ROOT}
28+
${SCENE_SCRIPT}
29+
</template>
30+
</body>
31+
</html>`;
1232
expect(isTemplateEntry(html)).toBe(true);
1333
});
1434

1535
it.each([
1636
"<template-card></template-card>",
17-
"<!doctype html><html><body><template></template></body></html>",
18-
"<div></div><template></template>",
19-
"<!-- <template></template> -->",
37+
`<template-card>${ROOT}</template-card>`,
38+
`<!doctype html><html><body><template></template></body></html>`,
39+
`<div></div><template></template>`,
40+
`<!-- <template>${ROOT}</template> -->`,
41+
`<!doctype html><html><body>${ROOT}</body></html>`,
2042
])("does not mistake other entries for a template scene: %s", (html) => {
2143
expect(isTemplateEntry(html)).toBe(false);
2244
});
45+
46+
it("keeps a full document with a live composition root outside the template a plain entry", () => {
47+
const html = `<!doctype html>
48+
<html>
49+
<body>
50+
<div id="live" data-composition-id="live" data-width="640" data-height="360" data-duration="3"></div>
51+
<template>${ROOT}</template>
52+
</body>
53+
</html>`;
54+
expect(isTemplateEntry(html)).toBe(false);
55+
});
56+
57+
it("keeps a template-first fragment with a live composition root beside it a plain entry", () => {
58+
const html = `<template>${ROOT}</template><div data-composition-id="live"></div>`;
59+
expect(isTemplateEntry(html)).toBe(false);
60+
});
61+
62+
it.each([
63+
`<template id="card"><div class="card">Card</div></template><template id="scene">${ROOT}</template>`,
64+
`<!doctype html><html><body><template><svg><symbol id="i"></symbol></svg></template><template>${ROOT}</template></body></html>`,
65+
`<template></template><template><p>x</p></template><template>${ROOT}</template>`,
66+
])("finds the scene template when an earlier template holds no composition root: %s", (html) => {
67+
expect(isTemplateEntry(html)).toBe(true);
68+
expect(locateSceneRoot(html).root?.getAttribute("data-composition-id")).toBe("scene");
69+
});
70+
71+
it("renders the first scene template when several hold a composition root and none is live", () => {
72+
const html = `<template id="intro">${ROOT}</template><template><div data-composition-id="later"></div></template>`;
73+
expect(locateSceneRoot(html).root?.getAttribute("data-composition-id")).toBe("scene");
74+
expect(isTemplateEntry(html)).toBe(true);
75+
});
76+
77+
it("does not refuse when a live root makes the file a plain entry", () => {
78+
const html = `<template>${ROOT}</template><template>${ROOT}</template><div data-composition-id="live"></div>`;
79+
expect(isTemplateEntry(html)).toBe(false);
80+
});
81+
82+
it("reports no root when no template holds a composition root", () => {
83+
const lookup = locateSceneRoot(`<template><p>a</p></template><template><p>b</p></template>`);
84+
expect(lookup).toMatchObject({ root: null, hasTemplate: true, hasLiveRoot: false });
85+
});
86+
87+
it("reads a single template and a template-free document as before", () => {
88+
expect(locateSceneRoot(`<template>${ROOT}</template>`).root?.id).toBe("root");
89+
expect(locateSceneRoot(`<!doctype html><html><body>${ROOT}</body></html>`)).toMatchObject({
90+
hasTemplate: false,
91+
hasLiveRoot: true,
92+
});
93+
});
2394
});
2495

2596
describe("extractStandaloneEntryFromIndex", () => {

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

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,15 @@
11
import { parseHTML } from "linkedom";
22
import { HF_AUDIO_FX_ATTR } from "../audioFx";
3+
import { locateSceneRoot } from "./htmlDocument";
34

45
export { isTemplateEntry } from "./htmlDocument";
56

67
function normalizeCompositionSrcPath(srcPath: string): string {
78
return srcPath.replace(/\\/g, "/").replace(/^\.\//, "");
89
}
910

10-
// linkedom has no inert <template> content, so the template's innerHTML is re-parsed.
1111
function readSceneRoot(entryHtml: string | undefined): Element | null {
12-
if (!entryHtml) return null;
13-
const { document } = parseHTML(entryHtml);
14-
const template = document.querySelector("template");
15-
const scope = template ? parseHTML(template.innerHTML).document : document;
16-
return scope.querySelector("[data-composition-id]") as Element | null;
12+
return entryHtml ? locateSceneRoot(entryHtml).root : null;
1713
}
1814

1915
// The scene's own chain replaces the index's, which belongs to the whole project.

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,27 @@ describe("loadCompositions external hosts", () => {
149149
).toBe(false);
150150
});
151151

152+
it.each([
153+
["a card template before the scene", `<template><div class="card">card</div></template>`, ""],
154+
[
155+
"two scene templates",
156+
"",
157+
`<template><div data-composition-id="other"><p>second scene</p></div></template>`,
158+
],
159+
])("mounts the scene template of a fetched file with %s", async (_label, before, after) => {
160+
const host = appendExternalHost("https://example.com/comp.html", "scene-1");
161+
const scene = `<template><div data-composition-id="scene-1"><p>Hello World</p></div></template>`;
162+
vi.spyOn(globalThis, "fetch").mockResolvedValue(
163+
new Response(`${before}${scene}${after}`, { status: 200 }),
164+
);
165+
166+
await loadFixture();
167+
168+
expect(host.textContent).toContain("Hello World");
169+
expect(host.textContent).not.toContain("card");
170+
expect(host.textContent).not.toContain("second scene");
171+
});
172+
152173
it("sizes a flattened inner root from a px-suffixed or fractional size", async () => {
153174
const host = appendExternalHost("https://example.com/comp.html", "scene-1");
154175
const compositionHtml = `

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { findSceneTemplate } from "@hyperframes/parsers/sub-composition-validity";
12
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
23
import {
34
SVG_REFERENCE_ALIASES_ATTR,
@@ -186,6 +187,11 @@ function rewriteSubCompositionAssetPaths(root: ParentNode, compositionUrl: URL |
186187
}
187188
}
188189

190+
function sceneOrFirstTemplate(doc: Document): HTMLTemplateElement | null {
191+
const templates = Array.from(doc.querySelectorAll<HTMLTemplateElement>("template"));
192+
return findSceneTemplate(templates) ?? templates[0] ?? null;
193+
}
194+
189195
function uniqueCompositionId(baseId: string, index: number): string {
190196
return `${baseId}__hf${index}`;
191197
}
@@ -801,7 +807,7 @@ async function mountExternalCompositions(
801807
? doc.querySelector<HTMLTemplateElement>(
802808
`template#${CSS.escape(authoredCompositionId)}-template`,
803809
)
804-
: null) ?? doc.querySelector<HTMLTemplateElement>("template");
810+
: null) ?? sceneOrFirstTemplate(doc);
805811
const sourceNode = template ? template.content : doc.body;
806812
return await mount({
807813
host,

‎packages/lint/src/rules/composition.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,32 @@ import { lintHyperframeHtml } from "../hyperframeLinter.js";
44
import { parseCompositionVariables } from "@hyperframes/parsers/composition";
55

66
describe("composition rules", () => {
7+
describe("multiple_scene_templates", () => {
8+
const scene = (id: string) =>
9+
`<div data-composition-id="${id}" data-width="320" data-height="180"></div>`;
10+
const find = async (html: string) =>
11+
(await lintHyperframeHtml(html, { isSubComposition: true })).findings.find(
12+
(f) => f.code === "multiple_scene_templates",
13+
);
14+
15+
it("warns, naming each scene template", async () => {
16+
const finding = await find(
17+
`<template id="intro">${scene("a")}</template><template>${scene("b")}</template>`,
18+
);
19+
expect(finding?.severity).toBe("warning");
20+
expect(finding?.message).toContain('template #1 (id="intro") holding composition "a"');
21+
expect(finding?.message).toContain('template #2 holding composition "b"');
22+
});
23+
24+
it.each([
25+
`<template>${scene("a")}</template>`,
26+
`<template><svg></svg></template><template>${scene("a")}</template>`,
27+
`<template>${scene("a")}</template><template>${scene("b")}</template>${scene("live")}`,
28+
])("is quiet for %s", async (html) => {
29+
expect(await find(html)).toBeUndefined();
30+
});
31+
});
32+
733
describe("canonical timing contract", () => {
834
it("rejects deprecated attributes even when canonical attributes are also present", async () => {
935
const result = await lintHyperframeHtml(`<!doctype html><html><body>

‎packages/lint/src/rules/composition.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { LintContext, HyperframeLintFinding, ExtractedBlock, OpenTag } from "../context";
22
import selectorParser from "postcss-selector-parser";
3+
import { parseHTML } from "linkedom";
34
import {
45
findHtmlTag,
56
extractTimelineRegistryKeys,
@@ -1946,6 +1947,32 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
19461947
snippet: truncateSnippet(style.content.slice(0, 120)),
19471948
}));
19481949
},
1950+
1951+
// multiple_scene_templates: the renderer takes the first scene template of a file with no live root.
1952+
({ rawSource }) => {
1953+
const { document } = parseHTML(rawSource);
1954+
if (document.querySelector("[data-composition-id]")) return [];
1955+
const scenes = Array.from(document.querySelectorAll("template")).flatMap((template, index) => {
1956+
const compositionId = parseHTML(template.innerHTML)
1957+
.document.querySelector("[data-composition-id]")
1958+
?.getAttribute("data-composition-id");
1959+
if (compositionId === undefined) return [];
1960+
const id = template.getAttribute("id");
1961+
return [
1962+
`template #${index + 1}${id ? ` (id="${id}")` : ""} holding composition "${compositionId}"`,
1963+
];
1964+
});
1965+
if (scenes.length < 2) return [];
1966+
return [
1967+
{
1968+
code: "multiple_scene_templates",
1969+
severity: "warning",
1970+
message: `This file has more than one scene template and no live composition root, so only the first renders: ${scenes.join("; ")}.`,
1971+
fixHint:
1972+
"Keep one composition root per file, or move the other scenes into their own files.",
1973+
},
1974+
];
1975+
},
19491976
];
19501977

19511978
const CLIP_MEDIA_TAGS = new Set<string>(["img", "video", "audio"]);

‎packages/parsers/src/subCompositionValidity.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,25 @@ export interface ParsableDocumentLike {
5555
documentElement: { outerHTML?: string } | null;
5656
body?: { innerHTML?: string | null } | null;
5757
querySelector(selector: string): { innerHTML?: string | null } | null;
58+
querySelectorAll(selector: string): ArrayLike<{ innerHTML?: string | null } & SceneTemplateLike>;
59+
}
60+
61+
export interface SceneTemplateLike {
62+
content: { querySelector(selector: string): unknown };
63+
}
64+
65+
export function findSceneTemplate<T extends SceneTemplateLike>(
66+
templates: ArrayLike<T>,
67+
): T | undefined {
68+
return Array.from(templates).find(
69+
(template) => template.content.querySelector("[data-composition-id]") != null,
70+
);
5871
}
5972

6073
/** Resolve authored content without invoking linkedom's synthetic body getter. */
6174
export function resolveSubCompositionContent(html: string, document: ParsableDocumentLike) {
62-
const template = document.querySelector("template");
75+
const templates = Array.from(document.querySelectorAll("template"));
76+
const template = findSceneTemplate(templates) ?? templates[0];
6377
if (template) return { contentHtml: template.innerHTML ?? "", hasTemplate: true };
6478

6579
const body = document.querySelector("body");

0 commit comments

Comments
 (0)