Files
hyperframes/packages/core/src/runtime/farScenes.ts
T
Miguel Ángel 70187a13b5 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
2026-10-25 19:39:14 +00:00

120 lines
4.6 KiB
TypeScript

import { SCENE_PART_ATTR } from "../sceneParts";
import { STUDIO_PREVIEW_FAR_SCENE_ATTR as FAR } from "../studioPreviewMark";
type Span = { start: number; end: number } | null;
const HOSTS = `[${SCENE_PART_ATTR}]:not(style, script)`;
const OUT_OF_FLOW = new Set(["absolute", "fixed"]);
type Timed = { host: HTMLElement; span: { start: number; end: number } };
/** Whether each span, sorted by start, is the playing one or a neighbour; in a gap, the one before it plays. */
function nearPlayhead(spans: Array<{ start: number; end: number }>, time: number): boolean[] {
const playing = spans.flatMap((span, i) => (span.start <= time && time <= span.end ? [i] : []));
const before = spans.filter((span) => span.start <= time).length - 1;
const lo = playing.length > 0 ? playing[0]! : before;
const hi = playing.length > 0 ? playing[playing.length - 1]! : before;
return spans.map((_, i) => i >= lo - 1 && i <= hi + 1);
}
function farFrom(timed: Timed[], time: number): Set<HTMLElement> {
const near = nearPlayhead(
timed.map((s) => s.span),
time,
);
return new Set(timed.filter((_, i) => !near[i]).map((s) => s.host));
}
type Box = { size: string; outOfFlow: boolean };
const boxOf = (host: Element, size: string): Box => ({
size,
outOfFlow: OUT_OF_FLOW.has(getComputedStyle(host).position),
});
/**
* Each host's box and position as of its last render, so a cut reads them without forcing style and layout.
* A host not reported yet is read directly.
*/
function createLastRender() {
const rendered = new WeakMap<Element, Box>();
const observer =
typeof ResizeObserver === "function"
? new ResizeObserver((entries) => {
for (const { target, borderBoxSize } of entries) {
const box = borderBoxSize?.[0];
if (box)
rendered.set(
target,
boxOf(target, `${Math.round(box.inlineSize)}px ${Math.round(box.blockSize)}px`),
);
}
})
: null;
let watched: HTMLElement[] = [];
return {
watch(hosts: HTMLElement[]) {
// An observed element stays alive with its observer, so a host that left the page is let go.
for (const host of watched) if (!host.isConnected) observer?.unobserve(host);
for (const host of hosts) observer?.observe(host);
watched = hosts;
},
of: (host: HTMLElement): Box =>
rendered.get(host) ?? boxOf(host, `${host.offsetWidth}px ${host.offsetHeight}px`),
};
}
/**
* Preview scenes beyond the playing scene's neighbours stay mounted but skip style, layout and paint,
* keeping their last rendered size. Only preview bundles tag scene hosts, so renders never skip.
*/
export function createFarSceneSkip(spanOf: (host: Element) => Span): (time: number) => void {
let hosts: HTMLElement[] | null = null;
let sheet: HTMLStyleElement | null = null;
const sizes = new Map<string, string>();
const lastRender = createLastRender();
const timedHosts = (list: HTMLElement[]): Timed[] =>
list
.map((host) => ({ host, span: spanOf(host) }))
.filter((s): s is Timed => Number.isFinite(s.span?.start))
.sort((a, b) => a.span.start - b.span.start);
// Measured before any is marked, so one layout serves them all; true when a size changed.
const measureLeaving = (far: Set<HTMLElement>): boolean => {
let resized = false;
for (const host of far) {
if (host.hasAttribute(FAR)) continue;
const { size, outOfFlow } = lastRender.of(host);
// Containment makes a host a containing block and margin boundary; only an out-of-flow one already is.
if (!outOfFlow) {
far.delete(host);
continue;
}
const name = host.getAttribute(SCENE_PART_ATTR)!;
resized ||= sizes.get(name) !== size;
sizes.set(name, size);
}
return resized;
};
const writeSheet = () => {
sheet ??= document.createElement("style");
sheet.textContent = [
`[${FAR}] { content-visibility: hidden; }`,
...Array.from(
sizes,
([name, size]) =>
`[${SCENE_PART_ATTR}="${CSS.escape(name)}"][${FAR}] { contain-intrinsic-size: ${size}; }`,
),
].join("\n");
if (!sheet.isConnected) document.head.appendChild(sheet);
};
return (time) => {
if (!hosts || hosts.some((host) => !host.isConnected))
lastRender.watch((hosts = Array.from(document.querySelectorAll<HTMLElement>(HOSTS))));
if (hosts.length === 0) return;
const far = farFrom(timedHosts(hosts), time);
if (measureLeaving(far) || !sheet?.isConnected) writeSheet();
for (const host of hosts)
if (far.has(host) !== host.hasAttribute(FAR)) host.toggleAttribute(FAR);
};
}