Skip to content

Commit 08b53f8

Browse files
fix: nested GSAP sub-composition lint and render handling (heygen-com#405)
## Summary - allow nested sub-composition files to inherit GSAP from their host without tripping `missing_gsap_script` - keep nested render seeks stable for sub-compositions without regressing producer baselines - stop producer render-hint detection from treating the compiler's own nested mount retry wrapper as user-authored `requestAnimationFrame()` usage ## Root Cause - the core linter treated template-based nested compositions like standalone root compositions, so it incorrectly required a local GSAP loader even when the host composition already provided GSAP - producer `detectRenderModeHints()` runs before CDN scripts are inlined, so nested GSAP exports were never failing because of the GSAP payload itself - the nested-only false positive came from the compiler-generated mount bootstrap that waits for the inlined sub-composition root with `requestAnimationFrame()` before running the hoisted inline script - preview and export seek paths also needed to stay split so the nested timeline re-arm behavior that stabilizes scrubbing does not collapse render baselines ## What Changed - lint: keep the nested GSAP false-positive fix and regression coverage for template sub-compositions - runtime: keep the render-seek behavior that preserves nested child offsets during export without changing preview scrubbing behavior - producer: mark compiler-owned mount bootstrap blocks and strip only those blocks before scanning inline scripts for raw `requestAnimationFrame()` - producer tests now cover both cases: compiler-generated wrappers are ignored, but real user-authored nested `requestAnimationFrame()` still opts into screenshot mode ## Validation - `bun test packages/core/src/lint/rules/gsap.test.ts` - `bun test packages/producer/src/services/htmlCompiler.test.ts` - `bunx oxfmt packages/producer/src/services/htmlCompiler.ts packages/producer/src/services/htmlCompiler.test.ts` - `bunx oxlint packages/producer/src/services/htmlCompiler.ts packages/producer/src/services/htmlCompiler.test.ts` - `bun run --filter @hyperframes/producer test --sequential chat style-11-prod` - `style-11-prod` passed locally - `chat` still shows local-only visual drift on this macOS/ARM workstation, but the render metadata now reports `renderModeHints.recommendScreenshot=false`, which is the concrete acceptance condition for `heygen-com#402` - Docker CI-image repro is blocked locally by OrbStack x86/arm64 loader mismatch, so final regression confirmation is deferred to GitHub Actions Closes heygen-com#392 Closes heygen-com#402
1 parent 1c254b4 commit 08b53f8

6 files changed

Lines changed: 188 additions & 10 deletions

File tree

‎packages/core/src/lint/rules/gsap.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,42 @@ describe("GSAP rules", () => {
142142
expect(finding).toBeUndefined();
143143
});
144144

145+
it("does NOT require a local GSAP script for sub-compositions", () => {
146+
const html = `<template id="intro-template">
147+
<div data-composition-id="intro" data-width="1920" data-height="1080">
148+
<div class="title">Hello</div>
149+
<script>
150+
window.__timelines = window.__timelines || {};
151+
const tl = gsap.timeline({ paused: true });
152+
tl.from(".title", { opacity: 0, duration: 1 });
153+
window.__timelines["intro"] = tl;
154+
</script>
155+
</div>
156+
</template>`;
157+
158+
const result = lintHyperframeHtml(html, { isSubComposition: true });
159+
const finding = result.findings.find((f) => f.code === "missing_gsap_script");
160+
expect(finding).toBeUndefined();
161+
});
162+
163+
it("does NOT require a local GSAP script when a template composition is linted in isolation", () => {
164+
const html = `<template id="intro-template">
165+
<div data-composition-id="intro" data-width="1920" data-height="1080">
166+
<div class="title">Hello</div>
167+
<script>
168+
window.__timelines = window.__timelines || {};
169+
const tl = gsap.timeline({ paused: true });
170+
tl.from(".title", { opacity: 0, duration: 1 });
171+
window.__timelines["intro"] = tl;
172+
</script>
173+
</div>
174+
</template>`;
175+
176+
const result = lintHyperframeHtml(html, { filePath: "compositions/intro.html" });
177+
const finding = result.findings.find((f) => f.code === "missing_gsap_script");
178+
expect(finding).toBeUndefined();
179+
});
180+
145181
it("ERRORS when GSAP animates visibility on a clip element", () => {
146182
const html = `
147183
<html><body>

‎packages/core/src/lint/rules/gsap.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -432,11 +432,13 @@ export const gsapRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
432432
},
433433

434434
// missing_gsap_script
435-
({ scripts }) => {
435+
({ scripts, rawSource, options }) => {
436436
const allScriptTexts = scripts.filter((s) => !/\bsrc\s*=/.test(s.attrs)).map((s) => s.content);
437437
const allScriptSrcs = scripts
438438
.map((s) => readAttr(`<script ${s.attrs}>`, "src") || "")
439439
.filter(Boolean);
440+
const canInheritGsapFromHost =
441+
options.isSubComposition || rawSource.trimStart().toLowerCase().startsWith("<template");
440442

441443
const usesGsap = allScriptTexts.some((t) =>
442444
/gsap\.(to|from|fromTo|timeline|set|registerPlugin)\b/.test(t),
@@ -455,7 +457,7 @@ export const gsapRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
455457
(t.length > 5000 && /\bgsap\b/i.test(t)),
456458
);
457459

458-
if (!usesGsap || hasGsapScript || hasInlineGsap) return [];
460+
if (!usesGsap || hasGsapScript || hasInlineGsap || canInheritGsapFromHost) return [];
459461
return [
460462
{
461463
code: "missing_gsap_script",

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -381,7 +381,7 @@ describe("createRuntimePlayer", () => {
381381
expect(deps.onRenderFrameSeek).toHaveBeenCalled();
382382
});
383383

384-
it("renderSeek rearms paused siblings before seeking the master timeline", () => {
384+
it("renderSeek rearms paused siblings and keeps them active for export frames", () => {
385385
const { master, scene1, scene2, scene5 } = createNestedTimelineHarness();
386386
const deps = createMockDeps(master);
387387
const player = createRuntimePlayer({
@@ -390,12 +390,16 @@ describe("createRuntimePlayer", () => {
390390
});
391391
player.pause();
392392
player.renderSeek(5);
393+
expect(master.totalTime).toHaveBeenCalledWith(5, false);
393394
expect(scene1.time()).toBe(1.5);
394395
expect(scene2.time()).toBe(3.5);
395396
expect(scene5.time()).toBe(0);
396397
expect(scene1.play).toHaveBeenCalledTimes(1);
397398
expect(scene2.play).toHaveBeenCalledTimes(1);
398399
expect(scene5.play).toHaveBeenCalledTimes(1);
400+
expect(scene1.pause).toHaveBeenCalledTimes(1);
401+
expect(scene2.pause).toHaveBeenCalledTimes(1);
402+
expect(scene5.pause).toHaveBeenCalledTimes(1);
399403
});
400404
});
401405

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

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,15 @@ function seekMasterAndSiblingTimelinesDeterministically(
8383
}
8484
}
8585

86+
function activateSiblingTimelines(
87+
registry: Record<string, RuntimeTimelineLike | undefined> | undefined | null,
88+
master: RuntimeTimelineLike,
89+
): void {
90+
forEachSiblingTimeline(registry, master, (tl) => {
91+
tl.play();
92+
});
93+
}
94+
8695
export function createRuntimePlayer(deps: PlayerDeps): RuntimePlayer {
8796
return {
8897
_timeline: null,
@@ -156,12 +165,13 @@ export function createRuntimePlayer(deps: PlayerDeps): RuntimePlayer {
156165
// their animations advance. Without this, non-GSAP compositions freeze
157166
// on their initial frame.
158167
const quantized = timeline
159-
? seekMasterAndSiblingTimelinesDeterministically(
160-
deps.getTimelineRegistry?.(),
161-
timeline,
162-
timeSeconds,
163-
canonicalFps,
164-
)
168+
? (() => {
169+
// Export seeks run frame-by-frame through the resolved root timeline.
170+
// If nested siblings stay paused, GSAP collapses the root back to the
171+
// authored master duration and later frames clamp incorrectly.
172+
activateSiblingTimelines(deps.getTimelineRegistry?.(), timeline);
173+
return seekTimelineDeterministically(timeline, timeSeconds, canonicalFps);
174+
})()
165175
: quantizeTimeToFrame(Math.max(0, Number(timeSeconds) || 0), canonicalFps);
166176
deps.onDeterministicSeek(quantized);
167177
deps.setIsPlaying(false);

‎packages/producer/src/services/htmlCompiler.test.ts‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
44
import { join } from "node:path";
55
import {
66
collectExternalAssets,
7+
compileForRender,
78
detectRenderModeHints,
89
inlineExternalScripts,
910
} from "./htmlCompiler.js";
@@ -343,4 +344,115 @@ describe("detectRenderModeHints", () => {
343344
expect(result.recommendScreenshot).toBe(false);
344345
expect(result.reasons).toEqual([]);
345346
});
347+
348+
it("ignores compiler-generated nested mount wrappers when detecting requestAnimationFrame", () => {
349+
const html = `<!DOCTYPE html>
350+
<html><body>
351+
<div data-composition-id="root" data-width="1920" data-height="1080"></div>
352+
<script>
353+
(function(){
354+
var __compId = "intro";
355+
var __run = function() {
356+
const label = "safe";
357+
};
358+
if (!__compId) { __run(); return; }
359+
/* __HF_COMPILER_MOUNT_START__ */
360+
var __selector = '[data-composition-id="intro"]';
361+
var __attempt = 0;
362+
var __tryRun = function() {
363+
if (document.querySelector(__selector)) { __run(); return; }
364+
if (++__attempt >= 8) { __run(); return; }
365+
requestAnimationFrame(__tryRun);
366+
};
367+
__tryRun();
368+
/* __HF_COMPILER_MOUNT_END__ */
369+
})();
370+
</script>
371+
</body></html>`;
372+
373+
const result = detectRenderModeHints(html);
374+
375+
expect(result.recommendScreenshot).toBe(false);
376+
expect(result.reasons).toEqual([]);
377+
});
378+
379+
it("still flags user-authored requestAnimationFrame inside nested composition scripts", () => {
380+
const html = `<!DOCTYPE html>
381+
<html><body>
382+
<div data-composition-id="root" data-width="1920" data-height="1080"></div>
383+
<script>
384+
(function(){
385+
var __compId = "intro";
386+
var __run = function() {
387+
function tick() {
388+
requestAnimationFrame(tick);
389+
}
390+
tick();
391+
};
392+
if (!__compId) { __run(); return; }
393+
/* __HF_COMPILER_MOUNT_START__ */
394+
var __selector = '[data-composition-id="intro"]';
395+
var __attempt = 0;
396+
var __tryRun = function() {
397+
if (document.querySelector(__selector)) { __run(); return; }
398+
if (++__attempt >= 8) { __run(); return; }
399+
requestAnimationFrame(__tryRun);
400+
};
401+
__tryRun();
402+
/* __HF_COMPILER_MOUNT_END__ */
403+
})();
404+
</script>
405+
</body></html>`;
406+
407+
const result = detectRenderModeHints(html);
408+
409+
expect(result.recommendScreenshot).toBe(true);
410+
expect(result.reasons.map((reason) => reason.code)).toEqual(["requestAnimationFrame"]);
411+
});
412+
413+
it("does not recommend screenshot mode for nested compositions that hoist GSAP from a CDN script", async () => {
414+
const projectDir = mkdtempSync(join(tmpdir(), "hf-render-mode-"));
415+
const compositionsDir = join(projectDir, "compositions");
416+
mkdirSync(compositionsDir, { recursive: true });
417+
418+
writeFileSync(
419+
join(projectDir, "index.html"),
420+
`<!DOCTYPE html>
421+
<html><body>
422+
<div data-composition-id="root" data-width="1920" data-height="1080">
423+
<div data-composition-id="intro" data-composition-src="compositions/intro.html" data-start="0"></div>
424+
</div>
425+
</body></html>`,
426+
);
427+
writeFileSync(
428+
join(compositionsDir, "intro.html"),
429+
`<template id="intro-template">
430+
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
431+
<div data-composition-id="intro" data-width="1920" data-height="1080">
432+
<div class="title">Hello</div>
433+
<script>
434+
window.__timelines = window.__timelines || {};
435+
window.__timelines["intro"] = gsap.timeline({ paused: true });
436+
</script>
437+
</div>
438+
</template>`,
439+
);
440+
441+
const originalFetch = globalThis.fetch;
442+
globalThis.fetch = mock(async () => {
443+
return new Response(
444+
"window.gsap = { timeline: function() { return { paused: true }; } }; function __ticker(){ requestAnimationFrame(__ticker); }",
445+
{ status: 200 },
446+
);
447+
}) as any;
448+
449+
try {
450+
const result = await compileForRender(projectDir, join(projectDir, "index.html"), projectDir);
451+
452+
expect(result.renderModeHints.recommendScreenshot).toBe(false);
453+
expect(result.renderModeHints.reasons).toEqual([]);
454+
} finally {
455+
globalThis.fetch = originalFetch;
456+
}
457+
});
346458
});

‎packages/producer/src/services/htmlCompiler.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,23 @@ function dedupeElementsById<T extends { id: string }>(elements: T[]): T[] {
7474
}
7575

7676
const INLINE_SCRIPT_PATTERN = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
77+
const COMPILER_MOUNT_BLOCK_START = "/* __HF_COMPILER_MOUNT_START__ */";
78+
const COMPILER_MOUNT_BLOCK_END = "/* __HF_COMPILER_MOUNT_END__ */";
7779

7880
function stripJsComments(source: string): string {
7981
return source.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
8082
}
8183

84+
function stripCompilerMountBootstrap(source: string): string {
85+
return source.replace(
86+
new RegExp(
87+
`${COMPILER_MOUNT_BLOCK_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${COMPILER_MOUNT_BLOCK_END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
88+
"g",
89+
),
90+
"",
91+
);
92+
}
93+
8294
export function detectRenderModeHints(html: string): RenderModeHints {
8395
const reasons: RenderModeHint[] = [];
8496
const { document } = parseHTML(html);
@@ -96,7 +108,7 @@ export function detectRenderModeHints(html: string): RenderModeHints {
96108
while ((scriptMatch = scriptPattern.exec(html)) !== null) {
97109
const attrs = scriptMatch[1] || "";
98110
if (/\bsrc\s*=/i.test(attrs)) continue;
99-
const content = stripJsComments(scriptMatch[2] || "");
111+
const content = stripJsComments(stripCompilerMountBootstrap(scriptMatch[2] || ""));
100112
if (!/requestAnimationFrame\s*\(/.test(content)) continue;
101113
reasons.push({
102114
code: "requestAnimationFrame",
@@ -664,6 +676,7 @@ function inlineSubCompositions(
664676
}
665677
};
666678
if (!__compId) { __run(); return; }
679+
${COMPILER_MOUNT_BLOCK_START}
667680
var __selector = '[data-composition-id="' + (__compId + '').replace(/"/g, '\\\\"') + '"]';
668681
var __attempt = 0;
669682
var __tryRun = function() {
@@ -672,6 +685,7 @@ function inlineSubCompositions(
672685
requestAnimationFrame(__tryRun);
673686
};
674687
__tryRun();
688+
${COMPILER_MOUNT_BLOCK_END}
675689
})()`);
676690
}
677691
scriptEl.remove();

0 commit comments

Comments
 (0)