Skip to content

Open source CapCut alternative.

TypeScript

refactor(site): one vertical drag model for every timeline lane

David Leb90e7093063e
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index c99ebd13..d11ce9cf 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -49,7 +49,7 @@ import { useExports } from "@/cut/lib/exportStore";
import { isDragActive, startDrag, subscribeDragActive } from "@/cut/lib/drag";
import { keyboardToEditor, shortcutDecline } from "@/cut/lib/shortcutGate";
import { additiveClick } from "@/cut/lib/hostKeys";
-import { CLIP_GAP, laneDragFor, laneDragParts, startLaneMove, startLaneTrim, type LaneDrag, type LaneKind } from "@/cut/lib/laneTracks";
+import { CLIP_GAP, laneDragFor, laneDragParts, resolveRow, startLaneMove, startLaneTrim, type LaneDrag, type RowBox } from "@/cut/lib/laneTracks";
import { reportSwallowed } from "@/cut/lib/report";
import { downloadMedia, dropEdgeFrames, ensurePeaks, importImage, importStockMusic, importStockVideo, peekEdgeFrame, requestEdgeFrame, revealMedia, stripFailedFor, subscribeStripStatus } from "@/cut/lib/media";
import { planFilmstrip, type FilmTile } from "@/cut/lib/filmstrip";
@@ -114,12 +114,6 @@ function useDropPreview<T>(initial: T): [T, (next: T) => void] {
/** Video row height: the picture band plus the sound band under it. */
const VIDEO_H = 88;
-/** How far past the top or bottom of the video stack a drag has to carry a
- * clip to open a new track. Every drop inside the stack lands on a row, which
- * opens room for it, so this reach is the one gesture that adds a track — and
- * it is long enough that drifting off a row while sliding along it never
- * does. */
-const NEW_TRACK_PX = 24;
const OVERLAY_H = VIDEO_H; // every video track shares the same row height
/** Extra row height under a video row whose clips carry mask keys: room for
* the key rail below the bars. The diamonds read as part of the clip, so the
@@ -298,26 +292,27 @@ function EffectChipIcon({ effect }: { effect: EffectId }) {
* length — so the landing ghost matches what the drop makes. */
const ELEMENT_DROP_SECONDS = 3;
+/** The video stack's landing-slot chrome. */
+const VIDEO_SLOT =
+ "rounded-[2.5px] bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4)]";
+
const FAMILY_STYLE: Record<
OverlayFamily,
- { bar: string; row: string; rowIdle: string; slot: string }
+ { bar: string; row: string; slot: string }
> = {
text: {
bar: "bg-[#7B4BD1]",
row: "border-[#7B4BD1]/70 bg-[#7B4BD1]/5",
- rowIdle: "border-[#7B4BD1]/25",
slot: "bg-[#7B4BD1]/10 shadow-[inset_0_0_0_1.5px_rgba(123,75,209,0.5)]",
},
element: {
bar: "bg-[#C43C87]",
row: "border-[#C43C87]/70 bg-[#C43C87]/5",
- rowIdle: "border-[#C43C87]/25",
slot: "bg-[#C43C87]/10 shadow-[inset_0_0_0_1.5px_rgba(196,60,135,0.5)]",
},
effect: {
bar: "bg-[#0D8577]",
row: "border-[#0D8577]/70 bg-[#0D8577]/5",
- rowIdle: "border-[#0D8577]/25",
slot: "bg-[#0D8577]/10 shadow-[inset_0_0_0_1.5px_rgba(13,133,119,0.5)]",
},
};
@@ -667,9 +662,6 @@ export function Timeline() {
} | 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
- // would-be new tracks past the stack's edges.
- const [videoDragging, setVideoDragging] = useState(false);
// The pending drop preview: which track/gap, at what time, for how long —
// and which resident clips slide right to open the room, so the row can
// paint them parting ahead of the drop.
@@ -685,10 +677,9 @@ export function Timeline() {
} | null>(null);
// Stage-x pixel a snapped title edge sits at, for the guide line (null = off).
const [snapX, setSnapX] = useState<number | null>(null);
- const videoDragActive = videoDragging || dropType === "video";
- // The drop the pointer resolved to last, so a new track that has opened
- // under the pointer keeps its hold until the drag returns to a row.
- const lastDrop = useRef<TrackTarget | null>(null);
+ // The row an external drag resolved to last, so a new track that has
+ // opened under the pointer keeps its hold until the drag returns to a row.
+ const heldRow = useRef<number | null>(null);
// Residents sliding ahead of an in-flight drop: clip id → the start it
// previews at. Painted as an animated left offset, so the row opens room
@@ -700,56 +691,33 @@ export function Timeline() {
return m;
}, [assetDrop, overlayDrop]);
- // Which drop the cursor is over. Inside the video stack the answer is always
- // a row: the row under the pointer takes the clip and opens room for it, so
- // aiming anywhere over a track lands on that track. A new track comes from
- // one gesture — carrying the clip past the top or the bottom of the stack —
- // and that new row then mounts under the pointer, so it holds itself while
- // the pointer stays out there and lets go the moment it returns to a row.
- // `draggedId` is the clip being carried, when one is; every drag flavor
- // resolves through here, clips grabbed off the timeline and external media
- // alike.
- const resolveDropTrack = useCallback(
- (clientX: number, clientY: number, draggedId?: string): TrackTarget => {
+ // The video stack's rows as screen boxes, top first — the frontmost layer
+ // down to track 0 — read live, since rows mount and shift while a drag runs.
+ const videoRows = () =>
+ Array.from(innerRef.current?.querySelectorAll<HTMLElement>("[data-tl-vrow]") ?? [], (el) => {
+ const r = el.getBoundingClientRect();
+ return { track: Number(el.dataset.tlVrow), top: r.top, h: r.height };
+ }).sort((a, b) => a.top - b.top);
+
+ // Which drop an external media drag is over: the same row rule every lane
+ // drag uses — the row under the pointer takes the clip and opens room for
+ // it, and a new track comes from carrying it past the top or the bottom of
+ // the stack, where the new row then mounts and holds itself.
+ const resolveDropTrack = useCallback((clientY: number): TrackTarget => {
// An empty video timeline has no base yet: the first clip always lands on
// track 0, whatever height the pointer is at. Otherwise a drop above the
// thin empty row resolves to an overlay track, leaving track 0 empty — and
// an empty track 0 plays black (the compositor's master lives there).
const st = useEditor.getState();
- const answer = (t: TrackTarget) => ((lastDrop.current = t), t);
- if (st.clips.length === 0) return answer(TRACK_ZERO);
- const rows = Array.from(
- innerRef.current?.querySelectorAll<HTMLElement>("[data-tl-vrow]") ?? []
- )
- .map((el) => ({ track: Number(el.dataset.tlVrow), r: el.getBoundingClientRect() }))
- .sort((a, b) => a.r.top - b.r.top);
- if (!rows.length) return answer(TRACK_ZERO);
- const top = rows[0];
- const bottom = rows[rows.length - 1];
- const held = lastDrop.current?.kind === "insert" ? lastDrop.current.level : null;
- const topLevel = Math.max(0, ...overlayLayers(st.clips).map((c) => c.track)) + 1;
- // A clip alone on the outermost row has no new track to open on that side:
- // the row it left collapses behind it, so it would land alone on a fresh
- // row with the same picture on it. The reach that way aims at rows only;
- // the other way still reorders the stack, so it stays live.
- const dragged = draggedId ? st.clips.find((c) => c.id === draggedId) : undefined;
- const soleTrack =
- dragged && st.clips.every((c) => c.track !== dragged.track || c.id === dragged.id)
- ? dragged.track
- : null;
- // Past the stack: a new top layer above it, a new track 0 below it (the
- // spine transplants onto the drop). Reaching there takes NEW_TRACK_PX of
- // travel; holding it takes none, since by then the new track's own row
- // fills the space the pointer is in.
- if (soleTrack !== top.track && clientY < top.r.top - (held === topLevel ? 0 : NEW_TRACK_PX))
- return answer({ kind: "insert", level: topLevel });
- if (soleTrack !== bottom.track && clientY > bottom.r.bottom + (held === 0 ? 0 : NEW_TRACK_PX))
- return answer({ kind: "insert", level: 0 });
- // Inside the stack: the row the pointer is over, or the one under it when
- // the pointer sits in the gap between two rows. The row makes space for
- // the drop — nothing new opens between two tracks.
- const row = rows.find((r) => clientY <= r.r.bottom) ?? bottom;
- return answer({ kind: "track", track: row.track });
+ if (st.clips.length === 0) return TRACK_ZERO;
+ const rows = videoRows();
+ if (!rows.length) return TRACK_ZERO;
+ const row = resolveRow(rows, clientY, heldRow.current, { top: true, bottom: true });
+ heldRow.current = row;
+ if (row < 0)
+ return { kind: "insert", level: Math.max(0, ...overlayLayers(st.clips).map((c) => c.track)) + 1 };
+ if (row >= rows.length) return { kind: "insert", level: 0 };
+ return { kind: "track", track: rows[row].track };
}, []);
// Drive the drop preview while a clip is dragged across tracks: highlight the
@@ -761,7 +729,7 @@ export function Timeline() {
// The drag let go of the placement system (it is home, or it ended): the
// next resolve starts from the geometry alone.
if (target === null) {
- lastDrop.current = null;
+ heldRow.current = null;
return setOverlayDrop(null);
}
const landing =
@@ -780,35 +748,17 @@ export function Timeline() {
// A drag that left the timeline or landed lets go of the placement hold too,
// so the next one starts from the geometry alone.
const endCrossDrag = useCallback(() => {
- lastDrop.current = null;
+ heldRow.current = null;
setOverlayDrop(null);
}, []);
- // Releasing a track-0 clip on any other track lifts it out onto that track
- // (or a new one); on its own track the lane coordinator commits the move.
- const onClipCrossDrop = useCallback(
- (id: string, target: TrackTarget, start: number) => {
- previewCross(null);
- if (samePlacement(target, TRACK_ZERO)) return;
- useEditor.getState().dropVideoClip(id, target, start);
- },
- [previewCross]
- );
-
- // Releasing an overlay clip anywhere: another track, a new inserted track, or
- // down onto track 0.
- const onOverlayCrossDrop = useCallback(
- (id: string, target: TrackTarget, start: number) => {
- previewCross(null);
- useEditor.getState().dropVideoClip(id, target, start);
- },
- [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);
+ // A video clip is being dragged (internal or external): the would-be new
+ // tracks past the stack's edges can open, and every clip parts.
+ const videoDragActive = laneDrag?.kind === "video" || dropType === "video";
// Right-click on any row's empty space — video, audio, or title: a small
// popover offering to close that row's gap under the cursor. The cut is
@@ -906,7 +856,7 @@ export function Timeline() {
const rowOf = new Map(used.map((l, i) => [l, i]));
return { used, rowOf, count: used.length };
}, [overlays]);
- // The color an element drag paints its landing rows with: the carried item's
+ // The color an element drag paints its landing slot with: the carried item's
// own, so the move reads as one thing from grab to drop.
const draggedFamily = useMemo<OverlayFamily>(() => {
const held = laneDrag?.kind === "overlay" ? overlays.find((o) => o.id === laneDrag.id) : null;
@@ -924,6 +874,9 @@ export function Timeline() {
// new top layer above, or a new track 0 below (the spine transplants there).
const topInsertLevel = (aboveTracks[0] ?? 0) + 1;
const bottomInsertLevel = 0;
+ // A video track's display row, top first: the layers in stack order, then
+ // track 0 at the bottom — the row numbers a video lane drag speaks in.
+ const videoRowCount = aboveTracks.length + 1;
// Audio tracks mirror the title tracks: clips carry a `lane`; used lanes
// compact to contiguous display rows, so empty tracks disappear on their own.
@@ -1002,25 +955,28 @@ export function Timeline() {
// The band's rows in screen space, top row first. The video stack measures
// its own row elements (their heights vary with the mask key rail); the
// stacked bands are uniform, so their rows come off the band's top edge.
- const rowBoxes = useCallback(
- (band: RowBand): { top: number; h: number }[] => {
- if (band === "video")
- return Array.from(
- innerRef.current?.querySelectorAll<HTMLElement>("[data-tl-vrow]") ?? [],
- (el) => {
- const r = el.getBoundingClientRect();
- return { top: r.top, h: r.height };
- }
- );
- const el = band === "overlay" ? overlayRef.current : audioRef.current;
- if (!el) return [];
- const h = band === "overlay" ? TEXT_H : AUDIO_H;
- const n = band === "overlay" ? overlayLanes.count : audioLanes.count;
- const top = el.getBoundingClientRect().top;
- return Array.from({ length: n }, (_, r) => ({ top: top + r * h, h }));
- },
- [overlayLanes.count, audioLanes.count]
- );
+ const rowBoxes = useCallback((band: RowBand): RowBox[] => {
+ if (band === "video") return videoRows();
+ const el = band === "overlay" ? overlayRef.current : audioRef.current;
+ return Array.from(el?.querySelectorAll<HTMLElement>("[data-tl-row]") ?? [], (row) => {
+ const r = row.getBoundingClientRect();
+ return { top: r.top, h: r.height };
+ });
+ }, []);
+ const videoRowBoxes = useCallback(() => rowBoxes("video"), [rowBoxes]);
+ const audioRowBoxes = useCallback(() => rowBoxes("audio"), [rowBoxes]);
+ const overlayRowBoxes = useCallback(() => rowBoxes("overlay"), [rowBoxes]);
+ /** The row boxes a stacked band lays out for its used rows, so gestures
+ * can read the band's geometry live. */
+ const rowMarks = (n: number, h: number, shift: number) =>
+ Array.from({ length: n }, (_, r) => (
+ <div
+ key={`row-${r}`}
+ data-tl-row=""
+ className="pointer-events-none absolute inset-x-0"
+ style={{ top: r * h + shift, height: h }}
+ />
+ ));
// Grab a row by its gutter cell and carry it to a new place in the band.
const gripRow = (band: RowBand, row: number) => (e: React.PointerEvent) => {
const rows = rowBoxes(band);
@@ -1101,13 +1057,6 @@ export function Timeline() {
return map;
}, [clips, assets]);
- // 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(
@@ -1423,7 +1372,7 @@ export function Timeline() {
if (!surface) return null;
const r = surface.getBoundingClientRect();
if (y < r.top || y > r.bottom || x < r.left || x > r.right) return null;
- return { at: dropTimeAt(x), place: resolveDropTrack(x, y) };
+ return { at: dropTimeAt(x), place: resolveDropTrack(y) };
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[resolveDropTrack]
@@ -1432,8 +1381,8 @@ export function Timeline() {
const [transitionDrag, setTransitionDrag] = useState<XBar | null>(null);
// A drag past the top edge opens a row there, pushing the stack down by one
// for as long as it is aimed that way.
- const topRowShift =
- laneDrag?.kind === "overlay" && laneDrag.targetRow < 0 ? TEXT_H : 0;
+ const topRowShift = laneDrag?.kind === "overlay" && laneDrag.targetRow < 0 ? TEXT_H : 0;
+ const audioTopShift = laneDrag?.kind === "audio" && laneDrag.targetRow < 0 ? AUDIO_H : 0;
// Where a dropped asset should land. An empty timeline has no arrangement to
// read a position against, so the drop starts the film at 0 no matter where
@@ -1817,7 +1766,7 @@ export function Timeline() {
schedulePreview(() => {
setAssetDrop(null);
setDropType("video"); // keep the insertion zones lit however the drag entered
- previewCross(resolveDropTrack(x, y), Math.max(0, timeAt(x)), vid.duration, vid.ghost);
+ previewCross(resolveDropTrack(y), Math.max(0, timeAt(x)), vid.duration, vid.ghost);
});
},
onDragLeave: (e: React.DragEvent) => {
@@ -1832,7 +1781,7 @@ export function Timeline() {
e.preventDefault();
e.stopPropagation();
cancelPreview();
- const place = resolveDropTrack(e.clientX, e.clientY);
+ const place = resolveDropTrack(e.clientY);
const t = Math.max(0, timeAt(e.clientX));
endCrossDrag();
setDropType(null);
@@ -1948,11 +1897,17 @@ export function Timeline() {
// track at z-level `level`.
const newTrackRow = (level: number) => {
const place: TrackTarget = { kind: "insert", level };
- if (!videoDragActive || !samePlacement(overlayDrop?.target ?? null, place)) return null;
+ const aimed =
+ (laneDrag?.kind === "video" && laneDrag.targetRow === (level === 0 ? videoRowCount : -1)) ||
+ (dropType === "video" && samePlacement(overlayDrop?.target ?? null, place));
+ if (!aimed) return null;
return (
<div className="relative mt-1.5" style={{ height: OVERLAY_H }}>
{laneRail(OVERLAY_H - 2)}
{trackSlot(place, OVERLAY_H - 4)}
+ {laneDrag?.kind === "video" && (
+ <LaneSlot drag={laneDrag} pps={pps} top={2} barH={OVERLAY_H - 4} className={VIDEO_SLOT} />
+ )}
</div>
);
};
@@ -2004,7 +1959,7 @@ export function Timeline() {
}
setDropType("video");
setAudioDrop(null);
- const place = resolveDropTrack(x, y);
+ const place = resolveDropTrack(y);
if (place.kind === "insert") {
setAssetDrop(null);
setOverlayDrop({ target: place, t: dropTimeAt(x), len });
@@ -2115,7 +2070,7 @@ export function Timeline() {
}
// Past the stack's edges the drop opens a new track: preview it in
// the would-be new row instead of track 0.
- const place = resolveDropTrack(x, y);
+ const place = resolveDropTrack(y);
if (place.kind === "insert") {
setAssetDrop(null);
setOverlayDrop({ target: place, t: dropTimeAt(x), len: duration, ghost });
@@ -2150,7 +2105,7 @@ export function Timeline() {
if (draggedFiles(e)) {
fileLanding.current = {
at: dropTimeAt(e.clientX),
- place: resolveDropTrack(e.clientX, e.clientY),
+ place: resolveDropTrack(e.clientY),
};
}
// Resolve the hovered rows before the previews (and their rows) clear.
@@ -2159,7 +2114,7 @@ export function Timeline() {
setElementDrop(null);
setJointDrop(null);
setXTileDrag(null);
- const videoPlace = resolveDropTrack(e.clientX, e.clientY);
+ const videoPlace = resolveDropTrack(e.clientY);
setAssetDrop(null);
endCrossDrag();
setAudioDrop(null);
@@ -2443,9 +2398,9 @@ export function Timeline() {
height:
Math.max(
overlayLanes.count,
- // An in-flight element drag shows its whole landing area —
- // only the rows it can actually reach.
- laneDrag?.kind === "overlay" ? laneDrag.maxRow + 1 : 0,
+ // An in-flight element drag aimed under the band opens
+ // the row it will land on.
+ laneDrag?.kind === "overlay" ? laneDrag.targetRow + 1 : 0,
// A panel drag over an empty band opens the first row for
// its landing preview.
elementDrop !== null ? elementDrop.row + 1 : 0
@@ -2456,9 +2411,16 @@ export function Timeline() {
onPointerDown={deselectIfSelf}
onContextMenu={openStackedGapMenu("overlay", TEXT_H, overlayLanes.used)}
>
- {Array.from({ length: overlayLanes.count }, (_, r) =>
- laneRail((r + 1) * TEXT_H - 4 + topRowShift, r)
+ {Array.from(
+ {
+ length:
+ overlayLanes.count +
+ (topRowShift ? 1 : 0) +
+ (laneDrag?.kind === "overlay" && laneDrag.targetRow === overlayLanes.count ? 1 : 0),
+ },
+ (_, r) => laneRail((r + 1) * TEXT_H - 4, r)
)}
+ {rowMarks(overlayLanes.count, TEXT_H, topRowShift)}
{overlayLanes.used.map((lane, r) => (
<Fragment key={`tgap-${lane}`}>
{gapHighlight(
@@ -2545,38 +2507,12 @@ export function Timeline() {
</>
);
})()}
- {/* The new row above, revealed once the drag heads past the top
- edge — showing it any earlier would push every row down
- under a freshly grabbed bar. */}
- {topRowShift > 0 && (
- <div
- className={cn(
- "pointer-events-none absolute inset-x-0 rounded-[3px] border border-dashed",
- FAMILY_STYLE[draggedFamily].row
- )}
- style={{ top: 2, height: TEXT_H - 6 }}
- />
- )}
- {laneDrag?.kind === "overlay" &&
- Array.from({ length: laneDrag.maxRow + 1 }, (_, r) => (
- <div
- key={r}
- className={cn(
- "pointer-events-none absolute inset-x-0 rounded-[3px] border border-dashed transition-colors",
- r === laneDrag.targetRow
- ? FAMILY_STYLE[draggedFamily].row
- : FAMILY_STYLE[draggedFamily].rowIdle
- )}
- style={{ top: r * TEXT_H + 2 + topRowShift, height: TEXT_H - 6 }}
- />
- ))}
{laneDrag?.kind === "overlay" && (
<LaneSlot
drag={laneDrag}
pps={pps}
- rowH={TEXT_H}
+ top={laneDrag.targetRow * TEXT_H + 2 + topRowShift}
barH={TEXT_H - 6}
- shift={topRowShift}
className={cn("rounded-[3px]", FAMILY_STYLE[draggedFamily].slot)}
/>
)}
@@ -2597,7 +2533,7 @@ export function Timeline() {
: "part"
: null
}
- laneCount={overlayLanes.count}
+ rows={overlayRowBoxes}
selected={selKeys.has(`overlay:${o.id}`)}
drag={drag}
parting={laneDragParts(laneDrag, "overlay", o.id)}
@@ -2748,14 +2684,8 @@ export function Timeline() {
>
{laneRail(rowH - 2 + railH)}
{gapHighlight({ kind: "video", index: track }, rowH - 4)}
- {draggedOverlayTrack === track && laneDrag && (
- <LaneSlot
- drag={laneDrag}
- pps={pps}
- rowH={rowH}
- barH={rowH - 4}
- className="rounded-[2.5px] bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4)]"
- />
+ {laneDrag?.kind === "video" && laneDrag.targetRow === row && (
+ <LaneSlot drag={laneDrag} pps={pps} top={2} barH={rowH - 4} className={VIDEO_SLOT} />
)}
{trackSpans.map((span) => (
<ClipView
@@ -2764,17 +2694,13 @@ export function Timeline() {
mention={clipMentions.get(span.clip.id)}
pps={pps}
selected={selKeys.has(`clip:${span.clip.id}`)}
- drag={laneDragFor(laneDrag, "overlayClip", span.clip.id)}
- parting={
- laneDragParts(laneDrag, "overlayClip", span.clip.id) || videoDragActive
- }
+ drag={laneDragFor(laneDrag, "video", span.clip.id)}
+ parting={laneDragParts(laneDrag, "video", span.clip.id) || videoDragActive}
partAt={dropPartAt.get(span.clip.id)}
+ homeRow={row}
+ rows={videoRowBoxes}
onDrag={setLaneDrag}
onSnap={setSnapX}
- resolveTarget={resolveDropTrack}
- onCrossMove={previewCross}
- onCrossDrop={onOverlayCrossDrop}
- onDragActive={setVideoDragging}
onFrameMenu={openFrameMenu}
/>
))}
@@ -2814,14 +2740,8 @@ export function Timeline() {
{spans.length > 0 && laneRail(rowH0 - 2 + rail0)}
{gapHighlight({ kind: "video", index: 0 }, rowH0 - 4)}
{trackSlot(TRACK_ZERO, rowH0 - 4)}
- {laneDrag?.kind === "clip" && !laneDrag.away && (
- <LaneSlot
- drag={laneDrag}
- pps={pps}
- rowH={rowH0}
- barH={rowH0 - 4}
- className="rounded-[2.5px] 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)]"
- />
+ {laneDrag?.kind === "video" && laneDrag.targetRow === aboveTracks.length && (
+ <LaneSlot drag={laneDrag} pps={pps} top={2} barH={rowH0 - 4} className={VIDEO_SLOT} />
)}
{assetDrop &&
(assetDrop.ghost ? (
@@ -2843,15 +2763,13 @@ export function Timeline() {
mention={clipMentions.get(span.clip.id)}
pps={pps}
selected={selKeys.has(`clip:${span.clip.id}`)}
- drag={laneDragFor(laneDrag, "clip", span.clip.id)}
- parting={laneDragParts(laneDrag, "clip", span.clip.id) || videoDragActive}
+ drag={laneDragFor(laneDrag, "video", span.clip.id)}
+ parting={laneDragParts(laneDrag, "video", span.clip.id) || videoDragActive}
partAt={dropPartAt.get(span.clip.id)}
+ homeRow={aboveTracks.length}
+ rows={videoRowBoxes}
onDrag={setLaneDrag}
onSnap={setSnapX}
- resolveTarget={resolveDropTrack}
- onCrossMove={previewCross}
- onCrossDrop={onClipCrossDrop}
- onDragActive={setVideoDragging}
onFrameMenu={openFrameMenu}
/>
))}
@@ -2873,40 +2791,36 @@ export function Timeline() {
height:
Math.max(
audioLanes.count,
- // An in-flight audio drag shows its whole landing area —
- // only the rows it can actually reach.
- laneDrag?.kind === "audio" ? laneDrag.maxRow + 1 : 0,
+ // An in-flight audio drag aimed under the band opens the
+ // row it will land on.
+ laneDrag?.kind === "audio" ? laneDrag.targetRow + 1 : 0,
(audioDrop?.row ?? -1) + 1
- ) * AUDIO_H,
+ ) *
+ AUDIO_H +
+ audioTopShift,
}}
onPointerDown={deselectIfSelf}
onContextMenu={openStackedGapMenu("audio", AUDIO_H, audioLanes.used)}
>
- {Array.from({ length: audioLanes.count }, (_, r) =>
- laneRail((r + 1) * AUDIO_H - 2, r)
+ {Array.from(
+ {
+ length:
+ Math.max(audioLanes.count, (audioDrop?.row ?? -1) + 1) +
+ (audioTopShift ? 1 : 0) +
+ (laneDrag?.kind === "audio" && laneDrag.targetRow === audioLanes.count ? 1 : 0),
+ },
+ (_, r) => laneRail((r + 1) * AUDIO_H - 2, r)
)}
+ {rowMarks(audioLanes.count, AUDIO_H, audioTopShift)}
{audioLanes.used.map((lane, r) => (
<Fragment key={`agap-${lane}`}>
{gapHighlight(
{ kind: "audio", index: lane },
AUDIO_H - 4,
- stackedRowTop("audio", r, AUDIO_H)
+ stackedRowTop("audio", r, AUDIO_H) + audioTopShift
)}
</Fragment>
))}
- {laneDrag?.kind === "audio" &&
- Array.from({ length: laneDrag.maxRow + 1 }, (_, r) => (
- <div
- key={r}
- className={cn(
- "pointer-events-none absolute inset-x-0 rounded-[2.5px] border border-dashed transition-colors",
- r === laneDrag.targetRow
- ? "border-emerald-500/70 bg-emerald-500/5"
- : "border-emerald-500/25"
- )}
- style={{ top: r * AUDIO_H + 2, height: AUDIO_H - 4 }}
- />
- ))}
{audioDrop && (
<div
className="tl-audio-drop-slot pointer-events-none absolute rounded-[2.5px] border-[1.5px] border-dashed border-emerald-500/80 bg-emerald-500/10 transition-[left] duration-150 ease-out"
@@ -2918,11 +2832,11 @@ export function Timeline() {
}}
/>
)}
- {laneDrag?.kind === "audio" && !laneDrag.away && (
+ {laneDrag?.kind === "audio" && (
<LaneSlot
drag={laneDrag}
pps={pps}
- rowH={AUDIO_H}
+ top={laneDrag.targetRow * AUDIO_H + 2 + audioTopShift}
barH={AUDIO_H - 4}
className="rounded-[2.5px] bg-emerald-500/10 shadow-[inset_0_0_0_1.5px_rgba(16,185,129,0.5)]"
/>
@@ -2937,7 +2851,7 @@ export function Timeline() {
asset={assets.find((x) => x.id === a.assetId)}
mention={audioMentions.get(a.id)}
pps={pps}
- top={stackedRowTop("audio", homeRow, AUDIO_H)}
+ top={stackedRowTop("audio", homeRow, AUDIO_H) + audioTopShift}
homeRow={homeRow}
rowMove={
rowDrag?.band === "audio"
@@ -2946,7 +2860,7 @@ export function Timeline() {
: "part"
: null
}
- laneCount={audioLanes.count}
+ rows={audioRowBoxes}
selected={selKeys.has(`audio:${a.id}`)}
drag={drag}
parting={laneDragParts(laneDrag, "audio", a.id)}
@@ -2970,19 +2884,11 @@ export function Timeline() {
{[...new Set(subtitles.cues.map((c) => c.lane ?? 0))].map((lane) =>
laneRail((lane + 1) * SUB_H - 3, lane)
)}
- {laneDrag?.kind === "cue" && (
- // A cue belongs to its language track, so that one row is the
- // whole landing area while the ghost floats free.
- <div
- className="pointer-events-none absolute inset-x-0 rounded-[2.5px] border border-dashed border-amber-500/50"
- style={{ top: laneDrag.targetRow * SUB_H + 1, height: SUB_H - 4 }}
- />
- )}
{laneDrag?.kind === "cue" && (
<LaneSlot
drag={laneDrag}
pps={pps}
- rowH={SUB_H}
+ top={laneDrag.targetRow * SUB_H + 1}
barH={SUB_H - 4}
className="rounded-[2.5px] bg-amber-400/15 shadow-[inset_0_0_0_1.5px_rgba(245,158,11,0.55)]"
/>
@@ -3865,12 +3771,10 @@ function ClipView({
drag,
parting,
partAt,
+ homeRow,
+ rows,
onDrag,
onSnap,
- resolveTarget,
- onCrossMove,
- onCrossDrop,
- onDragActive,
onFrameMenu,
}: {
span: ClipSpan;
@@ -3886,18 +3790,11 @@ function ClipView({
parting: boolean;
/** The start this clip previews at while a hovering drop parts its row. */
partAt?: number;
+ /** The clip's display row in the stack, and the stack's rows read live. */
+ homeRow: number;
+ rows: () => RowBox[];
onDrag: (d: LaneDrag | null) => void;
onSnap: (x: number | null) => void;
- /** Which drop the given screen point is over: a video row, or a new track
- * past the stack's edge. The carried clip's id decides whether a new track
- * is on offer at all. */
- resolveTarget: (clientX: number, clientY: number, draggedId?: string) => TrackTarget;
- /** Preview a cross-track drop (null clears it). */
- onCrossMove: (target: TrackTarget | null, start?: number, len?: number) => void;
- /** Commit a cross-track drop of this clip at `start`. */
- onCrossDrop: (id: string, target: TrackTarget, start: number) => void;
- /** Toggle the between-track insertion zones while this clip is dragging. */
- onDragActive: (active: boolean) => void;
/** Right-click: offer the frame under the pointer to the chat composer. */
onFrameMenu: (
e: React.MouseEvent,
@@ -3905,10 +3802,7 @@ function ClipView({
) => void;
}) {
const { clip, asset } = span;
- // The row the clip lives on names its lane; the two gesture kinds write
- // through different store actions.
- const lane: LaneKind = clip.track === 0 ? "clip" : "overlayClip";
- const spine = lane === "clip";
+ const spine = clip.track === 0;
const loading = useEditor((s) => s.loadingMedia.has(asset.fileName));
const baking = useMatteBakes((s) => s.jobs[clip.id]?.status === "running");
const rt = retimeOf(clip);
@@ -3961,26 +3855,9 @@ function ClipView({
);
useTileFrames(boxRef, clip.id, asset, filmstrip, filmIn, w, pps, rt.key, onTileFrame);
- // The move gesture is the shared lane behavior (parting, snapping); its
- // verticality is the video placement system — the other tracks and the new
- // tracks past the stack — resolved from the rows' geometry.
- const ui = {
- pps,
- rowH: VIDEO_H,
- laneCount: 0,
- homeRow: 0,
- visStart: span.start,
- onDrag,
- onSnap,
- vertical: {
- resolve: (ev: PointerEvent) => resolveTarget(ev.clientX, ev.clientY, clip.id),
- 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,
- },
- };
+ // The move gesture is the shared lane behavior: parting, snapping, and
+ // retracking across the stack's rows.
+ const ui = { pps, rows, homeRow, visStart: span.start, onDrag, onSnap };
return (
<>
@@ -4010,7 +3887,7 @@ function ClipView({
addBeatAt(e, asset, clip, pps);
return;
}
- startLaneMove(e, lane, clip.id, ui);
+ startLaneMove(e, "video", clip.id, ui);
}}
onContextMenu={(e) => {
if (asset.type !== "video") return;
@@ -4130,11 +4007,11 @@ function ClipView({
<BeatDots asset={asset} lo={clip.in} hi={clip.out} retime={rt} pps={pps} w={barW} />
<span
className={cn(trimFor(barW), "tl-trim-l left-0")}
- onPointerDown={(e) => startLaneTrim(e, lane, clip.id, "l", ui)}
+ onPointerDown={(e) => startLaneTrim(e, "video", clip.id, "l", ui)}
/>
<span
className={cn(trimFor(barW), "tl-trim-r right-0")}
- onPointerDown={(e) => startLaneTrim(e, lane, clip.id, "r", ui)}
+ onPointerDown={(e) => startLaneTrim(e, "video", clip.id, "r", ui)}
/>
</div>
<ClipMaskKeyStrip
@@ -5381,7 +5258,7 @@ function AudioView({
pps,
top,
homeRow,
- laneCount,
+ rows,
selected,
drag,
parting,
@@ -5398,7 +5275,8 @@ function AudioView({
/** Home-row top in px; while carried the ghost adds the pointer's offset. */
top: number;
homeRow: number;
- laneCount: number;
+ /** The band's rows read live, for the drag's row resolution. */
+ rows: () => RowBox[];
selected: boolean;
/** This bar's live drag when it is the one being carried (ghost mode). */
drag: LaneDrag | null;
@@ -5431,7 +5309,7 @@ function AudioView({
if (!asset) return null;
- const ui = { pps, rowH: AUDIO_H, laneCount, homeRow, onDrag, onSnap };
+ const ui = { pps, rows, homeRow, onDrag, onSnap };
return (
<div
@@ -5788,7 +5666,7 @@ function TextBar({
pps,
top,
homeRow,
- laneCount,
+ rows,
selected,
drag,
parting,
@@ -5801,7 +5679,8 @@ function TextBar({
pps: number;
top: number;
homeRow: number;
- laneCount: number;
+ /** The band's rows read live, for the drag's row resolution. */
+ rows: () => RowBox[];
selected: boolean;
/** A row drag is running in this band: "lift" is the row being carried,
* "part" a row sliding into the place it closes up into. */
@@ -5821,9 +5700,7 @@ function TextBar({
// The bar is drawn a gutter narrower than the footprint; the keys on it
// measure against that.
const barW = Math.max(8, w - CLIP_GAP);
- // Element rows are a z-order, so the top of the stack is a place a drag
- // can reach: past the top edge opens a row there.
- const ui = { pps, rowH: TEXT_H, laneCount, homeRow, topInsert: true, onDrag, onSnap };
+ const ui = { pps, rows, homeRow, onDrag, onSnap };
// Per-kind chip content: a title shows its text, a shape its name behind a
// shape glyph, a sticker its glyph and name.
const ShapeIcon = SHAPE_CHIP_ICONS[o.kind === "shape" ? o.shape : "rect"];
@@ -5935,7 +5812,8 @@ function SubBar({
onSnap: (x: number | null) => void;
}) {
const w = Math.max(8, (cue.end - cue.start) * pps);
- const ui = { pps, rowH: SUB_H, laneCount: 0, homeRow, onDrag, onSnap };
+ // A cue never leaves its language row, so the band's rows go unread.
+ const ui = { pps, rows: () => [], homeRow, onDrag, onSnap };
return (
<div
@@ -5974,23 +5852,21 @@ function SubBar({
);
}
-/** 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. */
+/** The landing-slot preview for an in-flight lane drag, drawn in the band's
+ * own chrome; it tracks the coordinator's resolved slot, at the row top the
+ * band resolves for it. */
function LaneSlot({
drag,
pps,
- rowH,
+ top,
barH,
- shift = 0,
className,
}: {
drag: LaneDrag;
pps: number;
- rowH: number;
+ top: number;
barH: number;
- /** Rows pushed down by a new row opening above them. */
- shift?: number;
- className?: string;
+ className: string;
}) {
return (
<div
@@ -6000,7 +5876,7 @@ function LaneSlot({
)}
style={{
left: drag.slotStart * pps,
- top: drag.targetRow * rowH + 2 + shift,
+ top,
width: Math.max(8, drag.len * pps - CLIP_GAP),
height: barH,
}}
diff --git a/site/src/cut/lib/laneTracks.test.ts b/site/src/cut/lib/laneTracks.test.ts
new file mode 100644
index 00000000..e636806b
--- /dev/null
+++ b/site/src/cut/lib/laneTracks.test.ts
@@ -0,0 +1,207 @@
+import { beforeEach, describe, expect, test } from "bun:test";
+import { commitRow, NEW_ROW_PX, partAround, resolveRow } from "./laneTracks";
+import { clipLen, useEditor } from "./store";
+import { emptySubtitles } from "./types";
+import type { AudioClip, VideoClip } from "./types";
+
+/**
+ * One vertical model for every lane kind: the row under the pointer takes
+ * the item, a reach past either edge of the band opens a new row, an
+ * outermost row held alone offers nothing on its side, and a commit renumbers
+ * lanes contiguous. Video and audio go through the same functions; the only
+ * difference is which way the video stack counts its rows.
+ */
+
+let n = 0;
+const vclip = (o: Partial<VideoClip>): VideoClip => ({
+ id: `c${++n}`,
+ assetId: "x",
+ track: 0,
+ start: 0,
+ in: 0,
+ out: 2,
+ muted: false,
+ ...o,
+});
+const aclip = (o: Partial<AudioClip>): AudioClip => ({
+ id: `au${++n}`,
+ assetId: "x",
+ start: 0,
+ in: 0,
+ out: 2,
+ volume: 1,
+ ...o,
+});
+const s = () => useEditor.getState();
+const clipById = (id: string) => s().clips.find((c) => c.id === id)!;
+const audioById = (id: string) => s().audioClips.find((c) => c.id === id)!;
+
+beforeEach(() => {
+ useEditor.setState({
+ clips: [],
+ transitions: [],
+ audioClips: [],
+ overlays: [],
+ subtitles: emptySubtitles(),
+ selection: null,
+ multiSelection: [],
+ });
+});
+
+describe("resolveRow", () => {
+ // Three rows of 40px stacked from y=100.
+ const rows = [
+ { top: 100, h: 40 },
+ { top: 140, h: 40 },
+ { top: 180, h: 40 },
+ ];
+ const open = { top: true, bottom: true };
+
+ test("the row under the pointer takes the item", () => {
+ expect(resolveRow(rows, 110, null, open)).toBe(0);
+ expect(resolveRow(rows, 150, null, open)).toBe(1);
+ expect(resolveRow(rows, 219, null, open)).toBe(2);
+ });
+
+ test("a pointer in the gap between rows takes the row below", () => {
+ const gapped = [
+ { top: 100, h: 40 },
+ { top: 146, h: 40 },
+ ];
+ expect(resolveRow(gapped, 143, null, open)).toBe(1);
+ });
+
+ test("a new row opens only past the reach beyond either edge", () => {
+ expect(resolveRow(rows, 100 - NEW_ROW_PX + 1, null, open)).toBe(0);
+ expect(resolveRow(rows, 100 - NEW_ROW_PX - 1, null, open)).toBe(-1);
+ expect(resolveRow(rows, 220 + NEW_ROW_PX - 1, null, open)).toBe(2);
+ expect(resolveRow(rows, 220 + NEW_ROW_PX + 1, null, open)).toBe(3);
+ });
+
+ test("a held new row keeps its hold with no reach until the pointer returns to a row", () => {
+ expect(resolveRow(rows, 99, -1, open)).toBe(-1);
+ expect(resolveRow(rows, 101, -1, open)).toBe(0);
+ expect(resolveRow(rows, 221, 3, open)).toBe(3);
+ expect(resolveRow(rows, 219, 3, open)).toBe(2);
+ });
+
+ test("a closed edge offers no new row, however far the drag reaches", () => {
+ expect(resolveRow(rows, 0, null, { top: false, bottom: true })).toBe(0);
+ expect(resolveRow(rows, 400, null, { top: true, bottom: false })).toBe(2);
+ });
+});
+
+describe("partAround", () => {
+ const item = (id: string, start: number, len: number) => ({ view: { id, start, len, lane: 0 } });
+ const rest = (x: { view: { start: number } }) => x.view.start;
+
+ test("residents past the pointer slide right as one run", () => {
+ const a = item("a", 1, 2);
+ const b = item("b", 3, 2);
+ const part = partAround([a, b], 1.2, 1.2, 2, rest);
+ expect(part.slotStart).toBeCloseTo(1.2);
+ expect(part.clamped).toBe(false);
+ expect(part.at(a)).toBeCloseTo(3.2);
+ expect(part.at(b)).toBeCloseTo(5.2);
+ });
+
+ test("a resident whose midpoint sits before the pointer holds, and clamps the slot after it", () => {
+ const a = item("a", 0, 2);
+ const part = partAround([a], 1.5, 0.5, 2, rest);
+ expect(part.slotStart).toBeCloseTo(2);
+ expect(part.clamped).toBe(true);
+ expect(part.at(a)).toBe(0);
+ });
+});
+
+describe("commitRow on the video stack", () => {
+ test("the row past the top opens a new highest track", () => {
+ const spine = vclip({ track: 0 });
+ const layer = vclip({ track: 1 });
+ const mover = vclip({ track: 0, start: 2 });
+ useEditor.setState({ clips: [spine, layer, mover] });
+ commitRow("video", mover.id, -1);
+ expect(clipById(mover.id).track).toBe(2);
+ expect(clipById(layer.id).track).toBe(1);
+ expect(clipById(spine.id).track).toBe(0);
+ });
+
+ test("the row past the bottom makes the clip the new track 0 and renumbers the stack", () => {
+ const spine = vclip({ track: 0 });
+ const mover = vclip({ track: 1 });
+ const anchor = vclip({ track: 1, start: 3 });
+ useEditor.setState({ clips: [spine, mover, anchor] });
+ commitRow("video", mover.id, 2);
+ expect(clipById(mover.id).track).toBe(0);
+ expect(clipById(spine.id).track).toBe(1);
+ expect(clipById(anchor.id).track).toBe(2);
+ });
+
+ test("a row in the stack is the track drawn there", () => {
+ const spine = vclip({ track: 0 });
+ const layer = vclip({ track: 1 });
+ const mover = vclip({ track: 0, start: 2 });
+ useEditor.setState({ clips: [spine, layer, mover] });
+ commitRow("video", mover.id, 0);
+ expect(clipById(mover.id).track).toBe(1);
+ });
+
+ test("the only track-0 clip moving up grounds the stack", () => {
+ const mover = vclip({ track: 0 });
+ const resident = vclip({ track: 1, start: 3 });
+ useEditor.setState({ clips: [mover, resident] });
+ commitRow("video", mover.id, 0);
+ expect(clipById(mover.id).track).toBe(0);
+ expect(clipById(resident.id).track).toBe(0);
+ });
+});
+
+describe("commitRow on the audio lanes", () => {
+ test("the row past the top opens a new first lane", () => {
+ const bed = aclip({});
+ const fx = aclip({ lane: 1 });
+ useEditor.setState({ audioClips: [bed, fx] });
+ commitRow("audio", fx.id, -1);
+ expect(audioById(fx.id).lane).toBeUndefined();
+ expect(audioById(bed.id).lane).toBe(1);
+ });
+
+ test("the row past the bottom opens a new last lane", () => {
+ const bed = aclip({});
+ const fx = aclip({ start: 3 });
+ useEditor.setState({ audioClips: [bed, fx] });
+ commitRow("audio", fx.id, 1);
+ expect(audioById(fx.id).lane).toBe(1);
+ expect(audioById(bed.id).lane).toBeUndefined();
+ });
+
+ test("an emptied lane collapses", () => {
+ const a = aclip({});
+ const b = aclip({ lane: 1 });
+ const c = aclip({ lane: 2 });
+ useEditor.setState({ audioClips: [a, b, c] });
+ commitRow("audio", b.id, 0);
+ expect(audioById(b.id).lane).toBeUndefined();
+ expect(audioById(c.id).lane).toBe(1);
+ });
+});
+
+describe("a cross-row move keeps the lane sound", () => {
+ test("landing among residents parts them and the commit takes the row", () => {
+ const mover = vclip({ track: 0, start: 0, out: 2 });
+ const anchor = vclip({ track: 0, start: 2, out: 2 });
+ const resident = vclip({ track: 1, start: 1, out: 2 });
+ useEditor.setState({ clips: [mover, anchor, resident] });
+ const st = s();
+ const view = (c: VideoClip) => ({ view: { id: c.id, start: c.start, len: clipLen(c), lane: c.track } });
+ const part = partAround([view(resident)], 1.2, 1.2, 2, (x) => x.view.start);
+ st.updateClipsTransient([
+ { id: mover.id, patch: { start: part.slotStart } },
+ { id: resident.id, patch: { start: part.at(view(resident)) } },
+ ]);
+ commitRow("video", mover.id, 0);
+ expect(clipById(mover.id).track).toBe(1);
+ expect(clipById(mover.id).start).toBeCloseTo(1.2);
+ expect(clipById(resident.id).start).toBeCloseTo(3.2);
+ });
+});
diff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.ts
index 26078f10..88fa8bbb 100644
--- a/site/src/cut/lib/laneTracks.ts
+++ b/site/src/cut/lib/laneTracks.ts
@@ -4,18 +4,20 @@ import { retimeOf, type Retimable, type SpeedNode } from "@donkeycut/effects-kit
/**
* 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.
+ * tracks behave. Video clips, audio, titles, and subtitle cues all route
+ * their pointer gestures through here, so selection, moving, resizing,
+ * collision, snapping, and retracking 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.
+ * - Move: the bar ghosts under the pointer while the neighbors on the row it
+ * aims at part around the landing slot; either edge snaps to logical
+ * times. The row under the pointer takes the item; carrying it past the
+ * top or bottom of its band by `NEW_ROW_PX` opens a brand-new row there,
+ * which then holds itself until the pointer returns to a row. Lanes stay
+ * contiguous, so an emptied row collapses.
* - Resize: edges snap; growing into a neighbor pushes its whole run along;
* each edge rubber-bands past its source bound and springs back on release —
* the left past its floor (timeline start, packed leaders, or a media item's
@@ -24,16 +26,17 @@ import { retimeOf, type Retimable, type SpeedNode } from "@donkeycut/effects-kit
* lane — the store's `nextFreeStart` is that one primitive.
* - Cut: the store's `splitAtPlayhead` slices whichever kind is selected.
*
- * The video tracks keep their richer verticality (lifting between tracks,
- * insert zones, dropping onto track 0) by passing a `vertical` strategy to
- * the move gesture; everything else about them is the shared behavior.
+ * An adapter can vary exactly three things: `closesGap` (a video clip's
+ * slot heals behind it; a sound bed or title keeps its absolute time),
+ * `rowsDescend` (the video stack draws track 0 at the bottom), and
+ * `multiLane` (cues never leave their language row).
*/
import type React from "react";
import { refFromAsset, startPointerRefDrag } from "./assetRef";
import { startDrag } from "./drag";
import { additiveClick, snapHeldOff } from "./hostKeys";
-import { track0Clips, clipLen, getClipSpans, moveOverlayGroup, nextFreeStart, overlayLaneOrder, overlayLayers, projectDuration, reanchorTransitions, startTrimRipple, useEditor } from "./store";
+import { clipLen, getClipSpans, moveOverlayGroup, nextFreeStart, overlayLaneOrder, projectDuration, reanchorTransitions, startTrimRipple, useEditor } from "./store";
import { playheadAt } from "./playhead";
import type {
AudioClip,
@@ -46,27 +49,84 @@ import type {
type S = ReturnType<typeof useEditor.getState>;
-// A drag lane. "clip" is track 0, "overlayClip" a layer track —
-// distinct adapters, but both select as a plain video-clip selection.
-// "overlay" is the title lanes: every overlay element kind rides one adapter.
-export type LaneKind = "clip" | "audio" | "overlay" | "overlayClip" | "cue";
+// A drag lane: one per doc structure. "video" is every video track (a
+// clip's lane is its track number); "overlay" is the title lanes, where every
+// overlay element kind rides one adapter.
+export type LaneKind = "video" | "audio" | "overlay" | "cue";
-/** The Selection kind a lane maps to. Track-0 and layer video lanes both select
- * as `"clip"` — a video clip is a video clip whatever track it sits on. */
+/** The Selection kind a lane maps to: a video clip selects as `"clip"`. */
const laneSelectionKind = (kind: LaneKind): NonNullable<Selection>["kind"] =>
- kind === "overlayClip" ? "clip" : kind;
-
-/** The doc structure behind a lane kind. Track 0 and the layer tracks are two
- * lane kinds over one clip list, so collision and identity both key on the
- * structure, never the adapter. */
-type LaneStructure = "video" | "audio" | "overlay" | "cue";
-const structureOf = (kind: LaneKind): LaneStructure =>
- kind === "clip" || kind === "overlayClip" ? "video" : kind;
+ kind === "video" ? "clip" : kind;
/** Visual gutter between adjacent clips; 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 past the top or bottom of its band a drag has to carry an item to
+ * open a new row. Every drop inside the band lands on a row, which opens room
+ * for it, so this reach is the one gesture that adds a row — and it is long
+ * enough that drifting off a row while sliding along it never does. */
+export const NEW_ROW_PX = 24;
+
+/** A display row's screen box, top first in the order the band paints. */
+export interface RowBox {
+ top: number;
+ h: number;
+}
+
+/** The display row a drag aims at from the pointer's screen y: the row under
+ * the pointer (a pointer in the gap between two rows takes the row below),
+ * `-1` past the top of the band, `rows.length` past the bottom. Reaching past
+ * an edge takes `NEW_ROW_PX` of travel; holding it takes none, since by then
+ * the new row's own box fills the space the pointer is in — `held` is the row
+ * the drag resolved to last. An edge whose row the item holds alone offers
+ * nothing: the row it left would collapse behind it and the fresh one would
+ * renumber straight back to the picture already on screen, so `edges` says
+ * which sides are open. */
+export function resolveRow(
+ rows: readonly RowBox[],
+ y: number,
+ held: number | null,
+ edges: { top: boolean; bottom: boolean }
+): number {
+ const n = rows.length;
+ if (n === 0) return 0;
+ const top = rows[0];
+ const bottom = rows[n - 1];
+ if (edges.top && y < top.top - (held === -1 ? 0 : NEW_ROW_PX)) return -1;
+ if (edges.bottom && y > bottom.top + bottom.h + (held === n ? 0 : NEW_ROW_PX)) return n;
+ const i = rows.findIndex((r) => y <= r.top + r.h);
+ return i < 0 ? n - 1 : Math.max(0, i);
+}
+
+/** The lane an item lands on while its slot is laid out around the pointer:
+ * residents whose midpoint sits left of the pointer keep their spot (the
+ * slot lands after them), the rest slide right as a run to make room.
+ * Anchoring on the pointer rather than the ghost's geometric center lets an
+ * item take the front as soon as you point past a neighbor's middle — an
+ * item longer than the gap ahead could never drag its own center that far
+ * left. `restAt` is each resident's resting spot for this frame. Returns the
+ * slot start and where every resident should sit. */
+export function partAround<X extends { view: LaneItem }>(
+ residents: readonly X[],
+ pointerTime: number,
+ start: number,
+ len: number,
+ restAt: (x: X) => number
+): { slotStart: number; clamped: boolean; at: (x: X) => number } {
+ const others = [...residents].sort((a, b) => a.view.start - b.view.start);
+ const before = others.filter((x) => x.view.start + x.view.len / 2 <= pointerTime);
+ const after = others.filter((x) => x.view.start + x.view.len / 2 > pointerTime);
+ const clampFloor = before.reduce((m, b) => Math.max(m, restAt(b) + b.view.len), 0);
+ const slotStart = Math.max(start, clampFloor);
+ const delta = after.length ? Math.max(0, slotStart + len - restAt(after[0])) : 0;
+ const pushed = new Set(after.map((x) => x.view.id));
+ return {
+ slotStart,
+ clamped: slotStart !== start,
+ at: (x) => (pushed.has(x.view.id) ? restAt(x) + delta : restAt(x)),
+ };
+}
/** How far (px) an edge can rubber-band past its bound before springing back. */
const RUBBER_PX = 32;
@@ -89,6 +149,10 @@ interface LaneAdapter<T> {
minLen: number;
/** Vertical drag retracks among this kind's own lanes. */
multiLane: boolean;
+ /** Display rows run from the highest lane down: the video stack draws
+ * track 0 at the bottom, so the row past its top is a new highest track
+ * and the row past its bottom a new track 0. */
+ rowsDescend?: boolean;
raws(s: S): T[];
view(raw: T): LaneItem;
/** Apply patches transiently (no undo entry; the gesture checkpoints once). */
@@ -116,8 +180,9 @@ interface LaneAdapter<T> {
* moment the item leaves. Video tracks set this; free-form lanes (audio,
* titles, cues) hold every resting spot. */
closesGap?: boolean;
- /** After a committed move (e.g. keep cues sorted). */
- onMoved?(): void;
+ /** After a committed move: keep the list sorted, re-seat what rides the
+ * cuts. `before` is the state the gesture started from. */
+ onMoved?(before: S): void;
/** After a committed move, shift companions that ride along — a grouped
* overlay's peers keep their relative timing. Same undo step. */
afterMove?(raw: T, delta: number): void;
@@ -166,13 +231,12 @@ function videoMaxLen(s: S, c: VideoClip): number {
return mediaMaxLen(c, a?.duration);
}
-const clipAdapter: LaneAdapter<VideoClip> = {
+const videoAdapter: 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) => track0Clips(s.clips),
- view: (c) => ({ id: c.id, start: c.start, len: clipLen(c), lane: 0 }),
+ multiLane: true,
+ rowsDescend: true,
+ raws: (s) => s.clips,
+ view: (c) => ({ id: c.id, start: c.start, len: clipLen(c), lane: c.track }),
apply: (patches) => useEditor.getState().updateClipsTransient(patches),
movePatch: (c, start) => ({ id: c.id, patch: { start } }),
trimLeftPatch: (c, newStart) => ({
@@ -189,10 +253,17 @@ const clipAdapter: LaneAdapter<VideoClip> = {
}),
leftFloor: (s, c) => headFloor(c, s.assets.find((x) => x.id === c.assetId)?.duration),
maxLen: videoMaxLen,
+ lanePatch: (c, lane) => ({ id: c.id, patch: { track: lane } }),
closesGap: true,
assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId),
beatTimes: mediaBeatTimes,
- onMoved: () => useEditor.getState().sortClips(),
+ // Clips stay sorted by start, and the transition bars re-seat onto the
+ // cuts the move carried — the same settle every placement does.
+ onMoved: (before) =>
+ useEditor.setState((st) => {
+ const clips = [...st.clips].sort((a, b) => a.start - b.start);
+ return { clips, transitions: reanchorTransitions(before.clips, clips, st.transitions) };
+ }),
};
const audioAdapter: LaneAdapter<AudioClip> = {
@@ -236,34 +307,6 @@ const textAdapter: LaneAdapter<Overlay> = {
afterMove: (o, delta) => moveOverlayGroup(o, delta),
};
-const overlayClipAdapter: LaneAdapter<VideoClip> = {
- 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) => overlayLayers(s.clips),
- view: (c) => ({ id: c.id, start: c.start, len: clipLen(c), lane: c.track }),
- apply: (patches) => useEditor.getState().updateClipsTransient(patches),
- movePatch: (c, start) => ({ id: c.id, patch: { start } }),
- trimLeftPatch: (c, newStart) => ({
- id: c.id,
- patch: { start: newStart, ...headTrim(c, newStart, c.start) },
- }),
- trimRightPatch: (c, newEnd) => ({
- id: c.id,
- patch: tailTrim(c, newEnd, c.start),
- }),
- revealLeftPatch: (c, start, reveal) => ({
- id: c.id,
- patch: { start, ...headTrim(c, reveal, c.start) },
- }),
- leftFloor: (s, c) => headFloor(c, s.assets.find((x) => x.id === c.assetId)?.duration),
- maxLen: videoMaxLen,
- closesGap: true,
- assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId),
- beatTimes: mediaBeatTimes,
-};
-
const cueAdapter: LaneAdapter<SubtitleCue> = {
minLen: 0.15,
// One row per language track, but no vertical retracking: a cue belongs to
@@ -293,10 +336,9 @@ type LaneRaw = VideoClip | AudioClip | Overlay | 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>,
+ video: videoAdapter as unknown as LaneAdapter<LaneRaw>,
audio: audioAdapter as unknown as LaneAdapter<LaneRaw>,
overlay: textAdapter as unknown as LaneAdapter<LaneRaw>,
- overlayClip: overlayClipAdapter as unknown as LaneAdapter<LaneRaw>,
cue: cueAdapter as unknown as LaneAdapter<LaneRaw>,
};
@@ -305,7 +347,7 @@ const ADAPTERS: Record<LaneKind, LaneAdapter<LaneRaw>> = {
* track kinds, and every beat of an asset's detected grid mapped through its
* clips — a title can align to a music hit and vice versa. */
function snapTargets(s: S, kind: LaneKind, selfId: string, ownBeats = false): number[] {
- return snapTargetsExcluding(s, new Set([`${structureOf(kind)}:${selfId}`]), ownBeats);
+ return snapTargetsExcluding(s, new Set([`${kind}:${selfId}`]), ownBeats);
}
/** Snap targets with a whole set of items excluded — a group drag must not
@@ -332,7 +374,7 @@ function snapTargetsExcluding(
for (const k of Object.keys(ADAPTERS) as LaneKind[]) {
for (const raw of ADAPTERS[k].raws(s)) {
const v = ADAPTERS[k].view(raw);
- const self = excluded.has(`${structureOf(k)}:${v.id}`);
+ const self = excluded.has(`${k}:${v.id}`);
if (!self) {
pts.add(v.start);
pts.add(v.start + v.len);
@@ -434,24 +476,17 @@ function releaseOvershoot() {
}
/** 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. */
+ * landing slot, and grow the band while a new row is hovered. */
export interface LaneDrag {
kind: LaneKind;
id: string;
- /** Hovered display row. One past the end opens a new row below; -1 opens
- * one above the top, for a stack whose order is z-order. */
+ /** The display row the drag aims at: `-1` opens a new row above the band,
+ * one past the last row opens one below. */
targetRow: number;
- /** The rows this drag can land on, inclusive — the band paints exactly
- * these and nothing else. */
- minRow: number;
- maxRow: number;
ghostX: number; // ghost left in px — follows the pointer
ghostY: number; // ghost vertical offset in px from its resting row — 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;
/** The rest of a group drag's set: each member rides the pointer as its own
* ghost, shifted by the same delta as the grabbed item. */
members?: { kind: LaneKind; id: string; ghostX: number }[];
@@ -475,14 +510,11 @@ export function laneDragParts(d: LaneDrag | null, kind: LaneKind, id: string): b
return d.kind === kind || !!d.members?.some((m) => m.kind === kind);
}
-export interface LaneMoveUI<V = unknown> {
+export interface LaneMoveUI {
pps: number;
- rowH: number;
- /** Display rows currently in use; targetRow may go one past to open a new track. */
- laneCount: number;
- /** Dragging above the top row opens a new one there. On for stacks where a
- * row's place is its z-order — the element rows — so the top is reachable. */
- topInsert?: boolean;
+ /** The band's display rows as screen boxes, top first, read live: rows
+ * can mount and shift while a drag runs. */
+ rows(): RowBox[];
/** The grabbed item's current display row. */
homeRow: number;
/** Timeline second the item's box is rendered at, when it differs from the
@@ -493,16 +525,6 @@ export interface LaneMoveUI<V = unknown> {
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;
- };
}
// ── Group move ──────────────────────────────────────────────────────────────
@@ -521,8 +543,7 @@ interface GroupMember {
const memberOf = (s: S, sel: NonNullable<Selection>): GroupMember | null => {
if (sel.kind === "clip") {
const c = s.clips.find((x) => x.id === sel.id);
- if (!c) return null;
- return { kind: c.track === 0 ? "clip" : "overlayClip", raw: c, id: c.id, start: c.start, len: clipLen(c), lane: c.track };
+ return c ? { kind: "video", raw: c, id: c.id, start: c.start, len: clipLen(c), lane: c.track } : null;
}
if (sel.kind === "audio") {
const a = s.audioClips.find((x) => x.id === sel.id);
@@ -553,7 +574,7 @@ function startGroupMove(
e: React.PointerEvent,
grabbed: GroupMember,
members: GroupMember[],
- ui: LaneMoveUI<unknown>
+ ui: LaneMoveUI
) {
const s = useEditor.getState();
// The grab keeps the multi-selection and makes the grabbed item primary —
@@ -570,7 +591,7 @@ function startGroupMove(
if (s.readOnly) return;
s.pushHistory();
- const memberKeys = new Set(members.map((m) => `${structureOf(m.kind)}:${m.id}`));
+ const memberKeys = new Set(members.map((m) => `${m.kind}:${m.id}`));
const targets = snapTargetsExcluding(s, memberKeys);
const tol = SNAP_PX / ui.pps;
// The set is rigid, so the earliest member is the whole group's floor.
@@ -579,30 +600,24 @@ function startGroupMove(
// Everyone else's resting spot on the lanes the group touches, grouped by
// structure lane. Each frame re-lays these from rest, so a retreating drag
// lets parted neighbors flow back.
- const laneKey = (m: { kind: LaneKind; lane: number }) => `${structureOf(m.kind)}:${m.lane}`;
+ const laneKey = (m: { kind: LaneKind; lane: number }) => `${m.kind}:${m.lane}`;
const lanesTouched = new Set(members.map(laneKey));
const restOf = (kind: LaneKind) =>
ADAPTERS[kind]
.raws(s)
.map((raw) => ({ kind, raw, view: ADAPTERS[kind].view(raw) }))
- .filter((x) => !memberKeys.has(`${structureOf(kind)}:${x.view.id}`));
+ .filter((x) => !memberKeys.has(`${kind}:${x.view.id}`));
const rest = (
- [
- ...restOf("clip"),
- ...restOf("overlayClip"),
- ...restOf("audio"),
- ...restOf("overlay"),
- ...restOf("cue"),
- ] as { kind: LaneKind; raw: LaneRaw; view: LaneItem }[]
- ).filter((x) =>
- lanesTouched.has(
- `${structureOf(x.kind)}:${structureOf(x.kind) === "video" ? (x.raw as VideoClip).track : x.view.lane}`
- )
- );
+ [...restOf("video"), ...restOf("audio"), ...restOf("overlay"), ...restOf("cue")] as {
+ kind: LaneKind;
+ raw: LaneRaw;
+ view: LaneItem;
+ }[]
+ ).filter((x) => lanesTouched.has(laneKey({ kind: x.kind, lane: x.view.lane })));
// Vertical retracking, only when the whole selection is one multi-lane kind.
const oneKind = members.every((m) => m.kind === grabbed.kind);
- const vertical = oneKind && ADAPTERS[grabbed.kind].multiLane && !ui.vertical;
+ const vertical = oneKind && ADAPTERS[grabbed.kind].multiLane;
const usedLanes = vertical
? laneOrder(grabbed.kind, s, [...ADAPTERS[grabbed.kind].raws(s).map((r) => ADAPTERS[grabbed.kind].view(r).lane)])
: [];
@@ -622,18 +637,19 @@ function startGroupMove(
: [];
const holdsRowAlone = (row: number) =>
rowsHeld.has(row) && !others.some((v) => rowOf(v.lane) === row);
- const rowLo = vertical
- ? (ui.topInsert && !holdsRowAlone(0) ? -1 : 0) - Math.min(...rowsHeld)
- : 0;
+ const edges = { top: !holdsRowAlone(0), bottom: !holdsRowAlone(usedLanes.length - 1) };
+ const rowLo = vertical ? (edges.top ? -1 : 0) - Math.min(...rowsHeld) : 0;
const rowHi = vertical
- ? ui.laneCount - (holdsRowAlone(ui.laneCount - 1) ? 1 : 0) - Math.max(...rowsHeld)
+ ? usedLanes.length - (edges.bottom ? 0 : 1) - Math.max(...rowsHeld)
: 0;
const homeRow = vertical ? rowOf(grabbed.lane) : ui.homeRow;
const scroller = (e.currentTarget as HTMLElement).closest<HTMLElement>("[data-tl-scroll]");
const sc0 = scroller?.scrollLeft ?? 0;
- const rowEl = (e.currentTarget as HTMLElement).parentElement;
- const rowTop0 = rowEl?.getBoundingClientRect().top ?? 0;
+ // The ghosts' vertical anchor, as in the single-item move: the grabbed
+ // item's row can shift when a new row opens above it.
+ const homeTop = (rows: RowBox[]) => rows[homeRow]?.top ?? 0;
+ const rowTop0 = homeTop(ui.rows());
// Everyone in the set but the grabbed item: each rides the pointer as its
// own ghost, so the whole selection visibly moves as one.
@@ -653,12 +669,12 @@ function startGroupMove(
restStart: number,
want: number
) => {
- const cur = at.get(`${structureOf(kind)}:${id}`) ?? restStart;
+ const cur = at.get(`${kind}:${id}`) ?? restStart;
if (Math.abs(want - cur) <= 1e-9) return;
const list = buckets.get(kind) ?? [];
list.push(ADAPTERS[kind].movePatch(raw, want));
buckets.set(kind, list);
- at.set(`${structureOf(kind)}:${id}`, want);
+ at.set(`${kind}:${id}`, want);
};
const layout = (delta: number) => {
const buckets = new Map<LaneKind, Patch<LaneRaw>[]>();
@@ -671,10 +687,7 @@ function startGroupMove(
.filter((m) => laneKey(m) === key)
.map((m) => ({ start: m.start + delta, end: m.start + delta + m.len }));
const others = rest
- .filter(
- (x) =>
- `${structureOf(x.kind)}:${structureOf(x.kind) === "video" ? (x.raw as VideoClip).track : x.view.lane}` === key
- )
+ .filter((x) => laneKey({ kind: x.kind, lane: x.view.lane }) === key)
.sort((a, b) => a.view.start - b.view.start);
let floor = -Infinity;
for (const o of others) {
@@ -714,19 +727,21 @@ function startGroupMove(
guide = best.px;
}
}
- rowDelta = vertical ? Math.min(rowHi, Math.max(rowLo, Math.round(dy / ui.rowH))) : 0;
+ const rows = ui.rows();
+ if (vertical) {
+ const row = resolveRow(rows, ev.clientY, homeRow + rowDelta, edges);
+ rowDelta = Math.min(rowHi, Math.max(rowLo, row - homeRow));
+ }
ui.onSnap(guide);
layout(dt);
// Ghosts ride the raw pointer delta, clamped so the set's earliest
// member holds at 0 — the same rigid floor the landing uses.
const dtGhost = Math.max(-minStart, effDx / ui.pps);
- const ghostY = dy - (rowEl ? rowEl.getBoundingClientRect().top - rowTop0 : 0);
+ const ghostY = dy - (homeTop(rows) - rowTop0);
ui.onDrag({
kind: grabbed.kind,
id: grabbed.id,
targetRow: homeRow + rowDelta,
- minRow: homeRow + rowLo,
- maxRow: homeRow + rowHi,
ghostX: (grabbed.start + dtGhost) * ui.pps,
ghostY,
slotStart: grabbed.start + dt,
@@ -757,9 +772,7 @@ function startGroupMove(
commitGroupRows(grabbed.kind, members, rowDelta);
partClearOfMembers(grabbed.kind, new Set(members.map((m) => m.id)));
}
- const structures = new Set(members.map((m) => structureOf(m.kind)));
- if (structures.has("video")) useEditor.getState().sortClips();
- if (structures.has("cue")) useEditor.getState().sortCues();
+ for (const kind of new Set(members.map((m) => m.kind))) ADAPTERS[kind].onMoved?.(s);
},
});
}
@@ -801,13 +814,9 @@ function commitGroupRows(kind: LaneKind, members: GroupMember[], rowDelta: numbe
const raws = ad.raws(s);
const views = raws.map((r) => ad.view(r));
const used = laneOrder(kind, s, views.map((v) => v.lane));
- const minUsed = Math.min(0, ...used);
- const maxUsed = Math.max(-1, ...used);
const memberIds = new Set(members.map((m) => m.id));
- const laneFor = (row: number) =>
- row < 0 ? minUsed - 1 + (row + 1) : row < used.length ? used[row] : maxUsed + 1 + (row - used.length);
const moved = views.map((v) =>
- memberIds.has(v.id) ? laneFor(used.indexOf(v.lane) + rowDelta) : v.lane
+ memberIds.has(v.id) ? laneAtRow(kind, used, used.indexOf(v.lane) + rowDelta) : v.lane
);
const usedNext = [...new Set(moved)].sort((a, b) => a - b);
const remap = new Map(usedNext.map((l, i) => [l, i]));
@@ -816,12 +825,7 @@ function commitGroupRows(kind: LaneKind, members: GroupMember[], rowDelta: numbe
/** 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>
-) {
+export function startLaneMove(e: React.PointerEvent, kind: LaneKind, id: string, ui: LaneMoveUI) {
// A secondary button belongs to the clip's context menu, not to a drag: it
// selects what it points at — so the menu, and the next keystroke, act on
// that item — and leaves the playhead where it is. Pointing at something
@@ -853,21 +857,21 @@ export function startLaneMove<V = unknown>(
const members: GroupMember[] = [];
const admit = (m: GroupMember | null) => {
if (!m) return;
- const key = `${structureOf(m.kind)}:${m.id}`;
+ const key = `${m.kind}:${m.id}`;
if (seen.has(key)) return;
seen.add(key);
members.push(m);
};
for (const sel of s.multiSelection) if (sel) admit(memberOf(s, sel));
for (const m of [...members]) {
- const gid = structureOf(m.kind) === "overlay" ? (m.raw as Overlay).groupId : undefined;
+ const gid = m.kind === "overlay" ? (m.raw as Overlay).groupId : undefined;
if (!gid) continue;
for (const peer of s.overlays.filter((o) => o.groupId === gid))
admit(memberOf(s, { kind: "overlay", id: peer.id }));
}
const grabbed = members.find((m) => m.kind === kind && m.id === id) ?? members.find((m) => m.id === id);
if (grabbed && members.length > 1) {
- startGroupMove(e, grabbed, members, ui as LaneMoveUI<unknown>);
+ startGroupMove(e, grabbed, members, ui);
return;
}
}
@@ -913,20 +917,15 @@ export function startLaneMove<V = unknown>(
.filter((x) => x.view.lane === self.lane)
.reduce((m, x) => Math.max(m, restAt(x) + x.view.len), 0);
const usedLanes = laneOrder(kind, s, [...rest.map((x) => x.view.lane), self.lane]);
- // The rows this drag can reach. A row past either end opens a brand-new
- // track, and from an outermost row an item alone there has nothing to open
- // on its side: the row it left collapses behind it, so the fresh one
- // renumbers straight back to the picture already on screen. Single-lane
- // kinds stay on the row they were grabbed from.
+ // The edges this drag can open a new row past. From an outermost row an
+ // item alone there has nothing to open on its side: the row it left
+ // collapses behind it, so the fresh one renumbers straight back to the
+ // picture already on screen. Single-lane kinds stay on their row.
const alone = !rest.some((x) => x.view.lane === self.lane);
- const minRow = ad.multiLane
- ? ui.topInsert && !(alone && ui.homeRow === 0)
- ? -1
- : 0
- : ui.homeRow;
- const maxRow = ad.multiLane
- ? ui.laneCount - (alone && ui.homeRow === ui.laneCount - 1 ? 1 : 0)
- : ui.homeRow;
+ const edges = {
+ top: !(alone && ui.homeRow === 0),
+ bottom: !(alone && ui.homeRow === usedLanes.length - 1),
+ };
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
@@ -938,16 +937,15 @@ export function startLaneMove<V = unknown>(
const scroller = (e.currentTarget as HTMLElement).closest<HTMLElement>("[data-tl-scroll]");
const sc0 = scroller?.scrollLeft ?? 0;
// The ghost's vertical anchor: rows can mount mid-drag (a would-be new
- // track revealing itself), shifting this item's row in the layout. The
+ // row revealing itself above), shifting this item's row in the layout. The
// ghost offset subtracts that shift so it stays glued to the pointer.
- const rowEl = (e.currentTarget as HTMLElement).parentElement;
- const rowTop0 = rowEl?.getBoundingClientRect().top ?? 0;
+ const homeTop = (rows: RowBox[]) => rows[ui.homeRow]?.top ?? 0;
+ const rowTop0 = homeTop(ui.rows());
let live = false;
let targetRow = ui.homeRow;
let slotStart = start0;
let ds = start0;
- let awayTarget: V | null = null;
// Patch only items whose position actually changes this frame (plus
// restores of previously shifted ones): dragging one cue must not rebuild
@@ -985,7 +983,6 @@ export function startLaneMove<V = unknown>(
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);
if (scroller) {
@@ -996,43 +993,15 @@ export function startLaneMove<V = unknown>(
const effDx = dx + ((scroller?.scrollLeft ?? sc0) - sc0);
ds = Math.max(0, start0 + effDx / ui.pps);
const pointerTime = grabTime + effDx / ui.pps;
- const ghostY = dy - (rowEl ? rowEl.getBoundingClientRect().top - rowTop0 : 0);
-
- // Carried off its own lane set (an upper video layer headed to another
- // track, down to track 0, 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;
- // The hole the clip left stays closed while it hovers other tracks.
- applyMoves(restAt, parked);
- ui.onSnap(null);
- ui.vertical.preview(target, ds, len);
- ui.onDrag({
- kind,
- id,
- targetRow: ui.homeRow,
- minRow,
- maxRow,
- ghostX: ds * ui.pps,
- ghostY,
- slotStart: ds,
- len,
- away: true,
- });
- return;
- }
- awayTarget = null;
- ui.vertical.preview(null, 0, 0);
- }
-
- // Vertical drag retracks the item, across the rows it can reach.
- targetRow = Math.min(maxRow, Math.max(minRow, ui.homeRow + Math.round(dy / ui.rowH)));
+ const rows = ui.rows();
+ const ghostY = dy - (homeTop(rows) - rowTop0);
+ // The row under the pointer takes the item; past either edge of the
+ // band a new row opens. Single-lane kinds stay on their own row.
+ targetRow = ad.multiLane ? resolveRow(rows, ev.clientY, targetRow, edges) : ui.homeRow;
// Which lane to part/collide on: multi-lane rows are display indexes
- // into the compacted used-lane list (a row past the end is a brand-new
- // lane with no neighbors); single-lane kinds stay on their own lane —
- // their row number is not an index into that list.
+ // into the compacted used-lane list (a row past either end is a
+ // brand-new lane with no neighbors); single-lane kinds stay on their
+ // own lane — their row number is not an index into that list.
const lane = ad.multiLane
? targetRow < 0
? -Infinity
@@ -1058,92 +1027,81 @@ export function startLaneMove<V = unknown>(
guide = best.px;
}
}
- // Same-lane neighbors part around the cursor: ones whose midpoint sits
- // left of the pointer keep their spot (the slot lands after them), the
- // rest slide right as a run to make room. Anchoring on the cursor rather
- // than the ghost's geometric center lets a clip take the front as soon as
- // you point past a neighbor's middle — a clip longer than the gap ahead
- // could never drag its own center that far left, so it used to snap back.
- // A cross-dissolve is contact, not intrusion: the slot may overlap the
- // neighbor before it by that neighbor's declared transition, and only
- // pushes the run after it once the overlap into its first item exceeds the
- // item's own declared transition.
- // Order comes from the original midpoints, so a lifted clip keeps its
- // spot until the pointer truly crosses a neighbor's middle; the runs
- // themselves sit at their resting spots (closed on gap-closing lanes).
- const others = rest
- .filter((x) => x.view.lane === lane)
- .sort((a, b) => a.view.start - b.view.start);
- const before = others.filter((x) => x.view.start + x.view.len / 2 <= pointerTime);
- const after = others.filter((x) => x.view.start + x.view.len / 2 > pointerTime);
- const prev = before[before.length - 1];
- const clampFloor = prev
- ? Math.max(
- 0,
- ...before.slice(0, -1).map((b) => restAt(b) + b.view.len),
- restAt(prev) + prev.view.len
- )
- : 0;
- const clamped = Math.max(start, clampFloor);
- if (clamped !== start) guide = null;
- slotStart = clamped;
- const delta = after.length
- ? Math.max(0, clamped + len - restAt(after[0]))
- : 0;
- const pushed = new Set(after.map((x) => x.view.id));
+ // The aimed row's neighbors part around the cursor. Order comes from
+ // the original midpoints, so a lifted item keeps its spot until the
+ // pointer truly crosses a neighbor's middle; the runs themselves sit at
+ // their resting spots (closed on gap-closing lanes).
+ const part = partAround(
+ rest.filter((x) => x.view.lane === lane),
+ pointerTime,
+ start,
+ len,
+ restAt
+ );
+ if (part.clamped) guide = null;
+ slotStart = part.slotStart;
ui.onSnap(guide);
- applyMoves((x) => (pushed.has(x.view.id) ? restAt(x) + delta : restAt(x)), clamped);
+ // On a gap-closing lane the lifted item rides its slot while home and
+ // parks past the healed run while it aims at another row, so the doc
+ // never holds two items on one span.
+ applyMoves(part.at, targetRow === ui.homeRow ? slotStart : parked);
ui.onDrag({
kind,
id,
targetRow,
- minRow,
- maxRow,
ghostX: ds * ui.pps,
ghostY,
- slotStart: clamped,
+ slotStart,
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)) {
- // The cross-track commit closes the source gap itself, from resting
- // starts — undo the live closure first or the run slides twice.
- restRestore();
- ui.vertical.commit(id, awayTarget, ds);
return;
}
if (!live || !moved) return;
ad.apply([ad.movePatch(raw0, slotStart)]);
ad.afterMove?.(raw0, slotStart - start0);
commitRow(kind, id, targetRow);
- ad.onMoved?.();
+ ad.onMoved?.(s);
},
});
}
-/** 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. */
/** The display rows a kind shows, top first — the same order the timeline
* paints, so a row index means one thing to both. Overlay rows lead with the
- * effect rows; every other kind is plain lane order. */
+ * effect rows; the video stack runs highest track first; every other kind is
+ * plain lane order. */
function laneOrder(kind: LaneKind, s: S, lanes: number[]): number[] {
if (kind === "overlay") return overlayLaneOrder(s.overlays);
- return [...new Set(lanes)].sort((a, b) => a - b);
+ const used = [...new Set(lanes)].sort((a, b) => a - b);
+ return ADAPTERS[kind].rowsDescend ? used.reverse() : used;
+}
+
+/** The lane a display row names once the drag lands there: a row in use, or
+ * a brand-new lane past either end of the band — one clear of every lane in
+ * use on the side the band grows that way — which the contiguous renumber
+ * after the move folds back into 0..n-1. `beyond` counts rows past the end
+ * for a group whose members straddle the edge. */
+function laneAtRow(kind: LaneKind, used: number[], row: number): number {
+ if (row >= 0 && row < used.length) return used[row];
+ const lo = Math.min(0, ...used) - 1;
+ const hi = Math.max(-1, ...used) + 1;
+ const beyond = row < 0 ? -row - 1 : row - used.length;
+ const pastTop = row < 0;
+ const up = ADAPTERS[kind].rowsDescend ? pastTop : !pastTop;
+ return up ? hi + beyond : lo - beyond;
}
-function commitRow(kind: LaneKind, id: string, targetRow: number) {
+/** Land a dragged item on a display row: a row past either end becomes a
+ * brand-new lane, then lanes renumber contiguous so an emptied one
+ * collapses. The move's pointer-down already checkpointed history, so the
+ * whole gesture is one undo step. */
+export function commitRow(kind: LaneKind, id: string, targetRow: number) {
const s = useEditor.getState();
const ad = ADAPTERS[kind];
if (!ad.multiLane || !ad.lanePatch) return;
@@ -1152,14 +1110,7 @@ function commitRow(kind: LaneKind, id: string, targetRow: number) {
const used = laneOrder(kind, s, views.map((v) => v.lane));
const cur = views.find((v) => v.id === id);
if (!cur || targetRow === used.indexOf(cur.lane)) return;
- // A row past either end opens a brand-new lane, clear of the ones in use;
- // the remap below renumbers everything back to 0..n-1.
- const lane =
- targetRow < 0
- ? Math.min(0, ...used) - 1
- : targetRow < used.length
- ? used[targetRow]
- : Math.max(-1, ...used) + 1;
+ const lane = laneAtRow(kind, used, targetRow);
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]));
@@ -1214,7 +1165,7 @@ export function startLaneTrim(
// video tracks present the engine is null (the delete gate) and the trim
// keeps its own track's push rules.
const ripple =
- kind === "clip"
+ kind === "video" && self.lane === 0
? (startTrimRipple(s, id, self.start + self.len) as {
move: (shift: number, clipPatches: Patch<LaneRaw>[]) => void;
settle: (close?: { at: number; shift: number }) => void;
@@ -1222,7 +1173,7 @@ export function startLaneTrim(
: null;
// The clip layout the gesture started from, so a trim with no ripple engine
// behind it can still map the bars onto where it left the cuts.
- const clips0 = kind === "clip" ? s.clips : null;
+ const clips0 = kind === "video" && self.lane === 0 ? s.clips : null;
/** Close the gesture: the ripple settles the document when there is one,
* and either way the transition bars re-seat onto the cuts the trim moved.
* A dissolve follows its cut whether or not the project has overlay tracks. */
diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.ts
index b24c5055..c6c6a794 100644
--- a/site/src/cut/lib/store.test.ts
+++ b/site/src/cut/lib/store.test.ts
@@ -293,27 +293,6 @@ describe("video placement", () => {
expect(clipById(resident.id).track).toBe(2); // renumbered above the insert
});
- test("dragging a track-0 clip up onto an occupied track slides it clear", () => {
- const mover = vclip({ track: 0, start: 0, out: 2 });
- const anchor = vclip({ track: 0, start: 2, out: 2 });
- const resident = vclip({ track: 1, start: 1, out: 2 });
- useEditor.setState({ clips: [mover, anchor, resident] });
- s().dropVideoClip(mover.id, { kind: "track", track: 1 }, 1.2);
- expect(clipById(mover.id).track).toBe(1);
- expect(clipById(mover.id).start).toBeCloseTo(1.2);
- expect(clipById(resident.id).start).toBeCloseTo(3.2);
- expectLaneSound(videoLane(1));
- });
-
- test("dropping a layer clip down onto occupied track 0 slides it clear", () => {
- const resident = vclip({ track: 0, start: 0, out: 2 });
- const mover = vclip({ track: 1, start: 0.5, out: 2 });
- useEditor.setState({ clips: [resident, mover] });
- s().dropVideoClip(mover.id, { kind: "track", track: 0 }, 1);
- expect(clipById(mover.id).track).toBe(0);
- expect(clipById(mover.id).start).toBeCloseTo(2);
- expectLaneSound(videoLane(0));
- });
});
describe("committed video updates (AI chat / inspector)", () => {
@@ -1187,15 +1166,6 @@ describe("spine grounding", () => {
expect(clipById(upper.id).track).toBe(1);
});
- test("dragging the only track-0 clip up onto a layer grounds the stack", () => {
- const mover = vclip({ track: 0, start: 0, out: 2 });
- const resident = vclip({ track: 1, start: 1, out: 2 });
- useEditor.setState({ clips: [mover, resident] });
- s().dropVideoClip(mover.id, { kind: "track", track: 1 }, 1.2);
- expect(clipById(mover.id).track).toBe(0);
- expect(clipById(resident.id).track).toBe(0);
- expectLaneSound(videoLane(0));
- });
});
describe("upper-track transitions", () => {
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index bebe2695..c3207b39 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -178,13 +178,11 @@ export function groundTracks(clips: VideoClip[]): VideoClip[] {
return lift > 0 ? clips.map((c) => ({ ...c, track: c.track - lift })) : clips;
}
-/** Open a slot at `level`, shifting the tracks at/above it up by one. `exclude`
- * is the clip being placed (left untouched). Level 0 shifts the whole stack up:
- * the placed clip becomes the new track 0 — the spine transplants to it. */
-function openInsertSlot(clips: VideoClip[], level: number, exclude?: string): VideoClip[] {
- return clips.map((c) =>
- c.id !== exclude && c.track >= level ? { ...c, track: c.track + 1 } : c
- );
+/** Open a slot at `level`, shifting the tracks at/above it up by one. Level 0
+ * shifts the whole stack up: the placed clip becomes the new track 0 — the
+ * spine transplants to it. */
+function openInsertSlot(clips: VideoClip[], level: number): VideoClip[] {
+ return clips.map((c) => (c.track >= level ? { ...c, track: c.track + 1 } : c));
}
const shiftTracksUp = (clips: VideoClip[], place: VideoTrackPlacement): VideoClip[] =>
place.kind === "insert" ? openInsertSlot(clips, place.level) : clips;
@@ -210,19 +208,18 @@ const sole = (sel: NonNullable<Selection>) => ({ selection: sel, multiSelection:
* the landing start, and the ripple shifts it pushes onto that row. An
* existing track has residents — insert at the pointer and ripple that
* track's later clips right. An inserted track is brand-new, so the start
- * holds as-is. `exclude` is the clip being moved (left out of the ripple). */
+ * holds as-is. */
function landOnPlacement(
clips: VideoClip[],
place: VideoTrackPlacement,
start: number,
- len: number,
- exclude?: string
+ len: number
): { track: number; start: number; shifts: { id: string; start: number }[] } {
const track = place.kind === "insert" ? place.level : place.track;
const landing =
place.kind === "track"
? rippleInsert(
- clips.filter((c) => c.track === track && c.id !== exclude),
+ clips.filter((c) => c.track === track),
Math.max(0, start),
len
)
@@ -687,10 +684,6 @@ export interface EditorState {
/** Add a video asset to the timeline at a placement: an existing track or a
* freshly inserted one. Used by media / library drops. */
addVideoFromAsset: (assetId: string, place: VideoTrackPlacement, start: number) => void;
- /** Move an existing clip to a placement, preserving its trim/region/speed.
- * Inserting a track renumbers the ones above it; dropping onto track 0 lands
- * free-positioned at the drop time. Owns its own history. */
- dropVideoClip: (id: string, place: VideoTrackPlacement, start: number) => void;
/** "Detach Audio": lift the selected clip's sound onto the
* soundtrack track (and mute the clip) so it can be cut independently. */
detachAudio: () => void;
@@ -3527,52 +3520,6 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
);
},
- dropVideoClip: (id, place, start) => {
- const src = get().clips.find((c) => c.id === id);
- if (!src) return;
- // No checkpoint here: the lane coordinator's drag gesture already pushed
- // one at pointer-down, so the whole move is a single undo step.
- if (place.kind === "track" && place.track === src.track) {
- return; // a same-track move commits through the lane coordinator
- }
-
- // The clip leaves its track, so the hole it leaves closes behind it:
- // the source row's later clips slide left by its length. Matching by id
- // keeps the closure correct through an insert's track renumbering.
- const srcLen = clipLen(src);
- const closing: [string, number][] = get()
- .clips.filter(
- (c) => c.track === src.track && c.id !== id && c.start > src.start + 1e-9
- )
- .map((c) => [c.id, Math.max(0, c.start - srcLen)]);
-
- const { track, start: at, shifts } = landOnPlacement(
- get().clips,
- place,
- start,
- srcLen,
- id
- );
- const move = new Map([...shifts.map((sh) => [sh.id, sh.start] as const), ...closing]);
- set((st) => {
- // Inserting a new track opens the slot by renumbering the others; the
- // moved clip itself is excluded from the shift, then placed at `track`.
- const shifted =
- place.kind === "insert" ? openInsertSlot(st.clips, place.level, id) : st.clips;
- return placedState(
- st,
- shifted.map((c) =>
- c.id === id
- ? { ...c, track, start: at }
- : move.has(c.id)
- ? { ...c, start: move.get(c.id)! }
- : c
- ),
- id
- );
- });
- },
-
detachAudio: () => {
const { clips, assets, selection } = get();
if (selection?.kind !== "clip") return;