Skip to content

Commit 0408fbc

Browse files
perf(studio): scrubbing a large composition no longer stalls the editor (#3842)
* perf(studio): ask each ancestor once per off-canvas rebuild, not once per element The dashed off-canvas markers are rebuilt whenever anything in the preview changes, which during playback or a scrub is several times a second. Most of what a rebuild asked about an element was really a question about its ANCESTORS: does each node up to the root render, what does each contribute to the composed transform, which node is the source-file boundary. Two siblings share their whole chain, so a preview of a thousand elements asked the platform the same questions about the same ancestors a thousand times over. A rebuild now threads one measure pass through the walk, and each node answers once. On a 1689-element carousel that takes computed-style reads from 11,159 to 2,526 per rebuild and the rebuild itself from 59 to 12-18 ms per seek, with the rendered marker set byte-identical. The pass is deliberately not a cache. A cache would have to say what could have changed since last time, and for a measurement the answer is anything: an image finishing decode, a font swapping in, a transition frame, a container query, an inserted stylesheet rule all move an element's box with nothing written to the DOM and no record to invalidate on. A pass lives inside one synchronous measurement that only reads, so nothing can move under it, and it is dropped when the measurement ends. Every rebuild still measures every element. Layout reads are untouched on purpose: each element still takes its own client rect every rebuild, because that is the read that cannot be shared and must not be remembered. * test(studio): give one PropertyPanel case the file's own render timeout Every other render test in that file passes RENDER_TIMEOUT_MS; this it.each was left on vitest's 5s default and times out when the whole suite runs on a loaded machine. Unrelated to any behaviour: it passes on either side of the change when the machine is quiet, and fails in a full-suite run on either side when it is not. * refactor(studio): share the source-boundary walk and dedupe the rebuild fixtures Three follow-ups from review of the measure pass, none of them behaviour: The source boundary was memoized against the element that asked for it, so two siblings still walked their whole chain separately and only the answer was reused. It now memoizes every node on the way up, like the other two walks: an element's boundary IS its parent's unless the element is one itself. `isElementVisibleThroughAncestors` returns what it always returned, but it now resolves top-down, so the set of nodes it takes a style read for is different (smaller for a subtree hidden near the root). Three callers use it with no memo, so that is written down next to it rather than left to be discovered. The three rebuild fixtures in the indicator tests each carried their own copy of the iframe/overlay/layout-stub scaffolding, which is four clone groups and 126 duplicated lines. One `mountPreview` helper now serves all of them and the pre-existing selector-index fixture too. * test(studio): pin the measure pass to one rebuild through an ancestor-derived input The existing no-mutation-record test varies an element's own box, and the pass never memoizes a box — so hoisting the pass to module scope, which is exactly the mistake that would reintroduce cross-rebuild staleness, left every test green. This one fades a wrapper between two rebuilds and asserts the marker under it goes away. Visibility through ancestors IS memoized, so the pass surviving the rebuild serves the stale answer: with `createOverlayMeasurePass()` hoisted the suite exits 1 on this test alone, and exits 0 at head.
1 parent cd1a996 commit 0408fbc

8 files changed

Lines changed: 518 additions & 110 deletions

‎packages/studio/src/components/editor/PropertyPanel.test.tsx‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1001,20 +1001,24 @@ describe("PropertyPanel — Motion is for things that move", () => {
10011001
return element;
10021002
},
10031003
],
1004-
])("recognizes %s through the shared audio predicate", async (_label, makeElement) => {
1005-
const fixture = {
1006-
...audioClipElement(),
1007-
element: makeElement(),
1008-
tagName: "div",
1009-
};
1010-
const { host, root } = await renderPanel(true, fixture);
1011-
const titles = Array.from(
1012-
host.querySelectorAll<HTMLElement>("[data-flat-group-collapsed], [data-flat-group-open]"),
1013-
).map((node) => node.textContent ?? "");
1014-
expect(titles.some((title) => title.includes("Motion"))).toBe(false);
1015-
expect(titles.some((title) => title.includes("Timing"))).toBe(true);
1016-
act(() => root.unmount());
1017-
});
1004+
])(
1005+
"recognizes %s through the shared audio predicate",
1006+
async (_label, makeElement) => {
1007+
const fixture = {
1008+
...audioClipElement(),
1009+
element: makeElement(),
1010+
tagName: "div",
1011+
};
1012+
const { host, root } = await renderPanel(true, fixture);
1013+
const titles = Array.from(
1014+
host.querySelectorAll<HTMLElement>("[data-flat-group-collapsed], [data-flat-group-open]"),
1015+
).map((node) => node.textContent ?? "");
1016+
expect(titles.some((title) => title.includes("Motion"))).toBe(false);
1017+
expect(titles.some((title) => title.includes("Timing"))).toBe(true);
1018+
act(() => root.unmount());
1019+
},
1020+
RENDER_TIMEOUT_MS,
1021+
);
10181022

