Open source CapCut alternative.
TypeScript
feat(site): free-position the base video track on shared lane-track gestures
David Le3c283b11c563
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex c2133597..a1d9831c 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -1,6 +1,6 @@"use client";-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";import { AudioLines, Blend, Check, EllipsisVertical, Expand, Eye, EyeOff, FolderPlus, Loader2, Pause, Play, Plus, Scissors, SkipBack, Sunrise, Sunset, Trash2, Type, Volume2, VolumeX, ZoomIn, ZoomOut, type LucideIcon } from "lucide-react";import { Button } from "@/components/ui/button";import {@@ -21,7 +21,8 @@ import {} from "@/cut/lib/assetDrag";import { draggingRef, hasRefDrag, refFromAsset, startPointerRefDrag, type AssetRef } from "@/cut/lib/assetRef";import { importLibraryAsset, saveTemplate } from "@/cut/lib/library";-import { startDrag } from "@/cut/lib/drag";+import { isDragActive, startDrag, subscribeDragActive } from "@/cut/lib/drag";+import { CLIP_GAP, startLaneMove, startLaneTrim, type LaneDrag } from "@/cut/lib/laneTracks";import { ensurePeaks, importImage, importStockVideo } from "@/cut/lib/media";import { clipLen, clipSpeed, getClipSpans, projectDuration, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";import type { VideoTrackPlacement } from "@/cut/lib/store";@@ -76,12 +77,6 @@ const SUB_H = 22;const PAD_END = 320;/** Breathing room on both sides so the playhead cap is never clipped. */const PAD_SIDE = 20;-/** Visual gutter between adjacent clips (iMovie); time math stays exact. */-const CLIP_GAP = 4;-/** Pull a resized title edge to a logical time within this many screen px. */-const SNAP_PX = 6;-/** How far (px) the left edge can rubber-band past its limit before snapping back. */-const LEFT_RUBBER_PX = 32;// A high-contrast selected state: a bright blue ring drawn both inside and// (crucially) *outside* the box, so it stays visible on top of a clip's@@ -93,44 +88,6 @@ const SELECTED_SHADOW =const trimHandle ="tl-trim absolute top-0 bottom-0 z-3 w-[10px] cursor-ew-resize after:absolute after:top-1/2 after:left-[3px] after:h-[calc(100%-10px)] after:w-1 after:-translate-y-1/2 after:rounded-full after:bg-white after:opacity-0 after:shadow-[0_0_0_1px_rgba(0,0,0,0.35)] after:transition-opacity group-hover:after:opacity-90 hover:after:opacity-100";-/** Live reorder-drag on the video track: ghost offset plus the open slot. */-interface ClipDrag {- id: string;- dx: number; // ghost offset in px (mouse + auto-scroll)- dy: number; // vertical lift in px, clamped — iMovie's picked-up feel- from: number; // original index in spans- to: number; // insertion index while dragging- len: number; // dragged clip length, seconds- gapStart: number; // open slot position, seconds-}--interface TextDrag {- id: string;- targetRow: number; // hovered display row (one past the end = new track)- ghostX: number; // ghost left in px — follows the pointer- slotStart: number; // resolved landing start, seconds- len: number; // dragged title length, seconds-}--/**- * Insertion index for a dragged clip (iMovie): the edge leading the drag- * direction opens a slot once it crosses a neighbor's midpoint.- */-function dropIndex(spans: ClipSpan[], from: number, dxSec: number): number {- const d = spans[from];- let to = from;- if (dxSec > 0) {- const edge = d.start + d.len + dxSec; // right edge leads- for (let k = from + 1; k < spans.length; k++)- if (edge > spans[k].start + spans[k].len / 2) to = k;- } else if (dxSec < 0) {- const edge = d.start + dxSec; // left edge leads- for (let k = from - 1; k >= 0; k--)- if (edge < spans[k].start + spans[k].len / 2) to = k;- }- return to;-}-/** On-timeline length a dropped image occupies (it has no intrinsic duration). */const STILL_SECONDS = IMAGE_CLIP_SECONDS;@@ -156,14 +113,6 @@ function draggingStockVideo(e: React.DragEvent): AssetRef | null {return ref?.scope === "stock" && ref.kind === "video" ? ref : null;}-/** Insertion slot for a new clip dropped at time `t`: it lands before the- * first span whose midpoint is past `t` (spans.length = at the very end).- * Exported for the Editor's OS-file drops onto the timeline. */-export function videoInsertIndex(spans: ClipSpan[], t: number): number {- for (let k = 0; k < spans.length; k++) if (t < spans[k].start + spans[k].len / 2) return k;- return spans.length;-}-export function Timeline() {const clips = useEditor((s) => s.clips);const audioClips = useEditor((s) => s.audioClips);@@ -190,15 +139,18 @@ export function Timeline() {const spans = useMemo(() => getClipSpans(clips, assets), [clips, assets]);const total = projectDuration({ clips, overlayClips, audioClips });// Fill the viewport at minimum so a wide window never leaves the ruler/tracks- // cut off; grow past it once the content is longer.- const contentW = Math.max(total * pps + PAD_END, viewportW - PAD_SIDE * 2, 600);-- // Reorder drag on the video track: neighbors part to open a highlighted- // slot at the insertion point; releasing drops the clip into it.- const [clipDrag, setClipDrag] = useState<{ id: string; dx: number; dy: number } | null>(null);- // Insertion preview while dragging a media asset onto the video track:- // `index` is the span it lands before (spans.length = end), `len` its length.- const [assetDrop, setAssetDrop] = useState<{ index: number; len: number } | null>(null);+ // cut off; grow past it once the content is longer. While a trim/slide drag+ // is in flight, hold the width at its drag-start value so the scroll area+ // doesn't resize under the pointer; it commits on release.+ const dragging = useSyncExternalStore(subscribeDragActive, isDragActive, () => false);+ const liveContentW = Math.max(total * pps + PAD_END, viewportW - PAD_SIDE * 2, 600);+ const heldContentW = useRef(liveContentW);+ if (!dragging) heldContentW.current = liveContentW;+ const contentW = heldContentW.current;++ // Drop preview while dragging a media asset onto the base track: where the+ // pointer is and how long the clip would run.+ const [assetDrop, setAssetDrop] = useState<{ t: number; len: number } | null>(null);// Kind of external media being dragged over the timeline (audio vs video).const [dropType, setDropType] = useState<"video" | "audio" | null>(null);// A video clip is being dragged (internal or external): reveals the@@ -211,28 +163,6 @@ export function Timeline() {// Stage-x pixel a snapped title edge sits at, for the guide line (null = off).const [snapX, setSnapX] = useState<number | null>(null);const insertMode = videoDragging || dropType === "video";- const dragInfo = useMemo<ClipDrag | null>(() => {- if (!clipDrag) return null;- const from = spans.findIndex((sp) => sp.clip.id === clipDrag.id);- if (from < 0) return null;- const to = dropIndex(spans, from, clipDrag.dx / pps);- const len = spans[from].len;- const gapStart = to <= from ? spans[to].start : spans[to].start + spans[to].len - len;- return { id: clipDrag.id, dx: clipDrag.dx, dy: clipDrag.dy, from, to, len, gapStart };- }, [clipDrag, spans, pps]);-- const onClipDrag = useCallback(- (id: string, dx: number, dy: number) => setClipDrag({ id, dx, dy }),- []- );- const onClipDrop = useCallback((id: string, dx: number | null) => {- setClipDrag(null);- if (dx === null) return;- const s = useEditor.getState();- const sp = getClipSpans(s.clips, s.assets);- const from = sp.findIndex((x) => x.clip.id === id);- if (from >= 0) s.moveClip(id, dropIndex(sp, from, dx / s.pxPerSec));- }, []);// Which drop the cursor is over: an upper track, the base row, or a gap// between/above/below tracks that would open a new one. Hit-test live via@@ -258,12 +188,11 @@ export function Timeline() {// target track, base slot, or a between-track insertion line.const previewCross = useCallback((target: TrackTarget | null, start = 0, len = 0) => {if (target === null) return setOverlayDrop(null);- setClipDrag(null);setOverlayDrop({ target, t: start, len });}, []);// Releasing a base clip anywhere but the base row lifts it out onto that track- // (or a new one); the base row itself is a plain reorder (via onClipDrop).+ // (or a new one); on the base row the lane coordinator commits the move.const onBaseCrossDrop = useCallback((id: string, target: TrackTarget, start: number) => {previewCross(null);@@ -283,9 +212,13 @@ export function Timeline() {[previewCross]);+ // The one in-flight lane-track drag (audio, title, upper layer, or cue):+ // the coordinator publishes it so each section can render the ghost, the+ // landing slot, and grow its row stack while a new row is hovered.+ const [laneDrag, setLaneDrag] = useState<LaneDrag | null>(null);+// Title tracks: overlays carry a `lane`; used lanes compact to contiguous// display rows, so empty tracks disappear on their own.- const [textDrag, setTextDrag] = useState<TextDrag | null>(null);const overlayLanes = useMemo(() => {const used = [...new Set(overlays.map((o) => o.lane ?? 0))].sort((a, b) => a - b);const rowOf = new Map(used.map((l, i) => [l, i]));@@ -304,19 +237,36 @@ export function Timeline() {[overlayClips]);- const onTextDrag = useCallback((d: TextDrag | null) => setTextDrag(d), []);- const onTextLaneDrop = useCallback((id: string, targetRow: number) => {- setTextDrag(null);- const s = useEditor.getState();- const used = [...new Set(s.overlays.map((o) => o.lane ?? 0))].sort((a, b) => a - b);- const cur = s.overlays.find((o) => o.id === id);- if (!cur) return;- const curRow = used.indexOf(cur.lane ?? 0);- if (targetRow === curRow) return;- // A row past the end becomes a brand-new track above the current max.- const lane = targetRow < used.length ? used[targetRow] : (used[used.length - 1] ?? -1) + 1;- s.moveOverlayToLane(id, lane);- }, []);+ // Audio tracks mirror the title tracks: clips carry a `lane`; used lanes+ // compact to contiguous display rows, so empty tracks disappear on their own.+ // Drop preview while an audio asset is dragged over the timeline: which row+ // (one past the end = new track), at what time, for how long.+ const [audioDrop, setAudioDrop] = useState<{ row: number; t: number; len: number } | null>(null);+ const audioRef = useRef<HTMLDivElement>(null);+ const audioLanes = useMemo(() => {+ const used = [...new Set(audioClips.map((a) => a.lane ?? 0))].sort((a, b) => a - b);+ const rowOf = new Map(used.map((l, i) => [l, i]));+ return { used, rowOf, count: used.length };+ }, [audioClips]);++ // The home track of an in-flight upper-layer drag, so that row can render+ // the landing slot while the clip stays on its own track.+ const draggedOverlayTrack =+ laneDrag?.kind === "overlayClip" && !laneDrag.away+ ? overlayClips.find((c) => c.id === laneDrag.id)?.track ?? null+ : null;++ // The audio row under a screen y, one past the last row = a new track.+ // Before any audio exists there are no rows, so everything resolves to 0.+ const audioRowAt = useCallback(+ (clientY: number): number => {+ const el = audioRef.current;+ if (!el) return 0;+ const top = el.getBoundingClientRect().top;+ return Math.min(audioLanes.count, Math.max(0, Math.floor((clientY - top) / AUDIO_H)));+ },+ [audioLanes.count]+ );const timeAt = (clientX: number) => {const rect = innerRef.current!.getBoundingClientRect();@@ -447,20 +397,23 @@ export function Timeline() {return () => window.removeEventListener("keydown", onKey);}, [zoomTo]);- // Drop an asset onto the timeline: video snaps into the nearest slot at time- // `t`, audio lands free-form there.- const placeAssetAt = (assetId: string, type: "video" | "audio" | "image", t: number) => {+ // Drop an asset onto the timeline: every kind lands free-form at time `t`+ // (sliding to its lane's next free slot); audio targets the hovered audio+ // row, one past the last row opening a new track.+ const placeAssetAt = (+ assetId: string,+ type: "video" | "audio" | "image",+ t: number,+ audioRow = 0+ ) => {const s = useEditor.getState();if (isBaseType(type)) {- const sp = getClipSpans(s.clips, s.assets);- const spanIndex = videoInsertIndex(sp, t);- const clipsIndex =- spanIndex < sp.length- ? s.clips.findIndex((c) => c.id === sp[spanIndex].clip.id)- : s.clips.length;- s.addClipFromAsset(assetId, clipsIndex);+ s.addClipFromAsset(assetId, t);} else {- s.addAudioFromAsset(assetId, t);+ const used = [...new Set(s.audioClips.map((a) => a.lane ?? 0))].sort((a, b) => a - b);+ const lane =+ audioRow < used.length ? used[audioRow] : (used[used.length - 1] ?? -1) + 1;+ s.addAudioFromAsset(assetId, t, { lane });}};@@ -607,25 +560,37 @@ export function Timeline() {}// A still rides the base (video) lane: light its insertion zones.setDropType(isBaseType(type) ? "video" : type ?? null);+ if (type === "audio") {+ // Preview which audio row the sound would land on.+ setAudioDrop({+ row: audioRowAt(e.clientY),+ t: Math.max(0, timeAt(e.clientX)),+ len: duration,+ });+ setAssetDrop(null);+ return;+ }+ setAudioDrop(null);if (!isBaseType(type) || !duration) {setAssetDrop(null);return;}- const index = videoInsertIndex(spans, Math.max(0, timeAt(e.clientX)));- setAssetDrop((prev) =>- prev && prev.index === index && prev.len === duration ? prev : { index, len: duration }- );+ setAssetDrop({ t: Math.max(0, timeAt(e.clientX)), len: duration });}}onDragLeave={(e) => {if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {setAssetDrop(null);setOverlayDrop(null);+ setAudioDrop(null);setDropType(null);}}}onDrop={(e) => {+ // Resolve the hovered audio row before the preview (and its rows) clear.+ const audioRow = audioRowAt(e.clientY);setAssetDrop(null);setOverlayDrop(null);+ setAudioDrop(null);setDropType(null);const t = Math.max(0, timeAt(e.clientX));@@ -639,7 +604,7 @@ export function Timeline() {if (libId && lib && projectId) {e.preventDefault();void importLibraryAsset(projectId, lib)- .then((asset) => placeAssetAt(asset.id, asset.type, t))+ .then((asset) => placeAssetAt(asset.id, asset.type, t, audioRow)).catch(() => {});return;}@@ -648,7 +613,7 @@ export function Timeline() {if (id) {e.preventDefault();const asset = useEditor.getState().assets.find((a) => a.id === id);- if (asset) placeAssetAt(id, asset.type, t);+ if (asset) placeAssetAt(id, asset.type, t, audioRow);return;}@@ -736,6 +701,15 @@ export function Timeline() {{...overlayDropHandlers({ kind: "track", track })}>{insertMode && insertZone(track + 1)}+ {draggedOverlayTrack === track && laneDrag && (+ <LaneSlot+ drag={laneDrag}+ pps={pps}+ rowH={OVERLAY_H}+ barH={OVERLAY_H - 4}+ className="rounded-lg bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4)]"+ />+ )}{overlayClips.filter((c) => c.track === track).map((c) => (@@ -745,6 +719,10 @@ export function Timeline() {asset={assets.find((x) => x.id === c.assetId)}pps={pps}selected={selKeys.has(`overlayClip:${c.id}`)}+ drag={laneDrag?.kind === "overlayClip" && laneDrag.id === c.id ? laneDrag : null}+ parting={laneDrag?.kind === "overlayClip" && laneDrag.id !== c.id}+ onDrag={setLaneDrag}+ onSnap={setSnapX}resolveTarget={resolveDropTrack}onCrossMove={previewCross}onCrossDrop={onOverlayCrossDrop}@@ -787,21 +765,20 @@ export function Timeline() {}}/>)}- {dragInfo && (- <div- className="tl-drop-slot pointer-events-none absolute top-0.5 rounded-lg bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4),inset_0_2px_10px_rgba(10,60,140,0.08)] transition-[left] duration-150 ease-out"- style={{- left: dragInfo.gapStart * pps,- width: Math.max(10, dragInfo.len * pps - CLIP_GAP),- height: VIDEO_H - 4,- }}+ {laneDrag?.kind === "clip" && !laneDrag.away && (+ <LaneSlot+ drag={laneDrag}+ pps={pps}+ rowH={VIDEO_H}+ barH={VIDEO_H - 4}+ className="rounded-lg bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4),inset_0_2px_10px_rgba(10,60,140,0.08)]"/>)}{assetDrop && (<divclassName="tl-asset-drop-slot pointer-events-none absolute top-0.5 flex items-center justify-center rounded-lg border-[1.5px] border-dashed border-[#0a84ff]/70 bg-[#0a84ff]/10 text-[#0a84ff] transition-[left] duration-150 ease-out"style={{- left: (assetDrop.index < spans.length ? spans[assetDrop.index].start : total) * pps,+ left: assetDrop.t * pps,width: Math.max(10, assetDrop.len * pps - CLIP_GAP),height: VIDEO_H - 4,}}@@ -813,16 +790,13 @@ export function Timeline() {<ClipViewkey={span.clip.id}span={span}- index={i}prevOverlap={spans[i - 1]?.transitionOut ?? 0}pps={pps}selected={selKeys.has(`clip:${span.clip.id}`)}- drag={dragInfo}- insertAtIndex={assetDrop ? assetDrop.index : null}- insertLen={assetDrop ? assetDrop.len : 0}- scrollRef={scrollRef}- onDrag={onClipDrag}- onDrop={onClipDrop}+ drag={laneDrag?.kind === "clip" && laneDrag.id === span.clip.id ? laneDrag : null}+ parting={laneDrag?.kind === "clip" && laneDrag.id !== span.clip.id}+ onDrag={setLaneDrag}+ onSnap={setSnapX}resolveTarget={resolveDropTrack}onCrossMove={previewCross}onCrossDrop={onBaseCrossDrop}@@ -832,7 +806,7 @@ export function Timeline() {{/* Transition badge, floating in the gutter where the two clipsmeet (the overlap midpoint; a hard cut for edge styles),vertically centered on the clip row. */}- {!clipDrag &&+ {laneDrag?.kind !== "clip" &&spans.map((span, i) => {const d = span.clip.transition ?? 0;if (!spans[i + 1] || d <= 0) return null;@@ -868,6 +842,15 @@ export function Timeline() {{...overlayDropHandlers({ kind: "track", track })}>{insertMode && insertZone(track - 1, "bottom")}+ {draggedOverlayTrack === track && laneDrag && (+ <LaneSlot+ drag={laneDrag}+ pps={pps}+ rowH={OVERLAY_H}+ barH={OVERLAY_H - 4}+ className="rounded-lg bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4)]"+ />+ )}{overlayClips.filter((c) => c.track === track).map((c) => (@@ -877,6 +860,10 @@ export function Timeline() {asset={assets.find((x) => x.id === c.assetId)}pps={pps}selected={selKeys.has(`overlayClip:${c.id}`)}+ drag={laneDrag?.kind === "overlayClip" && laneDrag.id === c.id ? laneDrag : null}+ parting={laneDrag?.kind === "overlayClip" && laneDrag.id !== c.id}+ onDrag={setLaneDrag}+ onSnap={setSnapX}resolveTarget={resolveDropTrack}onCrossMove={previewCross}onCrossDrop={onOverlayCrossDrop}@@ -896,17 +883,60 @@ export function Timeline() {</div>))}- {audioClips.length > 0 && (- <div className="relative mt-1.5" style={{ height: AUDIO_H }} onPointerDown={deselectIfSelf}>- {audioClips.map((a) => (- <AudioView- key={a.id}- clip={a}- asset={assets.find((x) => x.id === a.assetId)}+ {(audioClips.length > 0 || audioDrop !== null) && (+ <div+ ref={audioRef}+ className="relative mt-1.5"+ style={{+ height:+ Math.max(+ audioLanes.count,+ (laneDrag?.kind === "audio" ? laneDrag.targetRow : -1) + 1,+ (audioDrop?.row ?? -1) + 1+ ) * AUDIO_H,+ }}+ onPointerDown={deselectIfSelf}+ >+ {audioDrop && (+ <div+ className="tl-audio-drop-slot pointer-events-none absolute rounded-[7px] border-[1.5px] border-dashed border-emerald-500/80 bg-emerald-500/10 transition-[left] duration-150 ease-out"+ style={{+ left: audioDrop.t * pps,+ top: audioDrop.row * AUDIO_H + 2,+ width: Math.max(10, audioDrop.len * pps - CLIP_GAP),+ height: AUDIO_H - 4,+ }}+ />+ )}+ {laneDrag?.kind === "audio" && !laneDrag.away && (+ <LaneSlot+ drag={laneDrag}pps={pps}- selected={selKeys.has(`audio:${a.id}`)}+ rowH={AUDIO_H}+ barH={AUDIO_H - 4}+ className="rounded-[7px] bg-emerald-500/10 shadow-[inset_0_0_0_1.5px_rgba(16,185,129,0.5)]"/>- ))}+ )}+ {audioClips.map((a) => {+ const baseRow = audioLanes.rowOf.get(a.lane ?? 0) ?? 0;+ const drag = laneDrag?.kind === "audio" && laneDrag.id === a.id ? laneDrag : null;+ return (+ <AudioView+ key={a.id}+ clip={a}+ asset={assets.find((x) => x.id === a.assetId)}+ pps={pps}+ top={(drag ? drag.targetRow : baseRow) * AUDIO_H}+ baseRow={baseRow}+ laneCount={audioLanes.count}+ selected={selKeys.has(`audio:${a.id}`)}+ drag={drag}+ parting={laneDrag?.kind === "audio" && laneDrag.id !== a.id}+ onDrag={setLaneDrag}+ onSnap={setSnapX}+ />+ );+ })}</div>)}@@ -915,37 +945,37 @@ export function Timeline() {className="relative mt-1.5"style={{height:- Math.max(overlayLanes.count, (textDrag?.targetRow ?? -1) + 1) * TEXT_H,+ Math.max(+ overlayLanes.count,+ (laneDrag?.kind === "text" ? laneDrag.targetRow : -1) + 1+ ) * TEXT_H,}}onPointerDown={deselectIfSelf}>- {textDrag && (- <div- className="tl-text-drop-slot pointer-events-none absolute rounded-md bg-purple-500/10 shadow-[inset_0_0_0_1.5px_rgba(168,85,247,0.5)] transition-[left] duration-150 ease-out"- style={{- left: textDrag.slotStart * pps,- top: textDrag.targetRow * TEXT_H + 2,- width: Math.max(8, textDrag.len * pps - CLIP_GAP),- height: TEXT_H - 6,- }}+ {laneDrag?.kind === "text" && (+ <LaneSlot+ drag={laneDrag}+ pps={pps}+ rowH={TEXT_H}+ barH={TEXT_H - 6}+ className="rounded-md bg-purple-500/10 shadow-[inset_0_0_0_1.5px_rgba(168,85,247,0.5)]"/>)}{overlays.map((o) => {const baseRow = overlayLanes.rowOf.get(o.lane ?? 0) ?? 0;- const row = textDrag?.id === o.id ? textDrag.targetRow : baseRow;+ const drag = laneDrag?.kind === "text" && laneDrag.id === o.id ? laneDrag : null;return (<TextBarkey={o.id}overlay={o}pps={pps}- top={row * TEXT_H}+ top={(drag ? drag.targetRow : baseRow) * TEXT_H}baseRow={baseRow}laneCount={overlayLanes.count}selected={selKeys.has(`text:${o.id}`)}- drag={textDrag?.id === o.id ? textDrag : null}- parting={textDrag !== null && textDrag.id !== o.id}- onDrag={onTextDrag}- onLaneDrop={onTextLaneDrop}+ drag={drag}+ parting={laneDrag?.kind === "text" && laneDrag.id !== o.id}+ onDrag={setLaneDrag}onSnap={setSnapX}/>);@@ -959,12 +989,25 @@ export function Timeline() {style={{ height: SUB_H }}onPointerDown={deselectIfSelf}>+ {laneDrag?.kind === "cue" && (+ <LaneSlot+ drag={laneDrag}+ pps={pps}+ rowH={SUB_H}+ barH={SUB_H - 4}+ className="rounded-[5px] bg-amber-400/15 shadow-[inset_0_0_0_1.5px_rgba(245,158,11,0.55)]"+ />+ )}{subtitles.cues.map((c) => (<SubBarkey={c.id}cue={c}pps={pps}selected={selKeys.has(`cue:${c.id}`)}+ drag={laneDrag?.kind === "cue" && laneDrag.id === c.id ? laneDrag : null}+ parting={laneDrag?.kind === "cue" && laneDrag.id !== c.id}+ onDrag={setLaneDrag}+ onSnap={setSnapX}/>))}</div>@@ -1579,12 +1622,31 @@ function AudioView({clip,asset,pps,+ top,+ baseRow,+ laneCount,selected,+ drag,+ parting,+ onDrag,+ onSnap,}: {clip: AudioClip;asset: MediaAsset | undefined;pps: number;+ /** Rendered row top in px — follows the drag's target row while carried. */+ top: number;+ baseRow: number;+ laneCount: number;selected: boolean;+ /** This bar's live drag when it is the one being carried (ghost mode). */+ drag: LaneDrag | null;+ /** Another sound is dragging: animate this bar's shifts as it parts. */+ parting: boolean;+ /** Publish (or clear) the in-flight drag so the slot and rows track it. */+ onDrag: (d: LaneDrag | null) => void;+ /** Paint (or clear) the snap guide at this stage-x pixel. */+ onSnap: (x: number | null) => void;}) {const canvasRef = useRef<HTMLCanvasElement>(null);const len = clipLen(clip);@@ -1614,67 +1676,27 @@ function AudioView({if (!asset) return null;- const onBody = (e: React.PointerEvent) => {- if (e.metaKey || e.shiftKey) {- useEditor.getState().toggleSelect({ kind: "audio", id: clip.id });- return;- }- const s = useEditor.getState();- s.select({ kind: "audio", id: clip.id });- s.seek(clip.start + (e.clientX - e.currentTarget.getBoundingClientRect().left) / pps);- s.pushHistory();- const start0 = clip.start;- const refDrag = startPointerRefDrag(refFromAsset(asset));- startDrag(e, {- onMove: (dx, _dy, ev) => {- refDrag.move(ev);- s.updateAudioTransient(clip.id, { start: Math.max(0, start0 + dx / pps) });- },- onUp: () => {- // A zone took the ref (e.g. an AI chat attachment); undo the slide.- if (refDrag.drop()) s.updateAudioTransient(clip.id, { start: start0 });- },- });- };-- const onTrimLeft = (e: React.PointerEvent) => {- const s = useEditor.getState();- s.select({ kind: "audio", id: clip.id });- s.pushHistory();- const in0 = clip.in;- const start0 = clip.start;- startDrag(e, {- onMove: (dx) => {- let d = dx / pps;- d = Math.max(d, -in0, -start0);- d = Math.min(d, clip.out - 0.15 - in0);- s.updateAudioTransient(clip.id, { in: in0 + d, start: start0 + d });- },- });- };-- const onTrimRight = (e: React.PointerEvent) => {- const s = useEditor.getState();- s.select({ kind: "audio", id: clip.id });- s.pushHistory();- const out0 = clip.out;- startDrag(e, {- onMove: (dx) => {- const nout = Math.max(clip.in + 0.15, Math.min(asset.duration, out0 + dx / pps));- s.updateAudioTransient(clip.id, { out: nout });- },- });- };+ const ui = { pps, rowH: AUDIO_H, laneCount, baseRow, onDrag, onSnap };return (<divclassName={cn(- "tl-audio-clip group absolute top-0.5 cursor-grab overflow-hidden rounded-[7px] bg-gradient-to-b from-emerald-500 to-emerald-600 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",+ "tl-audio-clip group absolute cursor-grab overflow-hidden rounded-[7px] bg-gradient-to-b from-emerald-500 to-emerald-600 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",selected && SELECTED_SHADOW,- clip.hidden && "opacity-40 grayscale"+ clip.hidden && "opacity-40 grayscale",+ drag+ ? "tl-audio-ghost pointer-events-none cursor-grabbing opacity-80 shadow-2xl"+ : parting && "transition-[left] duration-150 ease-out")}- style={{ left: clip.start * pps, width: Math.max(10, w - CLIP_GAP), height: AUDIO_H - 4 }}- onPointerDown={onBody}+ style={{+ left: drag ? drag.ghostX : clip.start * pps,+ top: top + 2,+ width: Math.max(10, w - CLIP_GAP),+ height: AUDIO_H - 4,+ // Inline so it beats SELECTED_SHADOW's z-10 class on the same element.+ zIndex: drag ? 20 : undefined,+ }}+ onPointerDown={(e) => startLaneMove(e, "audio", clip.id, ui)}><canvas ref={canvasRef} className="pointer-events-none absolute inset-x-0 inset-y-1" />{(clip.fadeIn ?? 0) > 0 && (@@ -1692,13 +1714,19 @@ function AudioView({<span className="pointer-events-none absolute top-[3px] left-2 text-[9.5px] whitespace-nowrap text-white/90 [text-shadow:0_1px_2px_rgba(0,0,0,0.35)]">{asset.name}</span>- <HideChip- hidden={!!clip.hidden}- className="top-[3px] right-1.5"+ <MuteChip+ muted={!!clip.hidden}+ className="bottom-1 left-1"onToggle={() => useEditor.getState().updateAudio(clip.id, { hidden: !clip.hidden })}/>- <span className={cn(trimHandle, "tl-trim-l left-0")} onPointerDown={onTrimLeft} />- <span className={cn(trimHandle, "tl-trim-r right-0")} onPointerDown={onTrimRight} />+ <span+ className={cn(trimHandle, "tl-trim-l left-0")}+ onPointerDown={(e) => startLaneTrim(e, "audio", clip.id, "l", ui)}+ />+ <span+ className={cn(trimHandle, "tl-trim-r right-0")}+ onPointerDown={(e) => startLaneTrim(e, "audio", clip.id, "r", ui)}+ /></div>);}@@ -1720,6 +1748,10 @@ function OverlayClipView({asset,pps,selected,+ drag,+ parting,+ onDrag,+ onSnap,resolveTarget,onCrossMove,onCrossDrop,@@ -1729,6 +1761,12 @@ function OverlayClipView({asset: MediaAsset | undefined;pps: number;selected: boolean;+ /** This clip's live drag when it is the one being carried (ghost mode). */+ drag: LaneDrag | null;+ /** Another upper-layer clip is dragging: animate this one's parting shifts. */+ parting: boolean;+ onDrag: (d: LaneDrag | null) => void;+ onSnap: (x: number | null) => void;resolveTarget: (clientX: number, clientY: number) => TrackTarget;onCrossMove: (target: TrackTarget | null, start?: number, len?: number) => void;onCrossDrop: (id: string, target: TrackTarget, start: number) => void;@@ -1756,75 +1794,24 @@ function OverlayClipView({if (!asset) return null;- const onBody = (e: React.PointerEvent) => {- if (e.metaKey || e.shiftKey) {- useEditor.getState().toggleSelect({ kind: "overlayClip", id: clip.id });- return;- }- const s = useEditor.getState();- s.select({ kind: "overlayClip", id: clip.id });- s.seek(clip.start + (e.clientX - e.currentTarget.getBoundingClientRect().left) / pps);- const start0 = clip.start;- let live = false;- let target: TrackTarget = { kind: "track", track: clip.track };- let dropStart = clip.start;- const refDrag = startPointerRefDrag(refFromAsset(asset));- startDrag(e, {- onMove: (dx, dy, ev) => {- if (!live && Math.abs(dx) < 4 && Math.abs(dy) < 4) return;- if (!live) {- s.pushHistory();- onDragActive(true);- }- live = true;- refDrag.move(ev);- dropStart = Math.max(0, start0 + dx / pps);- s.updateOverlayClipTransient(clip.id, { start: dropStart });- target = resolveTarget(ev.clientX, ev.clientY);- // Staying on its own track is a plain slide; anything else previews a move.- if (samePlacement(target, { kind: "track", track: clip.track })) onCrossMove(null);- else onCrossMove(target, dropStart, overlayLen(clip));- },- onUp: () => {- onDragActive(false);- onCrossMove(null);- if (live && refDrag.drop()) {- // A zone took the ref; put the clip back where the drag started.- s.updateOverlayClipTransient(clip.id, { start: start0 });- return;- }- if (live) onCrossDrop(clip.id, target, dropStart);- },- });- };-- const onTrimLeft = (e: React.PointerEvent) => {- const s = useEditor.getState();- s.select({ kind: "overlayClip", id: clip.id });- s.pushHistory();- const in0 = clip.in;- const start0 = clip.start;- startDrag(e, {- onMove: (dx) => {- let d = dx / pps;- d = Math.max(d, -in0, -start0);- d = Math.min(d, clip.out - 0.15 - in0);- s.updateOverlayClipTransient(clip.id, { in: in0 + d, start: start0 + d });- },- });- };-- const onTrimRight = (e: React.PointerEvent) => {- const s = useEditor.getState();- s.select({ kind: "overlayClip", id: clip.id });- s.pushHistory();- const out0 = clip.out;- startDrag(e, {- onMove: (dx) => {- const nout = Math.max(clip.in + 0.15, Math.min(asset.duration, out0 + dx / pps));- s.updateOverlayClipTransient(clip.id, { out: nout });- },- });+ // The move gesture is the shared lane behavior (parting, snapping); its+ // verticality is the video placement system — other tracks, insert gaps,+ // and the base row — resolved by DOM hit-testing.+ const ui = {+ pps,+ rowH: OVERLAY_H,+ laneCount: 0,+ baseRow: 0,+ onDrag,+ onSnap,+ vertical: {+ resolve: (ev: PointerEvent) => resolveTarget(ev.clientX, ev.clientY),+ isHome: (t: TrackTarget) => samePlacement(t, { kind: "track", track: clip.track }),+ preview: (t: TrackTarget | null, start: number, len: number) =>+ t ? onCrossMove(t, start, len) : onCrossMove(null),+ commit: (id: string, t: TrackTarget, start: number) => onCrossDrop(id, t, start),+ setActive: onDragActive,+ },};return (@@ -1832,10 +1819,19 @@ function OverlayClipView({className={cn("tl-overlay-clip group absolute top-0.5 cursor-grab overflow-hidden rounded-lg bg-neutral-200 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]",selected && SELECTED_SHADOW,- clip.hidden && "opacity-40 grayscale"+ clip.hidden && "opacity-40 grayscale",+ drag+ ? "tl-overlay-ghost pointer-events-none cursor-grabbing opacity-80 shadow-2xl"+ : parting && "transition-[left] duration-150 ease-out")}- style={{ left: clip.start * pps, width: Math.max(10, w - CLIP_GAP), height: OVERLAY_H - 4 }}- onPointerDown={onBody}+ style={{+ left: drag ? drag.ghostX : clip.start * pps,+ width: Math.max(10, w - CLIP_GAP),+ height: OVERLAY_H - 4,+ // Inline so it beats SELECTED_SHADOW's z-10 class on the same element.+ zIndex: drag ? 20 : undefined,+ }}+ onPointerDown={(e) => startLaneMove(e, "overlayClip", clip.id, ui)}><div className="tl-filmstrip pointer-events-none absolute inset-0">{filmstrip.map((f, k) => (@@ -1873,57 +1869,18 @@ function OverlayClipView({className="bottom-1 right-2"onToggle={() => useEditor.getState().updateOverlayClip(clip.id, { hidden: !clip.hidden })}/>- <span className={cn(trimHandle, "tl-trim-l left-0")} onPointerDown={onTrimLeft} />- <span className={cn(trimHandle, "tl-trim-r right-0")} onPointerDown={onTrimRight} />+ <span+ className={cn(trimHandle, "tl-trim-l left-0")}+ onPointerDown={(e) => startLaneTrim(e, "overlayClip", clip.id, "l", ui)}+ />+ <span+ className={cn(trimHandle, "tl-trim-r right-0")}+ onPointerDown={(e) => startLaneTrim(e, "overlayClip", clip.id, "r", ui)}+ /></div>);}-/** Logical times a title edge can snap to: the timeline start, the video's cut- * points and end, the playhead, and the other titles' edges (self excluded). */-function textSnapTargets(s: ReturnType<typeof useEditor.getState>, selfId: string): number[] {- const pts = new Set<number>([0]);- for (const sp of getClipSpans(s.clips, s.assets)) {- // The visible joint: a dissolved pair meets at the overlap midpoint (where- // the clip boxes are inset to), a hard cut at the footprint end.- pts.add(sp.start + sp.len - sp.transitionOut / 2);- }- pts.add(projectDuration(s));- pts.add(s.currentTime);- for (const o of s.overlays) {- if (o.id === selfId) continue;- pts.add(o.start);- pts.add(o.end);- }- return [...pts];-}--/** The nearest snap target within `tol` seconds, or null. */-function nearestSnap(t: number, targets: number[], tol: number): number | null {- let best: number | null = null;- let bd = tol;- for (const T of targets) {- const d = Math.abs(t - T);- if (d <= bd) {- bd = d;- best = T;- }- }- return best;-}--/** Ease that overshoots the target then settles — the elastic snap-back feel. */-function easeOutBack(p: number): number {- const c1 = 1.70158;- const c3 = c1 + 1;- return 1 + c3 * Math.pow(p - 1, 3) + c1 * Math.pow(p - 1, 2);-}--/** Damp an overshoot in px so it gives but resists, saturating near `max`. */-function rubberBand(overPx: number, max: number): number {- return max * (1 - Math.exp(-Math.max(0, overPx) / max));-}-function TextBar({overlay: o,pps,@@ -1934,7 +1891,6 @@ function TextBar({drag,parting,onDrag,- onLaneDrop,onSnap,}: {overlay: TextOverlay;@@ -1944,211 +1900,16 @@ function TextBar({laneCount: number;selected: boolean;/** This bar's live drag when it is the one being carried (ghost mode). */- drag: TextDrag | null;+ drag: LaneDrag | null;/** Another title is dragging: animate this bar's shifts as it parts. */parting: boolean;/** Publish (or clear) the in-flight drag so the slot and lanes track it. */- onDrag: (d: TextDrag | null) => void;- onLaneDrop: (id: string, targetRow: number) => void;+ onDrag: (d: LaneDrag | null) => void;/** Paint (or clear) the snap guide at this stage-x pixel. */onSnap: (x: number | null) => void;}) {const w = Math.max(8, (o.end - o.start) * pps);- // In-flight elastic snap-back for the left edge; cancelled by any new grab.- const snapRaf = useRef(0);-- // A snapped edge draws its guide where the bar is actually rendered: a left- // edge at the time itself, a right edge inset by the CLIP_GAP gutter, so the- // line hugs the clip's visible right edge instead of the next clip's start.- const leftGuide = (t: number) => t * pps;- const rightGuide = (t: number) => t * pps - CLIP_GAP;-- const onBody = (e: React.PointerEvent) => {- if (e.metaKey || e.shiftKey) {- useEditor.getState().toggleSelect({ kind: "text", id: o.id });- return;- }- const s = useEditor.getState();- s.select({ kind: "text", id: o.id });- s.pushHistory();- const start0 = o.start;- const len = o.end - o.start;- const targets = textSnapTargets(s, o.id);- const tol = SNAP_PX / pps;- // Everyone else's resting spot, captured once: each move re-lays the lane- // from these, so a retreating drag lets parted neighbors flow back.- const rest = s.overlays- .filter((t) => t.id !== o.id)- .map((t) => ({ id: t.id, lane: t.lane ?? 0, start: t.start, len: t.end - t.start }));- const usedLanes = [...new Set([...rest.map((r) => r.lane), o.lane ?? 0])].sort(- (a, b) => a - b- );- let targetRow = baseRow;- let slotStart = start0;- let live = false;- startDrag(e, {- onMove: (dx, dy, ev) => {- if (!live && Math.abs(dx) < 4 && Math.abs(dy) < 4) return;- live = true;- // Vertical drag retracks the title; one row past the end opens a new one.- targetRow = Math.min(laneCount, Math.max(0, baseRow + Math.round(dy / TEXT_H)));- // A brand-new row has no neighbors to part.- const lane = targetRow < usedLanes.length ? usedLanes[targetRow] : Infinity;- const ds = Math.max(0, start0 + dx / pps);- // Snap whichever edge of the moving title lands nearest a logical time.- let start = ds;- let guide: number | null = null;- if (!ev.metaKey) {- const end = start + len;- let best = { d: tol, start, px: null as number | null };- for (const T of targets) {- if (Math.abs(start - T) < best.d) best = { d: Math.abs(start - T), start: T, px: leftGuide(T) };- if (Math.abs(end - T) < best.d) best = { d: Math.abs(end - T), start: T - len, px: rightGuide(T) };- }- if (best.px !== null) {- start = Math.max(0, best.start);- guide = best.px;- }- }- // Same-lane neighbors part around the slot like video clips: ones whose- // midpoint sits left of the ghost's center keep their spot (the slot- // lands after them), the rest slide right as a run to make room.- const others = rest.filter((r) => r.lane === lane).sort((a, b) => a.start - b.start);- const center = ds + len / 2;- const before = others.filter((r) => r.start + r.len / 2 <= center);- const after = others.filter((r) => r.start + r.len / 2 > center);- const clamped = Math.max(start, ...before.map((b) => b.start + b.len));- if (clamped !== start) guide = null;- slotStart = clamped;- const delta = after.length ? Math.max(0, clamped + len - after[0].start) : 0;- const pushed = new Set(after.map((a) => a.id));- onSnap(guide);- s.updateOverlaysTransient(- rest.map((r) => {- const push = r.lane === lane && pushed.has(r.id) ? delta : 0;- return { id: r.id, patch: { start: r.start + push, end: r.start + r.len + push } };- })- );- onDrag({ id: o.id, targetRow, ghostX: ds * pps, slotStart: clamped, len });- },- onUp: (_dx, _dy, moved) => {- onSnap(null);- if (moved) s.updateOverlayTransient(o.id, { start: slotStart, end: slotStart + len });- onLaneDrop(o.id, targetRow);- },- });- };-- const onTrimLeft = (e: React.PointerEvent) => {- cancelAnimationFrame(snapRaf.current);- const s = useEditor.getState();- s.select({ kind: "text", id: o.id });- s.pushHistory();- const start0 = o.start;- const lane = o.lane ?? 0;- // Titles before this one on the same lane, at their original spots. The- // edge grows freely into the open gap; past the neighbor it shoves the run- // left, closing gap after gap until everything sits flush against 0 — the- // hard floor. `end - 0.2` keeps a minimum width when shrinking.- const leaders = s.overlays- .filter((t) => (t.lane ?? 0) === lane && t.id !== o.id && t.end <= start0 + 1e-3)- .map((t) => ({ id: t.id, start: t.start, len: t.end - t.start }))- .sort((a, b) => a.start - b.start);- const prevEnd = leaders.reduce((m, l) => Math.max(m, l.start + l.len), 0);- const floor = leaders.reduce((sum, l) => sum + l.len, 0);- const max = o.end - 0.2;- const targets = textSnapTargets(s, o.id);- const tol = SNAP_PX / pps;- startDrag(e, {- onMove: (dx, _dy, ev) => {- cancelAnimationFrame(snapRaf.current);- const desired = Math.min(max, start0 + dx / pps);- let start: number;- if (desired >= prevEnd) {- // Room to the left: grow freely, snapping to logical times.- start = desired;- const hit = ev.metaKey ? null : nearestSnap(start, targets, tol);- if (hit !== null && hit >= prevEnd && hit <= max) {- start = hit;- onSnap(leftGuide(hit));- } else onSnap(null);- } else {- // Pushing: past the floor it drags with resistance and snaps back.- start =- desired >= floor- ? desired- : Math.max(0, floor - rubberBand((floor - desired) * pps, LEFT_RUBBER_PX) / pps);- onSnap(null);- }- // Re-lay the leaders right-to-left from their resting spots: each one- // slides only as far as the pushed edge (or the title it now abuts)- // forces it, so a retreating drag lets the run flow back.- const patches: { id: string; patch: Partial<TextOverlay> }[] = [- { id: o.id, patch: { start } },- ];- let limit = Math.max(start, floor);- for (let i = leaders.length - 1; i >= 0; i--) {- const l = leaders[i];- const end = Math.min(l.start + l.len, limit);- patches.push({ id: l.id, patch: { start: end - l.len, end } });- limit = end - l.len;- }- s.updateOverlaysTransient(patches);- },- onUp: () => {- onSnap(null);- const from = useEditor.getState().overlays.find((x) => x.id === o.id)?.start ?? floor;- if (from >= floor - 1e-4) return; // settled within the room, nothing to undo- // Elastic snap back to the floor.- const t0 = performance.now();- const step = (now: number) => {- const p = Math.min(1, (now - t0) / 240);- const v = from + (floor - from) * easeOutBack(p);- useEditor.getState().updateOverlayTransient(o.id, { start: Math.max(0, v) });- if (p < 1) snapRaf.current = requestAnimationFrame(step);- else useEditor.getState().updateOverlayTransient(o.id, { start: floor });- };- snapRaf.current = requestAnimationFrame(step);- },- });- };-- const onTrimRight = (e: React.PointerEvent) => {- const s = useEditor.getState();- s.select({ kind: "text", id: o.id });- s.pushHistory();- const end0 = o.end;- const lane = o.lane ?? 0;- // Titles that sit after this one on the same lane, at their original spots.- // Extending the edge past the first of them pushes the whole run right.- const followers = s.overlays- .filter((t) => (t.lane ?? 0) === lane && t.id !== o.id && t.start >= o.start)- .map((t) => ({ id: t.id, start: t.start, len: t.end - t.start }))- .sort((a, b) => a.start - b.start);- const nextStart = followers.length ? followers[0].start : Infinity;- const targets = textSnapTargets(s, o.id);- const tol = SNAP_PX / pps;- startDrag(e, {- onMove: (dx, _dy, ev) => {- let end = Math.max(o.start + 0.2, end0 + dx / pps);- const hit = ev.metaKey ? null : nearestSnap(end, targets, tol);- if (hit !== null && hit > o.start + 0.2) {- end = hit;- onSnap(rightGuide(end));- } else onSnap(null);- // Ripple: extending past the next title shoves the whole run right by- // the overflow (their gaps preserved); pulling back lets them return.- const delta = Math.max(0, end - nextStart);- const patches: { id: string; patch: Partial<TextOverlay> }[] = [- { id: o.id, patch: { end } },- ];- for (const f of followers)- patches.push({ id: f.id, patch: { start: f.start + delta, end: f.start + delta + f.len } });- s.updateOverlaysTransient(patches);- },- onUp: () => onSnap(null),- });- };+ const ui = { pps, rowH: TEXT_H, laneCount, baseRow, onDrag, onSnap };return (<div@@ -2167,85 +1928,108 @@ function TextBar({// Inline so it beats SELECTED_SHADOW's z-10 class on the same element.zIndex: drag ? 20 : undefined,}}- onPointerDown={onBody}+ onPointerDown={(e) => startLaneMove(e, "text", o.id, ui)}><span className="pointer-events-none truncate px-2 text-[10.5px] font-medium text-white">{o.text.replace(/\n/g, " ")}</span>- <span className={cn(trimHandle, "tl-trim-l left-0")} onPointerDown={onTrimLeft} />- <span className={cn(trimHandle, "tl-trim-r right-0")} onPointerDown={onTrimRight} />+ <span+ className={cn(trimHandle, "tl-trim-l left-0")}+ onPointerDown={(e) => startLaneTrim(e, "text", o.id, "l", ui)}+ />+ <span+ className={cn(trimHandle, "tl-trim-r right-0")}+ onPointerDown={(e) => startLaneTrim(e, "text", o.id, "r", ui)}+ /></div>);}/** A subtitle cue on its track: click selects (⌫ deletes it), drag to retime,* edges to trim. Editing the words happens in the Subtitles panel. */-function SubBar({ cue, pps, selected }: { cue: SubtitleCue; pps: number; selected: boolean }) {+function SubBar({+ cue,+ pps,+ selected,+ drag,+ parting,+ onDrag,+ onSnap,+}: {+ cue: SubtitleCue;+ pps: number;+ selected: boolean;+ /** This bar's live drag when it is the one being carried (ghost mode). */+ drag: LaneDrag | null;+ /** Another cue is dragging: animate this bar's shifts as it parts. */+ parting: boolean;+ onDrag: (d: LaneDrag | null) => void;+ onSnap: (x: number | null) => void;+}) {const w = Math.max(8, (cue.end - cue.start) * pps);-- const finish = (moved: boolean) => {- const s = useEditor.getState();- if (moved) s.sortCues();- else s.seek(cue.start + 0.001);- };-- const onBody = (e: React.PointerEvent) => {- if (e.metaKey || e.shiftKey) {- useEditor.getState().toggleSelect({ kind: "cue", id: cue.id });- return;- }- const s = useEditor.getState();- s.select({ kind: "cue", id: cue.id });- s.pushHistory();- const start0 = cue.start;- const len = cue.end - cue.start;- startDrag(e, {- onMove: (dx) => {- const start = Math.max(0, start0 + dx / pps);- // Moving a cue detaches it from its word timings.- s.updateCueTransient(cue.id, { start, end: start + len, words: undefined });- },- onUp: (_dx, _dy, moved) => finish(moved),- });- };-- const trim = (side: "l" | "r") => (e: React.PointerEvent) => {- const s = useEditor.getState();- s.select({ kind: "cue", id: cue.id });- s.pushHistory();- const { start: start0, end: end0 } = cue;- startDrag(e, {- onMove: (dx) => {- if (side === "l")- s.updateCueTransient(cue.id, {- start: Math.min(end0 - 0.15, Math.max(0, start0 + dx / pps)),- words: undefined,- });- else- s.updateCueTransient(cue.id, {- end: Math.max(start0 + 0.15, end0 + dx / pps),- words: undefined,- });- },- onUp: (_dx, _dy, moved) => finish(moved),- });- };+ const ui = { pps, rowH: SUB_H, laneCount: 0, baseRow: 0, onDrag, onSnap };return (<divclassName={cn("tl-sub-bar group absolute top-px flex cursor-grab items-center overflow-hidden rounded-[5px] bg-gradient-to-b from-amber-300 to-amber-400 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]",- selected && SELECTED_SHADOW+ selected && SELECTED_SHADOW,+ drag+ ? "tl-sub-ghost pointer-events-none cursor-grabbing opacity-80 shadow-2xl"+ : parting && "transition-[left] duration-150 ease-out")}- style={{ left: cue.start * pps, width: Math.max(8, w - CLIP_GAP), height: SUB_H - 4 }}+ style={{+ left: drag ? drag.ghostX : cue.start * pps,+ width: Math.max(8, w - CLIP_GAP),+ height: SUB_H - 4,+ // Inline so it beats SELECTED_SHADOW's z-10 class on the same element.+ zIndex: drag ? 20 : undefined,+ }}title={cue.text}- onPointerDown={onBody}+ onPointerDown={(e) => startLaneMove(e, "cue", cue.id, ui)}><span className="pointer-events-none truncate px-1.5 text-[9.5px] font-medium text-amber-950/90">{cue.text}</span>- <span className={cn(trimHandle, "tl-trim-l left-0")} onPointerDown={trim("l")} />- <span className={cn(trimHandle, "tl-trim-r right-0")} onPointerDown={trim("r")} />+ <span+ className={cn(trimHandle, "tl-trim-l left-0")}+ onPointerDown={(e) => startLaneTrim(e, "cue", cue.id, "l", ui)}+ />+ <span+ className={cn(trimHandle, "tl-trim-r right-0")}+ onPointerDown={(e) => startLaneTrim(e, "cue", cue.id, "r", ui)}+ /></div>);}++/** The landing-slot preview for an in-flight lane drag, drawn in the track+ * family's own chrome; it tracks the coordinator's resolved slot and row. */+function LaneSlot({+ drag,+ pps,+ rowH,+ barH,+ className,+}: {+ drag: LaneDrag;+ pps: number;+ rowH: number;+ barH: number;+ className?: string;+}) {+ return (+ <div+ className={cn(+ "tl-lane-slot pointer-events-none absolute transition-[left] duration-150 ease-out",+ className+ )}+ style={{+ left: drag.slotStart * pps,+ top: drag.targetRow * rowH + 2,+ width: Math.max(8, drag.len * pps - CLIP_GAP),+ height: barH,+ }}+ />+ );+}diff --git a/site/src/cut/lib/drag.ts b/site/src/cut/lib/drag.tsindex 827ebfee..dba2e426 100644--- a/site/src/cut/lib/drag.ts+++ b/site/src/cut/lib/drag.ts@@ -7,13 +7,37 @@ interface DragOpts {onUp?: (dx: number, dy: number, moved: boolean) => void;}+// Live count of in-flight pointer drags, so layout that depends on clip+// geometry (e.g. the timeline's scrollable width) can hold still until release.+let activeDrags = 0;+const dragListeners = new Set<() => void>();++export function subscribeDragActive(fn: () => void) {+ dragListeners.add(fn);+ return () => {+ dragListeners.delete(fn);+ };+}++export function isDragActive() {+ return activeDrags > 0;+}+/** Pointer-drag helper: tracks deltas from pointerdown until release. */export function startDrag(e: React.PointerEvent, opts: DragOpts) {e.preventDefault();e.stopPropagation();+ // preventDefault also suppresses the browser's default focus move, so end+ // any in-progress text edit here or keyboard shortcuts keep typing into it.+ if (document.activeElement !== e.currentTarget) {+ (document.activeElement as HTMLElement | null)?.blur?.();+ }+const startX = e.clientX;const startY = e.clientY;let moved = false;+ activeDrags++;+ dragListeners.forEach((fn) => fn());const move = (ev: PointerEvent) => {const dx = ev.clientX - startX;@@ -25,6 +49,8 @@ export function startDrag(e: React.PointerEvent, opts: DragOpts) {window.removeEventListener("pointermove", move);window.removeEventListener("pointerup", up);window.removeEventListener("pointercancel", up);+ activeDrags--;+ dragListeners.forEach((fn) => fn());opts.onUp?.(ev.clientX - startX, ev.clientY - startY, moved);};window.addEventListener("pointermove", move);diff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.tsnew file mode 100644index 00000000..df235ae2--- /dev/null+++ b/site/src/cut/lib/laneTracks.ts@@ -0,0 +1,607 @@+"use client";++/**+ * The lane-track coordinator: the one place for how items on the timeline's+ * free-positioned tracks behave. Audio, titles, upper video layers, and+ * subtitle cues all route their pointer gestures through here, so selection,+ * moving, resizing, collision, and snapping work identically everywhere — and+ * a new track type gets every behavior by writing one small adapter.+ *+ * The shared behaviors:+ * - Grab: cmd/shift toggles the multi-selection; a plain grab selects the+ * item and moves the playhead under the pointer.+ * - Move: the bar ghosts under the pointer while same-lane neighbors part+ * around the landing slot; either edge snaps to logical times; on+ * multi-lane kinds a vertical drag retracks the item, one row past the end+ * opens a new track, and lanes stay contiguous so empty ones collapse.+ * - Resize: edges snap; growing into a neighbor pushes its whole run along;+ * the left edge rubber-bands past its floor (the timeline start, packed+ * leaders, or a media item's first sample) and springs back on release.+ * - Placement collision: adding/pasting slides to the next free slot on the+ * lane — the store's `nextFreeStart` is that one primitive.+ * - Cut: the store's `splitAtPlayhead` slices whichever kind is selected.+ *+ * The base video track and the upper video tracks keep their richer+ * verticality (lifting between tracks, insert zones, the base row) by passing+ * a `vertical` strategy to the move gesture; everything else about them is+ * the shared behavior.+ */++import type React from "react";+import { refFromAsset, startPointerRefDrag } from "./assetRef";+import { startDrag } from "./drag";+import { clipLen, getClipSpans, projectDuration, useEditor } from "./store";+import type {+ AudioClip,+ MediaAsset,+ OverlayClip,+ Selection,+ SubtitleCue,+ TextOverlay,+ VideoClip,+} from "./types";++type S = ReturnType<typeof useEditor.getState>;++export type LaneKind = "clip" | "audio" | "text" | "overlayClip" | "cue";++/** Visual gutter between adjacent clips (iMovie); time math stays exact. */+export const CLIP_GAP = 4;+/** Pull a dragged or resized edge to a logical time within this many px. */+export const SNAP_PX = 6;+/** How far (px) a left edge can rubber-band past its floor before springing back. */+const LEFT_RUBBER_PX = 32;++/** Normalized geometry of one item on a lane track. */+interface LaneItem {+ id: string;+ start: number;+ len: number;+ lane: number;+}++type Patch<T> = { id: string; patch: Partial<T> };++/**+ * Everything kind-specific, so the gestures stay generic. Patches are built+ * from gesture-start snapshots, which makes a retreating drag restore the+ * originals exactly (including a cue's word timings).+ */+interface LaneAdapter<T> {+ minLen: number;+ /** Vertical drag retracks among this kind's own lanes. */+ multiLane: boolean;+ raws(s: S): T[];+ view(raw: T): LaneItem;+ /** Apply patches transiently (no undo entry; the gesture checkpoints once). */+ apply(patches: Patch<T>[]): void;+ movePatch(raw: T, start: number): Patch<T>;+ trimLeftPatch(raw: T, newStart: number): Patch<T>;+ trimRightPatch(raw: T, newEnd: number): Patch<T>;+ /** Earliest timeline start the left edge can reveal to (media source floor). */+ leftFloor(raw: T): number;+ /** Longest timeline footprint the item can grow to (media source bound). */+ maxLen(s: S, raw: T): number;+ /** Write a committed lane number (multi-lane kinds only). */+ lanePatch?(raw: T, lane: number): Patch<T>;+ /** The media behind the item, so dragging it can feed reference drop zones. */+ assetOf?(s: S, raw: T): MediaAsset | undefined;+ /** After a committed move (e.g. keep cues sorted). */+ onMoved?(): void;+}++const speedOf = (c: { speed?: number }) => (c.speed && c.speed > 0 ? c.speed : 1);++const clipAdapter: LaneAdapter<VideoClip> = {+ minLen: 0.15,+ // Verticality is the video placement system (upper tracks and insert+ // zones), fed in as the move gesture's `vertical` strategy.+ multiLane: false,+ raws: (s) => s.clips,+ view: (c) => ({ id: c.id, start: c.start, len: clipLen(c), lane: 0 }),+ apply: (patches) => useEditor.getState().updateClipsTransient(patches),+ movePatch: (c, start) => ({ id: c.id, patch: { start } }),+ trimLeftPatch: (c, newStart) => ({+ id: c.id,+ patch: { start: newStart, in: c.in + (newStart - c.start) * speedOf(c) },+ }),+ trimRightPatch: (c, newEnd) => ({+ id: c.id,+ patch: { out: c.in + (newEnd - c.start) * speedOf(c) },+ }),+ leftFloor: (c) => Math.max(0, c.start - c.in / speedOf(c)),+ maxLen: (s, c) => {+ const a = s.assets.find((x) => x.id === c.assetId);+ // A still has no source length, so its clip can stretch to any duration.+ if (a?.type === "image") return Infinity;+ return ((a?.duration ?? c.out) - c.in) / speedOf(c);+ },+ assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId),+ onMoved: () => useEditor.getState().sortClips(),+};++const audioAdapter: LaneAdapter<AudioClip> = {+ minLen: 0.15,+ multiLane: true,+ raws: (s) => s.audioClips,+ view: (a) => ({ id: a.id, start: a.start, len: clipLen(a), lane: a.lane ?? 0 }),+ apply: (patches) => useEditor.getState().updateAudiosTransient(patches),+ movePatch: (a, start) => ({ id: a.id, patch: { start } }),+ trimLeftPatch: (a, newStart) => ({+ id: a.id,+ patch: { start: newStart, in: a.in + (newStart - a.start) * speedOf(a) },+ }),+ trimRightPatch: (a, newEnd) => ({+ id: a.id,+ patch: { out: a.in + (newEnd - a.start) * speedOf(a) },+ }),+ leftFloor: (a) => Math.max(0, a.start - a.in / speedOf(a)),+ maxLen: (s, a) =>+ ((s.assets.find((x) => x.id === a.assetId)?.duration ?? a.out) - a.in) / speedOf(a),+ lanePatch: (a, lane) => ({ id: a.id, patch: { lane: lane > 0 ? lane : undefined } }),+ assetOf: (s, a) => s.assets.find((x) => x.id === a.assetId),+};++const textAdapter: LaneAdapter<TextOverlay> = {+ minLen: 0.2,+ multiLane: true,+ raws: (s) => s.overlays,+ view: (o) => ({ id: o.id, start: o.start, len: o.end - o.start, lane: o.lane ?? 0 }),+ apply: (patches) => useEditor.getState().updateOverlaysTransient(patches),+ movePatch: (o, start) => ({ id: o.id, patch: { start, end: start + (o.end - o.start) } }),+ trimLeftPatch: (o, newStart) => ({ id: o.id, patch: { start: newStart } }),+ trimRightPatch: (o, newEnd) => ({ id: o.id, patch: { end: newEnd } }),+ leftFloor: () => 0,+ maxLen: () => Infinity,+ lanePatch: (o, lane) => ({ id: o.id, patch: { lane } }),+};++const overlayClipAdapter: LaneAdapter<OverlayClip> = {+ minLen: 0.15,+ // Verticality is the video placement system (tracks and insert zones), fed+ // in as the move gesture's `vertical` strategy.+ multiLane: false,+ raws: (s) => s.overlayClips,+ view: (c) => ({ id: c.id, start: c.start, len: clipLen(c), lane: c.track }),+ apply: (patches) => useEditor.getState().updateOverlayClipsTransient(patches),+ movePatch: (c, start) => ({ id: c.id, patch: { start } }),+ trimLeftPatch: (c, newStart) => ({+ id: c.id,+ patch: { start: newStart, in: c.in + (newStart - c.start) * speedOf(c) },+ }),+ trimRightPatch: (c, newEnd) => ({+ id: c.id,+ patch: { out: c.in + (newEnd - c.start) * speedOf(c) },+ }),+ leftFloor: (c) => Math.max(0, c.start - c.in / speedOf(c)),+ maxLen: (s, c) =>+ ((s.assets.find((x) => x.id === c.assetId)?.duration ?? c.out) - c.in) / speedOf(c),+ assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId),+};++const cueAdapter: LaneAdapter<SubtitleCue> = {+ minLen: 0.15,+ multiLane: false,+ raws: (s) => s.subtitles.cues,+ view: (c) => ({ id: c.id, start: c.start, len: c.end - c.start, lane: 0 }),+ apply: (patches) => useEditor.getState().updateCuesTransient(patches),+ // Retiming detaches a cue from its word timings; an unmoved patch restores+ // the originals, so parted neighbors that flow back keep theirs.+ movePatch: (c, start) => ({+ id: c.id,+ patch: {+ start,+ end: start + (c.end - c.start),+ words: Math.abs(start - c.start) < 1e-6 ? c.words : undefined,+ },+ }),+ trimLeftPatch: (c, newStart) => ({ id: c.id, patch: { start: newStart, words: undefined } }),+ trimRightPatch: (c, newEnd) => ({ id: c.id, patch: { end: newEnd, words: undefined } }),+ leftFloor: () => 0,+ maxLen: () => Infinity,+ onMoved: () => useEditor.getState().sortCues(),+};++type LaneRaw = VideoClip | AudioClip | TextOverlay | OverlayClip | SubtitleCue;+// The generic parameter is erased at the registry boundary; each gesture only+// feeds an adapter values that came out of that same adapter, so this is safe.+const ADAPTERS: Record<LaneKind, LaneAdapter<LaneRaw>> = {+ clip: clipAdapter as unknown as LaneAdapter<LaneRaw>,+ audio: audioAdapter as unknown as LaneAdapter<LaneRaw>,+ text: textAdapter as unknown as LaneAdapter<LaneRaw>,+ overlayClip: overlayClipAdapter as unknown as LaneAdapter<LaneRaw>,+ cue: cueAdapter as unknown as LaneAdapter<LaneRaw>,+};++/** Logical times an edge can snap to: the timeline start, the base track's+ * cut points and end, the playhead, and every other lane item's edges across+ * all track kinds — a title can align to a music hit and vice versa. */+function snapTargets(s: S, kind: LaneKind, selfId: string): number[] {+ const pts = new Set<number>([0]);+ for (const sp of getClipSpans(s.clips, s.assets)) {+ // The visible joint: a dissolved pair meets at the overlap midpoint (where+ // the clip boxes are inset to), a hard cut at the footprint end.+ pts.add(sp.start + sp.len - sp.transitionOut / 2);+ }+ pts.add(projectDuration(s));+ pts.add(s.currentTime);+ for (const k of Object.keys(ADAPTERS) as LaneKind[]) {+ for (const raw of ADAPTERS[k].raws(s)) {+ const v = ADAPTERS[k].view(raw);+ if (k === kind && v.id === selfId) continue;+ pts.add(v.start);+ pts.add(v.start + v.len);+ }+ }+ return [...pts];+}++/** The nearest snap target within `tol` seconds, or null. */+function nearestSnap(t: number, targets: number[], tol: number): number | null {+ let best: number | null = null;+ let bd = tol;+ for (const T of targets) {+ const d = Math.abs(t - T);+ if (d <= bd) {+ bd = d;+ best = T;+ }+ }+ return best;+}++/** Ease that overshoots the target then settles — the elastic snap-back feel. */+function easeOutBack(p: number): number {+ const c1 = 1.70158;+ const c3 = c1 + 1;+ return 1 + c3 * Math.pow(p - 1, 3) + c1 * Math.pow(p - 1, 2);+}++/** Damp an overshoot in px so it gives but resists, saturating near `max`. */+function rubberBand(overPx: number, max: number): number {+ return max * (1 - Math.exp(-Math.max(0, overPx) / max));+}++// A snapped edge draws its guide where the bar is actually rendered: a left+// edge at the time itself, a right edge inset by the CLIP_GAP gutter, so the+// line hugs the bar's visible right edge instead of the next item's start.+const leftGuide = (t: number, pps: number) => t * pps;+const rightGuide = (t: number, pps: number) => t * pps - CLIP_GAP;++// The in-flight elastic snap-back; any new gesture cancels it.+let snapBackRaf = 0;++/** The live move drag, published so the Timeline can render the ghost, the+ * landing slot, and grow the lane stack while a new row is hovered. */+export interface LaneDrag {+ kind: LaneKind;+ id: string;+ targetRow: number; // hovered display row (one past the end = new track)+ ghostX: number; // ghost left in px — follows the pointer+ slotStart: number; // resolved landing start, seconds+ len: number; // dragged item length, seconds+ /** Carried off its own lane set (an upper video layer headed elsewhere);+ * the home slot preview hides while away. */+ away?: boolean;+}++export interface LaneMoveUI<V = unknown> {+ pps: number;+ rowH: number;+ /** Display rows currently in use; targetRow may go one past to open a new track. */+ laneCount: number;+ /** The grabbed item's current display row. */+ baseRow: number;+ /** Publish (or clear) the in-flight drag so the slot and rows track it. */+ onDrag(d: LaneDrag | null): void;+ /** Paint (or clear) the snap guide at this stage-x pixel. */+ onSnap(x: number | null): void;+ /** Cross-structure verticality (upper video tracks): resolve where the+ * pointer is, preview non-home targets, and commit the drop. When absent,+ * vertical motion retracks among this kind's own lanes. */+ vertical?: {+ resolve(ev: PointerEvent): V;+ isHome(target: V): boolean;+ preview(target: V | null, start: number, len: number): void;+ commit(id: string, target: V, start: number): void;+ setActive?(active: boolean): void;+ };+}++/** Grab an item: select (or cmd/shift-toggle) it, then drag to move it along+ * and across lanes with parting, snapping, and lane retracking. */+export function startLaneMove<V = unknown>(+ e: React.PointerEvent,+ kind: LaneKind,+ id: string,+ ui: LaneMoveUI<V>+) {+ cancelAnimationFrame(snapBackRaf);+ const s = useEditor.getState();+ if (e.metaKey || e.shiftKey) {+ s.toggleSelect({ kind, id } as NonNullable<Selection>);+ return;+ }+ const ad = ADAPTERS[kind];+ const raw0 = ad.raws(s).find((r) => ad.view(r).id === id);+ if (!raw0) return;+ const self = ad.view(raw0);+ s.select({ kind, id } as Selection);+ // Clicking anywhere on the timeline moves the playhead — bars included.+ s.seek(self.start + (e.clientX - e.currentTarget.getBoundingClientRect().left) / ui.pps);+ s.pushHistory();++ const start0 = self.start;+ const len = self.len;+ // Everyone else's resting spot, captured once: each move re-lays the lane+ // from these, so a retreating drag lets parted neighbors flow back.+ const rest = ad+ .raws(s)+ .filter((r) => ad.view(r).id !== id)+ .map((r) => ({ raw: r, view: ad.view(r) }));+ const usedLanes = [...new Set([...rest.map((x) => x.view.lane), self.lane])].sort(+ (a, b) => a - b+ );+ const targets = snapTargets(s, kind, id);+ const tol = SNAP_PX / ui.pps;+ // Dragging a media-backed item can also hand its asset to a reference drop+ // zone (AI chat, the image/video creators).+ const asset = ad.assetOf?.(s, raw0);+ const refDrag = asset ? startPointerRefDrag(refFromAsset(asset)) : null;++ let live = false;+ let targetRow = ui.baseRow;+ let slotStart = start0;+ let ds = start0;+ let awayTarget: V | null = null;++ const restRestore = () => ad.apply(rest.map((x) => ad.movePatch(x.raw, x.view.start)));++ startDrag(e, {+ onMove: (dx, dy, ev) => {+ if (!live && Math.abs(dx) < 4 && Math.abs(dy) < 4) return;+ if (!live) ui.vertical?.setActive?.(true);+ live = true;+ refDrag?.move(ev);+ ds = Math.max(0, start0 + dx / ui.pps);++ // Carried off its own lane set (an upper video layer headed to another+ // track, the base row, or an insert gap): neighbors flow back and the+ // placement system previews the target instead.+ if (ui.vertical) {+ const target = ui.vertical.resolve(ev);+ if (!ui.vertical.isHome(target)) {+ awayTarget = target;+ restRestore();+ ui.onSnap(null);+ ui.vertical.preview(target, ds, len);+ ui.onDrag({+ kind,+ id,+ targetRow: ui.baseRow,+ ghostX: ds * ui.pps,+ slotStart: ds,+ len,+ away: true,+ });+ return;+ }+ awayTarget = null;+ ui.vertical.preview(null, 0, 0);+ }++ // Vertical drag retracks the item; one row past the end opens a new one.+ targetRow = ad.multiLane+ ? Math.min(ui.laneCount, Math.max(0, ui.baseRow + Math.round(dy / ui.rowH)))+ : ui.baseRow;+ // A brand-new row has no neighbors to part.+ const lane = targetRow < usedLanes.length ? usedLanes[targetRow] : Infinity;++ // Snap whichever edge of the moving item lands nearest a logical time.+ let start = ds;+ let guide: number | null = null;+ if (!ev.metaKey) {+ const end = start + len;+ let best = { d: tol, start, px: null as number | null };+ for (const T of targets) {+ if (Math.abs(start - T) < best.d)+ best = { d: Math.abs(start - T), start: T, px: leftGuide(T, ui.pps) };+ if (Math.abs(end - T) < best.d)+ best = { d: Math.abs(end - T), start: T - len, px: rightGuide(T, ui.pps) };+ }+ if (best.px !== null) {+ start = Math.max(0, best.start);+ guide = best.px;+ }+ }+ // Same-lane neighbors part around the slot: ones whose midpoint sits+ // left of the ghost's center keep their spot (the slot lands after+ // them), the rest slide right as a run to make room.+ const others = rest+ .filter((x) => x.view.lane === lane)+ .sort((a, b) => a.view.start - b.view.start);+ const center = ds + len / 2;+ const before = others.filter((x) => x.view.start + x.view.len / 2 <= center);+ const after = others.filter((x) => x.view.start + x.view.len / 2 > center);+ const clamped = Math.max(start, ...before.map((b) => b.view.start + b.view.len));+ if (clamped !== start) guide = null;+ slotStart = clamped;+ const delta = after.length ? Math.max(0, clamped + len - after[0].view.start) : 0;+ const pushed = new Set(after.map((x) => x.view.id));+ ui.onSnap(guide);+ ad.apply(+ rest.map((x) =>+ ad.movePatch(x.raw, pushed.has(x.view.id) ? x.view.start + delta : x.view.start)+ )+ );+ ui.onDrag({ kind, id, targetRow, ghostX: ds * ui.pps, slotStart: clamped, len });+ },+ onUp: (_dx, _dy, moved) => {+ ui.vertical?.setActive?.(false);+ ui.onSnap(null);+ ui.onDrag(null);+ if (live && refDrag?.drop()) {+ // A reference zone took the asset; undo every transient slide.+ restRestore();+ ui.vertical?.preview(null, 0, 0);+ return;+ }+ if (ui.vertical && awayTarget !== null && !ui.vertical.isHome(awayTarget)) {+ ui.vertical.commit(id, awayTarget, ds);+ return;+ }+ if (!live || !moved) return;+ ad.apply([ad.movePatch(raw0, slotStart)]);+ commitRow(kind, id, targetRow);+ ad.onMoved?.();+ },+ });+}++/** Land a dragged item on a display row: a row past the end becomes a+ * brand-new track after the current max, then lanes renumber to stay+ * contiguous so empty tracks collapse. The move's pointer-down already+ * checkpointed history, so the whole gesture is one undo step. */+function commitRow(kind: LaneKind, id: string, targetRow: number) {+ const s = useEditor.getState();+ const ad = ADAPTERS[kind];+ if (!ad.multiLane || !ad.lanePatch) return;+ const raws = ad.raws(s);+ const views = raws.map((r) => ad.view(r));+ const used = [...new Set(views.map((v) => v.lane))].sort((a, b) => a - b);+ const cur = views.find((v) => v.id === id);+ if (!cur || targetRow === used.indexOf(cur.lane)) return;+ const lane = targetRow < used.length ? used[targetRow] : (used[used.length - 1] ?? -1) + 1;+ const moved = views.map((v) => (v.id === id ? lane : v.lane));+ const usedNext = [...new Set(moved)].sort((a, b) => a - b);+ const remap = new Map(usedNext.map((l, i) => [l, i]));+ ad.apply(raws.map((r, i) => ad.lanePatch!(r, remap.get(moved[i]) ?? 0)));+}++export interface LaneTrimUI {+ pps: number;+ /** Paint (or clear) the snap guide at this stage-x pixel. */+ onSnap(x: number | null): void;+}++/** Resize an item from either edge, with snapping, neighbor pushing, source+ * bounds for media, and the rubber-band + spring-back left-edge floor. */+export function startLaneTrim(+ e: React.PointerEvent,+ kind: LaneKind,+ id: string,+ side: "l" | "r",+ ui: LaneTrimUI+) {+ cancelAnimationFrame(snapBackRaf);+ const s = useEditor.getState();+ const ad = ADAPTERS[kind];+ const raw0 = ad.raws(s).find((r) => ad.view(r).id === id);+ if (!raw0) return;+ const self = ad.view(raw0);+ s.select({ kind, id } as Selection);+ s.pushHistory();+ const targets = snapTargets(s, kind, id);+ const tol = SNAP_PX / ui.pps;+ const sameLane = ad+ .raws(s)+ .map((r) => ({ raw: r, view: ad.view(r) }))+ .filter((x) => x.view.id !== id && x.view.lane === self.lane);++ if (side === "l") {+ const start0 = self.start;+ const maxStart = start0 + self.len - ad.minLen;+ // Items before this one, at their original spots. The edge grows freely+ // into the open gap; past the neighbor it shoves the run left, closing+ // gap after gap until everything sits flush against 0 — plus a media+ // item's own floor: the edge can't reveal earlier than its first sample.+ const leaders = sameLane+ .filter((x) => x.view.start + x.view.len <= start0 + 1e-3)+ .sort((a, b) => a.view.start - b.view.start);+ const prevEnd = leaders.reduce((m, l) => Math.max(m, l.view.start + l.view.len), 0);+ const runFloor = leaders.reduce((sum, l) => sum + l.view.len, 0);+ const floor = Math.max(runFloor, ad.leftFloor(raw0));+ const free = Math.max(prevEnd, ad.leftFloor(raw0));+ startDrag(e, {+ onMove: (dx, _dy, ev) => {+ cancelAnimationFrame(snapBackRaf);+ const desired = Math.min(maxStart, start0 + dx / ui.pps);+ let start: number;+ if (desired >= free) {+ // Room to the left: grow freely, snapping to logical times.+ start = desired;+ const hit = ev.metaKey ? null : nearestSnap(start, targets, tol);+ if (hit !== null && hit >= free && hit <= maxStart) {+ start = hit;+ ui.onSnap(leftGuide(hit, ui.pps));+ } else ui.onSnap(null);+ } else {+ // Pushing: past the floor it drags with resistance and springs back.+ start =+ desired >= floor+ ? desired+ : Math.max(+ 0,+ floor - rubberBand((floor - desired) * ui.pps, LEFT_RUBBER_PX) / ui.pps+ );+ ui.onSnap(null);+ }+ // Re-lay the leaders right-to-left from their resting spots: each one+ // slides only as far as the pushed edge (or the item it now abuts)+ // forces it, so a retreating drag lets the run flow back.+ const patches = [ad.trimLeftPatch(raw0, start)];+ let limit = Math.max(start, runFloor);+ for (let i = leaders.length - 1; i >= 0; i--) {+ const l = leaders[i];+ const end = Math.min(l.view.start + l.view.len, limit);+ patches.push(ad.movePatch(l.raw, end - l.view.len));+ limit = end - l.view.len;+ }+ ad.apply(patches);+ },+ onUp: () => {+ ui.onSnap(null);+ const cur = ad.raws(useEditor.getState()).find((r) => ad.view(r).id === id);+ const from = cur ? ad.view(cur).start : floor;+ if (from >= floor - 1e-4) return; // settled within the room+ // Elastic spring back to the floor.+ const t0 = performance.now();+ const step = (now: number) => {+ const p = Math.min(1, (now - t0) / 240);+ const v = Math.max(0, from + (floor - from) * easeOutBack(p));+ ad.apply([ad.trimLeftPatch(raw0, p < 1 ? v : floor)]);+ if (p < 1) snapBackRaf = requestAnimationFrame(step);+ };+ snapBackRaf = requestAnimationFrame(step);+ },+ });+ return;+ }++ const end0 = self.start + self.len;+ const minEnd = self.start + ad.minLen;+ const maxEnd = self.start + ad.maxLen(s, raw0);+ // Items after this one, at their original spots: extending the edge past+ // the first of them pushes the whole run right (their gaps preserved);+ // pulling back lets them return.+ const followers = sameLane+ .filter((x) => x.view.start >= self.start)+ .sort((a, b) => a.view.start - b.view.start);+ const nextStart = followers.length ? followers[0].view.start : Infinity;+ startDrag(e, {+ onMove: (dx, _dy, ev) => {+ let end = Math.max(minEnd, Math.min(maxEnd, end0 + dx / ui.pps));+ const hit = ev.metaKey ? null : nearestSnap(end, targets, tol);+ if (hit !== null && hit > minEnd && hit <= maxEnd) {+ end = hit;+ ui.onSnap(rightGuide(end, ui.pps));+ } else ui.onSnap(null);+ const delta = Math.max(0, end - nextStart);+ ad.apply([+ ad.trimRightPatch(raw0, end),+ ...followers.map((f) => ad.movePatch(f.raw, f.view.start + delta)),+ ]);+ },+ onUp: () => ui.onSnap(null),+ });+}diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 91efea49..9cd1f460 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -130,20 +130,18 @@ export interface EditorState {updateAsset: (id: string, patch: Partial<MediaAsset>) => void;/** Remove a project asset and any clips/audio that reference it. */removeAsset: (id: string) => void;- /** Add a video clip from an asset. With `index`, insert at that position on- * the magnetic video track; otherwise append. */- addClipFromAsset: (assetId: string, index?: number) => void;+ /** Add a video clip from an asset onto the base track — at `start` (sliding+ * to the track's next free slot), or appended at the end when omitted. */+ addClipFromAsset: (assetId: string, start?: number) => void;/** Add a soundtrack clip from an audio asset at `start` (default: the* playhead). `opts.duck` marks it a voiceover that lowers everything else- * to that gain while it plays. */- addAudioFromAsset: (assetId: string, start?: number, opts?: { duck?: number }) => void;+ * to that gain while it plays; `opts.lane` picks the audio track it lands+ * on (default: the first one). */+ addAudioFromAsset: (assetId: string, start?: number, opts?: { duck?: number; lane?: number }) => void;addOverlay: () => void;- /** Move a title to a title track (row); lanes are renumbered to stay- * contiguous, so empty tracks collapse and a past-the-end lane adds one. */- moveOverlayToLane: (id: string, lane: number) => void;updateClip: (id: string, patch: Partial<VideoClip>) => void;- /** Set a clip's playback rate (0.25–4). The clip's timeline footprint- * changes, so later titles/captions ripple to stay in sync. */+ /** Set a clip's playback rate (0.25–4). A longer footprint pushes the+ * following clips right by the overflow; a shorter one opens a gap. */setClipSpeed: (id: string, speed: number) => void;/** Set the transition into the next clip (seconds; 0 clears it), optionally* changing its style; omitting the style keeps the clip's current one. */@@ -152,17 +150,26 @@ export interface EditorState {updateOverlay: (id: string, patch: Partial<TextOverlay>) => void;/** Live-drag updates that should not create undo entries. */updateOverlayTransient: (id: string, patch: Partial<TextOverlay>) => void;- /** Patch several titles in one commit (ripple resize pushes a whole lane). */+ /** Patch several items in one commit — the lane coordinator's gestures part+ * and push whole lanes at a time (one bulk patcher per lane-track kind). */updateOverlaysTransient: (patches: { id: string; patch: Partial<TextOverlay> }[]) => void;+ updateAudiosTransient: (patches: { id: string; patch: Partial<AudioClip> }[]) => void;+ updateOverlayClipsTransient: (patches: { id: string; patch: Partial<OverlayClip> }[]) => void;+ updateCuesTransient: (patches: { id: string; patch: Partial<SubtitleCue> }[]) => void;+ updateClipsTransient: (patches: { id: string; patch: Partial<VideoClip> }[]) => void;updateClipTransient: (id: string, patch: Partial<VideoClip>) => void;updateAudioTransient: (id: string, patch: Partial<AudioClip>) => void;+ /** Keep the clips array sorted by start (consumers read `clips[0]` as the+ * timeline's first clip). Called after a lane-coordinator move commits. */+ sortClips: () => void;+ /** Reorder the base track by index and re-pack it (the AI reorder op). */moveClip: (id: string, toIndex: number) => void;/** Add a video asset to the timeline at a placement: an upper track, the base* row, or a freshly inserted track. Used by media / library drops. */addVideoFromAsset: (assetId: string, place: VideoTrackPlacement, start: number) => void;/** Move an existing clip (base or upper) to a placement, preserving its- * trim/region/speed. Inserting a track renumbers the ones above it; dropping on- * the base row converts it back to a magnetic clip. Owns its own history. */+ * trim/region/speed. Inserting a track renumbers the ones above it; dropping+ * on the base row lands free-positioned at the drop time. Owns its own history. */dropVideoClip: (source: { kind: "base" | "overlay"; id: string },place: VideoTrackPlacement,@@ -217,11 +224,6 @@ export interface EditorState {/** ⌘/⇧-click: add the item to the selection (or remove it if already in),* making it the new primary. */toggleSelect: (sel: NonNullable<Selection>) => void;- /** Shift every free-positioned title and subtitle cue starting at or after- * `afterTime` by `delta` seconds (clamped to ≥0). Keeps annotations synced- * when the video track's length changes upstream. Caller owns the history- * checkpoint. */- rippleShift: (afterTime: number, delta: number) => void;seek: (t: number) => void;setPlaying: (p: boolean) => void;setPxPerSec: (v: number) => void;@@ -270,8 +272,9 @@ let clipboard: ClipboardItem[] = [];/** Earliest start at/after `t` where a `len`-long item fits between the* occupied `spans` of one lane: each blocker slides the candidate right to its- * end until a big-enough gap opens. */-function nextFreeStart(spans: { start: number; end: number }[], t: number, len: number): number {+ * end until a big-enough gap opens. The one placement-collision primitive for+ * every lane track (add, paste, drop). */+export function nextFreeStart(spans: { start: number; end: number }[], t: number, len: number): number {const sorted = [...spans].sort((a, b) => a.start - b.start);let at = t;for (const sp of sorted) {@@ -406,10 +409,13 @@ export const useEditor = create<EditorState>((set, get) => {...a,url: mediaUrl(id, a.fileName),}));+ // Older docs stored the base track packed (array order implied the+ // position); bake explicit starts in once so every clip is free-placed.+ const legacy = (doc.clips as LegacyClip[]).some((c) => typeof c.start !== "number");set({projectName: doc.name,assets,- clips: doc.clips,+ clips: legacy ? packStarts(doc.clips as LegacyClip[]) : doc.clips,audioClips: doc.audioClips,overlayClips: doc.overlayClips ?? [],overlays: doc.overlays,@@ -497,9 +503,8 @@ export const useEditor = create<EditorState>((set, get) => {const st = get();if (!st.assets.some((a) => a.id === id)) return;push();- // Cascade removes this asset's clips; ripple later annotations so they- // stay aligned with the content that survives.- const bump = makeRipple(st.clips, st.clips.filter((c) => c.assetId !== id), st.assets);+ // Cascade removes this asset's clips; every clip is free-positioned, so+ // the rest of the timeline (and its annotations) stays where it is.set((s) => {const goneClips = new Set(s.clips.filter((c) => c.assetId === id).map((c) => c.id));const goneAudio = new Set(s.audioClips.filter((c) => c.assetId === id).map((c) => c.id));@@ -512,43 +517,48 @@ export const useEditor = create<EditorState>((set, get) => {assets: s.assets.filter((a) => a.id !== id),clips: s.clips.filter((c) => c.assetId !== id),audioClips: s.audioClips.filter((c) => c.assetId !== id),- overlays: s.overlays.map(bump),- subtitles: { ...s.subtitles, cues: s.subtitles.cues.map(bump) },multiSelection,selection: keep(s.selection) ? s.selection : multiSelection[multiSelection.length - 1] ?? null,};});},- addClipFromAsset: (assetId, index) => {+ addClipFromAsset: (assetId, start) => {const asset = get().assets.find((a) => a.id === assetId);if (!asset || (asset.type !== "video" && asset.type !== "image")) return;push();+ const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;+ const len = Math.max(MIN_LEN, out);+ // Default: append at the end of the base track; with a target time,+ // slide to the track's next free slot there.+ const want = Math.max(0, start ?? totalDuration(get().clips));+ const taken = get().clips.map((c) => ({ start: c.start, end: c.start + clipLen(c) }));const clip: VideoClip = {id: uid(),assetId,+ start: nextFreeStart(taken, want, len),in: 0,- out: asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration,+ out,muted: false,};- set((s) => {- const at =- index === undefined ? s.clips.length : Math.max(0, Math.min(index, s.clips.length));- const clips = [...s.clips];- clips.splice(at, 0, clip);- return { clips, ...sole({ kind: "clip", id: clip.id }) };- });+ set((s) => ({+ clips: [...s.clips, clip].sort((a, b) => a.start - b.start),+ ...sole({ kind: "clip", id: clip.id }),+ }));},addAudioFromAsset: (assetId, start, opts) => {const asset = get().assets.find((a) => a.id === assetId);if (!asset || asset.type !== "audio") return;push();- // The soundtrack is one lane — slide the clip to the next free slot at or- // after the target so it never lands on top of an existing sound.+ // 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 len = Math.max(MIN_LEN, asset.duration);- const taken = get().audioClips.map((a) => ({ start: a.start, end: a.start + clipLen(a) }));+ const lane = opts?.lane ?? 0;+ const taken = get()+ .audioClips.filter((a) => (a.lane ?? 0) === lane)+ .map((a) => ({ start: a.start, end: a.start + clipLen(a) }));const clip: AudioClip = {id: uid(),assetId,@@ -559,6 +569,7 @@ export const useEditor = create<EditorState>((set, get) => {...(opts?.duck !== undefined && opts.duck < 1? { duck: Math.max(0, opts.duck) }: {}),+ ...(lane > 0 ? { lane } : {}),};set((s) => ({audioClips: [...s.audioClips, clip],@@ -570,7 +581,12 @@ export const useEditor = create<EditorState>((set, get) => {push();const t = get().currentTime;const total = totalDuration(get().clips);- const start = Math.min(t, Math.max(0, total - 0.5));+ // Aim for the playhead but slide to the first lane's next free slot so+ // the new title never lands on top of an existing one.+ const taken = get()+ .overlays.filter((o) => (o.lane ?? 0) === 0)+ .map((o) => ({ start: o.start, end: o.end }));+ const start = nextFreeStart(taken, Math.min(t, Math.max(0, total - 0.5)), 3);// Seed the visual style from the last-used title so repeated titles in a// project share one look; fall back to the built-in defaults.const remembered = readTextStyle();@@ -598,20 +614,6 @@ export const useEditor = create<EditorState>((set, get) => {}));},- moveOverlayToLane: (id, lane) => {- const overlays = get().overlays;- if (!overlays.some((o) => o.id === id)) return;- // No checkpoint here: the drag gesture that calls this already pushed- // one at pointer-down, so the whole move is a single undo step.- // Drop the title on the target row, then renumber so lanes stay- // contiguous — empty tracks vanish, and a past-the-end target becomes a- // fresh top-numbered track.- const moved = overlays.map((o) => (o.id === id ? { ...o, lane } : o));- const used = [...new Set(moved.map((o) => o.lane ?? 0))].sort((a, b) => a - b);- const remap = new Map(used.map((l, i) => [l, i]));- set({ overlays: moved.map((o) => ({ ...o, lane: remap.get(o.lane ?? 0) ?? 0 })) });- },-// The non-transient updaters are just a checkpoint plus the live update.updateClip: (id, patch) => {push();@@ -624,37 +626,62 @@ export const useEditor = create<EditorState>((set, get) => {if (!clip) return;const clamped = Math.max(SPEED_MIN, Math.min(SPEED_MAX, speed));if (Math.abs(clamped - clipSpeed(clip)) < 1e-4) return;- const span = getClipSpans(s.clips, s.assets).find((sp) => sp.clip.id === id);- const oldLen = span?.len ?? clipLen(clip);const newLen = Math.max(MIN_LEN, (clip.out - clip.in) / clamped);- const editEnd = (span?.start ?? 0) + oldLen;push();get().updateClipTransient(id, { speed: clamped });- get().rippleShift(editEnd, newLen - oldLen);+ // Free track: a longer footprint pushes the following run right by the+ // overflow (like a resize); a shorter one just opens a gap.+ const followers = s.clips.filter((c) => c.id !== id && c.start >= clip.start);+ const nextStart = followers.reduce((m, c) => Math.min(m, c.start), Infinity);+ const delta = Math.max(0, clip.start + newLen - nextStart);+ if (delta > 1e-6) {+ set((st) => ({+ clips: st.clips.map((c) =>+ c.id !== id && c.start >= clip.start ? { ...c, start: c.start + delta } : c+ ),+ }));+ }},setClipTransition: (id, seconds, style) => {const s = get();- const idx = s.clips.findIndex((c) => c.id === id);+ const spans = getClipSpans(s.clips, s.assets);+ const idx = spans.findIndex((sp) => sp.clip.id === id);if (idx < 0) return;- const clip = s.clips[idx];- const next = s.clips[idx + 1];+ const clip = spans[idx].clip;+ const next = spans[idx + 1]?.clip;const value = Math.max(0, Math.min(TRANSITION_MAX, seconds));const newStyle = value > 0 ? (style ?? clip.transitionStyle ?? "crossfade") : undefined;- const oldOverlap = transitionOverlap(clip, next);const newOverlap = transitionOverlap({ ...clip, transition: value, transitionStyle: newStyle },next);- const span = getClipSpans(s.clips, s.assets).find((sp) => sp.clip.id === id);- const editEnd = (span?.start ?? 0) + (span?.len ?? clipLen(clip));push();get().updateClipTransient(id, {transition: value || undefined,// "crossfade" is the default — store it as absence to keep docs lean.transitionStyle: newStyle === "crossfade" ? undefined : newStyle,});- get().rippleShift(editEnd, oldOverlap - newOverlap);+ // A dissolve is a physical overlap: setting one slides the next clip+ // (and the run behind it, gaps preserved) so it starts `newOverlap`+ // before this clip ends — closing any gap, since a dissolve needs+ // contact. Clearing one pushes the pair back to a hard cut. Edge styles+ // overlap nothing: they leave the layout alone.+ if (next) {+ const oldOverlap = spans[idx].transitionOut;+ const wantStart =+ newOverlap > 0 ? clip.start + clipLen(clip) - newOverlap : next.start + oldOverlap;+ const delta = wantStart - next.start;+ if (Math.abs(delta) > 1e-6) {+ set((st) => ({+ clips: st.clips+ .map((c) =>+ c.start >= next.start - 1e-6 ? { ...c, start: Math.max(0, c.start + delta) } : c+ )+ .sort((a, b) => a.start - b.start),+ }));+ }+ }},updateAudio: (id, patch) => {@@ -682,11 +709,61 @@ export const useEditor = create<EditorState>((set, get) => {};}),+ updateAudiosTransient: (patches) =>+ set((s) => {+ const byId = new Map(patches.map((p) => [p.id, p.patch]));+ return {+ audioClips: s.audioClips.map((c) => {+ const patch = byId.get(c.id);+ return patch ? { ...c, ...patch } : c;+ }),+ };+ }),++ updateOverlayClipsTransient: (patches) =>+ set((s) => {+ const byId = new Map(patches.map((p) => [p.id, p.patch]));+ return {+ overlayClips: s.overlayClips.map((c) => {+ const patch = byId.get(c.id);+ return patch ? { ...c, ...patch } : c;+ }),+ };+ }),++ updateCuesTransient: (patches) =>+ set((s) => {+ const byId = new Map(patches.map((p) => [p.id, p.patch]));+ return {+ subtitles: {+ ...s.subtitles,+ cues: s.subtitles.cues.map((c) => {+ const patch = byId.get(c.id);+ return patch ? { ...c, ...patch } : c;+ }),+ },+ };+ }),+updateClipTransient: (id, patch) =>set((s) => ({clips: s.clips.map((c) => (c.id === id ? { ...c, ...patch } : c)),})),+ updateClipsTransient: (patches) =>+ set((s) => {+ const byId = new Map(patches.map((p) => [p.id, p.patch]));+ return {+ clips: s.clips.map((c) => {+ const patch = byId.get(c.id);+ return patch ? { ...c, ...patch } : c;+ }),+ };+ }),++ sortClips: () =>+ set((s) => ({ clips: [...s.clips].sort((a, b) => a.start - b.start) })),+updateAudioTransient: (id, patch) =>set((s) => ({audioClips: s.audioClips.map((c) =>@@ -695,16 +772,18 @@ export const useEditor = create<EditorState>((set, get) => {})),moveClip: (id, toIndex) => {- const { clips } = get();+ // The AI reorder op: splice the clip to the target index (in start+ // order) and re-pack the whole track. Pointer drags never come here —+ // they free-place through the lane coordinator.+ const clips = [...get().clips].sort((a, b) => a.start - b.start);const from = clips.findIndex((c) => c.id === id);if (from < 0) return;const to = Math.max(0, Math.min(clips.length - 1, toIndex));if (to === from) return;push();- const next = [...clips];- const [moved] = next.splice(from, 1);- next.splice(to, 0, moved);- set({ clips: next });+ const [moved] = clips.splice(from, 1);+ clips.splice(to, 0, moved);+ set({ clips: packStarts(clips) });},addVideoFromAsset: (assetId, place, start) => {@@ -713,14 +792,19 @@ export const useEditor = create<EditorState>((set, get) => {const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;push();if (place.kind === "base") {- const v: VideoClip = { id: uid(), assetId, in: 0, out, muted: false };- set((s) => {- const spans = getClipSpans(s.clips, s.assets);- const at = spans.filter((sp) => sp.start + sp.len / 2 <= start).length;- const clips = [...s.clips];- clips.splice(Math.max(0, Math.min(at, clips.length)), 0, v);- return { clips, ...sole({ kind: "clip", id: v.id }) };- });+ const taken = get().clips.map((c) => ({ start: c.start, end: c.start + clipLen(c) }));+ const v: VideoClip = {+ id: uid(),+ assetId,+ start: nextFreeStart(taken, Math.max(0, start), Math.max(MIN_LEN, out)),+ in: 0,+ out,+ muted: false,+ };+ set((s) => ({+ clips: [...s.clips, v].sort((a, b) => a.start - b.start),+ ...sole({ kind: "clip", id: v.id }),+ }));return;}// Full-frame by default: covers the base ("topmost plays"); the inspector@@ -763,19 +847,18 @@ export const useEditor = create<EditorState>((set, get) => {};if (place.kind === "base") {- if (source.kind === "base") return; // base reorder is handled by moveClip- const clip: VideoClip = { id: uid(), ...v };- set((st) => {- const spans = getClipSpans(st.clips, st.assets);- const at = spans.filter((sp) => sp.start + sp.len / 2 <= start).length;- const clips = [...st.clips];- clips.splice(Math.max(0, Math.min(at, clips.length)), 0, clip);- return {- clips,- overlayClips: st.overlayClips.filter((c) => c.id !== source.id),- ...sole({ kind: "clip", id: clip.id }),- };- });+ if (source.kind === "base") return; // a same-track move commits through the lane coordinator+ const taken = s.clips.map((c) => ({ start: c.start, end: c.start + clipLen(c) }));+ const clip: VideoClip = {+ id: uid(),+ ...v,+ start: nextFreeStart(taken, Math.max(0, start), clipLen({ ...v, id: "", start: 0 })),+ };+ set((st) => ({+ clips: [...st.clips, clip].sort((a, b) => a.start - b.start),+ overlayClips: st.overlayClips.filter((c) => c.id !== source.id),+ ...sole({ kind: "clip", id: clip.id }),+ }));return;}@@ -885,6 +968,55 @@ export const useEditor = create<EditorState>((set, get) => {return;}+ // A title selected: both halves keep the full text and style.+ if (selection?.kind === "text") {+ const o = get().overlays.find((x) => x.id === selection.id);+ if (o && t > o.start + 0.05 && t < o.end - 0.05) {+ push();+ const left: TextOverlay = { ...o, end: t };+ const right: TextOverlay = { ...o, id: uid(), start: t };+ set((s) => ({+ overlays: s.overlays.flatMap((x) => (x.id === o.id ? [left, right] : [x])),+ ...sole({ kind: "text", id: right.id }),+ }));+ }+ return;+ }++ // A caption selected: word timings are absolute, so each half keeps the+ // words it covers and its text follows them; without timings the text+ // splits proportionally.+ if (selection?.kind === "cue") {+ const c = get().subtitles.cues.find((x) => x.id === selection.id);+ if (c && t > c.start + 0.05 && t < c.end - 0.05) {+ push();+ const lw = c.words?.filter((w) => w.t0 < t);+ const rw = c.words?.filter((w) => w.t0 >= t);+ const at = Math.round(c.text.length * ((t - c.start) / (c.end - c.start)));+ const left: SubtitleCue = {+ ...c,+ end: t,+ text: lw?.length ? lw.map((w) => w.w).join(" ") : c.text.slice(0, at).trim() || c.text,+ words: lw?.length ? lw : undefined,+ };+ const right: SubtitleCue = {+ ...c,+ id: uid(),+ start: t,+ text: rw?.length ? rw.map((w) => w.w).join(" ") : c.text.slice(at).trim() || c.text,+ words: rw?.length ? rw : undefined,+ };+ set((s) => ({+ subtitles: {+ ...s.subtitles,+ cues: s.subtitles.cues.flatMap((x) => (x.id === c.id ? [left, right] : [x])),+ },+ ...sole({ kind: "cue", id: right.id }),+ }));+ }+ return;+ }+const spans = getClipSpans(clips, assets);const span = spans.find((sp) => t > sp.start + 0.05 && t < sp.start + sp.len - 0.05@@ -894,9 +1026,9 @@ export const useEditor = create<EditorState>((set, get) => {// Source time advances `speed`× faster than timeline time.const cutAt = span.clip.in + (t - span.start) * clipSpeed(span.clip);// The left half hard-cuts into the right; the right keeps the original- // dissolve into whatever came after.+ // dissolve into whatever came after. Both halves stay in place.const left: VideoClip = { ...span.clip, out: cutAt, transition: undefined, transitionStyle: undefined };- const right: VideoClip = { ...span.clip, id: uid(), in: cutAt };+ const right: VideoClip = { ...span.clip, id: uid(), in: cutAt, start: t };set((s) => {const idx = s.clips.findIndex((c) => c.id === span.clip.id);const next = [...s.clips];@@ -925,19 +1057,16 @@ export const useEditor = create<EditorState>((set, get) => {const overlayClipIds = idsOf("overlayClip");const textIds = idsOf("text");const cueIds = idsOf("cue");- // Removing video clips shortens the track; ripple later titles/captions- // so they stay aligned with the content that survives.- const bump = clipIds.size- ? makeRipple(st.clips, st.clips.filter((c) => !clipIds.has(c.id)), st.assets)- : <T extends { start: number; end: number }>(x: T): T => x;+ // Every track is free-positioned: deleting leaves a gap and nothing+ // else moves, so annotations keep the timing they were placed at.set((s) => ({clips: s.clips.filter((c) => !clipIds.has(c.id)),audioClips: s.audioClips.filter((c) => !audioIds.has(c.id)),overlayClips: s.overlayClips.filter((c) => !overlayClipIds.has(c.id)),- overlays: s.overlays.filter((o) => !textIds.has(o.id)).map(bump),+ overlays: s.overlays.filter((o) => !textIds.has(o.id)),subtitles: {...s.subtitles,- cues: s.subtitles.cues.filter((c) => !cueIds.has(c.id)).map(bump),+ cues: s.subtitles.cues.filter((c) => !cueIds.has(c.id)),},selection: null,multiSelection: [],@@ -1027,7 +1156,7 @@ export const useEditor = create<EditorState>((set, get) => {if (!c) continue;const mi = mediaFor(c.assetId);if (mi == null) continue;- audio.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, volume: c.volume, fadeIn: c.fadeIn, fadeOut: c.fadeOut, speed: c.speed, duck: c.duck });+ audio.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, volume: c.volume, fadeIn: c.fadeIn, fadeOut: c.fadeOut, speed: c.speed, duck: c.duck, lane: c.lane });} else if (sel.kind === "text") {const o = s.overlays.find((x) => x.id === sel.id);if (o) texts.push({ ...o, start: o.start - start0, end: o.end - start0 });@@ -1055,6 +1184,7 @@ export const useEditor = create<EditorState>((set, get) => {const newClips: VideoClip[] = [...baseLayers].sort((a, b) => a.start - b.start).map((l) => ({+ start: l.start + shift,id: uid(),assetId: assetIds[l.media],in: l.in,@@ -1090,6 +1220,7 @@ export const useEditor = create<EditorState>((set, get) => {...(a.fadeOut ? { fadeOut: a.fadeOut } : {}),...(a.speed ? { speed: a.speed } : {}),...(a.duck !== undefined && a.duck < 1 ? { duck: a.duck } : {}),+ ...(a.lane ? { lane: a.lane } : {}),}));const newTexts: TextOverlay[] = template.texts.map((o) => ({...o,@@ -1104,7 +1235,7 @@ export const useEditor = create<EditorState>((set, get) => {end: c.end + shift,}));set((s) => ({- clips: [...s.clips, ...newClips],+ clips: [...s.clips, ...newClips].sort((a, b) => a.start - b.start),overlayClips: [...s.overlayClips, ...newOverlays],audioClips: [...s.audioClips, ...newAudio],overlays: [...s.overlays, ...newTexts],@@ -1128,25 +1259,6 @@ export const useEditor = create<EditorState>((set, get) => {return { multiSelection: next, selection: primary };}),- rippleShift: (afterTime, delta) => {- if (delta === 0) return;- set((s) => ({- overlays: s.overlays.map((o) =>- o.start >= afterTime - 0.001- ? { ...o, start: Math.max(0, o.start + delta), end: Math.max(0, o.end + delta) }- : o- ),- subtitles: {- ...s.subtitles,- cues: s.subtitles.cues.map((c) =>- c.start >= afterTime - 0.001- ? { ...c, start: Math.max(0, c.start + delta), end: Math.max(0, c.end + delta) }- : c- ),- },- }));- },-seek: (t) => {const total = projectDuration(get());set({ currentTime: Math.max(0, Math.min(total, t)) });@@ -1173,16 +1285,23 @@ export const useEditor = create<EditorState>((set, get) => {const spec = {duration,locale: s.subtitles.locale ?? "en-US",- clips: spans.map((sp) => ({- file: sp.asset.fileName,- in: sp.clip.in,- out: sp.clip.out,- muted: sp.clip.muted,- speed: clipSpeed(sp.clip),- // The clamped cross-dissolve overlap, so the transcribe mix overlaps- // clip audio the same way the timeline does and cues stay in sync.- transition: sp.transitionOut,- })),+ // The transcribe mix is a sequential fold, so gaps between the+ // free-placed clips ship as explicit silent spacers (empty file).+ clips: spanSequence(spans).flatMap(({ gapBefore, span: sp }) => [+ ...(gapBefore > 0+ ? [{ file: "", in: 0, out: gapBefore, muted: true, speed: 1, transition: 0 }]+ : []),+ {+ file: sp.asset.fileName,+ in: sp.clip.in,+ out: sp.clip.out,+ muted: sp.clip.muted,+ speed: clipSpeed(sp.clip),+ // The clamped cross-dissolve overlap, so the transcribe mix overlaps+ // clip audio the same way the timeline does and cues stay in sync.+ transition: sp.transitionOut,+ },+ ]),audio: s.audioClips.filter((a) => a.start < duration && assetById.has(a.assetId)).map((a) => ({@@ -1588,33 +1707,29 @@ export const useEditor = create<EditorState>((set, get) => {return false;push();const t = Math.max(0, s.currentTime);- // Video clips insert together, after the clip under the playhead.- const spans = getClipSpans(s.clips, s.assets);- let insertAt = s.clips.length;- for (let i = 0; i < spans.length; i++) {- if (t < spans[i].start + spans[i].len) {- insertAt = i + 1;- break;- }- }const newSel: Selection[] = [];set((cur) => {let clips = cur.clips;let audioClips = cur.audioClips;let overlayClips = cur.overlayClips;let overlays = cur.overlays;- let at = insertAt;- // Free-positioned items aim for the playhead but respect what already- // sits on their lane: an occupied spot slides the paste right to the- // next gap that fits. Earlier items of this same paste count too.+ // Every item aims for the playhead but respects what already sits on+ // its lane: an occupied spot slides the paste right to the next gap+ // that fits. Earlier items of this same paste count too.for (const cb of clipboard) {if (cb.kind === "clip") {- const clip: VideoClip = { ...cb.item, id: uid() };- clips = [...clips.slice(0, at), clip, ...clips.slice(at)];- at++;+ const taken = clips.map((c) => ({ start: c.start, end: c.start + clipLen(c) }));+ const clip: VideoClip = {+ ...cb.item,+ id: uid(),+ start: nextFreeStart(taken, t, clipLen(cb.item)),+ };+ clips = [...clips, clip].sort((a, b) => a.start - b.start);newSel.push({ kind: "clip", id: clip.id });} else if (cb.kind === "audio") {- const taken = audioClips.map((a) => ({ start: a.start, end: a.start + clipLen(a) }));+ const taken = audioClips+ .filter((a) => (a.lane ?? 0) === (cb.item.lane ?? 0))+ .map((a) => ({ start: a.start, end: a.start + clipLen(a) }));const item: AudioClip = { ...cb.item, id: uid(), start: nextFreeStart(taken, t, clipLen(cb.item)) };audioClips = [...audioClips, item];newSel.push({ kind: "audio", id: item.id });@@ -1747,29 +1862,63 @@ export function getClipSpans(): ClipSpan[] {// Map lookup, not a per-clip assets.find — this runs every playback frame.const byId = new Map(assets.map((a) => [a.id, a]));- // Lay out only clips whose media is present; a transition joins adjacent- // present clips, so resolve the list first.const present = clips.map((clip) => ({ clip, asset: byId.get(clip.assetId) }))- .filter((x): x is { clip: VideoClip; asset: MediaAsset } => !!x.asset);+ .filter((x): x is { clip: VideoClip; asset: MediaAsset } => !!x.asset)+ .sort((a, b) => a.clip.start - b.clip.start);const spans: ClipSpan[] = [];- let t = 0;for (let i = 0; i < present.length; i++) {const { clip, asset } = present[i];const len = clipLen(clip);- const overlap = transitionOverlap(clip, present[i + 1]?.clip);- spans.push({ clip, asset, start: t, len, transitionOut: overlap });- t += len - overlap; // the next clip starts early by the dissolve length+ const next = present[i + 1]?.clip;+ // A dissolve is a physical overlap with the next clip, capped by the+ // declared transition; clips dragged apart dissolve into nothing.+ const physical = next ? Math.max(0, clip.start + len - next.start) : 0;+ const overlap = Math.min(transitionOverlap(clip, next), physical);+ spans.push({ clip, asset, start: clip.start, len, transitionOut: overlap });}return spans;}+/** End of the base track: where its last clip runs out (clips are free-placed,+ * so gaps count toward this, they just play black). */export function totalDuration(clips: VideoClip[]) {+ let end = 0;+ for (const c of clips) end = Math.max(end, c.start + clipLen(c));+ return end;+}++/** A base clip as older docs stored it: packed by array order, no `start`. */+type LegacyClip = Omit<VideoClip, "start"> & { start?: number };++/** Assign packed sequential starts (each clip after the previous, dissolves+ * overlapping): the layout older docs implied by array order. Also the shape+ * `moveClip` (the AI reorder op) re-lays the track into. */+function packStarts(clips: LegacyClip[]): VideoClip[] {let t = 0;+ const out: VideoClip[] = [];for (let i = 0; i < clips.length; i++) {- t += clipLen(clips[i]) - transitionOverlap(clips[i], clips[i + 1]);+ const clip = { ...clips[i], start: t } as VideoClip;+ const next = clips[i + 1] ? ({ ...clips[i + 1], start: 0 } as VideoClip) : undefined;+ t += clipLen(clip) - transitionOverlap(clip, next);+ out.push(clip);+ }+ return out;+}++/** The base track as a gapless sequence for the sequential render graphs+ * (export, transcription): each span in start order, with the length of the+ * black/silent spacer that precedes it wherever the free-placed clips leave+ * the track empty. Sub-50ms gaps are treated as abutting. */+export function spanSequence(spans: ClipSpan[]): { gapBefore: number; span: ClipSpan }[] {+ const out: { gapBefore: number; span: ClipSpan }[] = [];+ let cursor = 0;+ for (const sp of spans) {+ const gap = sp.start - cursor;+ out.push({ gapBefore: gap > 0.05 ? gap : 0, span: sp });+ cursor = sp.start + sp.len - sp.transitionOut;}- return Math.max(0, t);+ return out;}/** The playable length of the whole project: the base track plus anything that@@ -1790,16 +1939,6 @@ export function projectDuration(s: {return Math.max(0, end);}-/**- * Build the annotation shifter for a video-track edit (clip delete, asset- * removal). Titles and cues are pinned to timeline time, so when clips go the- * track re-lays-out and everything downstream must move with the content it- * sat over. Comparing the real old/new overlap-aware layouts — rather than- * assuming each removed clip vacates its full length — keeps annotations- * aligned even across cross-dissolves. An annotation over surviving content- * moves by that clip's shift; one over a removed gap collapses to the join;- * one past everything shifts by the whole-timeline length change.- *//** Spread a cue's words across [start, end], each word's slice proportional to* its length. Used when re-timing captions to a generated voiceover, which* carries no per-word timestamps of its own. */@@ -1822,27 +1961,4 @@ function spreadWordsEvenly(});}-function makeRipple(oldClips: VideoClip[], newClips: VideoClip[], assets: MediaAsset[]) {- const newStart = new Map(getClipSpans(newClips, assets).map((sp) => [sp.clip.id, sp.start]));- const totalDelta = totalDuration(newClips) - totalDuration(oldClips);- const survivors = getClipSpans(oldClips, assets)- .filter((sp) => newStart.has(sp.clip.id))- .map((sp) => ({- oldStart: sp.start,- oldEnd: sp.start + sp.len,- newStart: newStart.get(sp.clip.id)!,- }));- const shiftFor = (a: number) => {- for (const s of survivors) {- if (a <= s.oldEnd + 1e-6)- return a >= s.oldStart - 1e-6 ? s.newStart - s.oldStart : s.newStart - a;- }- return totalDelta;- };- return <T extends { start: number; end: number }>(item: T): T => {- const d = shiftFor(item.start);- return d ? { ...item, start: Math.max(0, item.start + d), end: Math.max(0, item.end + d) } : item;- };-}-export const useTotalDuration = () => useEditor((s) => totalDuration(s.clips));diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex e13c863c..ba4baec0 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -98,10 +98,13 @@ export function regionLabel(r: FrameRect): string {return "PiP";}-/** A clip on the magnetic video track. Order in the array is timeline order. */+/** A clip on the base video track — free-positioned in time like every other+ * track. The array is kept sorted by `start` (older docs stored a packed+ * sequence; loading bakes their implied starts in). */export interface VideoClip {id: string;assetId: string;+ start: number; // timeline position, secondsin: number; // trim-in inside the source, secondsout: number; // trim-out inside the source, secondsmuted: boolean;@@ -225,6 +228,9 @@ export interface AudioClip {* audio and other soundtrack clips) drops to this gain, 0..1. Absent = no* ducking. Ducking clips never duck each other. */duck?: number;+ /** Which audio track (row) this sits on, 0-based. Tracks are kept+ * contiguous: empty ones collapse and dragging past the last adds one. */+ lane?: number;}/**@@ -265,6 +271,7 @@ export interface TemplateAudio {fadeOut?: number;speed?: number;duck?: number;+ lane?: number;}export interface LibraryTemplate {id: string;