Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

perf(timeline): stop the playhead from re-rendering the whole editor every frame

Etienne Lescotf468bd1ef33d
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index deeb4fdb3..442573131 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -47,11 +47,41 @@ interface SeekTarget {
requestId: number;
}
+/**
+ * Renders nothing. Exists purely so the per-frame `currentTimeSec` subscription
+ * that feeds the native transport lives in a LEAF instead of in the shell.
+ *
+ * `currentTimeSec` is rewritten on every animation frame during playback
+ * (VirtualPreview's rAF tick → onTimeChange → setCurrentTime). Reading it
+ * directly in NewEditorShell re-rendered the entire editor — timeline, clips,
+ * waveforms, inspector, preview — 60×/s, which is what made the playhead and
+ * the transcript cue point stutter: the whole tree had to commit before the
+ * playhead's own DOM node moved. Everything that genuinely needs the live
+ * playhead now subscribes to it where it is actually rendered (PlayheadOverlay,
+ * TransportBar, Preview, TranscriptPane, NativeCompositorOverlay, and this
+ * component); the shell itself reads it imperatively via getState() in the
+ * handlers that need it. The store write cadence is unchanged — `currentTimeSec`
+ * is still the source of truth, still updated every frame.
+ */
+function NativePlaybackSync({
+ visibleClips,
+ clips,
+}: {
+ visibleClips: AxcutClip[];
+ clips: AxcutClip[];
+}) {
+ const playing = useProjectStore((s) => s.playing);
+ const currentTimeSec = useProjectStore((s) => s.currentTimeSec);
+ // visibleClips = trim-compressed native stream; `clips` = RAW layout currentTimeSec
+ // is measured against. resolveNativePosition needs both (see timelineMap).
+ useNativePlaybackSync(playing, currentTimeSec, visibleClips, clips);
+ return null;
+}
+
export function NewEditorShell() {
const te = useScopedT("editor");
const document = useProjectStore((s) => s.document);
const projectId = useProjectStore((s) => s.projectId);
- const currentTimeSec = useProjectStore((s) => s.currentTimeSec);
const dirty = useProjectStore((s) => s.dirty);
const createProject = useProjectStore((s) => s.createProject);
const addAsset = useProjectStore((s) => s.addAsset);
@@ -138,9 +168,6 @@ export function NewEditorShell() {
void primaryAssetPath;
const clips: AxcutClip[] = document?.timeline.clips ?? [];
const visibleClips = useMemo(() => (document ? resolveVisibleClips(document) : []), [document]);
- // visibleClips = trim-compressed native stream; `clips` = RAW layout currentTimeSec
- // is measured against. resolveNativePosition needs both (see timelineMap).
- useNativePlaybackSync(playing, currentTimeSec, visibleClips, clips);
const hasProject = Boolean(document);
const hasAsset = projectId !== null && (document?.assets.length ?? 0) > 0;
const project = document?.project
@@ -368,13 +395,12 @@ export function NewEditorShell() {
[tl, clips.length],
);
- // Refs so the 'ended' listener below always sees the latest clips/playhead without
- // tearing down and re-registering the DOM listener on every rAF-driven currentTimeSec
- // update (which would happen every tick during playback if they were plain deps).
+ // Ref so the 'ended' listener below always sees the latest clips without tearing
+ // down and re-registering the DOM listener on every document change. (The playhead
+ // it also needs is read straight off the store at call time — see NativePlaybackSync
+ // above for why nothing in this component subscribes to it.)
const clipsForEndedRef = useRef(clips);
clipsForEndedRef.current = clips;
- const currentTimeSecRef = useRef(currentTimeSec);
- currentTimeSecRef.current = currentTimeSec;
// ponytail: the transport bar (play/pause, prev/next, loop, fullscreen)
// lives in the timeline header now, not under the preview canvas — it
@@ -395,9 +421,8 @@ export function NewEditorShell() {
// suivant ?" déjà utilisé par handleNextClip juste au-dessus — seul point de
// vérité pour "y a-t-il encore de la timeline à jouer".
const onEnded = () => {
- const hasNextClip = clipsForEndedRef.current.some(
- (c) => c.timelineStartSec > currentTimeSecRef.current + 0.1,
- );
+ const playhead = useProjectStore.getState().currentTimeSec;
+ const hasNextClip = clipsForEndedRef.current.some((c) => c.timelineStartSec > playhead + 0.1);
if (!hasNextClip) setPlaying(false);
};
el.addEventListener("play", onPlay);
@@ -425,25 +450,27 @@ export function NewEditorShell() {
const handlePrevClip = useCallback(() => {
if (clips.length === 0) return;
// ponytail: navigate in virtual timeline space, not source-media time.
+ const playhead = useProjectStore.getState().currentTimeSec;
let prevStart = 0;
for (let i = clips.length - 1; i >= 0; i--) {
const c = clips[i];
- if (c.timelineEndSec <= currentTimeSec - 0.1) {
+ if (c.timelineEndSec <= playhead - 0.1) {
prevStart = c.timelineStartSec;
break;
}
}
handleSeek(prevStart);
handleTimeChange(prevStart);
- }, [clips, currentTimeSec, handleSeek, handleTimeChange]);
+ }, [clips, handleSeek, handleTimeChange]);
const handleNextClip = useCallback(() => {
if (clips.length === 0) return;
- const next = clips.find((c) => c.timelineStartSec > currentTimeSec + 0.1);
+ const playhead = useProjectStore.getState().currentTimeSec;
+ const next = clips.find((c) => c.timelineStartSec > playhead + 0.1);
if (!next) return;
handleSeek(next.timelineStartSec);
handleTimeChange(next.timelineStartSec);
- }, [clips, currentTimeSec, handleSeek, handleTimeChange]);
+ }, [clips, handleSeek, handleTimeChange]);
const handleTranscribe = useCallback(async () => {
if (!document || !document.project.primaryAssetId) return;
@@ -701,7 +728,7 @@ export function NewEditorShell() {
const { pasteClipboard } = await import("@/lib/ai-edition/store/regionClipboard");
const clip = pasteClipboard();
if (!clip) return;
- const timeMs = Math.round(currentTimeSec * 1000);
+ const timeMs = Math.round(useProjectStore.getState().currentTimeSec * 1000);
const region = { ...clip.region, id: crypto.randomUUID() };
if (clip.kind === "zoom") {
const zoom = region as unknown as (typeof doc.zoomRanges)[number];
@@ -731,7 +758,7 @@ export function NewEditorShell() {
});
}
toast.success("Region pasted");
- }, [currentTimeSec, saveDocument]);
+ }, [saveDocument]);
const handleCopyRegion = useCallback(async () => {
const doc = useProjectStore.getState().document;
@@ -963,7 +990,8 @@ export function NewEditorShell() {
e.preventDefault();
const frameStepSec = 1 / 60;
const direction = e.key === "ArrowLeft" ? -1 : 1;
- handleSeek(Math.max(0, currentTimeSec + direction * frameStepSec));
+ const playhead = useProjectStore.getState().currentTimeSec;
+ handleSeek(Math.max(0, playhead + direction * frameStepSec));
return;
}
};
@@ -983,7 +1011,6 @@ export function NewEditorShell() {
isMac,
togglePlay,
handleSeek,
- currentTimeSec,
]);
const showTimeline = mode !== "rec";
@@ -1046,7 +1073,6 @@ export function NewEditorShell() {
assets: document?.assets ?? [],
trimRanges: document?.timeline?.trimRanges ?? [],
busy: isTranscribing,
- currentTimeSec,
onSeek: handleSeek,
onAddTrimRange: handleAddTrimRange,
onRemoveTrimRange: handleRemoveTrimRange,
@@ -1060,6 +1086,7 @@ export function NewEditorShell() {
className={v4.app}
style={{ gridTemplateRows: `58px 1fr ${showTimeline ? timelineRow : "0px"}` }}
>
+ <NativePlaybackSync visibleClips={visibleClips} clips={clips} />
<EditorTopBar
mode={mode}
onModeChange={setMode}
@@ -1161,7 +1188,6 @@ export function NewEditorShell() {
onSeek={handleSeek}
onLoadedMetadata={handleLoadedMetadata}
onVideoElement={setVideoElement}
- currentTimeSec={currentTimeSec}
playing={playing}
/>
</div>
@@ -1214,7 +1240,6 @@ export function NewEditorShell() {
) : null}
<V4Timeline
tl={tl}
- currentTimeSec={currentTimeSec}
setCurrentTime={handleSeek}
variant={mode === "media" ? "media" : "edit"}
onDropAsset={handleDropAsset}
diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsx
index 057be3680..65751b93c 100644
--- a/src/components/ai-edition/Preview.tsx
+++ b/src/components/ai-edition/Preview.tsx
@@ -7,6 +7,7 @@ import type {
AxcutTrimRange,
AxcutZoomRegion,
} from "@/lib/ai-edition/schema";
+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import type { SpeedRegion } from "@/lib/ai-edition/timeline/speed";
import { EditorEmptyState } from "./EditorEmptyState";
import styles from "./NewEditorShell.module.css";
@@ -38,7 +39,6 @@ interface PreviewProps {
onSeek: (sec: number) => void;
onLoadedMetadata: (sec: number, assetId: string) => void;
onVideoElement: (el: HTMLVideoElement | null) => void;
- currentTimeSec: number;
// ponytail: the transport bar (play/pause, prev/next, loop, scrub) moved
// into the timeline header (Bottombar), so playback state now lives in
// the parent shell — Preview only needs `playing` to report it on the
@@ -70,10 +70,16 @@ export function Preview({
onSeek,
onLoadedMetadata,
onVideoElement,
- currentTimeSec,
playing,
}: PreviewProps) {
const te = useScopedT("editor");
+ // Subscribed HERE rather than passed down from NewEditorShell: the playhead is
+ // rewritten every animation frame during playback, and reading it in the shell
+ // re-rendered the whole editor (timeline included) once per frame — see
+ // NativePlaybackSync in NewEditorShell.tsx. The preview subtree genuinely has to
+ // re-render at that rate (annotations, captions, crop, Full Camera all animate
+ // against it); the timeline does not.
+ const currentTimeSec = useProjectStore((s) => s.currentTimeSec);
// ponytail: when the <video> fails to load (e.g. a truncated recording
// from a bad MediaRecorder capture), swap to the empty state so the user
// can import a different file instead of staring at a broken preview.
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 5b68d84a3..c26cf1662 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -17,6 +17,7 @@ import {
import {
type ChangeEvent,
type FormEvent,
+ memo,
type ClipboardEvent as ReactClipboardEvent,
type KeyboardEvent as ReactKeyboardEvent,
type ReactNode,
@@ -505,7 +506,6 @@ export function TranscriptPane({
assets,
trimRanges,
busy,
- currentTimeSec,
onSeek,
onAddTrimRange,
onRemoveTrimRange,
@@ -518,7 +518,6 @@ export function TranscriptPane({
assets: AxcutAsset[];
trimRanges: AxcutTrimRange[];
busy: boolean;
- currentTimeSec: number;
onSeek: (sec: number) => void;
onAddTrimRange: (assetId: string, startSec: number, endSec: number, reason: string) => void;
onRemoveTrimRange: (trimId: string) => void;
@@ -527,6 +526,13 @@ export function TranscriptPane({
isTranscribing: boolean;
}) {
const ts = useScopedT("settings");
+ // Subscribed here, not passed down: the playhead is rewritten every animation
+ // frame during playback, and reading it in NewEditorShell re-rendered the whole
+ // editor (timeline included) once per frame — see NativePlaybackSync there. Only
+ // the cue word derived below actually moves, and `TranscriptClipBlock` is memoised
+ // on `cueWordId`, so a frame that doesn't cross a word boundary re-renders nothing
+ // but this component's own (cheap) lookup.
+ const currentTimeSec = useProjectStore((s) => s.currentTimeSec);
const sections = useMemo(
() => buildAggregatedSections(clips, transcripts, assets, trimRanges),
[clips, transcripts, assets, trimRanges],
@@ -618,7 +624,14 @@ export function TranscriptPane({
// word inside the clip's source range, color-coded by whether the word
// is inside any trimRange. Backspace/Delete adds a new trimRange via
// onAddTrimRange; hover-bin on a skip run removes it via onRemoveTrimRange.
-function TranscriptClipBlock({
+//
+// `memo` matters here: this renders one DOM node per transcript word, and its
+// parent now re-renders on every playhead tick (~60×/s during playback). The only
+// prop that actually moves with the playhead is `cueWordId`, which changes at word
+// boundaries — a few times per second, not sixty. Without the memo, every frame
+// would re-render the entire word stream, and React commits all pending updates in
+// one pass, so that cost would land on the playhead's own commit too.
+const TranscriptClipBlock = memo(function TranscriptClipBlock({
index,
section,
busy,
@@ -942,7 +955,7 @@ function TranscriptClipBlock({
)}
</span>
);
-}
+});
// One word inside the editable block. Kept words render plain; removed
// words (inside a skip range) render red+strikethrough with a hover bin.
diff --git a/src/components/ai-edition/TransportBar.test.tsx b/src/components/ai-edition/TransportBar.test.tsx
new file mode 100644
index 000000000..fa155430d
--- /dev/null
+++ b/src/components/ai-edition/TransportBar.test.tsx
@@ -0,0 +1,94 @@
+import "@testing-library/jest-dom";
+import { act, cleanup, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { I18nProvider } from "@/contexts/I18nContext";
+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
+import { TransportBar } from "./TransportBar";
+
+vi.mock("@/native/client", () => ({
+ nativeBridgeClient: { aiEdition: {} },
+}));
+
+const clips = [
+ {
+ id: "clip_a",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 30,
+ timelineStartSec: 0,
+ timelineEndSec: 30,
+ wordRefs: [],
+ origin: "user" as const,
+ reason: "",
+ },
+];
+
+const noop = vi.fn();
+
+describe("TransportBar reads the playhead from the store", () => {
+ beforeEach(() => {
+ useProjectStore.setState({ currentTimeSec: 0 });
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ });
+
+ // The counterpart to useTimeline.test.ts's "not re-rendered by playhead ticks":
+ // now that the editor shell no longer subscribes to the playhead, the pieces that
+ // DO display it have to pick it up themselves. Nothing here re-renders the parent
+ // — the store write alone must move the timecode.
+ it("updates the timecode on a store write, with no parent re-render", () => {
+ let parentRenders = 0;
+ function Parent() {
+ parentRenders++;
+ return (
+ <TransportBar
+ playing={false}
+ overrideTimeSec={null}
+ clips={clips}
+ onTogglePlay={noop}
+ onPrevClip={noop}
+ onNextClip={noop}
+ onSeek={noop}
+ />
+ );
+ }
+
+ render(
+ <I18nProvider>
+ <Parent />
+ </I18nProvider>,
+ );
+ const rendersAfterMount = parentRenders;
+ expect(screen.getByText("0:00.0")).toBeInTheDocument();
+
+ act(() => {
+ useProjectStore.getState().setCurrentTime(12.3);
+ });
+
+ expect(screen.getByText("0:12.3")).toBeInTheDocument();
+ expect(parentRenders).toBe(rendersAfterMount);
+ });
+
+ // A timeline scrub drag writes the store on a rAF, so for the frame in between the
+ // pointer position is only in `overrideTimeSec` — it has to win over the store.
+ it("prefers the live scrub override over the store value", () => {
+ useProjectStore.setState({ currentTimeSec: 12.3 });
+ render(
+ <I18nProvider>
+ <TransportBar
+ playing={false}
+ overrideTimeSec={4.5}
+ clips={clips}
+ onTogglePlay={noop}
+ onPrevClip={noop}
+ onNextClip={noop}
+ onSeek={noop}
+ />
+ </I18nProvider>,
+ );
+ expect(screen.getByText("0:04.5")).toBeInTheDocument();
+ });
+});
diff --git a/src/components/ai-edition/TransportBar.tsx b/src/components/ai-edition/TransportBar.tsx
index dc36a93c6..fa017ff13 100644
--- a/src/components/ai-edition/TransportBar.tsx
+++ b/src/components/ai-edition/TransportBar.tsx
@@ -2,6 +2,7 @@ import { Pause, Play, SkipBack, SkipForward } from "lucide-react";
import { memo } from "react";
import { useScopedT } from "@/contexts/I18nContext";
import type { AxcutClip } from "@/lib/ai-edition/schema";
+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import styles from "./NewEditorShell.module.css";
function formatTC(sec: number): string {
@@ -13,7 +14,8 @@ function formatTC(sec: number): string {
interface TransportBarProps {
playing: boolean;
- currentTimeSec: number;
+ /** Live scrub position while a timeline drag is in flight; null = follow the store. */
+ overrideTimeSec: number | null;
clips: AxcutClip[];
onTogglePlay: () => void;
onPrevClip: () => void;
@@ -25,7 +27,7 @@ interface TransportBarProps {
// so the header row covers both timeline tools and playback in one line.
export const TransportBar = memo(function TransportBar({
playing,
- currentTimeSec,
+ overrideTimeSec,
clips,
onTogglePlay,
onPrevClip,
@@ -33,6 +35,12 @@ export const TransportBar = memo(function TransportBar({
onSeek,
}: TransportBarProps) {
const te = useScopedT("editor");
+ // Same reason as PlayheadOverlay (see V4Timeline.tsx): the timecode and the
+ // scrub thumb are animated during playback, so they subscribe to the playhead
+ // directly instead of forcing V4Timeline — and the whole editor shell above it —
+ // to re-render once per frame to hand it down as a prop.
+ const storeTimeSec = useProjectStore((s) => s.currentTimeSec);
+ const currentTimeSec = overrideTimeSec ?? storeTimeSec;
const virtualDurationSec = clips.reduce(
(acc, c) => acc + (c.timelineEndSec - c.timelineStartSec),
0,
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index 1cbab2988..b56c41fd2 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -74,18 +74,40 @@ function fmtTick(sec: number): string {
}
interface PlayheadOverlayProps {
- pct: number;
+ /** Full timeline length in seconds — the denominator for the playhead's percentage. */
+ totalSec: number;
+ /** Live scrub position, when a drag is in flight. Takes precedence over the store. */
+ overrideTimeSec: number | null;
canvasStyle: React.CSSProperties;
onPointerDown: (e: ReactPointerEvent) => void;
playheadRef?: React.MutableRefObject<HTMLDivElement | null>;
}
+/**
+ * The playhead reads `currentTimeSec` from the store ITSELF instead of taking it
+ * as a prop from V4Timeline.
+ *
+ * It is the only animated element on the timeline — everything around it (clips,
+ * waveforms, ruler, lane pills) is static during playback. Threading the playhead
+ * position down as a prop meant V4Timeline (and, above it, NewEditorShell) had to
+ * re-render on every one of the ~60 store writes per second that playback
+ * produces, just to move this one line: React had to render and commit the whole
+ * editor before the playhead's DOM node moved, and any frame where that took
+ * longer than ~16 ms showed up as visible playhead stutter.
+ *
+ * Subscribing here instead keeps the per-frame re-render confined to these three
+ * nodes. `memo` then stops the surrounding timeline's own re-renders (zoom/pan,
+ * clip edits) from re-rendering it for no reason.
+ */
const PlayheadOverlay = memo(function PlayheadOverlay({
- pct,
+ totalSec,
+ overrideTimeSec,
canvasStyle,
onPointerDown,
playheadRef,
}: PlayheadOverlayProps) {
+ const storeTimeSec = useProjectStore((s) => s.currentTimeSec);
+ const pct = ((overrideTimeSec ?? storeTimeSec) / totalSec) * 100;
return (
<div className={styles.tlPlayheadLayer} aria-hidden>
<div className={styles.tlCanvas} style={canvasStyle}>
@@ -200,7 +222,6 @@ interface LanePill {
export function V4Timeline({
tl,
- currentTimeSec,
setCurrentTime,
variant = "edit",
onDropAsset,
@@ -212,7 +233,6 @@ export function V4Timeline({
onEditClip,
}: {
tl: TimelineApi;
- currentTimeSec: number;
setCurrentTime: (sec: number) => void;
variant?: "edit" | "media";
onDropAsset?: (assetId: string) => void;
@@ -353,8 +373,11 @@ export function V4Timeline({
return out;
}, [total]);
+ // Live scrub position. The store write behind it is rAF-throttled (see
+ // seekToClientX), so this keeps the playhead and the timecode pinned to the
+ // pointer for the frame the store hasn't caught up on yet. Handed down as an
+ // override to the two components that read the playhead from the store.
const [scrubbingTimeSec, setScrubbingTimeSec] = useState<number | null>(null);
- const effectiveTimeSec = scrubbingTimeSec ?? currentTimeSec;
const rafSeekRef = useRef<number>(0);
const pendingSeekTimeRef = useRef<number | null>(null);
@@ -1170,7 +1193,7 @@ export function V4Timeline({
)}
<TransportBar
playing={playing}
- currentTimeSec={effectiveTimeSec}
+ overrideTimeSec={scrubbingTimeSec}
clips={clips}
onTogglePlay={onTogglePlay}
onPrevClip={onPrevClip}
@@ -1341,7 +1364,8 @@ export function V4Timeline({
same zoom/pan transform + width as the canvases, so its line stays
continuous from the ruler down through the clips and its head aligns. */}
<PlayheadOverlay
- pct={pctOf(effectiveTimeSec)}
+ totalSec={total}
+ overrideTimeSec={scrubbingTimeSec}
canvasStyle={canvasStyle}
onPointerDown={startScrub}
playheadRef={playheadElRef}
diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.ts
index 7131f3c27..ae57345ec 100644
--- a/src/lib/ai-edition/store/useTimeline.test.ts
+++ b/src/lib/ai-edition/store/useTimeline.test.ts
@@ -1,5 +1,6 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { AxcutDocument } from "../schema";
import { useProjectStore } from "./projectStore";
import { useTimeline } from "./useTimeline";
@@ -524,3 +525,69 @@ describe("useTimeline zoom modifiers (rotation + focus mode)", () => {
});
});
});
+
+// Regression guard for the playhead-stutter fix. `currentTimeSec` is rewritten on
+// every animation frame during playback, and `useTimeline()` is called by the editor
+// shell — so subscribing to the playhead here re-rendered the entire editor (timeline,
+// clips, waveforms, inspector) 60×/s, which is exactly what made the playhead itself
+// stutter. The hook must read the playhead imperatively: zero re-renders per tick, but
+// still the LIVE value at the moment an action fires.
+describe("useTimeline is not re-rendered by playhead ticks", () => {
+ beforeEach(() => {
+ useProjectStore.getState().clear();
+ for (const mock of Object.values(bridgeMocks)) mock.mockReset();
+ bridgeMocks.save.mockImplementation(async (doc: typeof sampleDoc) => ({
+ success: true,
+ document: doc,
+ }));
+ useProjectStore.setState({
+ projectId: "proj_test",
+ // The shared `sampleDoc` fixture predates a few schema fields (see the
+ // "Typecheck (tests)" ratchet in ci.yml); cast rather than add one more
+ // error to that backlog.
+ document: sampleDoc as unknown as AxcutDocument,
+ revision: 1,
+ status: "ready",
+ error: null,
+ currentTimeSec: 0,
+ });
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("does not re-render across a second of 60 Hz playhead writes", () => {
+ let renders = 0;
+ renderHook(() => {
+ renders++;
+ return useTimeline();
+ });
+ const baseline = renders;
+
+ // One act() per write: a single batched act() would collapse all 60 into one
+ // React pass and hide the very thing this asserts.
+ for (let i = 1; i <= 60; i++) {
+ act(() => {
+ useProjectStore.getState().setCurrentTime(i / 60);
+ });
+ }
+
+ expect(renders - baseline).toBe(0);
+ expect(useProjectStore.getState().currentTimeSec).toBeCloseTo(1);
+ });
+
+ it("still anchors a new region at the live playhead", async () => {
+ const { result } = renderHook(() => useTimeline());
+ act(() => {
+ useProjectStore.getState().setCurrentTime(4.2);
+ });
+ await act(async () => {
+ await result.current.addZoom();
+ });
+ expect(useProjectStore.getState().document?.zoomRanges.at(-1)).toMatchObject({
+ startMs: 4200,
+ endMs: 6200,
+ });
+ });
+});
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index cf824b787..4d430c886 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -64,10 +64,29 @@ function patchPillById<T extends { id: string; startMs: number; endMs: number }>
return regions.map((r) => (under.has(r.id) ? { ...r, ...patch } : r));
}
+/**
+ * Playhead position at CALL time, read imperatively — deliberately not a
+ * subscription.
+ *
+ * `currentTimeSec` is rewritten on every animation frame during playback (see
+ * VirtualPreview's rAF tick). Subscribing to it here would give this hook's
+ * return value a new identity 60×/s and re-render every consumer with it — and
+ * `useTimeline()` is called by the editor shell, so that meant re-rendering the
+ * whole editor (timeline, clips, waveforms, inspector) once per frame just to
+ * move the playhead a few pixels. That render cascade was the playhead's own
+ * stutter: React had to commit the entire tree before the playhead's DOM moved.
+ *
+ * Nothing in this hook RENDERS the playhead — the add* actions below only need
+ * its value at the instant the user fires them, which is exactly what a
+ * getState() read gives (and is strictly fresher than a captured render value).
+ */
+function playheadSec(): number {
+ return useProjectStore.getState().currentTimeSec;
+}
+
export function useTimeline() {
const document = useProjectStore((s) => s.document);
const projectId = useProjectStore((s) => s.projectId);
- const currentTimeSec = useProjectStore((s) => s.currentTimeSec);
const saveDocument = useProjectStore((s) => s.saveDocument);
const setDocument = useProjectStore((s) => s.setDocument);
const [selection, setSelection] = useState<RegionHandle | null>(null);
@@ -136,7 +155,7 @@ export function useTimeline() {
// clip; the ruler renders them as one pill because their properties are equal.
const addZoom = useCallback(async () => {
if (!document) return;
- const timeMs = Math.round(currentTimeSec * 1000);
+ const timeMs = Math.round(playheadSec() * 1000);
const anchored = anchorRegionsWithDerivedMs(
[
{
@@ -156,7 +175,7 @@ export function useTimeline() {
zoomRanges: [...document.zoomRanges, ...anchored] as AxcutDocument["zoomRanges"],
};
await saveDocument(next);
- }, [document, currentTimeSec, saveDocument]);
+ }, [document, saveDocument]);
// Append several auto-generated zoom regions in one save (auto-enhance).
// Suggestions come from buildAutoZoomSuggestions, which already reserves
@@ -198,11 +217,8 @@ export function useTimeline() {
// straight into startSec (as before) only happened to be right for an
// identity single-clip project — for trimmed/reordered clips it landed
// the trim at the wrong source position.
- const resolved = resolveTimelineSpanToTrim(
- currentTimeSec,
- currentTimeSec + 2,
- document.timeline.clips,
- );
+ const playhead = playheadSec();
+ const resolved = resolveTimelineSpanToTrim(playhead, playhead + 2, document.timeline.clips);
const asset =
document.assets.find((a) => a.id === document.project.primaryAssetId) ?? document.assets[0];
if (!resolved && !asset) return;
@@ -215,8 +231,8 @@ export function useTimeline() {
{
id: createId("trim"),
assetId: resolved?.assetId ?? asset!.id,
- startSec: resolved?.sourceStartSec ?? currentTimeSec,
- endSec: resolved?.sourceEndSec ?? currentTimeSec + 2,
+ startSec: resolved?.sourceStartSec ?? playhead,
+ endSec: resolved?.sourceEndSec ?? playhead + 2,
reason: "manual",
origin: "user" as const,
},
@@ -224,11 +240,11 @@ export function useTimeline() {
},
};
await saveDocument(next);
- }, [document, currentTimeSec, saveDocument]);
+ }, [document, saveDocument]);
const addAnnotation = useCallback(async () => {
if (!document) return;
- const timeMs = Math.round(currentTimeSec * 1000);
+ const timeMs = Math.round(playheadSec() * 1000);
const ann: AnnotationRegion = {
id: createId("ann"),
startMs: timeMs,
@@ -267,11 +283,11 @@ export function useTimeline() {
const newId = created[0]?.id ?? ann.id;
setMultiSelection([{ kind: "annotation", id: newId }]);
setSelection({ kind: "annotation", id: newId });
- }, [document, currentTimeSec, saveDocument]);
+ }, [document, saveDocument]);
const addSpeed = useCallback(async () => {
if (!document) return;
- const timeMs = Math.round(currentTimeSec * 1000);
+ const timeMs = Math.round(playheadSec() * 1000);
const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};
const prev = (legacy.speedRegions as unknown[]) ?? [];
const next: AxcutDocument = {
@@ -289,13 +305,13 @@ export function useTimeline() {
},
};
await saveDocument(next);
- }, [document, currentTimeSec, saveDocument]);
+ }, [document, saveDocument]);
// Full Camera: a plain time span (no value) during which the preview/export
// grows the webcam overlay to (almost) fill the canvas and eases it back.
const addCameraFullscreen = useCallback(async () => {
if (!document) return;
- const timeMs = Math.round(currentTimeSec * 1000);
+ const timeMs = Math.round(playheadSec() * 1000);
const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};
const prev = (legacy.cameraFullscreenRegions as unknown[]) ?? [];
const next: AxcutDocument = {
@@ -313,7 +329,7 @@ export function useTimeline() {
},
};
await saveDocument(next);
- }, [document, currentTimeSec, saveDocument]);
+ }, [document, saveDocument]);
// Like updateTrimRange but also re-attaches the trim to a (possibly
// different) asset — needed when a trim is dragged across a clip boundary
diff --git a/tests/e2e/v4-shell.spec.ts b/tests/e2e/v4-shell.spec.ts
index 123f812f2..919928105 100644
--- a/tests/e2e/v4-shell.spec.ts
+++ b/tests/e2e/v4-shell.spec.ts
@@ -148,4 +148,58 @@ test.describe("v4 editor shell", () => {
await zoom(40);
await expect.poll(widthPct).toBe(2);
});
+
+ // The playhead reads `currentTimeSec` off the project store itself rather than
+ // receiving it as a prop from the editor shell, so that playback (which rewrites
+ // it ~60×/s) no longer re-renders the whole editor to move one line — see
+ // PlayheadOverlay in V4Timeline.tsx. This covers both directions of that: a bare
+ // store write must move it, and a scrub drag must still drive it and the store.
+ test("the playhead follows both a store write and a scrub drag", async ({ page }) => {
+ await seedAndOpen(page);
+
+ // `left` is a percentage of the 600 s fixture timeline. Addressed by position
+ // in the overlay rather than by class: `tlPlayhead`, `tlPlayheadLayer` and
+ // `tlPlayheadDiamond` all share a `[class*=]` prefix.
+ const playhead = page.locator('[class*="tlPlayheadLayer"] > [class*="tlCanvas"] > div');
+ const leftPct = () =>
+ playhead.evaluate((el) => Number.parseFloat((el as HTMLElement).style.left));
+ const storeTimeSec = () =>
+ page.evaluate(
+ () =>
+ (
+ window as unknown as {
+ __osProjectStore: { getState: () => { currentTimeSec: number } };
+ }
+ ).__osProjectStore.getState().currentTimeSec,
+ );
+
+ expect(await leftPct()).toBe(0);
+
+ // Nothing re-renders the shell here — the store write alone has to move it.
+ await page.evaluate(() =>
+ (
+ window as unknown as {
+ __osProjectStore: { getState: () => { setCurrentTime: (s: number) => void } };
+ }
+ ).__osProjectStore
+ .getState()
+ .setCurrentTime(300),
+ );
+ await expect.poll(leftPct).toBeCloseTo(50, 1);
+ await expect(page.getByRole("toolbar", { name: /playback/i })).toContainText("5:00.0");
+
+ // Scrub: press at 25% of the timeline canvas, drag to 75%, release. The
+ // playhead tracks the pointer and the store lands on the release position.
+ const canvas = page.locator('[class*="tlTracks"] [class*="tlCanvas"]').first();
+ const box = await canvas.boundingBox();
+ if (!box) throw new Error("timeline canvas has no bounding box");
+ const y = box.y + box.height / 2;
+ await page.mouse.move(box.x + box.width * 0.25, y);
+ await page.mouse.down();
+ await expect.poll(leftPct).toBeCloseTo(25, 0);
+ await page.mouse.move(box.x + box.width * 0.75, y, { steps: 8 });
+ await page.mouse.up();
+ await expect.poll(leftPct).toBeCloseTo(75, 0);
+ expect(await storeTimeSec()).toBeGreaterThan(400);
+ });
});