Skip to content

Commit 5a74db9

Browse files
fix(studio): playback no longer re-renders the whole app every frame (#4529)
* fix(studio): playback no longer re-renders the whole app every frame * fix(studio): pausing by hiding the tab keeps the playhead where it stopped * fix(studio): hiding the tab stops a reverse shuttle like any other pause * test(studio): pin the shuttle speed reset on a hidden-tab pause * style(studio): format the hidden-tab pause test
1 parent 0f14691 commit 5a74db9

5 files changed

Lines changed: 164 additions & 20 deletions

File tree

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// @vitest-environment happy-dom
2+
3+
import React, { act } from "react";
4+
import { createRoot, type Root } from "react-dom/client";
5+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
6+
import { liveTime, usePlayerStore } from "../player";
7+
import { useFrameCapture } from "./useFrameCapture";
8+
9+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
10+
11+
let renders = 0;
12+
let capture: ReturnType<typeof useFrameCapture>;
13+
14+
function Harness() {
15+
renders += 1;
16+
capture = useFrameCapture({
17+
projectId: "p",
18+
activeCompPath: null,
19+
showToast: () => {},
20+
waitForPendingDomEditSaves: async () => {},
21+
});
22+
return null;
23+
}
24+
25+
const shownTime = () => new URL(capture.captureFrameHref).searchParams.get("t");
26+
27+
let host: HTMLDivElement;
28+
let root: Root;
29+
30+
beforeEach(async () => {
31+
usePlayerStore.setState({ isPlaying: false, currentTime: 2 });
32+
renders = 0;
33+
host = document.createElement("div");
34+
document.body.append(host);
35+
root = createRoot(host);
36+
await act(async () => root.render(React.createElement(Harness)));
37+
});
38+
39+
afterEach(async () => {
40+
await act(async () => root.unmount());
41+
host.remove();
42+
});
43+
44+
describe("useFrameCapture", () => {
45+
it("does not re-render on playback frames", () => {
46+
usePlayerStore.setState({ isPlaying: true });
47+
const before = renders;
48+
act(() => {
49+
for (let i = 1; i <= 30; i++) liveTime.notify(2 + i / 60);
50+
});
51+
expect(renders).toBe(before);
52+
});
53+
54+
it("points the capture at the live playhead while playing", () => {
55+
usePlayerStore.setState({ isPlaying: true });
56+
act(() => liveTime.notify(7.5));
57+
act(() => capture.refreshCaptureFrameTime());
58+
expect(shownTime()).toBe("7.500");
59+
});
60+
61+
it("points the capture at the store time while paused", () => {
62+
act(() => liveTime.notify(7.5));
63+
usePlayerStore.setState({ isPlaying: false, currentTime: 3 });
64+
act(() => capture.refreshCaptureFrameTime());
65+
expect(shownTime()).toBe("3.000");
66+
});
67+
});

‎packages/studio/src/hooks/useFrameCapture.ts‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,28 @@ export function useFrameCapture({
1616
showToast,
1717
waitForPendingDomEditSaves,
1818
}: UseFrameCaptureParams) {
19-
const [captureFrameTime, setCaptureFrameTime] = useState(0);
19+
const [captureFrameTime, setCaptureFrameTime] = useState(
20+
() => usePlayerStore.getState().currentTime,
21+
);
2022
const [capturing, setCapturing] = useState(false);
2123
const capturingRef = useRef(false);
24+
const livePlayheadRef = useRef(captureFrameTime);
2225

23-
useMountEffect(() => {
24-
setCaptureFrameTime(usePlayerStore.getState().currentTime);
25-
return liveTime.subscribe(setCaptureFrameTime);
26-
});
26+
useMountEffect(() =>
27+
liveTime.subscribe((time) => {
28+
livePlayheadRef.current = time;
29+
}),
30+
);
2731

28-
const refreshCaptureFrameTime = useCallback(() => {
29-
setCaptureFrameTime(usePlayerStore.getState().currentTime);
32+
const playheadTime = useCallback(() => {
33+
const { isPlaying, currentTime } = usePlayerStore.getState();
34+
return isPlaying ? livePlayheadRef.current : currentTime;
3035
}, []);
3136

37+
const refreshCaptureFrameTime = useCallback(() => {
38+
setCaptureFrameTime(playheadTime());
39+
}, [playheadTime]);
40+
3241
const handleCaptureFrameClick = useCallback(
3342
async (event: MouseEvent<HTMLAnchorElement>) => {
3443
if (!projectId) return;
@@ -39,7 +48,7 @@ export function useFrameCapture({
3948
capturingRef.current = true;
4049
setCapturing(true);
4150
try {
42-
const time = usePlayerStore.getState().currentTime;
51+
const time = playheadTime();
4352
setCaptureFrameTime(time);
4453
await Promise.race([
4554
waitForPendingDomEditSaves(),
@@ -91,7 +100,7 @@ export function useFrameCapture({
91100
setCapturing(false);
92101
}
93102
},
94-
[activeCompPath, projectId, showToast, waitForPendingDomEditSaves],
103+
[activeCompPath, playheadTime, projectId, showToast, waitForPendingDomEditSaves],
95104
);
96105

97106
const captureFrameHref = projectId
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// @vitest-environment happy-dom
2+
3+
import { act } from "react";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { usePlayerStore } from "../store/playerStore";
6+
import {
7+
attachIframeWindow,
8+
makeAdapterWindow,
9+
renderTimelinePlayerHarness,
10+
resetPlayerStore,
11+
} from "./timelinePlayerTestHarness";
12+
13+
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
14+
15+
afterEach(() => {
16+
vi.restoreAllMocks();
17+
document.body.innerHTML = "";
18+
resetPlayerStore();
19+
});
20+
21+
describe("useTimelinePlayer tab hidden while playing", () => {
22+
it("pauses on the adapter's time, like any other pause", () => {
23+
const { api, root } = renderTimelinePlayerHarness();
24+
const { adapter, win } = makeAdapterWindow();
25+
attachIframeWindow(api, win);
26+
act(() => api.play());
27+
adapter.seek(6);
28+
29+
vi.spyOn(document, "hidden", "get").mockReturnValue(true);
30+
act(() => void document.dispatchEvent(new Event("visibilitychange")));
31+
32+
expect(usePlayerStore.getState().isPlaying).toBe(false);
33+
expect(usePlayerStore.getState().currentTime).toBe(6);
34+
act(() => root.unmount());
35+
});
36+
37+
it("stops a reverse shuttle for good", async () => {
38+
const { api, root } = renderTimelinePlayerHarness();
39+
const { adapter, win } = makeAdapterWindow();
40+
attachIframeWindow(api, win);
41+
adapter.seek(20);
42+
act(() => void window.dispatchEvent(new KeyboardEvent("keydown", { code: "KeyJ", key: "j" })));
43+
await act(() => new Promise((r) => setTimeout(r, 100)));
44+
expect(usePlayerStore.getState().isPlaying).toBe(true);
45+
46+
vi.spyOn(document, "hidden", "get").mockReturnValue(true);
47+
act(() => void document.dispatchEvent(new Event("visibilitychange")));
48+
const stoppedAt = adapter.getTime();
49+
await act(() => new Promise((r) => setTimeout(r, 200)));
50+
51+
expect(usePlayerStore.getState().isPlaying).toBe(false);
52+
expect(adapter.getTime()).toBe(stoppedAt);
53+
expect(usePlayerStore.getState().currentTime).toBe(stoppedAt);
54+
act(() => root.unmount());
55+
});
56+
57+
it("does not carry the shuttle speed past the pause", () => {
58+
const { api, root } = renderTimelinePlayerHarness();
59+
attachIframeWindow(api, makeAdapterWindow().win);
60+
const pressL = () =>
61+
act(
62+
() => void window.dispatchEvent(new KeyboardEvent("keydown", { code: "KeyL", key: "l" })),
63+
);
64+
pressL();
65+
pressL();
66+
expect(usePlayerStore.getState().playbackRate).toBe(2);
67+
68+
vi.spyOn(document, "hidden", "get").mockReturnValue(true);
69+
act(() => void document.dispatchEvent(new Event("visibilitychange")));
70+
pressL();
71+
72+
expect(usePlayerStore.getState().playbackRate).toBe(1);
73+
act(() => root.unmount());
74+
});
75+
});

‎packages/studio/src/player/hooks/useTimelinePlayer.ts‎

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -456,8 +456,8 @@ export function useTimelinePlayer({
456456
applyPreviewVariablesToUrl(url);
457457
beginShadowReload(url.toString());
458458
}, [saveSeekPosition, getAdapter, beginShadowReload]);
459-
const getAdapterRef = useRef(getAdapter);
460-
getAdapterRef.current = getAdapter;
459+
const pauseRef = useRef(pause);
460+
pauseRef.current = pause;
461461

462462
useMountEffect(() => {
463463
const handleWindowKeyDown = (e: KeyboardEvent) => playbackKeyDownRef.current(e);
@@ -473,14 +473,7 @@ export function useTimelinePlayer({
473473
});
474474

475475
const handleVisibilityChange = () => {
476-
if (document.hidden && usePlayerStore.getState().isPlaying) {
477-
const adapter = getAdapterRef.current?.();
478-
if (adapter) {
479-
adapter.pause();
480-
setIsPlaying(false);
481-
stopRAFLoop();
482-
}
483-
}
476+
if (document.hidden && usePlayerStore.getState().isPlaying) pauseRef.current();
484477
};
485478

486479
window.addEventListener("keydown", handleWindowKeyDown, true);

‎packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ export function useTimelineSyncCallbacks({
244244
adapter.pause();
245245
const startTime = seekAdapterToRestorePoint(adapter, pendingSeekRef);
246246
const commit = () => {
247-
// Keep non-React listeners such as the capture link and time display in sync
247+
// Keep non-React listeners such as the time display in sync
248248
// with the initial adapter seek on iframe load.
249249
liveTime.notify(startTime);
250250
syncAdapterDuration(adapter, setDuration);

0 commit comments

Comments
 (0)