Skip to content

Commit 9549e03

Browse files
perf(studio): a paused editor stops redrawing its overlays sixty times a second (#3846)
* perf(studio): run the editor overlays on one parkable frame loop The composition rect, the selection and hover boxes, the off-canvas indicators and the snap guides each owned an animation-frame loop that re-armed unconditionally. On a paused, untouched editor that is four callbacks per frame reading layout, and the snap-guide loop writes style on every one of them, so the compositor kept committing 55 frames a second with nothing moving. None of the four has a clock of its own; each only changes when something observable happens. They now share one loop that runs at full rate for a moment after a pointer, key, wheel, scroll, resize or visibility change, after a preview message reporting a frame the overlays have not drawn, or after a mutation inside the preview document, and otherwise polls four times a second so a wake source nobody thought of costs a quarter second of staleness rather than a frozen overlay. The frame comparison on preview messages is load-bearing rather than an optimisation: the paused preview posts an unchanged status message every 80 ms so any listener can confirm its position, and treating that as news held the overlays at 60 fps for the life of the tab. * fix(studio): one overlay's throw must not stop the other four The shared frame loop re-armed after running its subscribers, so a subscriber that threw took down the loop and its idle-poll safety net permanently. The four loops it replaced each re-armed first, which kept that failure to the one overlay that caused it. It now re-arms before running anything and isolates each subscriber, rethrowing out of band so the error still reaches the page's error reporting. The wake also sat outside the recognised-message check, so postMessage traffic from an extension, devtools or any other embed on the page held the overlays awake for 400ms at a time. Only the preview's own messages wake it now, and a repeated paused status post still does not. useMotionPathData had the same unconditional loop and is live whenever a keyframed element is selected; it joins the shared one. * fix(studio): wake the overlays only for the preview
1 parent eae4892 commit 9549e03

7 files changed

Lines changed: 466 additions & 23 deletions

File tree

‎packages/studio/src/components/editor/SnapGuideOverlay.tsx‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { memo, useRef, type RefObject } from "react";
22
import { useMountEffect } from "../../hooks/useMountEffect";
33
import { resolveGuideLineRect, type SnapGuide, type SpacingGuide } from "./snapEngine";
4+
import { subscribeOverlayFrame } from "./overlayFrameLoop";
45

56
export interface SnapGuidesState {
67
guides: SnapGuide[];
@@ -47,12 +48,8 @@ export const SnapGuideOverlay = memo(function SnapGuideOverlay({
4748
};
4849

4950
useMountEffect(() => {
50-
let frame = 0;
51-
5251
// fallow-ignore-next-line complexity
5352
const update = () => {
54-
frame = requestAnimationFrame(update);
55-
5653
const state = snapGuidesRef.current;
5754
const guides = state?.guides ?? [];
5855
const spacingGuides = state?.spacingGuides ?? [];
@@ -116,8 +113,7 @@ export const SnapGuideOverlay = memo(function SnapGuideOverlay({
116113
}
117114
};
118115

119-
frame = requestAnimationFrame(update);
120-
return () => cancelAnimationFrame(frame);
116+
return subscribeOverlayFrame(update);
121117
});
122118

123119
return (

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

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
drainPendingLayerMutations,
88
} from "./domEditLayerWalkCache";
99
import { recomputeOffCanvasIndicators } from "./offCanvasIndicatorGeometry";
10+
import { requestOverlayFrames, subscribeOverlayFrame } from "./overlayFrameLoop";
1011

1112
interface OffCanvasIndicatorRefreshOptions {
1213
iframeRef: React.RefObject<HTMLIFrameElement | null>;
@@ -78,12 +79,16 @@ export function rebuildDue(dirty: boolean, lastAt: number, now: number): boolean
7879
export function startOffCanvasIndicatorRefresh(
7980
options: OffCanvasIndicatorRefreshOptions,
8081
): () => void {
81-
let frame = 0;
8282
let lastCompSig = "";
8383
let lastRecomputeAt = Number.NEGATIVE_INFINITY;
8484
const walkCache = createDomEditLayerWalkCache();
8585
const markDirty = () => {
8686
options.dirtyRef.current = true;
87+
// A rebuild is owed, so the shared loop has to be running to pay it. The
88+
// preview's own MutationObserver is the wake source the top frame's
89+
// pointer and message listeners cannot be: an edit inside the iframe
90+
// reaches this callback and nothing else.
91+
requestOverlayFrames();
8792
};
8893
const attachObserver = (doc: Document | null) => {
8994
options.observerRef.current?.disconnect();
@@ -97,7 +102,6 @@ export function startOffCanvasIndicatorRefresh(
97102
options.sigRef.current = "";
98103
};
99104
const update = () => {
100-
frame = requestAnimationFrame(update);
101105
const iframe = options.iframeRef.current;
102106
const overlayEl = options.overlayRef.current;
103107
const doc = iframe?.contentDocument ?? null;
@@ -133,9 +137,9 @@ export function startOffCanvasIndicatorRefresh(
133137
walkCache,
134138
);
135139
};
136-
frame = requestAnimationFrame(update);
140+
const unsubscribe = subscribeOverlayFrame(update);
137141
return () => {
138-
cancelAnimationFrame(frame);
142+
unsubscribe();
139143
options.observerRef.current?.disconnect();
140144
options.observerRef.current = null;
141145
options.observedDocRef.current = null;
Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
// @vitest-environment happy-dom
2+
3+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
import {
5+
IDLE_POLL_MS,
6+
requestOverlayFrames,
7+
resetOverlayFrameLoopForTests,
8+
subscribeOverlayFrame,
9+
} from "./overlayFrameLoop";
10+
11+
/**
12+
* The editor's overlay polls run on one shared, parkable frame loop. The two
13+
* things that must hold: it stops asking for frames when nothing is happening,
14+
* and every route by which something CAN happen starts it again.
15+
*/
16+
describe("overlay frame loop", () => {
17+
const originalRaf = window.requestAnimationFrame;
18+
const originalCancelRaf = window.cancelAnimationFrame;
19+
let queued: Array<() => void>;
20+
21+
/** Run whatever frames are queued, once. */
22+
const step = (): number => {
23+
const batch = queued;
24+
queued = [];
25+
for (const callback of batch) callback();
26+
return batch.length;
27+
};
28+
29+
/** Frames requested over `ms` of wall time, stepping each one. */
30+
const framesOver = (ms: number): number => {
31+
let frames = 0;
32+
for (let elapsed = 0; elapsed < ms; elapsed += 16) {
33+
vi.advanceTimersByTime(16);
34+
frames += step();
35+
}
36+
return frames;
37+
};
38+
39+
beforeEach(() => {
40+
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance", "Date"] });
41+
queued = [];
42+
window.requestAnimationFrame = ((callback: FrameRequestCallback) => {
43+
queued.push(() => callback(performance.now()));
44+
return queued.length;
45+
}) as typeof window.requestAnimationFrame;
46+
window.cancelAnimationFrame = (() => {
47+
queued = [];
48+
}) as typeof window.cancelAnimationFrame;
49+
});
50+
51+
afterEach(() => {
52+
resetOverlayFrameLoopForTests();
53+
vi.useRealTimers();
54+
window.requestAnimationFrame = originalRaf;
55+
window.cancelAnimationFrame = originalCancelRaf;
56+
});
57+
58+
it("runs every subscriber on one frame, not one frame each", () => {
59+
const calls: string[] = [];
60+
subscribeOverlayFrame(() => calls.push("a"));
61+
subscribeOverlayFrame(() => calls.push("b"));
62+
expect(step()).toBe(1);
63+
expect(calls).toEqual(["a", "b"]);
64+
});
65+
66+
it("drops to the idle poll rate once nothing has happened", () => {
67+
let runs = 0;
68+
subscribeOverlayFrame(() => {
69+
runs += 1;
70+
});
71+
// Awake first: the subscriber has never read anything.
72+
framesOver(500);
73+
const runsWhileAwake = runs;
74+
runs = 0;
75+
framesOver(1000);
76+
// A second of silence is four idle polls, not sixty frames.
77+
expect(runsWhileAwake).toBeGreaterThan(10);
78+
expect(runs).toBeLessThanOrEqual(Math.ceil(1000 / IDLE_POLL_MS) + 1);
79+
});
80+
81+
it("wakes to full rate on a pointer event", () => {
82+
let runs = 0;
83+
subscribeOverlayFrame(() => {
84+
runs += 1;
85+
});
86+
framesOver(1000);
87+
runs = 0;
88+
window.dispatchEvent(new Event("pointermove"));
89+
expect(framesOver(200)).toBeGreaterThan(5);
90+
expect(runs).toBeGreaterThan(5);
91+
});
92+
93+
const previewState = (frame: number, isPlaying = false): void => {
94+
window.dispatchEvent(
95+
new MessageEvent("message", {
96+
data: { source: "hf-preview", type: "state", frame, isPlaying },
97+
origin: window.location.origin,
98+
}),
99+
);
100+
};
101+
102+
it("wakes to full rate when the preview reports a new frame", () => {
103+
let runs = 0;
104+
subscribeOverlayFrame(() => {
105+
runs += 1;
106+
});
107+
previewState(0);
108+
framesOver(1000);
109+
runs = 0;
110+
previewState(1);
111+
framesOver(200);
112+
expect(runs).toBeGreaterThan(5);
113+
});
114+
115+
it("ignores the paused heartbeat, which repeats a frame the overlays already drew", () => {
116+
let runs = 0;
117+
subscribeOverlayFrame(() => {
118+
runs += 1;
119+
});
120+
previewState(7);
121+
framesOver(1000);
122+
runs = 0;
123+
// The bridge posts an unchanged state every 80ms while paused. Treating
124+
// that as news would hold the overlays at 60fps for the life of the tab.
125+
for (let beat = 0; beat < 12; beat += 1) {
126+
previewState(7);
127+
framesOver(80);
128+
}
129+
expect(runs).toBeLessThanOrEqual(Math.ceil(960 / IDLE_POLL_MS) + 1);
130+
});
131+
132+
it("wakes on an explicit request, which is how preview-document mutations arrive", () => {
133+
let runs = 0;
134+
subscribeOverlayFrame(() => {
135+
runs += 1;
136+
});
137+
framesOver(1000);
138+
runs = 0;
139+
requestOverlayFrames();
140+
framesOver(200);
141+
expect(runs).toBeGreaterThan(5);
142+
});
143+
144+
it("keeps every other subscriber running, and the loop alive, when one throws", () => {
145+
const runs = { a: 0, c: 0 };
146+
// The loop rethrows out of band so the error still reaches the page's
147+
// error reporting. Capture those instead of letting them escape the test,
148+
// and assert every one of them was surfaced rather than swallowed.
149+
const rethrown: Array<() => void> = [];
150+
vi.spyOn(globalThis, "queueMicrotask").mockImplementation((fn: () => void) => {
151+
rethrown.push(fn);
152+
});
153+
154+
subscribeOverlayFrame(() => {
155+
runs.a += 1;
156+
});
157+
subscribeOverlayFrame(() => {
158+
throw new Error("subscriber blew up");
159+
});
160+
subscribeOverlayFrame(() => {
161+
runs.c += 1;
162+
});
163+
164+
for (let i = 0; i < 5; i += 1) step();
165+
166+
// The survivors ran on every frame, every failure was reported, and the
167+
// loop is still asking for more frames.
168+
expect(runs.a).toBe(5);
169+
expect(runs.c).toBe(5);
170+
expect(rethrown).toHaveLength(5);
171+
expect(() => rethrown[0]()).toThrow("subscriber blew up");
172+
expect(queued.length).toBeGreaterThan(0);
173+
});
174+
175+
it("does not wake for a message that is not the preview's", () => {
176+
let runs = 0;
177+
subscribeOverlayFrame(() => {
178+
runs += 1;
179+
});
180+
framesOver(1000);
181+
runs = 0;
182+
window.dispatchEvent(
183+
new MessageEvent("message", {
184+
data: { source: "some-extension" },
185+
origin: window.location.origin,
186+
}),
187+
);
188+
window.dispatchEvent(
189+
new MessageEvent("message", { data: "a string", origin: window.location.origin }),
190+
);
191+
framesOver(200);
192+
expect(runs).toBeLessThanOrEqual(2);
193+
});
194+
195+
it("ignores a preview-shaped message from another origin", () => {
196+
let runs = 0;
197+
subscribeOverlayFrame(() => {
198+
runs += 1;
199+
});
200+
framesOver(1000);
201+
runs = 0;
202+
// Same payload the preview sends, from somewhere that is not the preview.
203+
// Anything embedded on the page can post this; only the origin tells them
204+
// apart, and waking on it would hold the overlays at full rate for free.
205+
window.dispatchEvent(
206+
new MessageEvent("message", {
207+
data: { source: "hf-preview", type: "state", frame: 42, isPlaying: false },
208+
origin: "https://not-the-preview.example",
209+
}),
210+
);
211+
framesOver(200);
212+
expect(runs).toBeLessThanOrEqual(2);
213+
});
214+
215+
it("wakes for a preview message that is not a state post", () => {
216+
let runs = 0;
217+
subscribeOverlayFrame(() => {
218+
runs += 1;
219+
});
220+
framesOver(1000);
221+
runs = 0;
222+
// A new clip manifest is news whatever the playhead is doing.
223+
window.dispatchEvent(
224+
new MessageEvent("message", {
225+
data: { source: "hf-preview", type: "timeline", clips: [] },
226+
origin: window.location.origin,
227+
}),
228+
);
229+
framesOver(200);
230+
expect(runs).toBeGreaterThan(5);
231+
});
232+
233+
it("stops entirely, and stops listening, once the last subscriber leaves", () => {
234+
let runs = 0;
235+
const unsubscribe = subscribeOverlayFrame(() => {
236+
runs += 1;
237+
});
238+
framesOver(100);
239+
unsubscribe();
240+
runs = 0;
241+
window.dispatchEvent(new Event("pointermove"));
242+
framesOver(1000);
243+
expect(runs).toBe(0);
244+
expect(queued).toHaveLength(0);
245+
});
246+
});

0 commit comments

Comments
 (0)