Skip to content

Write HTML. Render video. Built for agents.

perf(studio): a paused editor stops redrawing its overlays sixty times a second (#3846)

Miguel Ángel9549e038c43a
diff --git a/packages/studio/src/components/editor/SnapGuideOverlay.tsx b/packages/studio/src/components/editor/SnapGuideOverlay.tsx
index 850d98adf5..ad6f98e2c9 100644
--- a/packages/studio/src/components/editor/SnapGuideOverlay.tsx
+++ b/packages/studio/src/components/editor/SnapGuideOverlay.tsx
@@ -1,6 +1,7 @@
import { memo, useRef, type RefObject } from "react";
import { useMountEffect } from "../../hooks/useMountEffect";
import { resolveGuideLineRect, type SnapGuide, type SpacingGuide } from "./snapEngine";
+import { subscribeOverlayFrame } from "./overlayFrameLoop";
export interface SnapGuidesState {
guides: SnapGuide[];
@@ -47,12 +48,8 @@ export const SnapGuideOverlay = memo(function SnapGuideOverlay({
};
useMountEffect(() => {
- let frame = 0;
-
// fallow-ignore-next-line complexity
const update = () => {
- frame = requestAnimationFrame(update);
-
const state = snapGuidesRef.current;
const guides = state?.guides ?? [];
const spacingGuides = state?.spacingGuides ?? [];
@@ -116,8 +113,7 @@ export const SnapGuideOverlay = memo(function SnapGuideOverlay({
}
};
- frame = requestAnimationFrame(update);
- return () => cancelAnimationFrame(frame);
+ return subscribeOverlayFrame(update);
});
return (
diff --git a/packages/studio/src/components/editor/offCanvasIndicatorRefresh.ts b/packages/studio/src/components/editor/offCanvasIndicatorRefresh.ts
index 039402cf4d..6bf169c148 100644
--- a/packages/studio/src/components/editor/offCanvasIndicatorRefresh.ts
+++ b/packages/studio/src/components/editor/offCanvasIndicatorRefresh.ts
@@ -7,6 +7,7 @@ import {
drainPendingLayerMutations,
} from "./domEditLayerWalkCache";
import { recomputeOffCanvasIndicators } from "./offCanvasIndicatorGeometry";
+import { requestOverlayFrames, subscribeOverlayFrame } from "./overlayFrameLoop";
interface OffCanvasIndicatorRefreshOptions {
iframeRef: React.RefObject<HTMLIFrameElement | null>;
@@ -78,12 +79,16 @@ export function rebuildDue(dirty: boolean, lastAt: number, now: number): boolean
export function startOffCanvasIndicatorRefresh(
options: OffCanvasIndicatorRefreshOptions,
): () => void {
- let frame = 0;
let lastCompSig = "";
let lastRecomputeAt = Number.NEGATIVE_INFINITY;
const walkCache = createDomEditLayerWalkCache();
const markDirty = () => {
options.dirtyRef.current = true;
+ // A rebuild is owed, so the shared loop has to be running to pay it. The
+ // preview's own MutationObserver is the wake source the top frame's
+ // pointer and message listeners cannot be: an edit inside the iframe
+ // reaches this callback and nothing else.
+ requestOverlayFrames();
};
const attachObserver = (doc: Document | null) => {
options.observerRef.current?.disconnect();
@@ -97,7 +102,6 @@ export function startOffCanvasIndicatorRefresh(
options.sigRef.current = "";
};
const update = () => {
- frame = requestAnimationFrame(update);
const iframe = options.iframeRef.current;
const overlayEl = options.overlayRef.current;
const doc = iframe?.contentDocument ?? null;
@@ -133,9 +137,9 @@ export function startOffCanvasIndicatorRefresh(
walkCache,
);
};
- frame = requestAnimationFrame(update);
+ const unsubscribe = subscribeOverlayFrame(update);
return () => {
- cancelAnimationFrame(frame);
+ unsubscribe();
options.observerRef.current?.disconnect();
options.observerRef.current = null;
options.observedDocRef.current = null;
diff --git a/packages/studio/src/components/editor/overlayFrameLoop.test.ts b/packages/studio/src/components/editor/overlayFrameLoop.test.ts
new file mode 100644
index 0000000000..a0cf26c0c0
--- /dev/null
+++ b/packages/studio/src/components/editor/overlayFrameLoop.test.ts
@@ -0,0 +1,246 @@
+// @vitest-environment happy-dom
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ IDLE_POLL_MS,
+ requestOverlayFrames,
+ resetOverlayFrameLoopForTests,
+ subscribeOverlayFrame,
+} from "./overlayFrameLoop";
+
+/**
+ * The editor's overlay polls run on one shared, parkable frame loop. The two
+ * things that must hold: it stops asking for frames when nothing is happening,
+ * and every route by which something CAN happen starts it again.
+ */
+describe("overlay frame loop", () => {
+ const originalRaf = window.requestAnimationFrame;
+ const originalCancelRaf = window.cancelAnimationFrame;
+ let queued: Array<() => void>;
+
+ /** Run whatever frames are queued, once. */
+ const step = (): number => {
+ const batch = queued;
+ queued = [];
+ for (const callback of batch) callback();
+ return batch.length;
+ };
+
+ /** Frames requested over `ms` of wall time, stepping each one. */
+ const framesOver = (ms: number): number => {
+ let frames = 0;
+ for (let elapsed = 0; elapsed < ms; elapsed += 16) {
+ vi.advanceTimersByTime(16);
+ frames += step();
+ }
+ return frames;
+ };
+
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance", "Date"] });
+ queued = [];
+ window.requestAnimationFrame = ((callback: FrameRequestCallback) => {
+ queued.push(() => callback(performance.now()));
+ return queued.length;
+ }) as typeof window.requestAnimationFrame;
+ window.cancelAnimationFrame = (() => {
+ queued = [];
+ }) as typeof window.cancelAnimationFrame;
+ });
+
+ afterEach(() => {
+ resetOverlayFrameLoopForTests();
+ vi.useRealTimers();
+ window.requestAnimationFrame = originalRaf;
+ window.cancelAnimationFrame = originalCancelRaf;
+ });
+
+ it("runs every subscriber on one frame, not one frame each", () => {
+ const calls: string[] = [];
+ subscribeOverlayFrame(() => calls.push("a"));
+ subscribeOverlayFrame(() => calls.push("b"));
+ expect(step()).toBe(1);
+ expect(calls).toEqual(["a", "b"]);
+ });
+
+ it("drops to the idle poll rate once nothing has happened", () => {
+ let runs = 0;
+ subscribeOverlayFrame(() => {
+ runs += 1;
+ });
+ // Awake first: the subscriber has never read anything.
+ framesOver(500);
+ const runsWhileAwake = runs;
+ runs = 0;
+ framesOver(1000);
+ // A second of silence is four idle polls, not sixty frames.
+ expect(runsWhileAwake).toBeGreaterThan(10);
+ expect(runs).toBeLessThanOrEqual(Math.ceil(1000 / IDLE_POLL_MS) + 1);
+ });
+
+ it("wakes to full rate on a pointer event", () => {
+ let runs = 0;
+ subscribeOverlayFrame(() => {
+ runs += 1;
+ });
+ framesOver(1000);
+ runs = 0;
+ window.dispatchEvent(new Event("pointermove"));
+ expect(framesOver(200)).toBeGreaterThan(5);
+ expect(runs).toBeGreaterThan(5);
+ });
+
+ const previewState = (frame: number, isPlaying = false): void => {
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ data: { source: "hf-preview", type: "state", frame, isPlaying },
+ origin: window.location.origin,
+ }),
+ );
+ };
+
+ it("wakes to full rate when the preview reports a new frame", () => {
+ let runs = 0;
+ subscribeOverlayFrame(() => {
+ runs += 1;
+ });
+ previewState(0);
+ framesOver(1000);
+ runs = 0;
+ previewState(1);
+ framesOver(200);
+ expect(runs).toBeGreaterThan(5);
+ });
+
+ it("ignores the paused heartbeat, which repeats a frame the overlays already drew", () => {
+ let runs = 0;
+ subscribeOverlayFrame(() => {
+ runs += 1;
+ });
+ previewState(7);
+ framesOver(1000);
+ runs = 0;
+ // The bridge posts an unchanged state every 80ms while paused. Treating
+ // that as news would hold the overlays at 60fps for the life of the tab.
+ for (let beat = 0; beat < 12; beat += 1) {
+ previewState(7);
+ framesOver(80);
+ }
+ expect(runs).toBeLessThanOrEqual(Math.ceil(960 / IDLE_POLL_MS) + 1);
+ });
+
+ it("wakes on an explicit request, which is how preview-document mutations arrive", () => {
+ let runs = 0;
+ subscribeOverlayFrame(() => {
+ runs += 1;
+ });
+ framesOver(1000);
+ runs = 0;
+ requestOverlayFrames();
+ framesOver(200);
+ expect(runs).toBeGreaterThan(5);
+ });
+
+ it("keeps every other subscriber running, and the loop alive, when one throws", () => {
+ const runs = { a: 0, c: 0 };
+ // The loop rethrows out of band so the error still reaches the page's
+ // error reporting. Capture those instead of letting them escape the test,
+ // and assert every one of them was surfaced rather than swallowed.
+ const rethrown: Array<() => void> = [];
+ vi.spyOn(globalThis, "queueMicrotask").mockImplementation((fn: () => void) => {
+ rethrown.push(fn);
+ });
+
+ subscribeOverlayFrame(() => {
+ runs.a += 1;
+ });
+ subscribeOverlayFrame(() => {
+ throw new Error("subscriber blew up");
+ });
+ subscribeOverlayFrame(() => {
+ runs.c += 1;
+ });
+
+ for (let i = 0; i < 5; i += 1) step();
+
+ // The survivors ran on every frame, every failure was reported, and the
+ // loop is still asking for more frames.
+ expect(runs.a).toBe(5);
+ expect(runs.c).toBe(5);
+ expect(rethrown).toHaveLength(5);
+ expect(() => rethrown[0]()).toThrow("subscriber blew up");
+ expect(queued.length).toBeGreaterThan(0);
+ });
+
+ it("does not wake for a message that is not the preview's", () => {
+ let runs = 0;
+ subscribeOverlayFrame(() => {
+ runs += 1;
+ });
+ framesOver(1000);
+ runs = 0;
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ data: { source: "some-extension" },
+ origin: window.location.origin,
+ }),
+ );
+ window.dispatchEvent(
+ new MessageEvent("message", { data: "a string", origin: window.location.origin }),
+ );
+ framesOver(200);
+ expect(runs).toBeLessThanOrEqual(2);
+ });
+
+ it("ignores a preview-shaped message from another origin", () => {
+ let runs = 0;
+ subscribeOverlayFrame(() => {
+ runs += 1;
+ });
+ framesOver(1000);
+ runs = 0;
+ // Same payload the preview sends, from somewhere that is not the preview.
+ // Anything embedded on the page can post this; only the origin tells them
+ // apart, and waking on it would hold the overlays at full rate for free.
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ data: { source: "hf-preview", type: "state", frame: 42, isPlaying: false },
+ origin: "https://not-the-preview.example",
+ }),
+ );
+ framesOver(200);
+ expect(runs).toBeLessThanOrEqual(2);
+ });
+
+ it("wakes for a preview message that is not a state post", () => {
+ let runs = 0;
+ subscribeOverlayFrame(() => {
+ runs += 1;
+ });
+ framesOver(1000);
+ runs = 0;
+ // A new clip manifest is news whatever the playhead is doing.
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ data: { source: "hf-preview", type: "timeline", clips: [] },
+ origin: window.location.origin,
+ }),
+ );
+ framesOver(200);
+ expect(runs).toBeGreaterThan(5);
+ });
+
+ it("stops entirely, and stops listening, once the last subscriber leaves", () => {
+ let runs = 0;
+ const unsubscribe = subscribeOverlayFrame(() => {
+ runs += 1;
+ });
+ framesOver(100);
+ unsubscribe();
+ runs = 0;
+ window.dispatchEvent(new Event("pointermove"));
+ framesOver(1000);
+ expect(runs).toBe(0);
+ expect(queued).toHaveLength(0);
+ });
+});
diff --git a/packages/studio/src/components/editor/overlayFrameLoop.ts b/packages/studio/src/components/editor/overlayFrameLoop.ts
new file mode 100644
index 0000000000..62938b92f2
--- /dev/null
+++ b/packages/studio/src/components/editor/overlayFrameLoop.ts
@@ -0,0 +1,204 @@
+/**
+ * One animation frame for every editor overlay that tracks preview geometry by
+ * polling — and no frame at all while the editor is sitting still.
+ *
+ * Each overlay used to own an unconditional `requestAnimationFrame(update)`.
+ * Four of them never stopped, so a paused, untouched Studio ran ~240 callbacks
+ * a second, every one of them reading layout and one of them writing style,
+ * which kept the compositor committing 55 frames a second with nothing moving.
+ *
+ * Parking is safe because none of these overlays has a clock of its own. They
+ * change only in response to something observable: a pointer, a key, a scroll
+ * or resize, a message from the preview (the runtime posts one on every frame
+ * the playhead moves), or a mutation inside the preview document. Those are the
+ * wake sources below, and `requestOverlayFrames` is the door for anything else.
+ *
+ * `IDLE_POLL_MS` is the safety net, and the reason a missed wake source is a
+ * quarter second of staleness rather than a permanently frozen overlay.
+ */
+
+/**
+ * How long the loop keeps running frames after the last wake.
+ *
+ * Long enough to outlast the consequences of the event that woke it, not just
+ * the event: a click opens a panel whose CSS transition moves the preview for
+ * the next couple of hundred milliseconds, and no further event is dispatched
+ * while it does.
+ */
+const AWAKE_MS = 400;
+/** How often a parked loop runs one frame anyway, in case a wake was missed. */
+export const IDLE_POLL_MS = 250;
+
+const subscribers = new Set<() => void>();
+
+let frameId: number | null = null;
+let idleTimerId: ReturnType<typeof setTimeout> | null = null;
+let awakeUntil = 0;
+let listenersAttached = false;
+
+/** Wake sources. All passive reads; none of them can be cancelled by us. */
+const WINDOW_EVENTS = [
+ "pointerdown",
+ "pointermove",
+ "pointerup",
+ "wheel",
+ "keydown",
+ "keyup",
+ "scroll",
+ "resize",
+ "visibilitychange",
+] as const;
+
+// The preview posts a `state` message on a fixed interval even when the
+// playhead has not moved — the control bridge's paused heartbeat, which exists
+// so a listener can confirm a paused position. Waking on every message would
+// therefore hold the overlays at 60 fps for as long as the editor is open,
+// which is exactly the cost this loop exists to remove. Wake on the messages
+// that carry news instead.
+let lastPreviewFrame: number | null = null;
+let lastPreviewPlaying: boolean | null = null;
+
+/**
+ * The preview iframe is served by the editor's own origin (`useTimelinePlayer`
+ * builds its src against `window.location.origin`), so a message from anywhere
+ * else is not the preview whatever its payload claims. Answered before the
+ * payload is read, because a sender we do not trust controls every field in it.
+ */
+function isFromPreviewOrigin(event: MessageEvent): boolean {
+ if (typeof window === "undefined") return true;
+ return event.origin === window.location.origin;
+}
+
+/**
+ * `window` also receives postMessage traffic from extensions, devtools and any
+ * other embed on the page. Waking on those would hold the overlays awake for
+ * reasons that have nothing to do with the preview.
+ */
+function isPreviewPayload(data: unknown): data is { type?: unknown } {
+ if (data == null || typeof data !== "object") return false;
+ return (data as { source?: unknown }).source === "hf-preview";
+}
+
+/** The playhead position a `state` post carries, or null for any other post. */
+function previewStateOf(data: {
+ type?: unknown;
+}): { frame: number | null; playing: boolean } | null {
+ if (data.type !== "state") return null;
+ const frame = (data as { frame?: unknown }).frame;
+ return {
+ frame: typeof frame === "number" ? frame : null,
+ playing: (data as { isPlaying?: unknown }).isPlaying === true,
+ };
+}
+
+function onPreviewMessage(event: MessageEvent): void {
+ if (!isFromPreviewOrigin(event)) return;
+ const data: unknown = event.data;
+ if (!isPreviewPayload(data)) return;
+ const state = previewStateOf(data);
+ if (state) {
+ if (state.frame === lastPreviewFrame && state.playing === lastPreviewPlaying) return;
+ lastPreviewFrame = state.frame;
+ lastPreviewPlaying = state.playing;
+ }
+ requestOverlayFrames();
+}
+
+function runFrame(): void {
+ frameId = null;
+ // Re-arm BEFORE running anything, exactly as the four separate loops this
+ // replaces did. A subscriber that throws must not take the loop down with
+ // it — and a shared loop makes that failure four overlays wide plus the
+ // idle-poll safety net, permanently, rather than one overlay's own problem.
+ schedule();
+ for (const subscriber of subscribers) {
+ try {
+ subscriber();
+ } catch (error) {
+ // Rethrown out of band so it still reaches window.onerror and whatever
+ // reports errors, without any subscriber becoming the others' fate.
+ queueMicrotask(() => {
+ throw error;
+ });
+ }
+ }
+}
+
+function schedule(): void {
+ if (subscribers.size === 0) return;
+ if (frameId != null || idleTimerId != null) return;
+ if (performance.now() < awakeUntil) {
+ frameId = requestAnimationFrame(runFrame);
+ return;
+ }
+ idleTimerId = setTimeout(() => {
+ idleTimerId = null;
+ frameId = requestAnimationFrame(runFrame);
+ }, IDLE_POLL_MS);
+}
+
+/** Something moved, or might have. Run frames at full rate for a moment. */
+export function requestOverlayFrames(): void {
+ awakeUntil = performance.now() + AWAKE_MS;
+ if (idleTimerId != null) {
+ clearTimeout(idleTimerId);
+ idleTimerId = null;
+ }
+ schedule();
+}
+
+function attachListeners(): void {
+ if (listenersAttached || typeof window === "undefined") return;
+ listenersAttached = true;
+ for (const type of WINDOW_EVENTS) {
+ window.addEventListener(type, requestOverlayFrames, { capture: true, passive: true });
+ }
+ window.addEventListener("message", onPreviewMessage, { capture: true, passive: true });
+}
+
+function detachListeners(): void {
+ if (!listenersAttached || typeof window === "undefined") return;
+ listenersAttached = false;
+ for (const type of WINDOW_EVENTS) {
+ window.removeEventListener(type, requestOverlayFrames, { capture: true });
+ }
+ window.removeEventListener("message", onPreviewMessage, { capture: true });
+}
+
+/**
+ * Run `update` on the shared loop. The subscriber must be a pure poll: it is
+ * called on an ordinary animation frame while the editor is active and roughly
+ * four times a second while it is not.
+ */
+export function subscribeOverlayFrame(update: () => void): () => void {
+ subscribers.add(update);
+ attachListeners();
+ // A fresh subscriber has never read anything, so it starts awake.
+ requestOverlayFrames();
+ return () => {
+ subscribers.delete(update);
+ if (subscribers.size > 0) return;
+ if (frameId != null) {
+ cancelAnimationFrame(frameId);
+ frameId = null;
+ }
+ if (idleTimerId != null) {
+ clearTimeout(idleTimerId);
+ idleTimerId = null;
+ }
+ detachListeners();
+ };
+}
+
+/** Test seam: the loop is module state, and tests need it back at zero. */
+export function resetOverlayFrameLoopForTests(): void {
+ subscribers.clear();
+ if (frameId != null) cancelAnimationFrame(frameId);
+ if (idleTimerId != null) clearTimeout(idleTimerId);
+ frameId = null;
+ idleTimerId = null;
+ awakeUntil = 0;
+ lastPreviewFrame = null;
+ lastPreviewPlaying = null;
+ detachListeners();
+}
diff --git a/packages/studio/src/components/editor/useDomEditCompositionRect.ts b/packages/studio/src/components/editor/useDomEditCompositionRect.ts
index a950f9fff3..4cac7bb922 100644
--- a/packages/studio/src/components/editor/useDomEditCompositionRect.ts
+++ b/packages/studio/src/components/editor/useDomEditCompositionRect.ts
@@ -1,5 +1,6 @@
import { useState, type RefObject } from "react";
import { useMountEffect } from "../../hooks/useMountEffect";
+import { subscribeOverlayFrame } from "./overlayFrameLoop";
export interface DomEditCompositionRect {
left: number;
@@ -39,10 +40,8 @@ export function useDomEditCompositionRect({
});
useMountEffect(() => {
- let frame = 0;
// fallow-ignore-next-line complexity
const update = () => {
- frame = requestAnimationFrame(update);
const iframe = iframeRef.current;
const overlayEl = overlayRef.current;
if (!iframe || !overlayEl) return;
@@ -60,8 +59,7 @@ export function useDomEditCompositionRect({
const next = { left, top, width: iRect.width, height: iRect.height, scaleX, scaleY };
setCompRect((prev) => (sameRect(prev, next) ? prev : next));
};
- frame = requestAnimationFrame(update);
- return () => cancelAnimationFrame(frame);
+ return subscribeOverlayFrame(update);
});
return compRect;
diff --git a/packages/studio/src/components/editor/useDomEditOverlayRects.ts b/packages/studio/src/components/editor/useDomEditOverlayRects.ts
index e9b2973402..884873ec09 100644
--- a/packages/studio/src/components/editor/useDomEditOverlayRects.ts
+++ b/packages/studio/src/components/editor/useDomEditOverlayRects.ts
@@ -20,6 +20,7 @@ import {
orientedVisibleOverlayRect,
} from "./domEditOverlayGeometry";
import { computeOverlayRootScale } from "./domEditOverlayBasis";
+import { subscribeOverlayFrame } from "./overlayFrameLoop";
function childRectsEqual(a: OverlayRect[], b: OverlayRect[]): boolean {
if (a.length !== b.length) return false;
@@ -107,8 +108,6 @@ export function useDomEditOverlayRects({
};
useMountEffect(() => {
- let frame = 0;
-
const clearAll = () => {
setOverlayRect(null);
setHoverRect(null);
@@ -116,7 +115,6 @@ export function useDomEditOverlayRects({
};
const update = () => {
- frame = requestAnimationFrame(update);
if (rafPausedRef.current) {
if (childRectsRef.current.length > 0) {
childRectsRef.current = [];
@@ -263,8 +261,7 @@ export function useDomEditOverlayRects({
setHoverRect(orientedGroupAwareOverlayRect(overlayEl, iframe, hoverEl, scale));
};
- frame = requestAnimationFrame(update);
- return () => cancelAnimationFrame(frame);
+ return subscribeOverlayFrame(update);
});
return {
diff --git a/packages/studio/src/components/editor/useMotionPathData.ts b/packages/studio/src/components/editor/useMotionPathData.ts
index 1f5cd67ce5..46a69cbe9e 100644
--- a/packages/studio/src/components/editor/useMotionPathData.ts
+++ b/packages/studio/src/components/editor/useMotionPathData.ts
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState, type RefObject } from "react";
import { readRuntimeKeyframes } from "../../hooks/gsapRuntimeKeyframes";
import { isElementVisibleForOverlay } from "./domEditOverlayGeometry";
import { buildMotionPathGeometry, type MotionPathGeometry } from "./motionPathGeometry";
+import { subscribeOverlayFrame } from "./overlayFrameLoop";
type Rect = { left: number; top: number; width: number; height: number };
@@ -121,7 +122,6 @@ export function useMotionPathData(
return;
}
setHome(null);
- let raf = 0;
const tick = () => {
const el = iframeRef.current;
if (el) {
@@ -153,10 +153,8 @@ export function useMotionPathData(
setPScale((p) => (Math.abs(p - ps) < 0.001 ? p : ps));
}
}
- raf = requestAnimationFrame(tick);
};
- raf = requestAnimationFrame(tick);
- return () => cancelAnimationFrame(raf);
+ return subscribeOverlayFrame(tick);
}, [selector, iframeRef]);
useEffect(() => {