Skip to content

Open source CapCut alternative.

TypeScript

feat(site): take the preview frame loop out of React

David Lee9cce9729481
diff --git a/site/src/cut/components/AssetRefs.tsx b/site/src/cut/components/AssetRefs.tsx
index e31bd62e..59ed7d86 100644
--- a/site/src/cut/components/AssetRefs.tsx
+++ b/site/src/cut/components/AssetRefs.tsx
@@ -16,6 +16,7 @@ import { useInView } from "@/cut/hooks/useInView";
import { revealRef } from "@/cut/lib/refReveal";
import { formatTime } from "@/cut/lib/time";
import { clipLen, getClipSpans, useEditor } from "@/cut/lib/store";
+import { playheadAt } from "@/cut/lib/playhead";
import { AudioPillSurface } from "@/cut/components/AudioPanel";
import { ScrubValue, parseTimeInput } from "@/cut/components/ScrubValue";
import { Slider } from "@/components/ui/slider";
@@ -507,7 +508,7 @@ function RefChip({
function playheadMoment(ref: AssetRef): number | null {
if (ref.scope !== "clip" && ref.scope !== "project") return null;
const s = useEditor.getState();
- const now = s.currentTime;
+ const now = playheadAt();
const sp = getClipSpans(s.clips, s.assets).find(
(x) =>
now >= x.start &&
diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsx
index 3abf9a30..ae6fdf15 100644
--- a/site/src/cut/components/AudioPanel.tsx
+++ b/site/src/cut/components/AudioPanel.tsx
@@ -50,6 +50,7 @@ import { genPulseOverlay, useGenNotify } from "@/cut/lib/genNotify";
import { enrichAsset } from "@/cut/lib/media";
import { usePreviewAudio } from "@/cut/lib/previewAudio";
import { useEditor } from "@/cut/lib/store";
+import { playheadAt } from "@/cut/lib/playhead";
import { formatTime } from "@/cut/lib/time";
import { NoCreditsError, synthesizeSpeech } from "@/cut/lib/tts";
import { useLocalPref } from "@/cut/lib/uiState";
@@ -385,7 +386,7 @@ function VoiceGenerator({ projectId }: { projectId: string }) {
const settle = useGenNotify.getState().begin("audio");
setError(null);
try {
- const playhead = useEditor.getState().currentTime;
+ const playhead = playheadAt();
// Label with the spoken line, not just its first words, so the preview
// fills across the row (each surface truncates to its own width). Collapse
// whitespace and cap it so project.json stays lean.
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 4fc9cfef..b29e75c9 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -46,6 +46,7 @@ import {
storedAssets,
useEditor,
} from "@/cut/lib/store";
+import { playheadAt, skimAt } from "@/cut/lib/playhead";
import type { MediaAsset } from "@/cut/lib/types";
import { AiPanel } from "./AiPanel";
import { ExportDialog } from "./ExportDialog";
@@ -274,7 +275,7 @@ export function Editor({
const version = res.headers.get("x-cut-doc-version");
const showing = loadedDocVersion(projectId);
if (version && showing && version !== showing) {
- const at = useEditor.getState().currentTime;
+ const at = playheadAt();
await useEditor.getState().loadProject(projectId, { inPlace: true });
for (const asset of useEditor.getState().assets) void enrichAsset(asset);
useEditor.getState().seek(at);
@@ -763,7 +764,7 @@ export function Editor({
if (e.code === "Space" && !controlFocused) {
e.preventDefault();
- if (!s.playing && s.currentTime >= projectDuration(s) - 0.01) s.seek(0);
+ if (!s.playing && playheadAt() >= projectDuration(s) - 0.01) s.seek(0);
s.setPlaying(!s.playing);
} else if (e.key === "Backspace" || e.key === "Delete") {
e.preventDefault();
@@ -782,9 +783,9 @@ export function Editor({
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "b") {
e.preventDefault();
// Cut at the skimmer when the mouse is over the timeline.
- s.splitAtPlayhead(s.skimTime ?? undefined);
+ s.splitAtPlayhead(skimAt() ?? undefined);
} else if (e.key.toLowerCase() === "s" && !e.metaKey && !e.ctrlKey) {
- s.splitAtPlayhead(s.skimTime ?? undefined);
+ s.splitAtPlayhead(skimAt() ?? undefined);
} else if (e.key.toLowerCase() === "t" && !e.metaKey && !e.ctrlKey) {
s.addOverlay();
} else if ((e.key === "ArrowLeft" || e.key === "ArrowRight") && !controlFocused) {
@@ -793,7 +794,7 @@ export function Editor({
// never pauses); paused, they step a frame — 1s with Shift — for
// precise editing.
const step = s.playing ? 1 : e.shiftKey ? 1 : 1 / 30;
- s.seek(s.currentTime + (e.key === "ArrowLeft" ? -step : step));
+ s.seek(playheadAt() + (e.key === "ArrowLeft" ? -step : step));
} else if (e.key === "Escape") {
s.select(null);
}
diff --git a/site/src/cut/components/EffectsPanel.tsx b/site/src/cut/components/EffectsPanel.tsx
index f0d4f159..9d8bd042 100644
--- a/site/src/cut/components/EffectsPanel.tsx
+++ b/site/src/cut/components/EffectsPanel.tsx
@@ -16,6 +16,7 @@ import { clearElementDrag, setElementDragData, setObjectDragImage } from "@/cut/
import { SubTabs } from "@/cut/components/SubTabs";
import { getPreviewCanvas } from "@/cut/lib/previewCanvas";
import { useEditor } from "@/cut/lib/store";
+import { usePreviewTimeEvery } from "@/cut/lib/playhead";
import { isEffectOverlay, type EffectOverlay } from "@/cut/lib/types";
import { useLocalPref } from "@/cut/lib/uiState";
import { cn } from "@/lib/utils";
@@ -134,7 +135,7 @@ function usePlayheadFrame(): string | null {
const [frame, setFrame] = useState<string | null>(() =>
lastFrame && lastFrame.project === projectId ? lastFrame.url : null
);
- const tick = useEditor((s) => Math.round(s.currentTime * 5));
+ const tick = usePreviewTimeEvery(5);
const epoch = useEditor((s) => s.loadEpoch);
const hasClips = useEditor((s) => s.clips.length > 0);
useEffect(() => {
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index bb491382..2d7a4ee2 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -44,6 +44,7 @@ import {
type OverlayLoopStyle,
} from "@donkeycut/effects-kit";
import { clipWindow, useEditor, type EditorState } from "@/cut/lib/store";
+import { usePreviewTime } from "@/cut/lib/playhead";
import { clipKeyed, clipPoseAt } from "@/cut/lib/types";
import { AnimationTiles } from "@/cut/components/AnimationTiles";
import { GenerateSubtitlesAudio } from "@/cut/components/VoicePicker";
@@ -1812,7 +1813,7 @@ function TransformRows({ overlay: o }: { overlay: Overlay }) {
const opacityCk = useSliderCheckpoint();
const scaleCk = useSliderCheckpoint();
const posCk = useSliderCheckpoint();
- const now = useEditor((s) => s.currentTime);
+ const now = usePreviewTime();
// With keys in play these rows edit the pose at the playhead rather than the
// element's resting fields — which is what makes them a track.
const keyed = hasOverlayKeys(o);
@@ -1969,7 +1970,7 @@ function localTimeOf(o: { start: number; end: number }, now: number): number {
* element or pulling those same rows.
*/
function KeyframeControls({ overlay: o }: { overlay: Overlay }) {
- const now = useEditor((s) => s.currentTime);
+ const now = usePreviewTime();
const seek = useEditor((s) => s.seek);
const st = () => useEditor.getState();
return (
@@ -2108,7 +2109,7 @@ interface MaskTarget {
function ClipTransformSection({ clip }: { clip: VideoClip }) {
const clips = useEditor((s) => s.clips);
const assets = useEditor((s) => s.assets);
- const now = useEditor((s) => s.currentTime);
+ const now = usePreviewTime();
const seek = useEditor((s) => s.seek);
const posCk = useSliderCheckpoint();
const scaleCk = useSliderCheckpoint();
@@ -2338,7 +2339,7 @@ function ClipMaskSection({ clip }: { clip: VideoClip }) {
* same contract as Transform; otherwise they edit the mask's resting fields.
*/
function MaskSection({ target }: { target: MaskTarget }) {
- const now = useEditor((s) => s.currentTime);
+ const now = usePreviewTime();
const seek = useEditor((s) => s.seek);
const posCk = useSliderCheckpoint();
const sizeCk = useSliderCheckpoint();
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index 7a3f6e5c..1244b976 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
import { startDrag } from "@/cut/lib/drag";
+import { useSkim, usePreviewTime } from "@/cut/lib/playhead";
import { useEditor } from "@/cut/lib/store";
import {
captionStyle,
@@ -36,6 +37,8 @@ import {
type StickerOverlay,
} from "@/cut/lib/types";
import { subjectMatteSnapshot } from "@/cut/lib/behindPass";
+import { stageEffectFilter, stageEffectTransform } from "@/cut/lib/effectStack";
+import { useLiveEffects } from "./StageEffects";
import { cn } from "@/lib/utils";
// Plate geometry as CSS, kept in lockstep with the export burn-in metrics.
@@ -98,20 +101,16 @@ const subtitleBoxId = (lane: number) => `subtitle-caption-${lane}`;
export function OverlayLayer({
stageWidth,
- transform,
- filter,
+ gradeAbove = null,
from = 0,
to = Infinity,
captions = true,
}: {
stageWidth: number;
- /** How a live effect moves the frame (shake, tearing) — the elements travel
- * with the picture they sit on. */
- transform?: string;
- /** The grade of every effect above these elements. An effect filters what
- * plays under it, so the ones below it wear its look and the ones above it
- * do not (see StageEffects). */
- filter?: string;
+ /** Effects on a lane shallower than this one grade and move these elements.
+ * An effect filters what plays under it, so the ones below it wear its look
+ * and the ones above it do not (see StageEffects). Null grades nothing. */
+ gradeAbove?: number | null;
/** The lanes this slice of the stack draws: [from, to). */
from?: number;
to?: number;
@@ -123,13 +122,19 @@ export function OverlayLayer({
() => allOverlays.filter((o) => laneOf(o) >= from && laneOf(o) < to),
[allOverlays, from, to]
);
- const currentTime = useEditor((s) => s.currentTime);
- const skimTime = useEditor((s) => s.skimTime);
- const playing = useEditor((s) => s.playing);
const selection = useEditor((s) => s.selection);
const aspect = useEditor((s) => s.aspect);
// Titles preview under the skimmer too (paused only), matching the canvas.
- const t = !playing && skimTime !== null ? skimTime : currentTime;
+ const t = usePreviewTime();
+ const skimTime = useSkim();
+ const live = useLiveEffects();
+ // The grade and frame motion of every effect above this slice.
+ const graded = useMemo(
+ () => (gradeAbove === null ? [] : live.filter((e) => e.lane < gradeAbove).map((e) => e.state)),
+ [live, gradeAbove]
+ );
+ const filter = stageEffectFilter(graded);
+ const transform = stageEffectTransform(graded);
const rootRef = useRef<HTMLDivElement>(null);
// Live box elements per on-screen item (titles and the subtitle caption), so
@@ -211,7 +216,7 @@ export function OverlayLayer({
// title off the playhead (e.g. focusing its text in the panel) edits it in
// isolation: it shows alone so it never stacks over whatever title is live.
// Not while scrubbing — the skimmer must still show the exact frame's titles.
- const scrubbing = !playing && skimTime !== null;
+ const scrubbing = skimTime !== null;
const sel =
selection?.kind === "overlay" ? overlays.find((o) => o.id === selection.id) : undefined;
const isolate = !!sel && !scrubbing && !(t >= sel.start && t <= sel.end);
@@ -319,11 +324,8 @@ function SubtitleCaption({
onSnapEnd: () => void;
}) {
const subtitles = useEditor((s) => s.subtitles);
- const currentTime = useEditor((s) => s.currentTime);
- const skimTime = useEditor((s) => s.skimTime);
- const playing = useEditor((s) => s.playing);
const frame = frameOf(useEditor((s) => s.aspect));
- const t = !playing && skimTime !== null ? skimTime : currentTime;
+ const t = usePreviewTime();
const cues = laneCues(subtitles, lane);
const cue = cueAt(cues, t);
diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsx
index 8d7746db..7196cca5 100644
--- a/site/src/cut/components/SubtitlesPanel.tsx
+++ b/site/src/cut/components/SubtitlesPanel.tsx
@@ -26,6 +26,7 @@ import {
import { useElapsed } from "@/cut/hooks/useElapsed";
import { useCutCaps } from "@/cut/lib/backend/hooks";
import { TIMELINE_H_MIN, useEditor } from "@/cut/lib/store";
+import { usePreviewSelector } from "@/cut/lib/playhead";
import { PLATE_PAD_X, PLATE_PAD_Y, PLATE_RADIUS, plateFill } from "@/cut/lib/textRender";
import {
FONTS,
@@ -561,10 +562,7 @@ function caretOffset(el: HTMLElement): number {
}
const CueSpan = memo(function CueSpan({ cue, gap }: { cue: SubtitleCue; gap: number }) {
- const active = useEditor((s) => {
- const t = !s.playing && s.skimTime !== null ? s.skimTime : s.currentTime;
- return t >= cue.start && t < cue.end;
- });
+ const active = usePreviewSelector((t) => t >= cue.start && t < cue.end);
const ref = useRef<HTMLSpanElement>(null);
const [focused, setFocused] = useState(false);
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index 2a3a40fd..d3d076c8 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -43,6 +43,7 @@ import { CLIP_GAP, startLaneMove, startLaneTrim, type LaneDrag } from "@/cut/lib
import { downloadMedia, ensurePeaks, importImage, importStockMusic, importStockVideo, peekEdgeFrame, requestEdgeFrame, revealMedia } from "@/cut/lib/media";
import { track0Clips, laneGapAt, sameLane, type LaneRef, clipLen, clipSpeed, footprints, getClipSpans, nextFreeStart, overlayLaneOrder, overlayLayers, projectDuration, resolveTransitions, rippleInsert, useEditor } from "@/cut/lib/store";
import type { VideoTrackPlacement } from "@/cut/lib/store";
+import { playheadAt, setSkim, skimAt, subscribePlayhead, usePlayhead, useSkim } from "@/cut/lib/playhead";
import { laneHidden, subtitleLaneCount } from "@/cut/lib/subtitles";
import { formatTime, formatTimecode } from "@/cut/lib/time";
import { EFFECT_LABELS } from "@donkeycut/effects-kit";
@@ -662,14 +663,14 @@ export function Timeline() {
menuPointer.current = { x: e.clientX, y: e.clientY };
};
window.addEventListener("pointermove", track);
- useEditor.getState().setSkimTime(frameMenu.t);
+ setSkim(frameMenu.t);
return () => {
window.removeEventListener("pointermove", track);
const p = menuPointer.current;
const r = scrollEl?.getBoundingClientRect();
const inside =
!!p && !!r && p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom;
- useEditor.getState().setSkimTime(inside ? Math.max(0, timeAt(p.x)) : null);
+ setSkim(inside ? Math.max(0, timeAt(p.x)) : null);
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- timeAt reads live refs
}, [frameMenu]);
@@ -1003,19 +1004,30 @@ export function Timeline() {
const dropTimeAt = (clientX: number) => (total <= 0 ? 0 : Math.max(0, timeAt(clientX)));
// Scrub with auto-scroll when the pointer nears the viewport edges.
+ //
+ // Both boxes are measured once, at the press. Reading a rect forces the
+ // browser to lay the page out, and a drag that measured per event paid for
+ // two layouts before it could work out what time the pointer was over.
const scrub = (e: React.PointerEvent) => {
const s = useEditor.getState();
if (s.playing) s.setPlaying(false);
- s.seek(timeAt(e.clientX));
const el = scrollRef.current;
+ const innerLeft = innerRef.current?.getBoundingClientRect().left ?? 0;
+ const view = el?.getBoundingClientRect() ?? null;
+ // The inner box travels with the scroller, so an auto-scroll shifts what
+ // a given screen x means; tracking the shift keeps the measurement true
+ // without re-reading the layout.
+ const scroll0 = el?.scrollLeft ?? 0;
+ const at = (clientX: number) =>
+ Math.max(0, (clientX - innerLeft + ((el?.scrollLeft ?? 0) - scroll0)) / pps);
+ useEditor.getState().seek(at(e.clientX));
startDrag(e, {
onMove: (_dx, _dy, ev) => {
- if (el) {
- const r = el.getBoundingClientRect();
- if (ev.clientX > r.right - 36) el.scrollLeft += 14;
- else if (ev.clientX < r.left + 36) el.scrollLeft -= 14;
+ if (el && view) {
+ if (ev.clientX > view.right - 36) el.scrollLeft += 14;
+ else if (ev.clientX < view.left + 36) el.scrollLeft -= 14;
}
- useEditor.getState().seek(timeAt(ev.clientX));
+ useEditor.getState().seek(at(ev.clientX));
},
});
};
@@ -1046,7 +1058,7 @@ export function Timeline() {
const clamped = Math.max(floor, Math.min(ZOOM_MAX, next));
if (Math.abs(clamped - cur.pxPerSec) < 0.01) return;
if (el) {
- const t = anchorT ?? cur.currentTime;
+ const t = anchorT ?? playheadAt();
const px = anchorPx ?? PAD_SIDE + t * cur.pxPerSec - el.scrollLeft;
pendingAnchor.current = { t, px };
}
@@ -1062,8 +1074,7 @@ export function Timeline() {
// The editing tools, as the toolbar button and its menu row both invoke them.
const split = useCallback(() => {
- const s = useEditor.getState();
- s.splitAtPlayhead(s.skimTime ?? undefined);
+ useEditor.getState().splitAtPlayhead(skimAt() ?? undefined);
}, []);
const addText = useCallback(() => useEditor.getState().addOverlay(), []);
const deleteSelection = useCallback(() => useEditor.getState().deleteSelection(), []);
@@ -2626,22 +2637,40 @@ function HoverLine({
* it, and the line darkens — the marker is the skimmer, held. */
hold: boolean;
}) {
- const skimTime = useEditor((s) => s.skimTime);
- useEffect(() => () => useEditor.getState().setSkimTime(null), []);
+ const skimTime = useSkim();
+ useEffect(() => () => setSkim(null), []);
useEffect(() => {
const el = scrollRef.current;
if (!el || hold) return;
+ // The inner box only moves when the timeline scrolls or zooms, so its left
+ // edge is read once per gesture instead of once per pointer event — the
+ // read forces a layout, and a scrub issues hundreds of them.
+ let left = 0;
+ let measured = false;
+ const remeasure = () => {
+ measured = false;
+ };
const move = (e: PointerEvent) => {
const inner = innerRef.current;
- const s = useEditor.getState();
- if (!inner || e.buttons) return s.setSkimTime(null);
- const t = (e.clientX - inner.getBoundingClientRect().left) / s.pxPerSec;
- s.setSkimTime(Math.max(0, t));
+ // The skimmer is a paused affordance: while the cut is playing the
+ // picture belongs to the playhead, wherever the pointer happens to rest.
+ if (!inner || e.buttons || useEditor.getState().playing) return setSkim(null);
+ if (!measured) {
+ left = inner.getBoundingClientRect().left;
+ measured = true;
+ }
+ const t = (e.clientX - left) / useEditor.getState().pxPerSec;
+ setSkim(Math.max(0, t));
};
- const leave = () => useEditor.getState().setSkimTime(null);
+ const leave = () => {
+ remeasure();
+ setSkim(null);
+ };
+ el.addEventListener("scroll", remeasure, { passive: true });
el.addEventListener("pointermove", move);
el.addEventListener("pointerleave", leave);
return () => {
+ el.removeEventListener("scroll", remeasure);
el.removeEventListener("pointermove", move);
el.removeEventListener("pointerleave", leave);
};
@@ -2837,15 +2866,19 @@ function SaveSelectionButton({ labels = true }: { labels?: boolean }) {
);
}
+/** The running time, on its own so the transport's buttons stay off the clock. */
+function Timecode() {
+ return <span className="tc-now">{formatTimecode(usePlayhead())}</span>;
+}
+
/** Playback transport, centered in the timeline toolbar. */
function Transport({ total }: { total: number }) {
const playing = useEditor((s) => s.playing);
- const currentTime = useEditor((s) => s.currentTime);
const hasClips = total > 0;
const toggle = () => {
const s = useEditor.getState();
- if (!s.playing && s.currentTime >= total - 0.01) s.seek(0);
+ if (!s.playing && playheadAt() >= total - 0.01) s.seek(0);
s.setPlaying(!s.playing);
};
@@ -2876,7 +2909,7 @@ function Transport({ total }: { total: number }) {
)}
</button>
<div className="flex min-w-30 items-baseline gap-1.5 font-mono text-xs tabular-nums">
- <span className="tc-now">{formatTimecode(currentTime)}</span>
+ <Timecode />
<span className="text-muted-foreground">/</span>
<span className="text-muted-foreground">{formatTimecode(total)}</span>
</div>
@@ -2924,14 +2957,13 @@ function Playhead({
scrollRef: React.RefObject<HTMLDivElement | null>;
onScrub: (e: React.PointerEvent) => void;
}) {
- const t = useEditor((s) => s.currentTime);
const playing = useEditor((s) => s.playing);
- const x = t * pps;
+ const ref = useRef<HTMLDivElement>(null);
// Follow the playhead while playing, but yield to the user: any manual
// scroll pauses following, which resumes after 5s of scroll idle. The
- // follow effect's own writes are told apart from user scrolls by matching
- // the scroll-event echo against the value it just wrote.
+ // follow's own writes are told apart from user scrolls by matching the
+ // scroll-event echo against the value it just wrote.
const manualUntil = useRef(0);
const followWrote = useRef<number | null>(null);
useEffect(() => {
@@ -2949,24 +2981,36 @@ function Playhead({
return () => el.removeEventListener("scroll", onScroll);
}, [scrollRef]);
+ // The marker is one transform. Rendering a component sixty times a second to
+ // write one style property costs a reconcile per frame and moves the same
+ // pixel, so the subscription writes it directly and the scroll-follow rides
+ // along in the same callback.
useEffect(() => {
- const el = scrollRef.current;
- if (!el || !playing) return;
- if (performance.now() < manualUntil.current) return;
- const sx = x + PAD_SIDE; // playhead position in scroll coordinates
- if (sx < el.scrollLeft + 24 || sx > el.scrollLeft + el.clientWidth - 80) {
- el.scrollLeft = Math.max(0, sx - 80);
- followWrote.current = el.scrollLeft; // read back: the browser clamps
- }
- }, [x, playing, scrollRef]);
+ const move = () => {
+ const el = ref.current;
+ if (!el) return;
+ const x = playheadAt() * pps;
+ el.style.transform = `translateX(${x}px)`;
+ const scroller = scrollRef.current;
+ if (!scroller || !playing) return;
+ if (performance.now() < manualUntil.current) return;
+ const sx = x + PAD_SIDE; // playhead position in scroll coordinates
+ if (sx < scroller.scrollLeft + 24 || sx > scroller.scrollLeft + scroller.clientWidth - 80) {
+ scroller.scrollLeft = Math.max(0, sx - 80);
+ followWrote.current = scroller.scrollLeft; // read back: the browser clamps
+ }
+ };
+ move();
+ return subscribePlayhead(move);
+ }, [pps, playing, scrollRef]);
return (
<div
+ ref={ref}
// Over the gutter as well as the clips: at 0 the playhead stands on the
// gutter's own edge. The clips pass under the gutter; the time it is
// showing does not. The grab cap lives in the pinned ruler.
className="pointer-events-none absolute top-0 bottom-0 left-0 z-50 w-[1.5px] bg-[#0a84ff] shadow-[0_0_8px_rgba(10,132,255,0.6)]"
- style={{ transform: `translateX(${x}px)` }}
/>
);
}
@@ -2980,11 +3024,18 @@ function PlayheadCap({
pps: number;
onScrub: (e: React.PointerEvent) => void;
}) {
- const t = useEditor((s) => s.currentTime);
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ const move = () => {
+ if (ref.current) ref.current.style.transform = `translateX(${playheadAt() * pps}px)`;
+ };
+ move();
+ return subscribePlayhead(move);
+ }, [pps]);
return (
<div
+ ref={ref}
className="tl-playhead-cap absolute top-0 left-[-7px] h-5 w-4 cursor-ew-resize"
- style={{ transform: `translateX(${t * pps}px)` }}
onPointerDown={onScrub}
>
<div className="mx-auto h-3 w-2.5 rounded-t-[3px] bg-[#0a84ff] [clip-path:polygon(0_0,100%_0,100%_58%,50%_100%,0_58%)]" />
diff --git a/site/src/cut/components/TransitionsPanel.tsx b/site/src/cut/components/TransitionsPanel.tsx
index c8d01fb3..c2d84274 100644
--- a/site/src/cut/components/TransitionsPanel.tsx
+++ b/site/src/cut/components/TransitionsPanel.tsx
@@ -7,6 +7,7 @@ import { clearElementDrag, setElementDragData, setObjectDragImage } from "@/cut/
import { peekEdgeFrame, requestEdgeFrame } from "@/cut/lib/media";
import { PICKED_RING, pickGridNav, useAssetPick } from "@/cut/lib/assetPick";
import { getClipSpans, resolveTransitions, useEditor } from "@/cut/lib/store";
+import { usePreviewTimeEvery } from "@/cut/lib/playhead";
import {
TRANSITION_STYLE_GROUPS,
TRANSITION_STYLE_LABELS,
@@ -121,7 +122,7 @@ function useCutFrames(): { a: string | null; b: string | null } {
const clips = useEditor((s) => s.clips);
const assets = useEditor((s) => s.assets);
// Re-pick the cut as the playhead crosses half-second marks.
- const tick = useEditor((s) => Math.round(s.currentTime * 2));
+ const tick = usePreviewTimeEvery(2);
const cut = useMemo(() => {
const spans = getClipSpans(clips, assets);
let best: {
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index 8ac0716b..83024096 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -4,6 +4,7 @@ import { hasOverlayAnim } from "@donkeycut/effects-kit";
import { chatOwner } from "./chatAssets";
import { useGenerate } from "./generate";
import { getClipSpans, overlayLayers, resolveTransitions, totalDuration, useEditor } from "./store";
+import { playheadAt, skimAt } from "./playhead";
import { laneCues, subtitleLaneCount } from "./subtitles";
import { watchSweepActive } from "./watch/sweep";
import { frameOf, rectOf, regionLabel, type ClipSpan, type Overlay, type VideoClip } from "./types";
@@ -122,8 +123,8 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
...(s.fadeIn > 0 ? { fadeIn: r(s.fadeIn) } : {}),
...(s.fadeOut > 0 ? { fadeOut: r(s.fadeOut) } : {}),
},
- playhead: r(s.currentTime),
- skimmer: s.skimTime === null ? null : r(s.skimTime),
+ playhead: r(playheadAt()),
+ skimmer: skimAt() === null ? null : r(skimAt()!),
playing: s.playing,
selection,
// Every project asset visible to this chat, timeline-placed or not (media
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index b75cf9f6..41a145dc 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -72,6 +72,7 @@ import { characterPrompt, stockAspectDims, stockTitle } from "./stock";
import { STOCK_IMAGES } from "./stockManifest";
import { STOCK_VIDEOS } from "./stockVideoManifest";
import { applyOverlayPatchSettled, track0Clips, laneGapAt, getClipSpans, nextFreeStart, overlayLayers, parkedTransitions, resolveTransitions, totalDuration, useEditor } from "./store";
+import { playheadAt } from "./playhead";
import { buildAiContext } from "./aiContext";
import { sampleClipFrameData } from "./previewCanvas";
import { laneCues, subtitleLaneCount } from "./subtitles";
@@ -739,7 +740,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
seek: (s, input) => {
if (!isNum(input.t)) throw new ToolError("t (seconds) is required.");
s.seek(input.t);
- return { playhead: useEditor.getState().currentTime };
+ return { playhead: playheadAt() };
},
set_playing: (s, input) => {
@@ -840,7 +841,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const asset = requireItem(s.assets, input.asset_id, "project asset");
if (asset.type !== "video" && asset.type !== "image")
throw new ToolError("Only video or image assets can sit on a video track.");
- const start = isNum(input.start) ? Math.max(0, input.start) : s.currentTime;
+ const start = isNum(input.start) ? Math.max(0, input.start) : playheadAt();
// Tracks stack bottom-up from track 0; overlays live on 1+. A stale
// negative (the old behind-track model) clamps to the first layer.
const track = isNum(input.track) ? Math.max(1, Math.round(input.track)) : 1;
@@ -1255,7 +1256,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const spans = getClipSpans(s.clips, s.assets);
if (spans.length === 0) throw new ToolError("The timeline is empty.");
const total = totalDuration(s.clips);
- const t = clamp(isNum(input.t) ? input.t : s.currentTime, 0, Math.max(0, total - 0.001));
+ const t = clamp(isNum(input.t) ? input.t : playheadAt(), 0, Math.max(0, total - 0.001));
const span = spans.find((sp) => t >= sp.start && t < sp.start + sp.len) ?? spans[spans.length - 1];
const srcTime = span.clip.in + (t - span.start);
let body: MediaAsset;
@@ -2075,7 +2076,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
voiceover_generate: (s, input) => {
if (typeof input.script !== "string" || !input.script.trim())
throw new ToolError("script is required.");
- const start = isNum(input.start) ? Math.max(0, input.start) : s.currentTime;
+ const start = isNum(input.start) ? Math.max(0, input.start) : playheadAt();
// Label with the spoken line (capped) so its preview fills across the row.
const lead = input.script.replace(/\s+/g, " ").trim().slice(0, 200);
const place = wantsTimeline(input, "start");
@@ -2149,7 +2150,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
note: "The music previews in this chat — the user can play it and drag it onto the soundtrack; pass add_to_timeline or start when they ask for it in the cut.",
};
}
- const start = isNum(input.start) ? Math.max(0, input.start) : cur.currentTime;
+ const start = isNum(input.start) ? Math.max(0, input.start) : playheadAt();
cur.addAudioFromAsset(asset.id, start);
// Sits under speech at a soft bed volume by default; the model can raise it.
const volume = isNum(input.volume) ? clamp(input.volume, 0, 1.5) : 0.4;
diff --git a/site/src/cut/lib/devHooks.ts b/site/src/cut/lib/devHooks.ts
index 7f1c1062..bf04ae33 100644
--- a/site/src/cut/lib/devHooks.ts
+++ b/site/src/cut/lib/devHooks.ts
@@ -10,6 +10,8 @@
import { useGenerate } from "./generate";
import { useGenScene } from "./genScene";
import { enrichAsset, importFileToProject } from "./media";
+import { awaitingFrame, startTrace, stopTrace } from "./perfTrace";
+import { playheadAt } from "./playhead";
import { useEditor } from "./store";
export function installDevHooks(): void {
@@ -20,5 +22,13 @@ export function installDevHooks(): void {
useGenScene,
importFileToProject,
enrichAsset,
+ playheadAt,
+ };
+ // The perf eval arms and reads the frame trace through here. Off until
+ // `start()` is called, so an ordinary dev session records nothing.
+ (window as unknown as Record<string, unknown>).__cutPerf = {
+ start: startTrace,
+ stop: stopTrace,
+ awaiting: awaitingFrame,
};
}
diff --git a/site/src/cut/lib/drag.ts b/site/src/cut/lib/drag.ts
index fb1d0fff..cebd62bb 100644
--- a/site/src/cut/lib/drag.ts
+++ b/site/src/cut/lib/drag.ts
@@ -63,17 +63,38 @@ export function startDrag(e: React.PointerEvent, opts: DragOpts) {
document.head.append(pin);
}
+ // Pointer events arrive faster than the screen can show the result — a
+ // high-rate mouse fires several times between two frames, and a trackpad
+ // delivers a burst at once. Handling each one runs the whole response (a
+ // seek, a clip move, a re-layout) for a position that is overwritten before
+ // anything is painted. Coalescing to one call per frame does the work once,
+ // for where the pointer actually ended up.
+ let latest: PointerEvent | null = null;
+ let frame = 0;
+ const flush = () => {
+ frame = 0;
+ const ev = latest;
+ if (!ev) return;
+ latest = null;
+ opts.onMove(ev.clientX - startX, ev.clientY - startY, ev);
+ holdCursor();
+ };
const move = (ev: PointerEvent) => {
const dx = ev.clientX - startX;
const dy = ev.clientY - startY;
if (Math.abs(dx) > 3 || Math.abs(dy) > 3) moved = true;
- opts.onMove(dx, dy, ev);
- holdCursor();
+ latest = ev;
+ if (!frame) frame = requestAnimationFrame(flush);
};
const up = (ev: PointerEvent) => {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
window.removeEventListener("pointercancel", up);
+ // Land the last position before the gesture ends, so a fast release
+ // finishes where the pointer was rather than one frame behind it.
+ if (frame) cancelAnimationFrame(frame);
+ frame = 0;
+ flush();
pin?.remove();
activeDrags--;
dragListeners.forEach((fn) => fn());
diff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.ts
index 8c571bba..06391a51 100644
--- a/site/src/cut/lib/laneTracks.ts
+++ b/site/src/cut/lib/laneTracks.ts
@@ -31,6 +31,7 @@ import type React from "react";
import { refFromAsset, startPointerRefDrag } from "./assetRef";
import { startDrag } from "./drag";
import { track0Clips, clipLen, getClipSpans, moveOverlayGroup, overlayLaneOrder, overlayLayers, projectDuration, useEditor } from "./store";
+import { playheadAt } from "./playhead";
import type {
AudioClip,
MediaAsset,
@@ -253,7 +254,7 @@ function snapTargets(s: S, kind: LaneKind, selfId: string): number[] {
pts.add(sp.start + sp.len);
}
pts.add(projectDuration(s));
- pts.add(s.currentTime);
+ pts.add(playheadAt());
for (const k of Object.keys(ADAPTERS) as LaneKind[]) {
for (const raw of ADAPTERS[k].raws(s)) {
const v = ADAPTERS[k].view(raw);
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index 5317367a..304c5507 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -19,6 +19,7 @@ import {
type Residency,
} from "./residency";
import { useEditor } from "./store";
+import { playheadAt } from "./playhead";
import type { LibraryTemplate, MediaAsset, TemplateMedia, TemplateSaveInput } from "./types";
import { IMAGE_CLIP_SECONDS, mediaUrl } from "./types";
@@ -428,7 +429,7 @@ export async function addTemplateToProject(
void enrichAsset(asset);
return asset.id;
});
- s.insertTemplate(template, assetIds, at ?? useEditor.getState().currentTime);
+ s.insertTemplate(template, assetIds, at ?? playheadAt());
}
/** Copy a library template into the project as a project template: its media
@@ -476,7 +477,7 @@ export function addProjectTemplateToTimeline(
void enrichAsset(asset);
return asset.id;
});
- useEditor.getState().insertTemplate(template, assetIds, at ?? useEditor.getState().currentTime);
+ useEditor.getState().insertTemplate(template, assetIds, at ?? playheadAt());
}
/** Copy a project asset into the shared library for reuse. It lands on the
diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.ts
index dda4b9cc..130c26fc 100644
--- a/site/src/cut/lib/store.test.ts
+++ b/site/src/cut/lib/store.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, test } from "bun:test";
import { groupRemap } from "@donkeycut/effects-kit";
import { adoptTransitionFields, clipLen, deriveTransitionFields, docOverlays, getClipSpans, liftClipLooks, moveOverlayGroup, overlayLaneOrder, normalizeElementLanes, parkedTransitions, placeInRun, projectDuration, reanchorTransitions, separateOverlaps, serializeDoc, useEditor } from "./store";
+import { playheadAt, setPlayhead } from "./playhead";
import { emptySubtitles } from "./types";
import type { AudioClip, MediaAsset, SubtitleCue, TextOverlay, VideoClip } from "./types";
@@ -604,11 +605,11 @@ describe("delete ripple and gaps", () => {
const far = vclip({ track: 0, start: 30, out: 4 });
useEditor.setState({ clips: [keep, far] });
s().seek(32);
- expect(s().currentTime).toBeCloseTo(32);
+ expect(playheadAt()).toBeCloseTo(32);
s().select({ kind: "clip", id: far.id });
s().deleteSelection();
- expect(s().currentTime).toBeCloseTo(projectDuration(s()));
- expect(s().currentTime).toBeLessThanOrEqual(4);
+ expect(playheadAt()).toBeCloseTo(projectDuration(s()));
+ expect(playheadAt()).toBeLessThanOrEqual(4);
});
test("an overlay left standing keeps the playhead reachable", () => {
@@ -616,7 +617,7 @@ describe("delete ripple and gaps", () => {
const late = title({ start: 6, end: 9 });
useEditor.setState({ clips: [clip], overlays: [late], audioClips: [] });
s().seek(8);
- expect(s().currentTime).toBeCloseTo(8);
+ expect(playheadAt()).toBeCloseTo(8);
});
test("removeLaneGap closes the gap on its own track only", () => {
@@ -737,7 +738,8 @@ describe("upper-track transitions", () => {
const c = vclip({ track: 1, start: 8, out: 4, assetId: av.id });
useEditor.setState({ assets: [av], clips: [spine, a, c] });
s().setClipTransition(a.id, 1);
- useEditor.setState({ selection: { kind: "clip", id: a.id }, currentTime: 4 });
+ useEditor.setState({ selection: { kind: "clip", id: a.id } });
+ setPlayhead(4);
s().splitAtPlayhead();
const halves = s().clips.filter((x) => x.track === 1 && x.id !== c.id);
expect(halves.length).toBe(2);
@@ -938,7 +940,7 @@ describe("bars and clip edges", () => {
multiSelection: [{ kind: "transition", id: bar.id }],
});
expect(s().copySelection()).toBe(true);
- useEditor.setState({ currentTime: 7.7 }); // in reach of the b|c cut at 8
+ setPlayhead(7.7); // in reach of the b|c cut at 8
expect(s().paste()).toBe(true);
expect(s().transitions.length).toBe(2);
// The paste plays that cut with the copied blend, fields and all.
@@ -962,7 +964,7 @@ describe("bars and clip edges", () => {
multiSelection: [{ kind: "transition", id: bar.id }],
});
s().copySelection();
- useEditor.setState({ currentTime: 8.2 });
+ setPlayhead(8.2);
s().paste();
// One bar on the b|c cut: the pasted wipe; the crossfade left with it.
expect(s().transitions.length).toBe(2);
@@ -983,7 +985,7 @@ describe("bars and clip edges", () => {
multiSelection: [{ kind: "transition", id: bar.id }],
});
s().copySelection();
- useEditor.setState({ currentTime: 6 }); // 2s from the cuts at 4 and 8
+ setPlayhead(6); // 2s from the cuts at 4 and 8
s().paste();
expect(s().transitions.length).toBe(2);
const pasted = s().transitions[1];
@@ -1008,7 +1010,7 @@ describe("bars and clip edges", () => {
],
});
expect(s().copySelection()).toBe(true);
- useEditor.setState({ currentTime: 8 });
+ setPlayhead(8);
expect(s().paste()).toBe(true);
const pastedClips = s().clips.filter((x) => x.id !== a.id && x.id !== b.id);
expect(pastedClips.map((x) => x.start)).toEqual([8, 11]);
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index db903c95..353de139 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -55,6 +55,7 @@ import {
import { renderMix, transcribeSamples, type CloudTranscribeSpec } from "./cloudTranscribe";
import { alignCues } from "./cueAlign";
import { useGenNotify } from "./genNotify";
+import { clampPlayhead, playheadAt, setPlayhead, setSkim } from "./playhead";
import { engineTranscribeSamples, withEngineStt } from "./localStt";
import { trackLocale } from "./subtitles";
import { ANIM_STYLE_IDS, animStyleOfTransition, clipPoseAt, emptySubtitles, frameOf, IMAGE_CLIP_SECONDS, isEffectOverlay, isStickerOverlay, MAX_SUBTITLE_LANES, mediaUrl, migrateBehindSubject, migrateLegacyTransitions, normalizeAspect, overlayAnimStyle, SPEED_FLOOR, SPEED_MIN, stampOverlayKinds, stripDefaultOverlayKinds, TRANSITION_MAX, TRANSITION_STYLE_IDS, transitionStyleOfAnim } from "./types";
@@ -180,7 +181,6 @@ export interface EditorState {
t: number;
track: "pose" | "mask";
} | null;
- currentTime: number;
playing: boolean;
/** While playing a scoped effect preview, the time playback auto-pauses at;
* null otherwise. Manual seek/play/pause clears it. */
@@ -188,8 +188,6 @@ export interface EditorState {
pxPerSec: number;
/** Timeline panel height in px (drag the panel's top border to change). */
timelineH: number;
- /** Timeline time under the mouse (the skimmer); null when off the timeline. */
- skimTime: number | null;
/** TikTok publishing metadata (caption, hashtags, sound title). */
publish: { caption: string; tags: string; soundTitle: string; handle: string };
/** Free-form maker notes: published date, source links, reminders. */
@@ -436,7 +434,6 @@ export interface EditorState {
detachAudio: () => void;
/** Split at the given time, or the playhead when omitted. */
splitAtPlayhead: (at?: number) => void;
- setSkimTime: (t: number | null) => void;
setPublish: (patch: Partial<{ caption: string; tags: string; soundTitle: string; handle: string }>) => void;
setNotes: (patch: Partial<{ text: string; publishedAt: string; links: string[] }>) => void;
/** Kick off (and poll) an on-device transcription of the current cut. */
@@ -1026,12 +1023,13 @@ function normalizeWrite(prev: EditorState, incoming: Partial<EditorState>): Part
// overflow — stretches the scroll area into empty space. Clamping here
// covers every edit that shortens anything, present and future.
if (next.clips || next.audioClips || next.overlays) {
- const total = projectDuration({
- clips: next.clips ?? prev.clips,
- audioClips: next.audioClips ?? prev.audioClips,
- overlays: next.overlays ?? prev.overlays,
- });
- if ((next.currentTime ?? prev.currentTime) > total) next = { ...next, currentTime: total };
+ clampPlayhead(
+ projectDuration({
+ clips: next.clips ?? prev.clips,
+ audioClips: next.audioClips ?? prev.audioClips,
+ overlays: next.overlays ?? prev.overlays,
+ })
+ );
}
return next;
}
@@ -1153,7 +1151,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const rest = place.shiftDown
? get().overlays.map((o) => ({ ...o, lane: (o.lane ?? 0) + 1 }))
: get().overlays;
- const t = aim.at ?? get().currentTime;
+ const t = aim.at ?? playheadAt();
const total = totalDuration(get().clips);
const taken = rest
.filter((o) => (o.lane ?? 0) === place.lane)
@@ -1193,12 +1191,10 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
selection: null,
multiSelection: [],
selectedKey: null,
- currentTime: 0,
playing: false,
previewStopAt: null,
pxPerSec: 60,
timelineH: TIMELINE_H_DEFAULT,
- skimTime: null,
publish: { caption: "", tags: "", soundTitle: "", handle: "" },
notes: { text: "", publishedAt: "", links: [] },
subtitles: emptySubtitles(),
@@ -1246,7 +1242,6 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
fadeOut: 0,
selection: null,
multiSelection: [],
- currentTime: 0,
playing: false,
previewStopAt: null,
subtitles: emptySubtitles(),
@@ -1862,7 +1857,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
push();
// Within its lane the clip slides to the next free slot at or after the
// target so it never lands on top of an existing sound.
- const want = Math.max(0, start ?? get().currentTime);
+ const want = Math.max(0, start ?? playheadAt());
const len = Math.max(MIN_LEN, asset.duration);
const lane = opts?.lane ?? 0;
const taken = footprints(get().audioClips.filter((a) => (a.lane ?? 0) === lane));
@@ -1969,7 +1964,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
// people mean: dropped anywhere over one, it opens covering that clip.
// Off the end of the cut it falls back to the standard length.
const s0 = get();
- const t = aim?.at ?? s0.currentTime;
+ const t = aim?.at ?? playheadAt();
const span = getClipSpans(s0.clips, s0.assets).find(
(sp) => t >= sp.start - 1e-6 && t < sp.start + sp.len
);
@@ -2662,8 +2657,8 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
},
splitAtPlayhead: (at) => {
- const { clips, audioClips, assets, currentTime, selection } = get();
- const t = at ?? currentTime;
+ const { clips, audioClips, assets, selection } = get();
+ const t = at ?? playheadAt();
// With a soundtrack clip selected, ⌘B slices it instead.
if (selection?.kind === "audio") {
@@ -3231,21 +3226,25 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
seek: (t) => {
const total = projectDuration(get());
+ setPlayhead(Math.max(0, Math.min(total, t)));
// A manual seek cancels any scoped effect preview.
- set({ currentTime: Math.max(0, Math.min(total, t)), previewStopAt: null });
+ if (get().previewStopAt !== null) set({ previewStopAt: null });
},
- // A manual play/pause cancels any scoped effect preview.
- setPlaying: (p) => set({ playing: p, previewStopAt: null }),
+ // A manual play/pause cancels any scoped effect preview. Starting playback
+ // also drops the skimmer: the picture belongs to the playhead again, and a
+ // pointer left standing over the timeline would otherwise keep claiming it.
+ setPlaying: (p) => {
+ if (p) setSkim(null);
+ set({ playing: p, previewStopAt: null });
+ },
previewRange: (start, end) => {
const total = projectDuration(get());
const from = Math.max(0, Math.min(total, start));
const to = Math.max(from + 0.05, Math.min(total, end));
- set({ currentTime: from, playing: true, previewStopAt: to });
- },
- setSkimTime: (t) => {
- if (get().skimTime !== t) set({ skimTime: t });
+ setPlayhead(from);
+ set({ playing: true, previewStopAt: to });
},
setPublish: (patch) => set((s) => ({ publish: { ...s.publish, ...patch } })),
setNotes: (patch) => set((s) => ({ notes: { ...s.notes, ...patch } })),
@@ -3972,7 +3971,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
)
return false;
push();
- const t = Math.max(0, s.currentTime);
+ const t = Math.max(0, playheadAt());
const newSel: Selection[] = [];
set((cur) => {
let clips = cur.clips;
@@ -4595,11 +4594,37 @@ export function separateOverlaps<
};
}
-export function getClipSpans(
- clips: VideoClip[],
- assets: MediaAsset[],
- track = 0
-): ClipSpan[] {
+/**
+ * Spans for one track, cached until the document moves.
+ *
+ * Every frame of playback and every pixel of a scrub asks for these, and some
+ * of the askers are React selectors that run on every store write. Rebuilding
+ * the list each time meant an asset `Map`, a filter/map/sort and a `ClipSpan`
+ * per clip — several times a frame, discarded. Clips and assets are replaced
+ * wholesale on an edit, so identity is a sound cache key: same arrays, same
+ * answer.
+ *
+ * Callers treat the result as read-only. Nothing sorts or pushes into it, and
+ * anything that wants to would be handing the next caller a different timeline.
+ */
+let spansClips: VideoClip[] | null = null;
+let spansAssets: MediaAsset[] | null = null;
+const spansByTrack = new Map<number, ClipSpan[]>();
+
+export function getClipSpans(clips: VideoClip[], assets: MediaAsset[], track = 0): ClipSpan[] {
+ if (clips !== spansClips || assets !== spansAssets) {
+ spansClips = clips;
+ spansAssets = assets;
+ spansByTrack.clear();
+ }
+ const hit = spansByTrack.get(track);
+ if (hit) return hit;
+ const built = buildClipSpans(clips, assets, track);
+ spansByTrack.set(track, built);
+ return built;
+}
+
+function buildClipSpans(clips: VideoClip[], assets: MediaAsset[], track: number): ClipSpan[] {
// One track's clips in sequence, each with its live dissolve overlap into
// the next. Track 0 is the spine that drives playback; upper tracks carry
// their own transitions between their own clips.
@@ -4966,11 +4991,24 @@ export function elementPlacement(
* runs past it on another video track, the soundtrack, or an element row.
* Drives the timeline extent, the seek clamp, and export length so content
* past track 0's end is reachable. */
+let durClips: VideoClip[] | null = null;
+let durAudio: AudioClip[] | null = null;
+let durOverlays: Overlay[] | null = null;
+let durValue = 0;
+
export function projectDuration(s: {
clips: VideoClip[];
audioClips: AudioClip[];
overlays: Overlay[];
}): number {
+ // Cached on the same identity rule as the spans above: every seek clamps
+ // against this, so a drag used to walk all three lists per pointer move.
+ if (s.clips === durClips && s.audioClips === durAudio && s.overlays === durOverlays) {
+ return durValue;
+ }
+ durClips = s.clips;
+ durAudio = s.audioClips;
+ durOverlays = s.overlays;
let end = 0;
// Anything on any row extends the timeline: a layer or soundtrack running
// past track 0's end is still reachable, and so is a title or sticker left
@@ -4978,7 +5016,8 @@ export function projectDuration(s: {
for (const c of s.clips) end = Math.max(end, c.start + clipLen(c));
for (const a of s.audioClips) end = Math.max(end, a.start + clipLen(a));
for (const o of s.overlays) end = Math.max(end, o.end);
- return Math.max(0, end);
+ durValue = Math.max(0, end);
+ return durValue;
}
/** Spread a cue's words across [start, end], each word's slice proportional to