10191023
it(
10201024
"calls the section Timing on an audio clip, and offers no tween editor",

‎packages/studio/src/components/editor/domEditOverlayGeometry.ts‎

Lines changed: 52 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
import { isElementVisibleThroughAncestors } from "./domEditingDom";
88
import { hugRectForElement } from "./domEditOverlayCrop";
99
import { composeElementTransform, type PlanarTransformOps } from "./domEditOverlayTransform";
10+
import { type OverlayMeasurePass, readThroughPass } from "./domEditOverlayMeasurePass";
1011

1112
export interface OverlayRect {
1213
left: number;
@@ -52,18 +53,28 @@ export function isElementVisibleForOverlay(el: HTMLElement): boolean {
5253
// shapes (rectangular cards, text, full-bleed media) don't have interior holes, so this
5354
// doesn't bite. If ring/cutout shapes become editable targets, sample more densely or
5455
// hit-test against the element's actual painted geometry instead of its bounding box.
55-
function findSourceBoundary(element: HTMLElement): HTMLElement | null {
56-
let current: HTMLElement | null = element;
57-
while (current) {
58-
if (
59-
current.hasAttribute("data-composition-file") ||
60-
current.hasAttribute("data-composition-src")
61-
) {
62-
return current;
56+
const isSourceBoundary = (node: HTMLElement): boolean =>
57+
node.hasAttribute("data-composition-file") || node.hasAttribute("data-composition-src");
58+
59+
/** With a `pass`, every node on the way up is memoized rather than only the
60+
* element asked about: an element's boundary IS its parent's unless it is one
61+
* itself, so siblings share the walk instead of each repeating it. */
62+
function findSourceBoundary(element: HTMLElement, pass?: OverlayMeasurePass): HTMLElement | null {
63+
const pending: HTMLElement[] = [];
64+
let boundary: HTMLElement | null | undefined;
65+
for (let node: HTMLElement | null = element; node; node = node.parentElement) {
66+
boundary = pass?.sourceBoundary.get(node);
67+
if (boundary !== undefined) break;
68+
if (isSourceBoundary(node)) {
69+
boundary = node;
70+
pass?.sourceBoundary.set(node, node);
71+
break;
6372
}
64-
current = current.parentElement;
73+
pending.push(node);
6574
}
66-
return null;
75+
const answer = boundary ?? null;
76+
if (pass) for (const node of pending) pass.sourceBoundary.set(node, answer);
77+
return answer;
6778
}
6879

6980
export function resolveDomEditCoordinateScale(input: {
@@ -157,6 +168,7 @@ interface ElementTransformSnapshot {
157168
function readElementTransformSnapshot(
158169
win: Window,
159170
element: HTMLElement,
171+
pass?: OverlayMeasurePass,
160172
): ElementTransformSnapshot | null {
161173
const DOMMatrixCtor = (win as Window & typeof globalThis).DOMMatrix;
162174
if (!DOMMatrixCtor) return null;
@@ -170,8 +182,11 @@ function readElementTransformSnapshot(
170182
compose: (outer, inner) => outer.multiply(inner),
171183
};
172184
try {
173-
const matrix = composeElementTransform(element, ops, (node) =>
174-
node === element ? cs : win.getComputedStyle(node),
185+
const matrix = composeElementTransform(
186+
element,
187+
ops,
188+
(node) => (node === element ? cs : win.getComputedStyle(node)),
189+
pass?.transform,
175190
);
176191
return matrix ? { matrix, cs } : null;
177192
} catch {
@@ -211,15 +226,23 @@ function toOverlayRect(
211226
iframe: HTMLIFrameElement,
212227
element: HTMLElement,
213228
precomputedScale?: OverlayRootScale | null,
229+
pass?: OverlayMeasurePass,
214230
): OverlayRect | null {
215231
const scale =
216232
precomputedScale ?? computeOverlayRootScale(overlayEl, iframe, iframe.contentDocument);
217233
if (!scale) return null;
218234
const { iframeRect, overlayRect, rootScaleX, rootScaleY } = scale;
219235

220236
const elementRect = element.getBoundingClientRect();
221-
const sourceBoundary = findSourceBoundary(element);
222-
const sourceBoundaryRect = sourceBoundary?.getBoundingClientRect();
237+
const sourceBoundary = findSourceBoundary(element, pass);
238+
// Every element inside one sub-composition shares this boundary, so its rect
239+
// is one layout read per boundary rather than one per element.
240+
const sourceBoundaryRect =
241+
sourceBoundary && pass
242+
? readThroughPass(pass.sourceBoundaryRect, sourceBoundary, () =>
243+
sourceBoundary.getBoundingClientRect(),
244+
)
245+
: sourceBoundary?.getBoundingClientRect();
223246
const editScale = resolveDomEditCoordinateScale({
224247
rootScaleX,
225248
rootScaleY,
@@ -363,15 +386,16 @@ export function orientedOverlayRect(
363386
iframe: HTMLIFrameElement,
364387
element: HTMLElement,
365388
precomputedScale?: OverlayRootScale | null,
389+
pass?: OverlayMeasurePass,
366390
): OverlayRect | null {
367391
const scale =
368392
precomputedScale ?? computeOverlayRootScale(overlayEl, iframe, iframe.contentDocument);
369393
if (!scale) return null;
370-
const base = toOverlayRect(overlayEl, iframe, element, scale);
394+
const base = toOverlayRect(overlayEl, iframe, element, scale, pass);
371395
if (!base) return null;
372396

373397
const win = iframe.contentWindow;
374-
const transform = win ? readElementTransformSnapshot(win, element) : null;
398+
const transform = win ? readElementTransformSnapshot(win, element, pass) : null;
375399
const angle = transform ? rotationDegreesFromMatrix(transform.matrix) : 0;
376400
if (Math.abs(angle) < ROTATION_GATE_EPSILON_DEG) return base;
377401

@@ -482,16 +506,23 @@ export function groupAwareOverlayRect(
482506
iframe: HTMLIFrameElement,
483507
el: HTMLElement,
484508
precomputedScale?: OverlayRootScale | null,
509+
pass?: OverlayMeasurePass,
485510
): OverlayRect | null {
486-
const rect = toOverlayRect(overlayEl, iframe, el, precomputedScale);
511+
const rect = toOverlayRect(overlayEl, iframe, el, precomputedScale, pass);
487512
if (!rect || !el.hasAttribute("data-hf-group")) return rect;
488513
// Union the MEMBERS' rendered rects — where the content actually is — not the
489514
// wrapper's own box. The wrapper is invisible and its box can sit apart from the
490515
// members once they've been moved/transformed, which would otherwise drag the
491516
// group's bounds (and its off-canvas marker) off to a stale position.
492517
const rects: OverlayRect[] = [];
493518
for (const child of Array.from(el.children)) {
494-
const childRect = toOverlayRect(overlayEl, iframe, child as HTMLElement, precomputedScale);
519+
const childRect = toOverlayRect(
520+
overlayEl,
521+
iframe,
522+
child as HTMLElement,
523+
precomputedScale,
524+
pass,
525+
);
495526
if (childRect) rects.push(childRect);
496527
}
497528
const union = rects.length > 0 ? resolveDomEditGroupOverlayRect(rects) : null;
@@ -519,10 +550,11 @@ export function orientedGroupAwareOverlayRect(
519550
iframe: HTMLIFrameElement,
520551
el: HTMLElement,
521552
precomputedScale?: OverlayRootScale | null,
553+
pass?: OverlayMeasurePass,
522554
): OverlayRect | null {
523555
return el.hasAttribute("data-hf-group")
524-
? groupAwareOverlayRect(overlayEl, iframe, el, precomputedScale)
525-
: orientedOverlayRect(overlayEl, iframe, el, precomputedScale);
556+
? groupAwareOverlayRect(overlayEl, iframe, el, precomputedScale, pass)
557+
: orientedOverlayRect(overlayEl, iframe, el, precomputedScale, pass);
526558
}
527559

528560
export function filterNestedDomEditGroupItems<T extends { element: HTMLElement }>(items: T[]): T[] {
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* Shared memory for ONE synchronous pass that measures many elements.
3+
*
4+
* The off-canvas indicator overlay re-measures every element in the preview
5+
* several times a second, and almost all of that work is per-ANCESTOR, not
6+
* per-element: a visibility read for every node up to the root, a transform
7+
* composed over the same nodes, and a walk for the source-file boundary. Two
8+
* siblings share their entire chain above themselves, so a preview of a
9+
* thousand elements asked the platform the same questions about the same
10+
* ancestors a thousand times.
11+
*
12+
* WHY THIS IS A PASS AND NOT A CACHE. A cache has to answer "what could have
13+
* changed since last time", and for a MEASUREMENT the honest answer is
14+
* "anything": an `<img>` finishing decode, a web font swapping in, a CSS
15+
* transition frame, a container query, a `CSSStyleSheet.insertRule` — each one
16+
* moves an element's box with nothing written to the DOM, so no mutation
17+
* record exists to invalidate on and no observer reports all of them. A pass
18+
* sidesteps the question instead of answering it wrong: it lives inside one
19+
* synchronous measurement that only READS, so nothing can move under it, and
20+
* it is dropped when the pass ends. Every rebuild still measures every
21+
* element, exactly as it did before; it just stops asking the same question
22+
* about the same ancestor once per descendant.
23+
*
24+
* Never store one of these across a rebuild, an await, or a frame.
25+
*/
26+
27+
/** The composed transform type the overlay's corner math uses. */
28+
type OverlayTransform = DOMMatrix;
29+
30+
export interface OverlayMeasurePass {
31+
/** Does this node render, given everything above it? */
32+
visible: Map<HTMLElement, boolean>;
33+
/** This node's transform composed with every ancestor's, up to the
34+
* composition root. `null` is an answer: some node's transform is
35+
* unusable. */
36+
transform: Map<HTMLElement, OverlayTransform | null>;
37+
/** The nearest ancestor carrying a source-file boundary, or null. */
38+
sourceBoundary: Map<HTMLElement, HTMLElement | null>;
39+
/** That boundary's client rect, which is shared by everything inside it. */
40+
sourceBoundaryRect: Map<HTMLElement, DOMRect>;
41+
}
42+
43+
export function createOverlayMeasurePass(): OverlayMeasurePass {
44+
return {
45+
visible: new Map(),
46+
transform: new Map(),
47+
sourceBoundary: new Map(),
48+
sourceBoundaryRect: new Map(),
49+
};
50+
}
51+
52+
/** Read through a pass's map, filling it on the way. `undefined` is the only
53+
* miss, so a memoized `null` stays an answer. */
54+
export function readThroughPass<K, V>(memo: Map<K, V>, key: K, compute: () => V): V {
55+
const answered = memo.get(key);
56+
if (answered !== undefined) return answered;
57+
const value = compute();
58+
memo.set(key, value);
59+
return value;
60+
}

‎packages/studio/src/components/editor/domEditOverlayTransform.ts‎

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,22 @@ export function individualRotateDegrees(value: string | undefined): number {
5858
return Number.isFinite(deg) ? deg : 0;
5959
}
6060

61+
/** One node's own contribution, with the individual properties applied before
62+
* `transform` the way CSS does. Null when the node's transform is unusable. */
63+
function ownNodeTransform<M>(
64+
node: HTMLElement,
65+
ops: PlanarTransformOps<M>,
66+
getStyle: (node: HTMLElement) => CSSStyleDeclaration | null,
67+
): M | null {
68+
const style = getStyle(node);
69+
if (!style) return null;
70+
const transform = style.transform;
71+
const own = transform && transform !== "none" ? ops.fromTransform(transform) : ops.identity();
72+
if (!own) return null;
73+
const spin = individualRotateDegrees(style.rotate);
74+
return spin === 0 ? own : ops.compose(ops.fromRotate(spin), own);
75+
}
76+
6177
/**
6278
* The element's transform composed with every ancestor's, up to the composition
6379
* root.
@@ -66,23 +82,45 @@ export function individualRotateDegrees(value: string | undefined): number {
6682
* `rotate` composes on the left of it. Between nodes, an ancestor applies
6783
* outside its child. Null means some node's transform was unusable and the
6884
* caller should fall back rather than guess.
85+
*
86+
* `memo` holds each node's COMPOSED chain, for a caller walking many elements
87+
* in one synchronous pass.
88+
*
89+
* A chain is `chain(parent)` composed with the node's own, so siblings share
90+
* everything above them and the whole tree costs one style read and one
91+
* compose per node instead of one per node PER DESCENDANT. Valid only for the
92+
* length of one pass, which is why the caller owns it: nothing here writes to
93+
* the DOM, so nothing can move under it, and it is dropped before anything
94+
* else runs. Omitted, every call composes its own chain from scratch.
6995
*/
7096
export function composeElementTransform<M>(
7197
element: HTMLElement,
7298
ops: PlanarTransformOps<M>,
7399
getStyle: (node: HTMLElement) => CSSStyleDeclaration | null,
100+
memo?: Map<HTMLElement, M | null>,
74101
): M | null {
75-
let acc = ops.identity();
102+
const pending: HTMLElement[] = [];
103+
// `undefined` means nothing on the way up was already composed, so the chain
104+
// starts from identity. A memoized `null` is an answer, not a miss: some node
105+
// above carries a transform this algebra cannot represent.
106+
let above: M | null | undefined;
76107
for (let node: HTMLElement | null = element; node; node = node.parentElement) {
77-
const style = getStyle(node);
78-
if (!style) return null;
79-
const transform = style.transform;
80-
let own = transform && transform !== "none" ? ops.fromTransform(transform) : ops.identity();
81-
if (!own) return null;
82-
const spin = individualRotateDegrees(style.rotate);
83-
if (spin !== 0) own = ops.compose(ops.fromRotate(spin), own);
84-
acc = ops.compose(own, acc);
108+
above = memo?.get(node);
109+
if (above !== undefined) break;
110+
pending.push(node);
85111
if (node.hasAttribute(COMPOSITION_ROOT_ATTR)) break;
86112
}
113+
114+
let acc: M | null = above === undefined ? ops.identity() : above;
115+
for (let i = pending.length - 1; i >= 0; i -= 1) {
116+
const node = pending[i]!;
117+
if (acc !== null) {
118+
const own = ownNodeTransform(node, ops, getStyle);
119+
// The ancestors' chain is the OUTER of the pair, as an ancestor applies
120+
// around its child.
121+
acc = own === null ? null : ops.compose(acc, own);
122+
}
123+
memo?.set(node, acc);
124+
}
87125
return acc;
88126
}

0 commit comments

Comments
 (0)