Skip to content

Commit 70187a1

Browse files
perf(core): the preview mounts and draws only the scenes near the playhead (#6189)
* perf(core): skip rendering preview scenes far from the playhead * refactor(core): split the far-scene pass into small helpers * perf(core): a first render reveals only the clips it reaches * fix(core): reveal the clips holding first-rendered tweens, wherever their window is * feat(core): a scene may load a project helper and wait for fonts and still swap * perf(core): the preview mounts only the scenes near the playhead * perf(core): a seek waits only for the scene it lands in; neighbours mount one per turn * feat(studio): selecting a clip in an unmounted scene mounts that scene first * fix(core): a source a play and a seek both need is fetched and decoded once * fix(core): a scene mounting during play joins the mix without restarting what plays * fix(studio): selecting a clip waits on a scene mount only in a preview that unmounts scenes * fix(core): far scenes still mount after an edit, and an edit to a parked scene keeps its styles * perf(core): web audio schedules a clip only as the playhead comes near it * chore(studio): trim the scene hold helper's comments to its package's share * fix(core): a scene the preview unmounts is freed, not kept by audio, caches or old roots * fix(studio): an unmounted scene's rows and their state come from the markup it mounts with * perf(core): the preview mounts scenes ahead of play and keeps recent ones mounted * refactor(core): keep the far-scene neighbour rule private to its module * style(core): format the far-scene neighbour rule * perf(core): the preview unmounts scenes the playhead leaves, as kept ones slowed each mount * fix(core): scenes that measure text, call their own animate or wait on font loads can unmount * fix(core): each preview scene carries the helpers it loads, so it mounts on its own * fix(core): a mounted scene shows though its stand-in was hidden by display * fix(core): a helper scenes share runs once for the film, and a remounted scene keeps showing * fix(core): a scene that also publishes its timeline under another id stays mounted * feat(core): scenes that draw in 2D or chain the timeline they register can unmount * perf(core): a play frame that draws nothing new skips the hidden-clip lookup * fix(core): a GSAP file copied into a project counts as the library for scene unmounting * style(core): drop an unneeded escape in the registered-chain pattern * chore: core and producer size budgets make room for the preview scene window * fix(core): a scene that draws on a 2D canvas stays mounted * fix(core): a scene the preview unmounts lets go of timelines it built after a font wait * perf(core): a scene leaving the playhead keeps its last rendered size, no forced layout at the cut * refactor(core): the far-scene skip keeps last-render boxes in their own helper * fix(core): a mounting scene never records the runtime's root timeline as its own * chore(producer): raise the size budget to the measured size with the preview runtime inlined * docs(core): keep the far-scene and scene-memory comments within the comment limits * perf(core): style each hidden clip visible once ahead of its cut, so the cut frame does not * fix(core): a seek into a scene still mounting as a neighbour waits for that mount * chore(core): keep comment share and size budgets to main plus the measured core growth
1 parent c509182 commit 70187a1

26 files changed

Lines changed: 2242 additions & 165 deletions

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

Lines changed: 175 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3559,9 +3559,8 @@ describe("bundleToSingleHtml sceneParts", () => {
35593559
"its script uses addEventListener",
35603560
);
35613561
expect(host("b")?.hasAttribute("data-hf-scene-no-swap")).toBe(false);
3562-
expect(host("c")?.getAttribute("data-hf-scene-no-swap")).toBe(
3563-
"it runs a script that is not a known library",
3564-
);
3562+
// A project file is read and held to the rules of an inline script.
3563+
expect(host("c")?.getAttribute("data-hf-scene-no-swap")).toBe("its script uses .animate(");
35653564
// The root loading the same URL does not make a scene's own initializer a library.
35663565
expect(host("d")?.getAttribute("data-hf-scene-no-swap")).toBe(
35673566
"it runs a script that is not a known library",
@@ -3577,6 +3576,179 @@ describe("bundleToSingleHtml sceneParts", () => {
35773576
expect(parseHTML(rendered).document.querySelector("[data-hf-scene-no-swap]")).toBeNull();
35783577
});
35793578

3579+
it("lets a scene load a project helper and wait for fonts, and refuses anything else either leaves pending", async () => {
3580+
const scenes: Record<string, string> = {
3581+
helper: `<script src="../lib/helper.js"></script><script>window.__timelines.helper = window.build("helper");</script>`,
3582+
fontsThen: `<script>document.fonts.ready.then(() => window.fit("fontsThen"));</script>`,
3583+
fontsAwait: `<script>(async () => { await document.fonts.ready; window.fit("fontsAwait"); })();</script>`,
3584+
timerHelper: `<script src="../lib/ticker.js"></script>`,
3585+
missingHelper: `<script src="../lib/gone.js"></script>`,
3586+
fetchThen: `<script>fetch("data.json").then((r) => r.json());</script>`,
3587+
otherAwait: `<script>(async () => { await document.fonts.ready; await window.load(); })();</script>`,
3588+
promise: `<script>new Promise((done) => done()).then(() => {});</script>`,
3589+
};
3590+
const names = Object.keys(scenes);
3591+
const dir = makeTempProject({
3592+
"index.html": `<!doctype html><html><head></head><body>
3593+
<div data-composition-id="main" data-width="1920" data-height="1080" data-duration="2">
3594+
${names.map((n) => `<div data-composition-id="${n}" data-composition-src="compositions/${n}.html" data-start="0" data-duration="2"></div>`).join("\n")}
3595+
</div></body></html>`,
3596+
"lib/helper.js": `window.build = function (id) { var tl = gsap.timeline({ paused: true }); tl.to(document.querySelector('[data-composition-id="' + id + '"] p'), { x: 1 }); return tl; };`,
3597+
"lib/ticker.js": `setInterval(function () {}, 100);`,
3598+
...Object.fromEntries(
3599+
names.map((n) => [
3600+
`compositions/${n}.html`,
3601+
`<template id="${n}-template"><div data-composition-id="${n}"><p>${n}</p>${scenes[n]}</div></template>`,
3602+
]),
3603+
),
3604+
});
3605+
const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
3606+
const refusals = Object.fromEntries(
3607+
names.map((n) => [
3608+
n,
3609+
doc.querySelector(`div[data-hf-scene="${n}"]`)?.getAttribute("data-hf-scene-no-swap") ??
3610+
null,
3611+
]),
3612+
);
3613+
expect(refusals).toEqual({
3614+
helper: null,
3615+
fontsThen: null,
3616+
fontsAwait: null,
3617+
timerHelper: "its script uses setInterval",
3618+
missingHelper: "it runs a script that is not a known library",
3619+
fetchThen: "its script uses fetch",
3620+
otherAwait: "its script uses async",
3621+
promise: "its script uses Promise",
3622+
});
3623+
});
3624+
3625+
it("runs a helper scenes share once for the film, so a scene mounts without the one that loaded it first", async () => {
3626+
const dir = makeTempProject({
3627+
"index.html": `<!doctype html><html><head></head><body>
3628+
<div data-composition-id="main" data-width="1920" data-height="1080" data-duration="4">
3629+
<div data-composition-id="late" data-composition-src="compositions/late.html" data-start="2" data-duration="2"></div>
3630+
<div data-composition-id="early" data-composition-src="compositions/early.html" data-start="0" data-duration="2"></div>
3631+
</div></body></html>`,
3632+
"lib/kit.js": `window.Kit = { build: function (id) { return id; } };`,
3633+
"lib/own.js": `window.Own = 1;`,
3634+
"compositions/late.html": `<template id="late-template"><div data-composition-id="late"><p>late</p><script src="../lib/kit.js"></script><script src="../lib/own.js"></script><script>window.Kit.build("late");</script></div></template>`,
3635+
"compositions/early.html": `<template id="early-template"><div data-composition-id="early"><p>early</p><script src="../lib/kit.js"></script><script>window.Kit.build("early");</script></div></template>`,
3636+
});
3637+
const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
3638+
const texts = (selector: string) =>
3639+
[...doc.querySelectorAll(selector)].map((el) => el.textContent ?? "").join("\n");
3640+
const film = texts("script:not([data-hf-scene])");
3641+
expect(film.match(/window\.Kit =/g)).toHaveLength(1);
3642+
expect(texts('script[data-hf-scene="late"]')).toContain("window.Own = 1");
3643+
expect(texts("script[data-hf-scene]")).not.toContain("window.Kit =");
3644+
const rendered = parseHTML(await bundleToSingleHtml(dir)).document.documentElement.outerHTML;
3645+
expect(rendered.match(/window\.Kit =/g)).toHaveLength(1);
3646+
});
3647+
3648+
it("treats a GSAP file copied into the project as the library, at the root and in a scene, and no other file", async () => {
3649+
const gsapCopy = `/*!\n * GSAP 3.14.2\n * https://gsap.com\n */\nwindow.gsap = { all: "*" }; requestAnimationFrame(() => {});`;
3650+
const project = (file: string) =>
3651+
makeTempProject({
3652+
"index.html": `<!doctype html><html><head><script src="vendor/${file}"></script></head><body>
3653+
<div data-composition-id="main" data-width="1920" data-height="1080" data-duration="2">
3654+
<div data-composition-id="a" data-composition-src="compositions/a.html" data-start="0" data-duration="1"></div>
3655+
<div data-composition-id="b" data-composition-src="compositions/b.html" data-start="1" data-duration="1"></div>
3656+
</div></body></html>`,
3657+
[`vendor/${file}`]:
3658+
file === "gsap.min.js" ? gsapCopy : gsapCopy.replace("GSAP 3.14.2", "Helpers 1.0.0"),
3659+
"compositions/a.html": `<template id="a-template"><div data-composition-id="a"><p>A</p><script src="../vendor/${file}"></script></div></template>`,
3660+
"compositions/b.html": `<template id="b-template"><div data-composition-id="b"><p>B</p></div></template>`,
3661+
});
3662+
const marks = async (dir: string) => {
3663+
const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
3664+
return ["a", "b"].map(
3665+
(id) =>
3666+
doc.querySelector(`div[data-hf-scene="${id}"]`)?.getAttribute("data-hf-scene-no-swap") ??
3667+
null,
3668+
);
3669+
};
3670+
expect(await marks(project("gsap.min.js"))).toEqual([null, null]);
3671+
expect(await marks(project("helpers.js"))).toEqual([
3672+
"its script uses requestAnimationFrame",
3673+
"a script outside the scene selects *",
3674+
]);
3675+
});
3676+
3677+
it("lets a scene measure text on an unattached canvas, chain a timeline into the registry, call its own animate and wait on font loads, and nothing more", async () => {
3678+
const measure = `let ctx = null; window.measure = (s) => { if (!ctx) { ctx = document.createElement("canvas").getContext("2d"); } ctx.font = "800 46px Outfit"; return ctx.measureText(s).width; };`;
3679+
const scenes: Record<string, string> = {
3680+
measureCanvas: `<script>${measure}</script>`,
3681+
ownAnimate: `<script>const built = { animate(t) { return t; } }; window.step = (t) => built.animate(t);</script>`,
3682+
fontLoads: `<script>Promise.all([document.fonts.load("800 46px Outfit"), document.fonts.load('112px "Gochi Hand"')]).then(window.build, window.build);</script>`,
3683+
fontLoadThen: `<script>document.fonts.load("700 30px Outfit").then(() => window.fit("fontLoadThen"));</script>`,
3684+
fontLoadAwait: `<script>(async () => { await document.fonts.load("700 30px Outfit"); window.fit("fontLoadAwait"); })();</script>`,
3685+
namedCanvas: `<script>const c = document.createElement("canvas"); c.getContext("2d");</script>`,
3686+
canvasBack: `<script>const x = document.createElement("canvas").getContext("2d"); window.keep = x.canvas;</script>`,
3687+
drawOnStage: `<script>const g = document.querySelector("canvas").getContext('2d'); g.fillRect(0, 0, 4, 4);</script>`,
3688+
registeredChain: `<script>const clock = { t: 0 }; window.__timelines["registeredChain"] = gsap.timeline({ paused: true, onUpdate: () => draw(clock.t) }).to(clock, { t: 2, duration: 2, ease: "none" });</script>`,
3689+
registeredChainByKey: `<script>const clock = { t: 0 }; __timelines[doc.scene_id] = gsap.timeline({ paused: true }).to(clock, { t: 2 });</script>`,
3690+
unregisteredChain: `<script>gsap.timeline().to(window.__sharedState, { x: 1 });</script>`,
3691+
chainKeptAside: `<script>const tl = gsap.timeline({ paused: true }).to({ t: 0 }, { t: 1 }); window.__timelines["chainKeptAside"] = tl;</script>`,
3692+
registeredChainAndTween: `<script>window.__timelines["registeredChainAndTween"] = gsap.timeline().to({}, { x: 1 }); gsap.to(window.__shared, { x: 1 });</script>`,
3693+
webglCanvas: `<script>document.createElement("canvas").getContext("webgl");</script>`,
3694+
webgl2Canvas: `<script>document.querySelector("canvas").getContext("webgl2");</script>`,
3695+
experimentalWebgl: `<script>document.querySelector("canvas").getContext("experimental-webgl");</script>`,
3696+
webgpuCanvas: `<script>document.querySelector("canvas").getContext("webgpu");</script>`,
3697+
bitmapCanvas: `<script>document.querySelector("canvas").getContext("bitmaprenderer");</script>`,
3698+
dynamicContext: `<script>document.querySelector("canvas").getContext(window.kind);</script>`,
3699+
browserAnimate: `<script>document.querySelector("p").animate([{ opacity: 0 }], { duration: 1000 });</script>`,
3700+
spreadAnimate: `<script>document.querySelector("p").animate(...window.frames);</script>`,
3701+
otherPromise: `<script>Promise.all([fetch("a.json")]).then(() => {});</script>`,
3702+
dynamicFontLoad: `<script>document.fonts.load(window.face).then(() => {});</script>`,
3703+
};
3704+
const names = Object.keys(scenes);
3705+
const dir = makeTempProject({
3706+
"index.html": `<!doctype html><html><head></head><body>
3707+
<div data-composition-id="main" data-width="1920" data-height="1080" data-duration="2">
3708+
${names.map((n) => `<div data-composition-id="${n}" data-composition-src="compositions/${n}.html" data-start="0" data-duration="2"></div>`).join("\n")}
3709+
</div></body></html>`,
3710+
...Object.fromEntries(
3711+
names.map((n) => [
3712+
`compositions/${n}.html`,
3713+
`<template id="${n}-template"><div data-composition-id="${n}"><p>${n}</p><canvas></canvas>${scenes[n]}</div></template>`,
3714+
]),
3715+
),
3716+
});
3717+
const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
3718+
const refusals = Object.fromEntries(
3719+
names.map((n) => [
3720+
n,
3721+
doc.querySelector(`div[data-hf-scene="${n}"]`)?.getAttribute("data-hf-scene-no-swap") ??
3722+
null,
3723+
]),
3724+
);
3725+
expect(refusals).toEqual({
3726+
measureCanvas: null,
3727+
ownAnimate: null,
3728+
fontLoads: null,
3729+
fontLoadThen: null,
3730+
fontLoadAwait: null,
3731+
namedCanvas: "its script uses getContext",
3732+
canvasBack: "its script uses getContext",
3733+
drawOnStage: "its script uses getContext",
3734+
registeredChain: null,
3735+
registeredChainByKey: null,
3736+
unregisteredChain: "its script uses gsap.timeline().to(",
3737+
chainKeptAside: "its script uses gsap.timeline({ paused: true }).to(",
3738+
registeredChainAndTween: "its script uses gsap.to(",
3739+
webglCanvas: "its script uses getContext",
3740+
webgl2Canvas: "its script uses getContext",
3741+
experimentalWebgl: "its script uses getContext",
3742+
webgpuCanvas: "its script uses getContext",
3743+
bitmapCanvas: "its script uses getContext",
3744+
dynamicContext: "its script uses getContext",
3745+
browserAnimate: "its script uses .animate(",
3746+
spreadAnimate: "its script uses .animate(",
3747+
otherPromise: "its script uses Promise",
3748+
dynamicFontLoad: "its script uses .then(",
3749+
});
3750+
});
3751+
35803752
const rootProject = (root: string, extra: Record<string, string> = {}) =>
35813753
makeTempProject({
35823754
"index.html": `<!doctype html><html><head></head><body>

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ import { readDeclaredDefaults } from "../runtime/getVariables";
6565
import {
6666
ensureExternalLinkTag,
6767
inlineSubCompositions,
68+
isLibraryCopy,
6869
refuseSwapsReachedByRootScripts,
6970
} from "./inlineSubCompositions";
7071
import { isSafePath, resolveWithinProject } from "../safePath.js";
@@ -1179,7 +1180,8 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
11791180
].map((el) => {
11801181
const src = el.getAttribute("src");
11811182
const path = src && isRelativeUrl(src) ? resolveEntryUrl(src) : null;
1182-
return src ? (path && safeReadFile(path)) || "" : el.textContent || "";
1183+
const text = src ? (path && safeReadFile(path)) || "" : el.textContent || "";
1184+
return isLibraryCopy(text) ? "" : text;
11831185
})
11841186
: [];
11851187

@@ -1218,6 +1220,10 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
12181220
},
12191221
flattenInnerRoot: prepareFlattenedInnerRoot,
12201222
tagScenes: options?.sceneParts === true,
1223+
readProjectScript: (path: string) => {
1224+
const resolved = isRelativeUrl(path) ? resolveEntryUrl(path) : null;
1225+
return resolved ? safeReadFile(resolved) : null;
1226+
},
12211227
readVariableDefaults: readDeclaredDefaults,
12221228
parseHostVariables: parseHostVariableValues,
12231229
buildScopeSelector: (compId: string) => cssAttributeSelector("data-composition-id", compId),
@@ -1241,6 +1247,10 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
12411247
...subCompResult.variablesByComp,
12421248
};
12431249
const seenCompScriptSrcs = new Set<string>();
1250+
const scenesBySrc = new Map<string, Set<string | undefined>>();
1251+
for (const item of subCompResult.scriptItems)
1252+
if (item.kind !== "inline")
1253+
scenesBySrc.set(item.src, (scenesBySrc.get(item.src) ?? new Set()).add(item.scene));
12441254
for (const scriptItem of subCompResult.scriptItems) {
12451255
if (scriptItem.kind === "inline") {
12461256
pushRun(scriptRuns, scriptItem.scene, scriptItem.content);
@@ -1254,13 +1264,15 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
12541264
}
12551265
if (seenCompScriptSrcs.has(extSrc)) continue;
12561266
seenCompScriptSrcs.add(extSrc);
1267+
// Run once for the film when scenes share it: a scene mounts without the one that loaded it first.
1268+
const scene = (scenesBySrc.get(extSrc)?.size ?? 0) > 1 ? undefined : scriptItem.scene;
12571269
if (isRelativeUrl(extSrc) && scriptItem.type !== "module") {
12581270
const jsPath = resolveEntryUrl(extSrc);
12591271
const js = jsPath ? safeReadFile(jsPath) : null;
12601272
if (js != null) {
12611273
const chunk = () =>
12621274
preserveLocalScriptIntegrity(document, extSrc, resolveEntryUrl) ? "" : js;
1263-
pushRun(scriptRuns, scriptItem.scene, chunk);
1275+
pushRun(scriptRuns, scene, chunk);
12641276
continue;
12651277
}
12661278
}

0 commit comments

Comments
 (0)