Skip to content

Write HTML. Render video. Built for agents.

fix(studio): a clip dropped on a row stays on that row at the nearest free time (#4663)

Miguel Ángel65d66cb2c349
diff --git a/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx b/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx
index d2b7508d58..d67028a873 100644
--- a/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx
+++ b/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx
@@ -6,6 +6,7 @@ import { useTimelineAssetDropOps } from "./useTimelineAssetDropOps";
import { mountReactHarness } from "./domSelectionTestHarness";
import { usePlayerStore } from "../player/store/playerStore";
import type { TimelineElement } from "../player";
+import type { TimelineDropPlacement } from "../player/components/timelineCallbacks";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -140,6 +141,143 @@ describe("useTimelineAssetDropOps handleTimelineAssetDrop", () => {
expect(written).toMatch(/<video id="clip"[^>]*data-track-index="1"/);
});
+ // A clip shown on timeline row `row` and written on file track `track`.
+ const rowClip = (
+ id: string,
+ start: number,
+ duration: number,
+ shown: { tag?: string; row?: number; track?: number } = {},
+ ): TimelineElement => ({
+ id,
+ key: id,
+ tag: shown.tag ?? "div",
+ start,
+ duration,
+ track: shown.row ?? 0,
+ authoredTrack: shown.track ?? shown.row ?? 0,
+ hfId: `hf-${id}`,
+ domId: id,
+ });
+ const rowSource = (clips: TimelineElement[]) =>
+ [
+ '<main data-composition-id="scene" data-duration="10" data-width="1920" data-height="1080">',
+ ...clips.map(
+ (c) =>
+ `<${c.tag} data-hf-id="hf-${c.id}" id="${c.id}" data-start="${c.start}" data-duration="${c.duration}" data-track-index="${c.authoredTrack}"></${c.tag}>`,
+ ),
+ "</main>",
+ ].join("\n");
+ const writtenClip = (written: string, tag: string) =>
+ written.match(new RegExp(`<${tag} id="[^"]*"[^>]*>`))?.[0] ?? "";
+
+ it("lands an asset dropped on an occupied row at that row's nearest free time", async () => {
+ const subtitle = rowClip("subtitle", 0, 6);
+ const writeProjectFile = vi.fn().mockResolvedValue(undefined);
+ const getDrop = renderDropHook(rowSource([subtitle]), writeProjectFile, [subtitle]);
+
+ await act(async () => {
+ await getDrop()("clip.mp4", { start: 2, track: 0 }, 5);
+ });
+
+ const [, written] = writeProjectFile.mock.calls[0] as [string, string];
+ const clip = writtenClip(written, "video");
+ expect(clip).toContain('data-start="6"');
+ expect(clip).toContain('data-track-index="0"');
+ expect(written).toContain(
+ 'id="subtitle" data-start="0" data-duration="6" data-track-index="0"',
+ );
+ });
+
+ // Drops two files (3 s images by default) onto `clips`; returns each written clip's start and track.
+ async function twoFileDrop(
+ clips: TimelineElement[],
+ placement: TimelineDropPlacement,
+ [names, tag] = [["one.png", "two.png"], "img"] as [string[], string],
+ ) {
+ const writeProjectFile = vi.fn().mockResolvedValue(undefined);
+ const uploadProjectFiles = vi.fn().mockResolvedValue(names);
+ const getDrop = renderDropHook(
+ rowSource(clips),
+ writeProjectFile,
+ clips,
+ undefined,
+ uploadProjectFiles,
+ );
+ const files = names.map((name) => new File([name], name));
+ await act(async () => {
+ await getDrop.file()(files, placement);
+ });
+ return writeProjectFile.mock.calls.map(([, written]) => {
+ const img = writtenClip(written as string, tag);
+ return [img.match(/data-start="([^"]*)"/)?.[1], img.match(/data-track-index="([^"]*)"/)?.[1]];
+ });
+ }
+
+ it("keeps a multi-file drop's clips off each other and off the row's clips", async () => {
+ const landed = await twoFileDrop([rowClip("a", 0, 4), rowClip("b", 8, 2)], {
+ start: 1,
+ track: 0,
+ });
+ // The first moves past a [0,4); the second is too long for [7,8) and goes after b.
+ expect(landed).toEqual([
+ ["4", "0"],
+ ["10", "0"],
+ ]);
+ });
+
+ it("puts a multi-file drop that opens a track back to back on that new track", async () => {
+ const landed = await twoFileDrop([rowClip("a", 0, 10)], {
+ start: 2,
+ track: 0,
+ insertRow: 0,
+ trackOrder: [0],
+ });
+ // Clip a moved down a row, so it no longer blocks the second file.
+ expect(landed).toEqual([
+ ["2", "0"],
+ ["5", "0"],
+ ]);
+ });
+
+ it("keeps a multi-file drop on the file track of the row it was dropped on", async () => {
+ const clips = [
+ rowClip("title", 0, 10, { track: 2 }),
+ rowClip("mid", 0, 1, { row: 1, track: 3 }),
+ rowClip("other", 0, 1, { row: 2, track: 5 }),
+ ];
+ // Row 0 is file track 2; the second file must not read that 2 back as row 2 (track 5).
+ expect(await twoFileDrop(clips, { start: 3, track: 0 })).toEqual([
+ ["10", "2"],
+ ["13", "2"],
+ ]);
+ });
+
+ it("reads a row's file track from every clip of the file, whether or not it names the file", async () => {
+ const unnamed = rowClip("unnamed", 0, 1, { row: 2, track: 0 });
+ const title = { ...rowClip("title", 0, 10), sourceFile: "index.html" };
+ const writeProjectFile = vi.fn().mockResolvedValue(undefined);
+ const getDrop = renderDropHook(rowSource([unnamed, title]), writeProjectFile, [unnamed, title]);
+ await act(async () => {
+ await getDrop()("pic.png", { start: 2, track: 0 }, 3);
+ });
+ const img = writtenClip(writeProjectFile.mock.calls[0][1] as string, "img");
+ expect(img).toContain('data-track-index="0"');
+ expect(img).toContain('data-start="10"');
+ });
+
+ it("keeps two audio files dropped on a visual row together, as a single one would go", async () => {
+ const clips = [
+ rowClip("title", 0, 10, { track: 1 }),
+ rowClip("music", 2, 3, { tag: "audio", row: 1, track: 0 }),
+ ];
+ const landed = await twoFileDrop(clips, { start: 12, track: 0 }, [["a.mp3", "b.mp3"], "audio"]);
+ // Audio length probing times out in this harness, so each file gets the 5 s default.
+ expect(landed).toEqual([
+ ["12", "0"],
+ ["17", "0"],
+ ]);
+ }, 30_000);
+
it("refuses an asset drop before reading or writing when editing is blocked", async () => {
const writeProjectFile = vi.fn().mockResolvedValue(undefined);
const checkEditable = vi.fn(() => false);
diff --git a/packages/studio/src/hooks/useTimelineAssetDropOps.ts b/packages/studio/src/hooks/useTimelineAssetDropOps.ts
index 47e1397284..5974a21b78 100644
--- a/packages/studio/src/hooks/useTimelineAssetDropOps.ts
+++ b/packages/studio/src/hooks/useTimelineAssetDropOps.ts
@@ -30,14 +30,20 @@ import { extendRootDurationInSource } from "../utils/rootDuration";
import { deriveTimelineStoreKeyForDomId } from "../player/lib/timelineElementHelpers";
import { selectAndRevealTimelineElement } from "../player/components/timelineDropReveal";
-/** The first uploaded file opens the new track (if asked); the rest land on the lane it landed on. */
+/** The first uploaded file opens the new track (if asked); each next one aims right after the previous. */
function fileDropPlacement(
index: number,
next: { start: number; track: number },
dropped: TimelineDropPlacement | undefined,
- landedTrack: number | undefined,
+ previous: TimelineElement | undefined,
): TimelineDropPlacement {
- return index === 0 ? { ...dropped, ...next } : { ...next, track: landedTrack ?? next.track };
+ if (index === 0) return { ...dropped, ...next };
+ return previous ? { start: previous.start + previous.duration, track: previous.track } : next;
+}
+
+interface DropGesture {
+ placed: TimelineElement[];
+ onNewTrack: boolean;
}
function timelineDropTarget(
@@ -90,7 +96,8 @@ export function useTimelineAssetDropOps({
assetPath: string,
placement: TimelineDropPlacement,
durationOverride?: number,
- ): Promise<number | undefined> => {
+ gesture: DropGesture = { placed: [], onNewTrack: false },
+ ): Promise<TimelineElement | undefined> => {
if (isRecordingRef?.current) {
showToast("Cannot edit timeline while recording", "error");
return undefined;
@@ -121,28 +128,32 @@ export function useTimelineAssetDropOps({
const resolvedAssetSrc = resolveTimelineAssetSrc(targetPath, assetPath);
const resolvedTargetPath = targetPath || "index.html";
- const relevantElements = timelineElements.filter(
- (te) => (te.sourceFile || activeCompPath || "index.html") === resolvedTargetPath,
- );
- const newElementZIndex = Math.max(1, relevantElements.length + 1);
+ const fileElements = timelineElements
+ .filter((te) => (te.sourceFile || activeCompPath || "index.html") === resolvedTargetPath)
+ .map((te) => ({ ...te, sourceFile: resolvedTargetPath }));
+ const newElementZIndex = Math.max(1, fileElements.length + gesture.placed.length + 1);
+ const tag = kind === "image" ? "img" : kind;
let newId = "";
let track = 0;
+ let start = normalizedStart;
const insertAsset = (originalContent: string) => {
newId = buildTimelineAssetId(assetPath, collectHtmlIds(originalContent));
const resolved = resolveDropTrack({
source: originalContent,
- // insertRow counts the rows the timeline shows, so plan against those.
- elements: relevantElements,
+ // Rows and insertRow count the rows the timeline shows; a track this drop opened has no others.
+ elements: gesture.onNewTrack ? [] : fileElements,
+ placed: gesture.placed,
placement,
dropped: {
id: newId,
- tag: kind === "image" ? "img" : kind,
+ tag,
start: normalizedStart,
duration: normalizedDuration,
},
});
track = resolved.track;
+ start = resolved.start;
return extendRootDurationInSource(
insertTimelineAssetIntoSource(
resolved.source,
@@ -151,7 +162,7 @@ export function useTimelineAssetDropOps({
hfId: `hf-${generateId()}`,
assetPath: resolvedAssetSrc,
kind,
- start: normalizedStart,
+ start,
duration: normalizedDuration,
track,
zIndex: newElementZIndex,
@@ -162,7 +173,7 @@ export function useTimelineAssetDropOps({
),
}),
),
- normalizedStart + normalizedDuration,
+ start + normalizedDuration,
);
};
@@ -178,7 +189,15 @@ export function useTimelineAssetDropOps({
selectAndRevealTimelineElement(deriveTimelineStoreKeyForDomId(newId, targetPath));
forceReloadSdkSession?.();
reloadPreview();
- return track;
+ const lane = placement.insertRow == null ? placement.track : track;
+ return {
+ id: newId,
+ tag,
+ start,
+ duration: normalizedDuration,
+ track: lane,
+ authoredTrack: track,
+ };
} catch (error) {
const message =
error instanceof Error ? error.message : "Failed to drop asset onto timeline";
@@ -234,15 +253,18 @@ export function useTimelineAssetDropOps({
placement ?? { start: 0, track: 0 },
durations,
);
- let landedTrack: number | undefined;
+ const gesture: DropGesture = { placed: [], onNewTrack: false };
for (const [index, assetPath] of uploaded.entries()) {
const next = placements[index] ?? placements[0];
- const track = await dropAssetAt(
+ const clip = await dropAssetAt(
assetPath,
- fileDropPlacement(index, next, placement, landedTrack),
+ fileDropPlacement(index, next, placement, gesture.placed.at(-1)),
durations[index],
+ gesture,
);
- if (index === 0) landedTrack = track;
+ if (!clip) continue;
+ gesture.placed.push(clip);
+ if (index === 0 && placement?.insertRow != null) gesture.onNewTrack = true;
}
},
[
diff --git a/packages/studio/src/player/components/timelineClipDragCommit.test.ts b/packages/studio/src/player/components/timelineClipDragCommit.test.ts
index 80cbea0524..f025796b65 100644
--- a/packages/studio/src/player/components/timelineClipDragCommit.test.ts
+++ b/packages/studio/src/player/components/timelineClipDragCommit.test.ts
@@ -1187,73 +1187,26 @@ describe("commitDraggedClipMove", () => {
});
});
- describe("magnetic main track on a track-insert", () => {
- it("a top-gutter insert that renumbers to literal track 0 snaps its start to 0", () => {
- // Sole visual clip sits on track 1 — the real main track (0) is genuinely
- // empty. Dragging it into the top insert-gutter creates a new lane that
- // normalizeToZones renumbers to literal 0, so the main-track rule must apply
- // even though the preview never saw a literal-0 landing track.
+ describe("a clip landing on an empty main track keeps its released start", () => {
+ it("a top-gutter insert that renumbers to literal track 0 commits at the released start", () => {
const elements = [el("v1", 1, 0, 5)];
const { onMoveElements } = runClipMove(
drag(elements[0], { previewStart: 8, previewTrack: 1, insertRow: 0 }),
{ elements, trackOrder: [1] },
);
- const map = editMap(onMoveElements.mock.calls[0][0]);
- expect(map.v1).toEqual({ start: 0, track: 0 });
- });
-
- it("the z-sync candidate reflects the snapped start, not the raw previewStart", async () => {
- // v1 snaps from previewStart 8 to 0 (see the test above). A foreign-file
- // sibling at [2, 5) only overlaps the SNAPPED window [0, 5), never the
- // raw [8, 13) — so a z-sync firing at all proves the candidate the
- // stacking check reads from carries the snapped start.
- const v1 = el("v1", 2, 0, 5);
- const sibling = el("s", 1, 2, 3); // [2, 5) — same source file, same paint scope
- const elements = [v1, sibling];
- const onStackingPatches = vi.fn();
- // v1 lands on lane 0, which paints above lane 1 (lower track paints higher),
- // yet carries the lower z: a violation only while the two overlap in time.
- commitDraggedClipMove(drag(v1, { previewStart: 8, previewTrack: 2, insertRow: 0 }), {
- elements,
- trackOrder: [1, 2],
- updateElement: vi.fn(),
- onMoveElement: vi.fn(),
- onMoveElements: vi.fn(),
- readZIndex: (element) => (element.key === "v1" ? 1 : 10),
- onStackingPatches,
- });
- await flushMicrotasks();
- expect(onStackingPatches).toHaveBeenCalledTimes(1);
+ expect(editMap(onMoveElements.mock.calls[0][0]).v1).toEqual({ start: 8, track: 0 });
});
- it("a plain lane change onto the empty main track snaps its committed start to 0", () => {
+ it("a plain lane change onto the empty main track commits at the released start", () => {
const elements = [el("v1", 1, 0, 5)];
const spies = runClipMove(drag(elements[0], { previewStart: 8, previewTrack: 0 }), {
elements,
trackOrder: [0, 1],
});
- expect(expectAtomicMoveMap(spies).v1).toEqual({ start: 0, track: 0 });
+ expect(expectAtomicMoveMap(spies).v1).toEqual({ start: 8, track: 0 });
});
- it("the z-sync candidate of a plain lane change carries the snapped start", async () => {
- // The sibling [2, 5) overlaps v1 only at the snapped [0, 5), never at the raw [8, 13).
- const v1 = el("v1", 2, 0, 5);
- const sibling = el("s", 1, 2, 3);
- const onStackingPatches = vi.fn();
- commitDraggedClipMove(drag(v1, { previewStart: 8, previewTrack: 0 }), {
- elements: [v1, sibling],
- trackOrder: [0, 1, 2],
- updateElement: vi.fn(),
- onMoveElement: vi.fn(),
- onMoveElements: vi.fn(),
- readZIndex: (element) => (element.key === "v1" ? 1 : 10),
- onStackingPatches,
- });
- await flushMicrotasks();
- expect(onStackingPatches).toHaveBeenCalledTimes(1);
- });
-
- it("a top-gutter insert that pushes the old track-0 clip down snaps to the new track 0", () => {
+ it("a top-gutter insert that pushes the old track-0 clip down keeps the released start", () => {
const oldMain = el("old", 0, 0, 3);
const dragged = el("v1", 2, 0, 5);
const { onMoveElements } = runClipMove(
@@ -1262,10 +1215,10 @@ describe("commitDraggedClipMove", () => {
);
const map = editMap(onMoveElements.mock.calls[0][0]);
expect(map.old.track).toBe(1);
- expect(map.v1).toEqual({ start: 0, track: 0 });
+ expect(map.v1).toEqual({ start: 8, track: 0 });
});
- it("an expanded child dragged with its host commits the HOST at 0", () => {
+ it("an expanded child dragged with its host onto the main track keeps the host's start", () => {
for (const [hostStart, childStart] of [
[30, 32],
[20, 22],
@@ -1283,11 +1236,14 @@ describe("commitDraggedClipMove", () => {
selectedKeys: new Set(["host", "child"]),
},
);
- expect(editMap(onMoveElements.mock.calls[0][0]).host).toEqual({ start: 0, track: 0 });
+ expect(editMap(onMoveElements.mock.calls[0][0]).host).toEqual({
+ start: hostStart,
+ track: 0,
+ });
}
});
- it("a multi-selection top-gutter insert does NOT snap (siblings key off the unsnapped start)", () => {
+ it("a multi-selection top-gutter insert keeps the grabbed clip's start", () => {
const dragged = el("v1", 1, 0, 5);
const sibling = el("v2", 1, 10, 5);
const elements = [dragged, sibling];
@@ -1296,7 +1252,7 @@ describe("commitDraggedClipMove", () => {
{ elements, trackOrder: [1], selectedKeys: new Set(["v1", "v2"]) },
);
const map = editMap(onMoveElements.mock.calls[0][0]);
- expect(map.v1.start).toBe(8); // unsnapped — multi-selection guard
+ expect(map.v1.start).toBe(8);
});
});
});
diff --git a/packages/studio/src/player/components/timelineClipDragCommit.ts b/packages/studio/src/player/components/timelineClipDragCommit.ts
index 385834891b..e0d6325ad1 100644
--- a/packages/studio/src/player/components/timelineClipDragCommit.ts
+++ b/packages/studio/src/player/components/timelineClipDragCommit.ts
@@ -5,7 +5,7 @@ import type { DraggedClipState } from "./useTimelineClipDrag";
// value-import edge stays acyclic.
import type { ZMirrorLaneMove } from "./timelineZMirror";
import { classifyZone } from "./timelineZones";
-import { layoutAfterTrackInsert, resolveDragLandingStart } from "./timelineDragLanding";
+import { layoutAfterTrackInsert } from "./timelineDragLanding";
import { computeStackingPatches, type StackingPatch } from "./timelineStackingSync";
import {
canMoveTimelineElement as canMoveElement,
@@ -19,6 +19,7 @@ import {
import { runLaneZGesture } from "../../components/nle/zLaneGesture";
import { refreshAfterDurableLaneMove } from "./timelineLaneMoveRefresh";
import { authoredTrackForLane } from "./timelineAuthoredTrack";
+import { resolveGroupMovers } from "./timelineMultiDragPreview";
type StartTrack = Pick<TimelineElement, "start" | "track">;
export interface TimelineMoveEdit {
@@ -63,9 +64,9 @@ export interface DragCommitDeps {
* the edited clip(s) get z-index patches so their canvas stacking matches lane
* order (higher lane = on top) relative to time-overlapping clips — see
* timelineStackingSync. Both deps must be supplied to engage; if either is
- * absent the z-sync is skipped (pure time-moves and horizontal collision bumps
- * never restack). `readZIndex` returns the clip's current z-index (from the
- * live DOM inline style / computed; "auto" ⇒ 0).
+ * absent the z-sync is skipped (pure time-moves never restack). `readZIndex`
+ * returns the clip's current z-index (from the live DOM inline style / computed;
+ * "auto" ⇒ 0).
*/
readZIndex?: (element: TimelineElement) => number;
/**
@@ -191,41 +192,20 @@ function resolveMultiSelection(
keys: ReadonlySet<string>;
movedStart: (e: TimelineElement) => number;
} | null {
- const { elements, selectedKeys } = deps;
const dragKey = keyOf(drag.element);
- if (!selectedKeys || selectedKeys.size <= 1 || !selectedKeys.has(dragKey)) return null;
- const keys = new Set(
- [...selectedKeys].filter((k) => {
- const el = elements.find((e) => keyOf(e) === k);
- return el ? canMoveElement(el) : false;
- }),
- );
+ const movers = resolveGroupMovers(deps.elements, deps.selectedKeys, dragKey);
+ if (!movers) return null;
+ const keys = new Set(movers.map(keyOf));
const delta = drag.previewStart - drag.element.start;
const movedStart = (e: TimelineElement): number =>
keyOf(e) === dragKey ? drag.previewStart : Math.max(0, round3(e.start + delta));
return { keys, movedStart };
}
-/**
- * Commit a finished clip drag.
- *
- * The lane model is CapCut-stable: a clip's display lane is its track, and editing
- * ONE clip must never re-lane or rewrite OTHER clips. Three outcomes:
- *
- * - **Pure time-move** (dragged clip keeps its lane, no insert): persist just the
- * dragged clip's start (multi-selection shifts every selected clip in time).
- * - **Lane change / collision relocation** (the dragged clip's OWN lane changes,
- * no new track): persist ONLY the dragged clip's start + lane. No other clip is
- * touched. z is synced only when the gesture is a DELIBERATE vertical move
- * (the pointer aimed at another lane) — a horizontal drag merely bumped to a
- * free lane never restacks.
- * - **Track insert** (a new lane at a gap boundary): the dragged clip lands on
- * the new lane and the clips at/below the insert are renumbered by +1 (the ONLY
- * permitted multi-clip write) via a whole-set re-normalize; persisted atomically.
- */
+// A move writes the dragged clip's start (each moving clip's, in a group); a lane change also writes its lane and
+// re-lanes no other clip; only a new track renumbers the rows below it.
// fallow-ignore-next-line complexity
-export function commitDraggedClipMove(rawDrag: DraggedClipState, deps: DragCommitDeps): void {
- const drag = { ...rawDrag, previewStart: resolveDragLandingStart(rawDrag, deps) };
+export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDeps): void {
const hostAlias = resolveExpandedHostAlias(drag, deps);
if (hostAlias) {
commitDraggedClipMove(hostAlias.drag, { ...deps, selectedKeys: hostAlias.selectedKeys });
@@ -236,11 +216,8 @@ export function commitDraggedClipMove(rawDrag: DraggedClipState, deps: DragCommi
const dragKey = keyOf(drag.element);
const isInsert = drag.insertRow != null;
const laneChanged = drag.previewTrack !== drag.element.track;
- // Deliberate VERTICAL gesture: the pointer aimed at a different lane, or at a
- // gap boundary (insert). A plain HORIZONTAL drag whose target span is occupied
- // gets the DRAGGED clip bumped to a free lane (previewTrack differs) while the
- // pointer never left its lane (desiredTrack === element.track) — that is NOT a
- // vertical move: it must neither rewrite other clips nor touch z.
+ // Deliberate VERTICAL gesture: the pointer aimed at a different lane, or at the
+ // empty space outside the rows (insert). Anything else never touches z.
const aimTrack = drag.desiredTrack ?? drag.previewTrack;
const isVertical = isInsert || aimTrack !== drag.element.track;
const multi = resolveMultiSelection(drag, deps);
@@ -279,7 +256,7 @@ export function commitDraggedClipMove(rawDrag: DraggedClipState, deps: DragCommi
return;
}
- // ── Lane change / collision relocation: persist ONLY the dragged clip ────────
+ // ── Lane change: persist ONLY the dragged clip ──────────────────────────────
// CapCut invariant — one edit never re-lanes another clip. The dragged clip
// takes its new lane (previewTrack); the rest of any selection shifts in time
// only. Nothing else is written.
diff --git a/packages/studio/src/player/components/timelineClipDragPreview.test.ts b/packages/studio/src/player/components/timelineClipDragPreview.test.ts
index 676add9245..f1be7cbb43 100644
--- a/packages/studio/src/player/components/timelineClipDragPreview.test.ts
+++ b/packages/studio/src/player/components/timelineClipDragPreview.test.ts
@@ -9,6 +9,8 @@ import {
import type { DraggedClipState } from "./timelineClipDragTypes";
import { commitDraggedClipMove, persistMoveEdits } from "./timelineClipDragCommit";
import { LANE_H, RULER_H, TRACKS_TOP_PAD, TRACK_H } from "./timelineLayout";
+import { isMultiDragPassenger } from "./timelineMultiDragPreview";
+import { resolveMultiDragPreview } from "./timelineProviderStateBuilders";
// ─────────────────────────────────────────────────────────────────────────────
// Regression bed for the live-reproduced BUG 1: a PLAIN HORIZONTAL drag of a clip
@@ -168,7 +170,7 @@ describe("computeDragPreview — plain horizontal drag never arms a phantom inse
expect(next.previewTrack).toBe(0);
});
- it("uses the expanded row midpoint when choosing the side for an automatic insert", () => {
+ it("an occupied aim in an expanded row stays on that row at the nearest free time", () => {
const rowHeights = [TRACK_H + 2 * LANE_H, TRACK_H];
const dragged = clip("dragged", 0, 0, 1, 3);
const occupied = [dragged, clip("block-0", 0, 0, 1, 2), clip("block-1", 1, 0, 1, 1)];
@@ -195,11 +197,13 @@ describe("computeDragPreview — plain horizontal drag never arms a phantom inse
...ctx(rowHeights, occupied),
trackOrder: [0, 1],
});
- expect(next.insertRow).toBe(0);
+ expect(next.insertRow).toBeNull();
+ expect(next.previewTrack).toBe(0);
+ expect(next.previewStart).toBe(1);
});
});
-describe("computeDragPreview — magnetic first clip on an empty main track", () => {
+describe("computeDragPreview — a clip landing on an empty main track keeps its released start", () => {
// v-lower sits alone on lane 1; lane 0 (the main track) is empty.
const vLower = clip("v-lower", 1, 10, 4, 5);
@@ -236,11 +240,11 @@ describe("computeDragPreview — magnetic first clip on an empty main track", ()
});
}
- it("dragging straight up onto the empty main track snaps the preview start to 0", () => {
+ it("dragging straight up onto the empty main track keeps the start", () => {
const next = dragUpToMainTrack([vLower]);
expect(next.previewTrack).toBe(0);
expect(next.insertRow).toBeNull();
- expect(next.previewStart).toBe(0);
+ expect(next.previewStart).toBe(10);
});
it("does not touch the start once the main track already holds a clip", () => {
@@ -249,13 +253,13 @@ describe("computeDragPreview — magnetic first clip on an empty main track", ()
expect(next.previewStart).toBe(10); // unchanged — main track wasn't empty
});
- it("aiming the top gutter over an empty main track snaps the ghost: the insert renumbers onto track 0", () => {
+ it("aiming the space above an empty main track opens a track there and keeps the start", () => {
const next = dragUpToMainTrack([vLower], -0.6);
expect(next.insertRow).toBe(0);
- expect(next.previewStart).toBe(0);
+ expect(next.previewStart).toBe(10);
});
- it("does not retime the rest of a multi-selection when the grabbed clip lands on the empty main track", () => {
+ it("does not retime a multi-selection whose grabbed clip lands on the empty main track", () => {
const vOther = clip("v-other", 1, 15, 3, 5);
const next = dragUpToMainTrack([vLower, vOther], 0.5, new Set(["v-lower", "v-other"]));
expect(next.previewTrack).toBe(0);
@@ -425,29 +429,107 @@ describe("computeDragPreview — the ghost start is the committed start", () =>
it("plain move onto the empty main track", () => {
const ghost = preview(lower, [lower], 1, 0.5);
- expect(ghost.previewStart).toBe(0);
+ expect(ghost.previewStart).toBe(10);
expect(committedStart(ghost, lower, [lower])).toBe(ghost.previewStart);
});
- it("top-gutter insert that pushes the old track-0 clip down lands on track 0 at 0", () => {
+ it("top-gutter insert that pushes the old track-0 clip down keeps the pointer start", () => {
const oldMain = clip("old-main", 0, 0, 3, 5);
const elements = [oldMain, lower];
const ghost = preview(lower, elements, 1, -0.6);
expect(ghost.insertRow).toBe(0);
- expect(ghost.previewStart).toBe(0);
- expect(committedStart(ghost, lower, elements)).toBe(0);
- });
-
- it("top-gutter insert with a clip staying on track 0 keeps the pointer start", () => {
- const stays = clip("stays", 0, 0, 3, 5);
- const elements = [stays, lower];
- // Insert between lane 0 and 1: the resident track-0 clip does not move.
- const ghost = preview(lower, elements, 1, 1.0);
expect(ghost.previewStart).toBe(10);
expect(committedStart(ghost, lower, elements)).toBe(10);
});
- it("expanded child dragged with its host: the host commits at 0 and the ghost matches", () => {
+ it("a move onto an occupied row lands at its nearest free time, ghost and commit alike", () => {
+ const blocker = clip("blocker", 0, 8, 4, 5);
+ const elements = [blocker, lower];
+ const ghost = preview(lower, elements, 1, 0.5);
+ expect(ghost.insertRow).toBeNull();
+ expect(ghost.previewTrack).toBe(0);
+ expect(ghost.previewStart).toBe(12);
+ expect(committedStart(ghost, lower, elements)).toBe(12);
+ });
+
+ describe("a drop onto an occupied row stays on that row", () => {
+ const title = clip("title", 0, 0, 10, 3, "text");
+ const subtitle = clip("subtitle", 1, 0, 6, 2, "text");
+ const tag = clip("tag", 2, 2, 5, 1, "text");
+ const rows = [title, subtitle, tag];
+
+ it("Tag dropped on the Subtitle row lands right after Subtitle, with no new track", () => {
+ const ghost = preview(tag, rows, 2, 1.5);
+ expect(ghost).toMatchObject({ insertRow: null, previewTrack: 1, previewStart: 6 });
+ expect(committedStart(ghost, tag, rows)).toBe(6);
+ });
+
+ it("Tag dropped on the top Title row stays on track 0 after Title, not snapped to 0", () => {
+ const ghost = preview(tag, rows, 2, 0.5);
+ expect(ghost).toMatchObject({ insertRow: null, previewTrack: 0, previewStart: 10 });
+ expect(committedStart(ghost, tag, rows)).toBe(10);
+ });
+
+ it("the edge of a row is still that row, not a new track", () => {
+ for (const edge of [0.02, 0.98, 1.02]) {
+ const ghost = preview(tag, rows, 2, edge);
+ expect(ghost.insertRow).toBeNull();
+ expect(ghost.previewTrack).toBe(Math.floor(edge));
+ }
+ });
+ });
+
+ describe("a clip released on or near its own spot stays there", () => {
+ // Frame-aligned edges with three decimals: no centisecond start fits m's own slot.
+ const a = clip("a", 0, 0, 3.333, 1);
+ const m = clip("m", 0, 3.333, 3.333, 1);
+ const b = clip("b", 0, 6.666, 4, 1);
+ const row = [a, m, b];
+
+ it("keeps its start and writes nothing when released where it started", () => {
+ const ghost = preview(m, row, 0, 0.5);
+ expect(ghost).toMatchObject({ previewTrack: 0, insertRow: null, previewStart: 3.333 });
+ expect(committedStart(ghost, m, row)).toBeUndefined();
+ });
+
+ it("goes back to its own spot from a small nudge, snapped or not", () => {
+ const snapped = [{ time: 3.333, type: "clip-edge" as const }];
+ for (const targets of [[], snapped]) {
+ const { drag, clientX, clientY } = horizontalDrag(m, 0.5, 0.1);
+ const ghost = computeDragPreview(drag, clientX, clientY, {
+ ...ctx(undefined, row),
+ buildSnapTargets: () => targets,
+ });
+ expect(ghost).toMatchObject({ previewTrack: 0, previewStart: 3.333 });
+ }
+ });
+
+ it("counts its own start only on its own row, where keeping it rewrites nothing", () => {
+ // Row 1 has the same off-grid slot, but a move there writes a rounded start that would overlap.
+ const c = clip("c", 1, 0, 3.333, 1);
+ const d = clip("d", 1, 6.666, 4, 1);
+ const ghost = preview(m, [...row, c, d], 0, 1.5);
+ expect(ghost).toMatchObject({ previewTrack: 1, insertRow: null, previewStart: 10.67 });
+ });
+ });
+
+ it("drops the snap guide when the row moves the clip off the snapped time", () => {
+ const a = clip("a", 0, 0, 6, 1);
+ const b = clip("b", 1, 3, 2, 1);
+ const { drag, clientX } = horizontalDrag(b, 1.5, 0);
+ const ghost = computeDragPreview(drag, clientX, yForRow(0.5), {
+ ...ctx(undefined, [a, b]),
+ buildSnapTargets: () => [{ time: 3, type: "beat" }],
+ });
+ expect(ghost).toMatchObject({
+ previewTrack: 0,
+ previewStart: 6,
+ snapTime: null,
+ snapType: null,
+ });
+ });
+
+ it("expanded child dragged with its host: the host keeps its start and the ghost matches", () => {
for (const [hostStart, childStart] of [
[30, 32],
[20, 22],
@@ -461,12 +543,121 @@ describe("computeDragPreview — the ghost start is the committed start", () =>
const keys = new Set(["host", "child"]);
const ghost = preview(child, elements, 2, 0.5, keys);
expect(ghost.previewTrack).toBe(0);
- expect(ghost.previewStart).toBe(childStart - hostStart);
- expect(committedStart(ghost, host, elements, keys)).toBe(0);
+ expect(ghost.previewStart).toBe(childStart);
+ expect(committedStart(ghost, host, elements, keys)).toBe(hostStart);
}
});
});
+describe("computeDragPreview — a group move keeps its shape", () => {
+ it("never bumps the grabbed clip further left than the group's 0 limit", () => {
+ const a = clip("a", 1, 0.5, 1, 1);
+ const b = clip("b", 2, 7, 2, 1);
+ const c = clip("c", 0, 6.4, 3.6, 1);
+ const elements = [c, a, b];
+ const selectedKeys = new Set(["a", "b"]);
+ const { drag } = horizontalDrag(b, 2.5, 0);
+ // Up two rows and 0.5 s left: the group limit allows 6.5 s, which overlaps c.
+ const ghost = computeDragPreview(drag, 800 - 0.5 * PPS, yForRow(0.5), {
+ ...ctx(undefined, elements),
+ selectedKeys,
+ });
+ expect(ghost).toMatchObject({ previewTrack: 0, insertRow: null, previewStart: 10 });
+ const onMoveElements = vi.fn();
+ commitDraggedClipMove(ghost, {
+ elements,
+ trackOrder: [0, 1, 2],
+ updateElement: vi.fn(),
+ onMoveElement: vi.fn(),
+ onMoveElements,
+ selectedKeys,
+ });
+ const edits = onMoveElements.mock.calls[0][0] as Array<{
+ element: TimelineElement;
+ updates: { start: number };
+ }>;
+ const moved = Object.fromEntries(
+ edits.map((e) => [e.element.id, e.updates.start - e.element.start]),
+ );
+ expect(moved).toEqual({ a: 3, b: 3 });
+ });
+
+ // Drags `grabbed` by `seconds` onto `row` and commits; returns each written clip's start.
+ function groupMove(
+ grabbed: TimelineElement,
+ elements: TimelineElement[],
+ selectedKeys: ReadonlySet<string>,
+ row: number,
+ seconds: number,
+ ) {
+ const { drag } = horizontalDrag(grabbed, grabbed.track + 0.5, 0);
+ const ghost = computeDragPreview(drag, 800 + seconds * PPS, yForRow(row + 0.5), {
+ ...ctx(undefined, elements),
+ selectedKeys,
+ });
+ const onMoveElements = vi.fn();
+ commitDraggedClipMove(ghost, {
+ elements,
+ trackOrder: [0, 1, 2],
+ updateElement: vi.fn(),
+ onMoveElement: vi.fn(),
+ onMoveElements,
+ selectedKeys,
+ });
+ const edits = onMoveElements.mock.calls[0][0] as Array<{
+ element: TimelineElement;
+ updates: { start: number; track: number };
+ }>;
+ return Object.fromEntries(edits.map((e) => [e.element.id, e.updates]));
+ }
+
+ it("lets a group whose leftmost clip starts off the centisecond grid reach 0 exactly", () => {
+ const a = clip("a", 1, 0.333, 1, 1);
+ const b = clip("b", 0, 7, 2, 1);
+ const written = groupMove(b, [a, b], new Set(["a", "b"]), 0, -20);
+ expect(written.a.start).toBe(0);
+ expect(written.b.start).toBeCloseTo(6.667, 6);
+ });
+
+ it("does not treat the clips moving with it as obstacles", () => {
+ const a = clip("a", 0, 0, 2, 1);
+ const b = clip("b", 0, 3, 2, 1);
+ const { drag, clientX, clientY } = horizontalDrag(a, 0.5, 2);
+ const ghost = computeDragPreview(drag, clientX, clientY, {
+ ...ctx(undefined, [a, b]),
+ selectedKeys: new Set(["a", "b"]),
+ });
+ // b moves 2 s too, so a may take 2 to 4 s; were b an obstacle, a would stop at 1 s.
+ expect(ghost).toMatchObject({ previewTrack: 0, previewStart: 2 });
+ });
+
+ it("treats a locked clip swept into the selection as an obstacle, since it does not move", () => {
+ const locked: TimelineElement = { ...clip("locked", 0, 4, 2, 1), timelineLocked: true };
+ const b = clip("b", 1, 0, 1, 1);
+ const written = groupMove(b, [locked, b], new Set(["locked", "b"]), 0, 4.5);
+ // 4.5 s overlaps the locked 4-6 s clip; 3 s and 6 s are equally near, and a tie goes later.
+ expect(written).toEqual({ b: { start: 6, track: 0 } });
+ });
+});
+
+describe("resolveMultiDragPreview — the live ghosts follow the clips that move", () => {
+ it("slides the movable selected clips but not a locked one swept into the selection", () => {
+ const locked: TimelineElement = { ...clip("locked", 0, 4, 2, 1), timelineLocked: true };
+ const b = clip("b", 1, 0, 1, 1);
+ const rider = clip("rider", 2, 8, 1, 1);
+ const elements = [locked, b, rider];
+ const selectedKeys = new Set(["locked", "b", "rider"]);
+ const { drag } = horizontalDrag(b, 1.5, 0);
+ const ghost = computeDragPreview(drag, 800 + 4.5 * PPS, yForRow(0.5), {
+ ...ctx(undefined, elements),
+ selectedKeys,
+ });
+ const preview = resolveMultiDragPreview(ghost, selectedKeys, elements);
+ expect(preview && isMultiDragPassenger("rider", preview)).toBe(true);
+ expect(preview && isMultiDragPassenger("locked", preview)).toBe(false);
+ });
+});
+
describe("a nested clip's drop stops at its host's start in the preview", () => {
// Host at 2 s: the clip may not start before 2 unless it was authored there.
const logo: TimelineElement = { ...clip("logo", 0, 5, 5, 0, "div"), parentCompositionStart: 2 };
diff --git a/packages/studio/src/player/components/timelineClipDragPreview.ts b/packages/studio/src/player/components/timelineClipDragPreview.ts
index c3a52999a0..52668e7af7 100644
--- a/packages/studio/src/player/components/timelineClipDragPreview.ts
+++ b/packages/studio/src/player/components/timelineClipDragPreview.ts
@@ -6,12 +6,7 @@ import {
} from "./timelineGroupEditing";
import type { TimelineElement } from "../store/playerStore";
import { clampToHostStart } from "../store/timelineElement";
-import {
- getTimelineInsertBoundaryBand,
- getTimelineRowFromY,
- getTimelineRowHeight,
- getTimelineRowPositionFromY,
-} from "./timelineLayout";
+import { getTimelineRowFromY } from "./timelineLayout";
import { isMusicTrack, isAudioTimelineElement } from "../../utils/timelineInspector";
import {
TIMELINE_SNAP_PX,
@@ -25,9 +20,8 @@ import {
applyTimelineGroupResizePreview,
type TimelineGroupResizeSession,
} from "./timelineGroupEditing";
-import { clampGroupMoveDelta } from "./timelineMultiDragPreview";
+import { groupMoveFloor, resolveGroupMovers } from "./timelineMultiDragPreview";
import type { DraggedClipState, ResizingClipState } from "./timelineClipDragTypes";
-import { resolveDragLandingStart } from "./timelineDragLanding";
import { STUDIO_PREVIEW_FPS } from "../lib/time";
/** Snap-target builder closure supplied by the hook (closes over refs + store). */
@@ -78,74 +72,61 @@ function resolveDragMaxStart(scroll: HTMLDivElement | null, pps: number, duratio
return Math.max(duration, scroll && pps > 0 ? scroll.scrollWidth / pps : duration);
}
-/**
- * Rigid group move: when the grabbed clip is part of a multi-selection, the
- * WHOLE formation shifts by its delta on commit (see timelineClipDragCommit).
- * Clamp that delta here, and a lone clip's as a group of one, so the grabbed
- * clip STOPS the instant any member would cross its floor (clampToHostStart),
- * exactly as it lands on commit. Lane changes still apply to the grabbed clip
- * only, so only the start (x) is constrained.
- */
-function resolveGroupClampedStart(
- snapStart: number,
- element: TimelineElement,
- dragKey: string,
- elements: TimelineElement[],
- selectedKeys: ReadonlySet<string>,
-): number {
- const inGroup = selectedKeys.size > 1 && selectedKeys.has(dragKey);
- const members = inGroup ? elements.filter((e) => selectedKeys.has(e.key ?? e.id)) : [element];
- const floors = members.map((e) => ({ start: e.start, minStart: clampToHostStart(e, 0) }));
- return element.start + clampGroupMoveDelta(snapStart - element.start, floors);
-}
-
-/**
- * The whole drop decision (no same-track overlap, zone-respecting, relocate or
- * create) — one tested pure function, so what runs here is what's verified.
- */
+/** The drop decision for the pointer's row (see resolveZoneDropPlacement). */
function resolveDropPlacement(
drag: DraggedClipState,
clientY: number,
previewStart: number,
desiredTrack: number,
ctx: DragPreviewContext,
-): { track: number; insertRow: number | null } {
+ group: GroupDrag,
+): { track: number; insertRow: number | null; start: number } {
const { scroll, trackOrder, rowHeights, elements } = ctx;
- // rowFloat = the pointer's position in track-heights from the top lane; a
- // near-boundary hover requests a deliberate new-track insert. Uses the
- // shared row→y inverse so the top breathing pad is subtracted consistently.
- const rowPosition = scroll
- ? getTimelineRowPositionFromY(
+ const rowFloat = scroll
+ ? getTimelineRowFromY(
clientY - scroll.getBoundingClientRect().top + scroll.scrollTop,
rowHeights,
)
- : { rowFloat: 0, row: 0, fraction: 0, rowHeight: getTimelineRowHeight(0, rowHeights) };
- // Geometry-exact band (the clip inset divided by this row's actual height) so
- // an insert only arms in the visible gutter between clip bodies.
- const rawInsertRow = resolveInsertRow(
- rowPosition.rowFloat,
- trackOrder.length,
- getTimelineInsertBoundaryBand(rowPosition.rowHeight),
- );
- // Pointer sub-row half: when a drop must auto-create a track (aimed span
- // occupied, no free lane), open it on the side the pointer is nearer.
- const preferInsertAbove = rowPosition.fraction < 0.5;
+ : 0;
+ const dragKey = drag.element.key ?? drag.element.id;
const audioTracks =
ctx.audioTracks ?? new Set(elements.filter(isAudioTimelineElement).map((e) => e.track));
return resolveZoneDropPlacement({
order: trackOrder,
audioTracks,
- elements,
+ elements: group.obstacles,
desiredTrack,
- deliberateInsertRow: rawInsertRow,
+ deliberateInsertRow: resolveInsertRow(rowFloat, trackOrder.length),
start: previewStart,
duration: drag.element.duration,
- dragKey: drag.element.key ?? drag.element.id,
+ dragKey,
isAudio: isAudioTimelineElement(drag.element),
- preferInsertAbove,
+ minStart: group.floor,
+ origin: { track: drag.element.track, start: drag.element.start },
});
}
+interface GroupDrag {
+ /** Clips the grabbed clip may not overlap: everything but the clips that move with it. */
+ obstacles: TimelineElement[];
+ /** Lowest start the grabbed clip may take (see groupMoveFloor). */
+ floor: number;
+}
+
+function resolveGroupDrag(drag: DraggedClipState, ctx: DragPreviewContext): GroupDrag {
+ const movers = resolveGroupMovers(
+ ctx.elements,
+ ctx.selectedKeys,
+ drag.element.key ?? drag.element.id,
+ );
+ if (!movers) return { obstacles: ctx.elements, floor: groupMoveFloor(drag.element, []) };
+ const moving = new Set(movers.map((e) => e.key ?? e.id));
+ return {
+ obstacles: ctx.elements.filter((e) => !moving.has(e.key ?? e.id)),
+ floor: groupMoveFloor(drag.element, movers),
+ };
+}
+
/** Recompute the dragged-clip preview (move + snap + group clamp + drop placement). */
export function computeDragPreview(
drag: DraggedClipState,
@@ -153,7 +134,7 @@ export function computeDragPreview(
clientY: number,
ctx: DragPreviewContext,
): DraggedClipState {
- const { scroll, pps, duration, trackOrder, elements, selectedKeys, buildSnapTargets } = ctx;
+ const { scroll, pps, duration, trackOrder, buildSnapTargets } = ctx;
const dragMaxStart = resolveDragMaxStart(scroll, pps, duration);
const scrollTop = scroll?.scrollTop ?? drag.originScrollTop;
const scrollRectTop = scroll?.getBoundingClientRect().top ?? 0;
@@ -196,40 +177,24 @@ export function computeDragPreview(
// rendered extent (see dragMaxStart) — the composition grows on commit.
dragMaxStart + drag.element.duration,
);
- const dragKey = drag.element.key ?? drag.element.id;
- const previewStart = resolveGroupClampedStart(
- snap.start,
- drag.element,
- dragKey,
- elements,
- selectedKeys,
- );
- const { track: previewTrack, insertRow } = resolveDropPlacement(
- drag,
- clientY,
- previewStart,
- nextMove.track,
- ctx,
- );
- const placed = { ...drag, previewStart, previewTrack, insertRow };
- const snappedStart = resolveDragLandingStart(placed, {
- elements,
- trackOrder,
- selectedKeys,
- });
+ // A group moves rigidly: the grabbed clip stops where any mover would cross its host's start.
+ const group = resolveGroupDrag(drag, ctx);
+ const previewStart = Math.max(snap.start, group.floor);
+ const placement = resolveDropPlacement(drag, clientY, previewStart, nextMove.track, ctx, group);
+ const { track: previewTrack, insertRow } = placement;
return {
...drag,
started: true,
pointerClientX: clientX,
pointerClientY: clientY,
- previewStart: snappedStart,
+ previewStart: placement.start,
previewTrack,
- // The lane the POINTER aims at (pre-collision): the commit reads it to tell a
- // deliberate vertical lane change from a horizontal drag merely bumped sideways.
+ // The lane the POINTER aims at (before the zone clamp): the commit reads it to
+ // tell a deliberate vertical lane change from a horizontal drag.
desiredTrack: nextMove.track,
insertRow,
- snapTime: previewStart === snap.start ? snap.snapTime : null,
- snapType: previewStart === snap.start ? snap.snapType : null,
+ snapTime: placement.start === snap.start ? snap.snapTime : null,
+ snapType: placement.start === snap.start ? snap.snapType : null,
};
}
diff --git a/packages/studio/src/player/components/timelineClipDragTypes.ts b/packages/studio/src/player/components/timelineClipDragTypes.ts
index 87bc4b1227..2f8ce3e6de 100644
--- a/packages/studio/src/player/components/timelineClipDragTypes.ts
+++ b/packages/studio/src/player/components/timelineClipDragTypes.ts
@@ -18,14 +18,9 @@ export interface DraggedClipState {
previewStart: number;
previewTrack: number;
/**
- * The lane the POINTER aims at (from the drag's vertical position), before
- * collision resolution. `previewTrack` is where the clip actually LANDS —
- * which may differ from `desiredTrack` when the aimed span is occupied and the
- * collision rules bump the dragged clip to a free lane. The commit reads this
- * to tell a deliberate VERTICAL lane change (pointer aimed at another lane →
- * stacking sync allowed) from a plain HORIZONTAL drag whose clip merely got
- * bumped sideways (never touches z). Optional: when absent the commit falls
- * back to `previewTrack` (pre-existing behaviour).
+ * The lane the POINTER aims at, before the kind-zone clamp picks `previewTrack`.
+ * The commit reads it to tell a deliberate vertical lane change (stacking sync
+ * allowed) from a horizontal drag. Absent: the commit falls back to `previewTrack`.
*/
desiredTrack?: number;
/**
diff --git a/packages/studio/src/player/components/timelineCollision.test.ts b/packages/studio/src/player/components/timelineCollision.test.ts
index 328c875708..22e6a16ff9 100644
--- a/packages/studio/src/player/components/timelineCollision.test.ts
+++ b/packages/studio/src/player/components/timelineCollision.test.ts
@@ -5,12 +5,10 @@ import {
isInsertAllowedForZone,
isLaneFree,
resolveInsertRow,
- resolveMainTrackDropStart,
- resolvePlacement,
+ resolveNearestFreeStart,
resolveZoneDropPlacement,
timeRangesOverlap,
} from "./timelineCollision";
-import { INSERT_BOUNDARY_BAND } from "./timelineLayout";
function el(id: string, track: number, start: number, duration: number): TimelineElement {
return { id, tag: "video", start, duration, track };
@@ -41,196 +39,84 @@ describe("isLaneFree", () => {
});
});
-describe("resolvePlacement", () => {
- const trackOrder = [0, 1, 2, 3];
+describe("resolveNearestFreeStart", () => {
+ const row = [el("a", 0, 2, 3), el("b", 0, 8, 2)]; // busy [2,5) and [8,10)
- it("keeps the desired lane when it is free", () => {
- const els = [el("a", 2, 0, 4)];
- expect(
- resolvePlacement({
- elements: els,
- desiredTrack: 1,
- start: 0,
- duration: 4,
- trackOrder,
- excludeKey: null,
- }),
- ).toEqual({
- track: 1,
- needsInsert: false,
- });
+ it("keeps a start whose span is already free", () => {
+ expect(resolveNearestFreeStart(row, 0, 5, 3, null)).toBe(5);
+ expect(resolveNearestFreeStart(row, 1, 3, 4, null)).toBe(3); // another row
});
- it("pushes up to the nearest free lane above when the target is occupied", () => {
- // desired = 2 occupied; 1 free above → land on 1
- const els = [el("blocker", 2, 0, 4)];
- expect(
- resolvePlacement({
- elements: els,
- desiredTrack: 2,
- start: 1,
- duration: 2,
- trackOrder,
- excludeKey: null,
- }),
- ).toEqual({ track: 1, needsInsert: false });
+ it("keeps the clip's own start between edges no centisecond start fits", () => {
+ const tight = [el("a", 0, 0, 3.333), el("b", 0, 6.666, 4)];
+ expect(resolveNearestFreeStart(tight, 0, 3.333, 3.333, null)).toBe(10.67);
+ expect(resolveNearestFreeStart(tight, 0, 3.333, 3.333, null, 0, 3.333)).toBe(3.333);
+ expect(resolveNearestFreeStart(tight, 0, 3.4, 3.333, null, 0, 3.333)).toBe(3.333);
});
- it("prefers up even when a lane below is also free", () => {
- // desired 2 occupied; both 1 (up) and 3 (down) free → up wins
- const els = [el("blocker", 2, 0, 5)];
- expect(
- resolvePlacement({
- elements: els,
- desiredTrack: 2,
- start: 0,
- duration: 3,
- trackOrder,
- excludeKey: null,
- }),
- ).toEqual({ track: 1, needsInsert: false });
+ it("keeps the clip's own start when float sums land a hair past a neighbour's edge", () => {
+ const after = [el("a", 0, 0, 0.333), el("b", 0, 2.066, 1)]; // 0.333 + 1.733 = 2.0660000000000003
+ expect(resolveNearestFreeStart(after, 0, 0.333, 1.733, null, 0, 0.333)).toBe(0.333);
+ const before = [el("a", 0, 0.1, 0.2), el("b", 0, 1.3, 1)]; // a ends at 0.30000000000000004
+ expect(resolveNearestFreeStart(before, 0, 0.3, 1, null, 0, 0.3)).toBe(0.3);
});
- it("falls to a lane below when every lane above is occupied", () => {
- // desired 1 occupied; 0 occupied above; 2 free below → land on 2
- const els = [el("x", 0, 0, 5), el("y", 1, 0, 5)];
- expect(
- resolvePlacement({
- elements: els,
- desiredTrack: 1,
- start: 1,
- duration: 2,
- trackOrder,
- excludeKey: null,
- }),
- ).toEqual({ track: 2, needsInsert: false });
+ it("takes the clip's own start only when it is free, not below minStart, and nearest", () => {
+ expect(resolveNearestFreeStart(row, 0, 4, 2, null, 0, 3.5)).toBe(5); // nearer, but its own spot overlaps a
+ expect(resolveNearestFreeStart(row, 0, 0, 1, null, 1, 0.5)).toBe(1); // below the floor
+ expect(resolveNearestFreeStart(row, 0, 6, 1, null, 0, 5.5)).toBe(6); // the release time is nearer
+ expect(resolveNearestFreeStart(row, 0, 6.5, 1, null, 0, 6)).toBe(6.5); // nearer again, not the origin
});
- it("signals needsInsert when no lane is free", () => {
- const els = [el("a", 0, 0, 9), el("b", 1, 0, 9), el("c", 2, 0, 9), el("d", 3, 0, 9)];
- expect(
- resolvePlacement({
- elements: els,
- desiredTrack: 2,
- start: 1,
- duration: 2,
- trackOrder,
- excludeKey: null,
- }),
- ).toEqual({ track: 2, needsInsert: true });
+ it("moves an overlapping span to the nearest time it fits", () => {
+ expect(resolveNearestFreeStart(row, 0, 4, 2, null)).toBe(5); // 1 s later beats 2 s earlier
+ expect(resolveNearestFreeStart(row, 0, 2.2, 1.5, null)).toBe(0.5); // 1.7 s earlier beats 2.8 s later
});
- it("signals needsInsert when the desired track is occupied but absent from the zone's lanes (#2195)", () => {
- // desiredTrack 5 is occupied yet not in trackOrder (its kind-zone has no lane
- // here). Landing on it would overlap, so the empty-zone branch must insert —
- // not silently land on the occupied track (the placement hole).
- const els = [el("blocker", 5, 0, 5)];
- expect(
- resolvePlacement({
- elements: els,
- desiredTrack: 5,
- start: 1,
- duration: 2,
- trackOrder: [],
- excludeKey: null,
- }),
- ).toEqual({ track: 5, needsInsert: true });
+ it("sends a tie to the later time", () => {
+ expect(resolveNearestFreeStart([el("a", 0, 2, 2)], 0, 2, 2, null)).toBe(4); // 0 and 4 both 2 s away
});
- it("signals needsInsert when the desired track is FREE but absent from the zone's lanes (#2195 free-span hole)", () => {
- // desiredTrack 5 is FREE (no overlap) yet not in trackOrder — its kind-zone has
- // no lane here. The old code short-circuited on isLaneFree and landed on the
- // foreign-zone lane; the zone check must win and signal an insert.
- const els = [el("elsewhere", 9, 0, 5)];
- expect(
- resolvePlacement({
- elements: els,
- desiredTrack: 5,
- start: 1,
- duration: 2,
- trackOrder: [],
- excludeKey: null,
- }),
- ).toEqual({ track: 5, needsInsert: true });
+ it("skips a gap too short for the clip and lands after the row's last clip", () => {
+ expect(resolveNearestFreeStart(row, 0, 5, 4, null)).toBe(10); // the [5,8) gap is 3 s
+ expect(resolveNearestFreeStart([el("a", 0, 0, 30)], 0, 12, 5, null)).toBe(30);
});
- it("placeholder-scenario excludes the dragged clip so it does not collide with itself", () => {
- const els = [el("self", 1, 0, 5)];
- expect(
- resolvePlacement({
- elements: els,
- desiredTrack: 1,
- start: 0,
- duration: 5,
- trackOrder,
- excludeKey: "self",
- }),
- ).toEqual({ track: 1, needsInsert: false });
- });
-});
-
-describe("resolveInsertRow", () => {
- const n = 3; // three lanes: rows 0,1,2
-
- it("targets the lane (null) when over its middle band", () => {
- expect(resolveInsertRow(1.5, n, 0.22)).toBe(null); // dead center of lane 1
- });
-
- it("inserts at the top boundary of a lane when near its top edge", () => {
- expect(resolveInsertRow(1.1, n, 0.22)).toBe(1); // just into lane 1 → boundary above it
- });
-
- it("inserts at the bottom boundary of a lane when near its bottom edge", () => {
- expect(resolveInsertRow(1.9, n, 0.22)).toBe(2); // near bottom of lane 1 → boundary below
+ it("ignores the excluded (dragged) clip", () => {
+ expect(resolveNearestFreeStart(row, 0, 2, 3, "a")).toBe(2);
});
- it("inserts above the top lane when the pointer is above everything", () => {
- expect(resolveInsertRow(-0.5, n, 0.22)).toBe(0);
+ it("never goes below the lowest allowed start", () => {
+ const blocked = [el("c", 0, 6.4, 3.6)]; // busy [6.4,10)
+ expect(resolveNearestFreeStart(blocked, 0, 6.5, 2, null)).toBe(4.4);
+ expect(resolveNearestFreeStart(blocked, 0, 6.5, 2, null, 6.5)).toBe(10);
+ expect(resolveNearestFreeStart([], 0, 6.667, 2, null, 6.667)).toBe(6.667); // not rounded up
});
- it("inserts below the bottom lane when the pointer is past the last lane", () => {
- expect(resolveInsertRow(3.4, n, 0.22)).toBe(3);
+ it("keeps a gap-bound start on centiseconds so a written start cannot overlap", () => {
+ const start = resolveNearestFreeStart([el("a", 0, 7.1, 2)], 0, 3, 5.045333, null);
+ expect(start).toBe(2.05);
+ expect(start + 5.045333).toBeLessThanOrEqual(7.1);
});
});
-describe("resolveInsertRow — production band only arms in the inter-clip gutter (UX rule 1)", () => {
- // The production band equals the clip inset (CLIP_Y / TRACK_H): a clip body fills
- // [band, 1 − band] of its row, so an insert must ONLY arm in the thin gutter that
- // straddles a boundary — never while the pointer is over a clip body. This is the
- // regression for the plain-horizontal-drag misfire (the old 0.32 band armed an
- // insert across ~64% of every row).
- const n = 3;
- const b = INSERT_BOUNDARY_BAND;
-
- it("the band is the clip inset (3/48), not the old feel-tuned 0.32", () => {
- expect(b).toBeCloseTo(3 / 48, 10);
- expect(b).toBeLessThan(0.1);
- });
-
- it("returns null across the WHOLE clip body of every lane (no insert = move-to-lane)", () => {
- // Sweep each lane's body [band+ε, 1−band−ε] in fine steps → always a move.
- for (let lane = 0; lane < n; lane++) {
- for (let frac = b + 0.01; frac <= 1 - b - 0.01 + 1e-9; frac += 0.02) {
- expect(resolveInsertRow(lane + frac, n, b)).toBeNull();
- }
+describe("resolveInsertRow (only empty space outside the rows opens a track)", () => {
+ const n = 3; // three rows: 0, 1, 2
+
+ it("stays on the row everywhere over it, edges included", () => {
+ for (let rowFloat = 0; rowFloat < n; rowFloat += 0.01) {
+ expect(resolveInsertRow(rowFloat, n)).toBeNull();
}
});
- it("arms an insert in the gutter straddling every internal boundary (dead-zone-free)", () => {
- // Just under a boundary → insert BELOW the upper lane; just over → ABOVE the
- // lower lane. Both resolve to the same boundary row, so the gutter has no dead
- // spot that neither moves nor inserts.
- expect(resolveInsertRow(1 - b / 2, n, b)).toBe(1); // bottom gutter of lane 0
- expect(resolveInsertRow(1 + b / 2, n, b)).toBe(1); // top gutter of lane 1
- expect(resolveInsertRow(2 - b / 2, n, b)).toBe(2);
- expect(resolveInsertRow(2 + b / 2, n, b)).toBe(2);
+ it("opens a track above the first row and below the last", () => {
+ expect(resolveInsertRow(-0.4, n)).toBe(0);
+ expect(resolveInsertRow(n, n)).toBe(n);
+ expect(resolveInsertRow(n + 0.4, n)).toBe(n);
});
- it("still arms a top / bottom insert above the first / below the last lane", () => {
- expect(resolveInsertRow(b / 2, n, b)).toBe(0); // top gutter of lane 0 → insert above top
- expect(resolveInsertRow(-0.4, n, b)).toBe(0); // in the top breathing pad
- expect(resolveInsertRow(n - b / 2, n, b)).toBe(n); // bottom gutter of last lane
- expect(resolveInsertRow(n + 0.4, n, b)).toBe(n); // in the bottom breathing pad
+ it("opens the first track on an empty timeline", () => {
+ expect(resolveInsertRow(0.5, 0)).toBe(0);
});
});
@@ -273,7 +159,7 @@ describe("isInsertAllowedForZone", () => {
});
});
-describe("resolveZoneDropPlacement (the whole drop decision, no same-track overlap)", () => {
+describe("resolveZoneDropPlacement (a drop on a row stays on that row, no overlap)", () => {
// order [0,1,2] visual + [3] audio. audioRow = 3.
const order = [0, 1, 2, 3];
const audioTracks = new Set([3]);
@@ -286,90 +172,49 @@ describe("resolveZoneDropPlacement (the whole drop decision, no same-track overl
dragKey: "x",
isAudio: false,
};
+ const allVisualOccupied = () => [el("a", 0, 0, 10), el("b", 1, 0, 10), el("c", 2, 0, 10)];
it("lands on the aimed track when it is free at that time", () => {
expect(
resolveZoneDropPlacement({ ...base, elements: [el("a", 1, 10, 3)], desiredTrack: 1 }),
- ).toEqual({ track: 1, insertRow: null });
+ ).toEqual({ track: 1, insertRow: null, start: 2 });
});
- it("relocates UP to the nearest free track when the aimed spot overlaps a clip", () => {
+ it("stays on the aimed row at its nearest free time when the aimed span is occupied", () => {
expect(
resolveZoneDropPlacement({ ...base, elements: [el("a", 1, 0, 5)], desiredTrack: 1 }),
- ).toEqual({ track: 0, insertRow: null });
+ ).toEqual({ track: 1, insertRow: null, start: 5 });
});
- it("relocates DOWN when the tracks above are also occupied", () => {
+ it("never hops to another row or opens a track when every row is occupied", () => {
expect(
- resolveZoneDropPlacement({
- ...base,
- elements: [el("a", 0, 0, 5), el("b", 1, 0, 5)],
- desiredTrack: 1,
- }),
- ).toEqual({ track: 2, insertRow: null });
+ resolveZoneDropPlacement({ ...base, elements: allVisualOccupied(), desiredTrack: 1 }),
+ ).toEqual({ track: 1, insertRow: null, start: 10 });
});
- it("crosses an occupied aim instead of snapping the dragged clip back to its origin", () => {
+ it("does not fall back to the dragged clip's origin row", () => {
expect(
resolveZoneDropPlacement({
...base,
elements: [el("a", 0, 0, 5), el("b", 1, 0, 5), el("x", 2, 0, 5)],
desiredTrack: 1,
}),
- ).toEqual({ track: 1, insertRow: 1 });
-
- expect(
- resolveZoneDropPlacement({
- ...base,
- elements: [el("x", 0, 0, 5), el("b", 1, 0, 5), el("a", 2, 0, 5)],
- desiredTrack: 1,
- }),
- ).toEqual({ track: 1, insertRow: 2 });
- });
-
- it("auto-creates a new track when EVERY lane in the zone is occupied at that time", () => {
- expect(
- resolveZoneDropPlacement({
- ...base,
- elements: [el("a", 0, 0, 5), el("b", 1, 0, 5), el("c", 2, 0, 5)],
- desiredTrack: 1,
- }),
- ).toEqual({ track: 1, insertRow: 2 });
+ ).toEqual({ track: 1, insertRow: null, start: 5 });
});
- // Every visual lane (0,1,2) occupied across the drop span → no free lane exists.
- const allVisualOccupied = () => [el("a", 0, 0, 10), el("b", 1, 0, 10), el("c", 2, 0, 10)];
-
- it("occupied aim with NO free lane creates an adjacent track — never snaps back (UX rule 3)", () => {
- // The clip must NOT return to its origin; it gets a fresh track adjacent to the
- // aim. Default bias = below the aimed row.
- const result = resolveZoneDropPlacement({
- ...base,
- elements: allVisualOccupied(),
- desiredTrack: 1,
+ it("Tag (2 s, 5 s long) onto the Subtitle row (0-6 s) lands at 6 s on that row", () => {
+ const elements = [el("title", 0, 0, 10), el("subtitle", 1, 0, 6), el("tag", 2, 2, 5)];
+ const drop = { ...base, elements, start: 2, duration: 5, dragKey: "tag" };
+ expect(resolveZoneDropPlacement({ ...drop, desiredTrack: 1 })).toEqual({
+ track: 1,
+ insertRow: null,
+ start: 6,
+ });
+ expect(resolveZoneDropPlacement({ ...drop, desiredTrack: 0 })).toEqual({
+ track: 0,
+ insertRow: null,
+ start: 10,
});
- expect(result.insertRow).not.toBeNull(); // a track is created, not an origin snap-back
- expect(result).toEqual({ track: 1, insertRow: 2 }); // adjacent, below the aimed row
- });
-
- it("opens the new adjacent track ABOVE the aimed row when the pointer is in its upper half (UX rule 3)", () => {
- expect(
- resolveZoneDropPlacement({
- ...base,
- elements: allVisualOccupied(),
- desiredTrack: 1,
- preferInsertAbove: true,
- }),
- ).toEqual({ track: 1, insertRow: 1 }); // boundary ABOVE lane 1
- // Same aim, pointer in the lower half → the track opens BELOW the aimed row.
- expect(
- resolveZoneDropPlacement({
- ...base,
- elements: allVisualOccupied(),
- desiredTrack: 1,
- preferInsertAbove: false,
- }),
- ).toEqual({ track: 1, insertRow: 2 });
});
it("shares a track for sequential (non-overlapping) clips", () => {
@@ -380,45 +225,37 @@ describe("resolveZoneDropPlacement (the whole drop decision, no same-track overl
desiredTrack: 1,
start: 2,
}),
- ).toEqual({ track: 1, insertRow: null });
+ ).toEqual({ track: 1, insertRow: null, start: 2 });
});
it("clamps a visual clip OUT of the audio zone before placing", () => {
expect(resolveZoneDropPlacement({ ...base, elements: [], desiredTrack: 3 })).toEqual({
track: 2,
insertRow: null,
+ start: 2,
});
});
it("clamps an audio clip INTO the audio zone before placing", () => {
expect(
resolveZoneDropPlacement({ ...base, elements: [], desiredTrack: 0, isAudio: true }),
- ).toEqual({ track: 3, insertRow: null });
+ ).toEqual({ track: 3, insertRow: null, start: 2 });
});
it("upward create-drag off the top lane inserts at the TOP of the visual zone, never below audio (reviewer repro)", () => {
- // 3-visual + 1-audio timeline. Dragging a top-lane visual clip up past the
- // create threshold emits the sentinel desiredTrack = minTrack-1 = -1. The
- // old hoist did order.indexOf(-1) = -1 and fell to below = order.length = 4,
- // creating the new track BELOW the audio zone — repro {track:-1, insertRow:4}.
- // It must now anchor to the top boundary of the visual zone.
+ // The sentinel desiredTrack = minTrack-1 = -1 must anchor to the visual zone's top boundary.
expect(
resolveZoneDropPlacement({ ...base, elements: allVisualOccupied(), desiredTrack: -1 }),
- ).toEqual({ track: -1, insertRow: 0 });
+ ).toEqual({ track: -1, insertRow: 0, start: 2 });
});
it("downward create-drag off the bottom visual lane inserts at the audio boundary, never below it", () => {
- // Sentinel desiredTrack = maxTrack+1 = 4 for a downward create-drag. A visual
- // clip must land at the bottom of the visual zone (row 3 = just above audio),
- // not past the audio lanes.
expect(
resolveZoneDropPlacement({ ...base, elements: allVisualOccupied(), desiredTrack: 4 }),
- ).toEqual({ track: 4, insertRow: 3 });
+ ).toEqual({ track: 4, insertRow: 3, start: 2 });
});
it("audio create-drag with an out-of-range aim inserts inside the audio zone", () => {
- // An audio clip aimed above its zone (sentinel below its own min lane) anchors
- // to the audio zone's top boundary (row 3), not into the visual zone.
expect(
resolveZoneDropPlacement({
...base,
@@ -426,22 +263,22 @@ describe("resolveZoneDropPlacement (the whole drop decision, no same-track overl
desiredTrack: -1,
isAudio: true,
}),
- ).toEqual({ track: -1, insertRow: 3 });
+ ).toEqual({ track: -1, insertRow: 3, start: 2 });
});
- it("honors a deliberate boundary insert in the clip's own zone", () => {
+ it("honors an insert aimed at the space outside the rows in the clip's own zone", () => {
expect(
- resolveZoneDropPlacement({ ...base, elements: [], desiredTrack: 1, deliberateInsertRow: 1 }),
- ).toEqual({ track: 1, insertRow: 1 });
+ resolveZoneDropPlacement({ ...base, elements: [], desiredTrack: 0, deliberateInsertRow: 0 }),
+ ).toEqual({ track: 0, insertRow: 0, start: 2 });
});
- it("ignores a deliberate insert that lands in the WRONG zone (visual into audio)", () => {
+ it("ignores an insert that lands in the WRONG zone (visual into audio)", () => {
expect(
resolveZoneDropPlacement({ ...base, elements: [], desiredTrack: 1, deliberateInsertRow: 4 }),
- ).toEqual({ track: 1, insertRow: null });
+ ).toEqual({ track: 1, insertRow: null, start: 2 });
});
- it("lets an AUDIO clip create a new audio track via a boundary insert", () => {
+ it("lets an AUDIO clip open a new audio track below the last row", () => {
expect(
resolveZoneDropPlacement({
...base,
@@ -450,69 +287,30 @@ describe("resolveZoneDropPlacement (the whole drop decision, no same-track overl
isAudio: true,
deliberateInsertRow: 4,
}),
- ).toEqual({ track: 3, insertRow: 4 });
+ ).toEqual({ track: 3, insertRow: 4, start: 2 });
});
- it("Abhai repro: audio dropped on a visual-only timeline over an occupied span → insert, no overlap (#2195)", () => {
- // No audio zone exists yet (audioTracks empty). The audio clip is aimed at the
- // sole visual lane, which is occupied at the drop time. The zone-drop must
- // create the audio zone's first lane (insertRow set) rather than stacking the
- // audio clip onto the occupied visual track — the no-overlap invariant.
- const result = resolveZoneDropPlacement({
+ it("audio dropped on a visual-only timeline opens its zone's first row, no overlap (#2195)", () => {
+ const drop = {
order: [0],
audioTracks: new Set<number>(),
elements: [el("v", 0, 0, 5)],
desiredTrack: 0,
deliberateInsertRow: null,
- start: 1,
duration: 2,
dragKey: "audio",
isAudio: true,
+ };
+ // Occupied and free spans alike: the visual row is not a row an audio clip may land on.
+ expect(resolveZoneDropPlacement({ ...drop, start: 1 })).toEqual({
+ track: 0,
+ insertRow: 1,
+ start: 1,
});
- expect(result.insertRow).not.toBeNull();
- expect(result).toEqual({ track: 0, insertRow: 1 });
- });
-
- it("free-span repro: audio dropped on a FREE stretch of a visual-only timeline → insert, not a visual lane (#2195)", () => {
- // Same visual-only timeline, but the audio clip is aimed at a stretch the sole
- // visual lane is FREE at. The zone check must still fire an insert (create the
- // audio zone) rather than short-circuiting on isLaneFree and dropping the audio
- // clip onto the visual lane — the kind-zone hole where the free-lane fast path
- // beat the wrong-zone check.
- const result = resolveZoneDropPlacement({
- order: [0],
- audioTracks: new Set<number>(),
- elements: [el("v", 0, 0, 5)],
- desiredTrack: 0,
- deliberateInsertRow: null,
- start: 10, // past the visual clip's end → the visual lane is FREE here
- duration: 2,
- dragKey: "audio",
- isAudio: true,
+ expect(resolveZoneDropPlacement({ ...drop, start: 10 })).toEqual({
+ track: 0,
+ insertRow: 1,
+ start: 10,
});
- expect(result.insertRow).not.toBeNull();
- expect(result).toEqual({ track: 0, insertRow: 1 });
- });
-});
-
-describe("resolveMainTrackDropStart (magnetic first clip on an empty main track)", () => {
- it("snaps to 0 when landing on an empty main track", () => {
- expect(resolveMainTrackDropStart([], 1, 0, false, 7)).toBe(0);
- });
-
- it("leaves the drop start alone once the main track already holds another clip", () => {
- expect(resolveMainTrackDropStart([el("other", 0, 0, 3)], 1, 0, false, 7)).toBe(7);
- });
-
- it("leaves the drop start alone when landing off the main track", () => {
- expect(resolveMainTrackDropStart([], 1, 2, false, 7)).toBe(7);
- });
-
- it("a clip already resident on the main track doing a horizontal move is a no-op", () => {
- expect(resolveMainTrackDropStart([], 0, 0, false, 7)).toBe(7);
- });
-
- it("an audio clip landing on track 0 is not the main track (visual zone only)", () => {
- expect(resolveMainTrackDropStart([], 1, 0, true, 7)).toBe(7);
});
});
diff --git a/packages/studio/src/player/components/timelineCollision.ts b/packages/studio/src/player/components/timelineCollision.ts
index ab24667610..25faaf8ea7 100644
--- a/packages/studio/src/player/components/timelineCollision.ts
+++ b/packages/studio/src/player/components/timelineCollision.ts
@@ -1,6 +1,4 @@
import type { TimelineElement } from "../store/playerStore";
-import { INSERT_BOUNDARY_BAND } from "./timelineLayout";
-import { isMainTrackElement } from "./timelineZones";
/**
* Keep a landing track inside the dragged clip's kind-zone: visual clips stay in
@@ -38,26 +36,6 @@ export function isInsertAllowedForZone(
return isAudio ? insertRow >= audioRow : insertRow <= audioRow;
}
-/**
- * The full drop-placement decision for a dragged clip — one pure, testable unit.
- * Enforces: NO time-overlap on a single track; a clip stays in its kind-zone;
- * a new track is created only when needed. Order of resolution:
- * 1. Deliberate boundary insert (pointer near a lane edge), if it's in the
- * clip's own zone → create a new track there.
- * 2. Otherwise land on a lane: clamp the aimed track to the clip's zone, take it
- * if free at [start, start+duration), else the nearest FREE lane in the zone
- * (prefer up), else auto-create a new track right below the aimed lane.
- * `audioTracks` = the set of track indices that currently hold audio (so the fn
- * needs no element-kind import). Returns the landing `track` and, when a new track
- * should be created, the `insertRow` boundary (else null).
- *
- * `preferInsertAbove` biases the auto-created track (occupied-aim → new adjacent
- * track) toward the boundary ABOVE the aimed row instead of below it, so the new
- * lane opens on whichever side of the aimed clip the pointer is nearer (the drag
- * preview passes the pointer's sub-row half). A clip whose aimed span is occupied
- * never snaps back to its origin — it relocates to a free lane, or (none free)
- * gets a fresh track next to the aim. Default (below) preserves prior behaviour.
- */
/**
* Insert-row boundary for an out-of-range aim — a `desired` track that isn't a
* real lane: the sentinel minTrack-1 an upward create-drag emits (#2214-adjacent
@@ -84,6 +62,50 @@ function outOfRangeZoneInsertRow(
return desired < Math.min(...zoneTracks) ? zoneTop : zoneBottom;
}
+const floorCenti = (v: number) => Math.floor(v * 100 + 1e-6) / 100;
+const ceilCenti = (v: number) => Math.ceil(v * 100 - 1e-6) / 100;
+
+/** Whether `candidate` is nearer `start` than `best`; a tie goes to the later time. */
+const isNearer = (candidate: number, best: number, start: number) => {
+ const gap = Math.abs(candidate - start) - Math.abs(best - start);
+ return gap < 0 || (gap === 0 && candidate > best);
+};
+
+/** The start nearest `start`, not below `minStart`, at which [start, start + duration) overlaps
+ * no clip on `track`. Ties go to the later time. The gap after the row's last clip always fits,
+ * so a row with no gap long enough puts the clip right after its last clip. `origin` is the
+ * clip's own start on this track: keeping it rewrites nothing, so it fits between any edges. */
+export function resolveNearestFreeStart(
+ elements: readonly TimelineElement[],
+ track: number,
+ start: number,
+ duration: number,
+ excludeKey: string | null,
+ minStart = 0,
+ origin: number | null = null,
+): number {
+ const busy = elements
+ .filter((el) => (el.key ?? el.id) !== excludeKey && el.track === track)
+ .sort((a, b) => a.start - b.start);
+ let best = Number.POSITIVE_INFINITY;
+ let gapStart = minStart;
+ for (const el of [...busy, null]) {
+ const latest = el ? floorCenti(el.start - duration) : Number.POSITIVE_INFINITY;
+ if (latest >= gapStart) {
+ const candidate = Math.min(Math.max(start, gapStart), latest);
+ if (Math.abs(candidate - start) <= Math.abs(best - start)) best = candidate;
+ }
+ if (el) gapStart = Math.max(gapStart, ceilCenti(el.start + el.duration));
+ }
+ if (origin === null || origin < minStart || !isNearer(origin, best, start)) return best;
+ // Float slack at both ends: 0.333 + 1.733 is 2.0660000000000003, a hair past a neighbour at 2.066.
+ const [from, to] = [origin + 1e-6, origin + duration - 1e-6];
+ const clear = busy.every((el) => !timeRangesOverlap(from, to, el.start, el.start + el.duration));
+ return clear ? origin : best;
+}
+
+// Where a dragged clip lands: on the aimed row of its kind, at the nearest free time there. Only an aim outside all
+// rows, or into a kind with no row yet, opens a track (`insertRow`).
export function resolveZoneDropPlacement(input: {
order: number[];
audioTracks: ReadonlySet<number>;
@@ -94,99 +116,54 @@ export function resolveZoneDropPlacement(input: {
duration: number;
dragKey: string;
isAudio: boolean;
- preferInsertAbove?: boolean;
-}): { track: number; insertRow: number | null } {
+ /** Lowest start the clip may take (every moving clip stays at or after its host's start). */
+ minStart?: number;
+ /** Where the dragged clip sits now. */
+ origin?: { track: number; start: number };
+}): { track: number; insertRow: number | null; start: number } {
const { order, audioTracks, elements, desiredTrack, deliberateInsertRow } = input;
- const { start, duration, dragKey, isAudio, preferInsertAbove } = input;
+ const { start, duration, dragKey, isAudio, minStart } = input;
const audioRow = order.findIndex((t) => audioTracks.has(t));
if (
deliberateInsertRow !== null &&
isInsertAllowedForZone(deliberateInsertRow, audioRow, isAudio)
) {
- return { track: desiredTrack, insertRow: deliberateInsertRow };
+ return { track: desiredTrack, insertRow: deliberateInsertRow, start };
}
const desired = clampTrackToZone(desiredTrack, order, audioRow, isAudio);
const zoneTracks = order.filter((t) => audioTracks.has(t) === isAudio);
- const placement = resolvePlacement({
+ // Only when the aim is outside the rows, or the clip's zone has no row yet.
+ if (!zoneTracks.includes(desired)) {
+ const desiredRow = order.indexOf(desired);
+ const insertRow =
+ desiredRow < 0
+ ? outOfRangeZoneInsertRow(order, zoneTracks, audioRow, desired)
+ : desiredRow + 1;
+ return { track: desired, insertRow, start };
+ }
+ const origin = input.origin?.track === desired ? input.origin.start : null;
+ const freeStart = resolveNearestFreeStart(
elements,
- desiredTrack: desired,
+ desired,
start,
duration,
- trackOrder: zoneTracks,
- excludeKey: dragKey,
- });
- const originTrack = elements.find((element) => (element.key ?? element.id) === dragKey)?.track;
- const snappedBackToOrigin =
- originTrack != null && desired !== originTrack && placement.track === originTrack;
- if (placement.needsInsert || snappedBackToOrigin) {
- const desiredRow = order.indexOf(desired);
- if (desiredRow < 0) {
- return {
- track: desired,
- insertRow: outOfRangeZoneInsertRow(order, zoneTracks, audioRow, desired),
- };
- }
- // When collision fallback found only the origin lane, insert on the far side
- // of the aimed lane so normalization cannot turn the gesture into a no-op.
- // Otherwise prefer the gap nearest the pointer, preserving normal insertion.
- const originRow = originTrack == null ? -1 : order.indexOf(originTrack);
- const insertAbove = snappedBackToOrigin
- ? originRow > desiredRow
- : preferInsertAbove && isInsertAllowedForZone(desiredRow, audioRow, isAudio);
- const insertRow = insertAbove ? desiredRow : desiredRow + 1;
- return { track: desired, insertRow };
- }
- return { track: placement.track, insertRow: null };
-}
-
-function landsOnMainTrack(landingTrack: number, isAudio: boolean): boolean {
- return isMainTrackElement({
- id: "",
- tag: isAudio ? "audio" : "video",
- start: 0,
- duration: 0,
- track: landingTrack,
- });
-}
-
-/** An existing clip newly landing on an empty main track commits at start=0.
- * No-op once the main track holds another clip, off the main track, or for
- * a clip already resident there. `others` excludes the landing clip itself. */
-export function resolveMainTrackDropStart(
- others: readonly TimelineElement[],
- originTrack: number,
- landingTrack: number,
- isAudio: boolean,
- desiredStart: number,
-): number {
- if (originTrack === landingTrack || !landsOnMainTrack(landingTrack, isAudio)) {
- return desiredStart;
- }
- return others.some(isMainTrackElement) ? desiredStart : 0;
+ dragKey,
+ minStart,
+ origin,
+ );
+ return { track: desired, insertRow: null, start: freeStart };
}
/**
- * Decide whether a vertical drag is inserting a new track at a lane boundary.
- * `rowFloat` is the pointer's position in track-height units from the top of the
- * first lane (0 = top of lane 0). Returns the boundary row to insert at
- * (0 = above the top lane, `trackCount` = below the bottom), or null when the
- * pointer is over a lane's middle band (a normal move/target). The default band
- * preserves collapsed-row behavior; production passes the concrete row's band.
+ * The row boundary a pointer opens a new track at, or null over a row. `rowFloat` is the pointer's
+ * position in row units from the top of the first row. Only the empty space above the first row
+ * (0) or below the last (`trackCount`) opens one: a drop anywhere on a row stays on that row.
*/
-export function resolveInsertRow(
- rowFloat: number,
- trackCount: number,
- band: number = INSERT_BOUNDARY_BAND,
-): number | null {
- if (trackCount === 0) return 0;
- if (rowFloat <= 0) return 0;
+export function resolveInsertRow(rowFloat: number, trackCount: number): number | null {
+ if (trackCount === 0 || rowFloat < 0) return 0;
if (rowFloat >= trackCount) return trackCount;
- const lane = Math.floor(rowFloat);
- const frac = rowFloat - lane;
- if (frac < band) return lane;
- if (frac > 1 - band) return lane + 1;
return null;
}
@@ -218,67 +195,3 @@ export function isLaneFree(
timeRangesOverlap(start, end, el.start, el.start + el.duration),
);
}
-
-export interface PlacementInput {
- elements: TimelineElement[];
- desiredTrack: number;
- start: number;
- duration: number;
- trackOrder: number[];
- excludeKey: string | null;
-}
-
-export interface PlacementResult {
- /** The lane the clip should land on. */
- track: number;
- /**
- * True when no existing lane was free and the caller should insert a new
- * track instead of landing on `track` (which is then the desired lane as a
- * last-resort fallback). Consumed in later stages (2b/2c); stage 2a ignores it.
- */
- needsInsert: boolean;
-}
-
-/**
- * Resolve where a dragged clip should land, avoiding overlap. If the desired
- * lane is free, keep it. Otherwise search the nearest free lane, **preferring
- * up** (all lanes above, nearest first), then down. If none is free, signal an
- * insert and fall back to the desired lane.
- */
-export function resolvePlacement({
- elements,
- desiredTrack,
- start,
- duration,
- trackOrder,
- excludeKey,
-}: PlacementInput): PlacementResult {
- const end = start + duration;
- const idx = trackOrder.indexOf(desiredTrack);
- // desiredTrack is not one of the zone's lanes — the clip's kind-zone has no lane
- // yet (e.g. an audio clip dropped on a visual-only timeline). This MUST be checked
- // BEFORE the isLaneFree short-circuit below: a free-aimed span on a foreign-zone
- // lane (an audio clip aimed at an empty stretch of a visual-only timeline) is
- // "free" only because that lane belongs to the wrong zone. Landing there would
- // put the clip in the wrong kind-zone, so signal an insert to create the zone's
- // first lane instead — regardless of whether the aimed span is occupied (#2195).
- if (idx === -1) return { track: desiredTrack, needsInsert: true };
-
- if (isLaneFree(elements, desiredTrack, start, end, excludeKey)) {
- return { track: desiredTrack, needsInsert: false };
- }
-
- // Prefer up: nearest lane above first, then the rest above.
- for (let up = idx - 1; up >= 0; up--) {
- if (isLaneFree(elements, trackOrder[up], start, end, excludeKey)) {
- return { track: trackOrder[up], needsInsert: false };
- }
- }
- // Then down: nearest lane below first.
- for (let down = idx + 1; down < trackOrder.length; down++) {
- if (isLaneFree(elements, trackOrder[down], start, end, excludeKey)) {
- return { track: trackOrder[down], needsInsert: false };
- }
- }
- return { track: desiredTrack, needsInsert: true };
-}
diff --git a/packages/studio/src/player/components/timelineDragDrop.test.tsx b/packages/studio/src/player/components/timelineDragDrop.test.tsx
index 73aecc7c5c..b8ee0f77ac 100644
--- a/packages/studio/src/player/components/timelineDragDrop.test.tsx
+++ b/packages/studio/src/player/components/timelineDragDrop.test.tsx
@@ -256,8 +256,10 @@ describe("useTimelineAssetDrop", () => {
describe("resolveDropInsertRow", () => {
const rows = [TRACK_H, TRACK_H, TRACK_H];
- it("arms a new track at the boundary between two lanes", () => {
- expect(resolveDropInsertRow(getTimelineRowTop(1, rows), rows, 3)).toBe(1);
+ it("stays on the row at the boundary between two rows", () => {
+ for (const dy of [-1, 0, 1]) {
+ expect(resolveDropInsertRow(getTimelineRowTop(1, rows) + dy, rows, 3)).toBeNull();
+ }
});
it("arms a new track above the first lane", () => {
expect(resolveDropInsertRow(getTimelineRowTop(0, rows) - 4, rows, 3)).toBe(0);
@@ -274,20 +276,32 @@ describe("resolveDropInsertRow", () => {
});
describe("useTimelineAssetDrop new-track drops", () => {
- it("previews and commits an insert row for an asset dropped between lanes", () => {
+ it("drops an asset released at the top edge of a row onto that row, with no new track", () => {
const onAssetDrop = vi.fn();
const view = renderHarness(onAssetDrop);
const transfer = assetTransfer(JSON.stringify({ path: "assets/a.png" }));
const y = getTimelineRowTop(1) + 1;
act(() => view.api.handleAssetDragOver(dragEvent(transfer, 400, y)));
- expect(view.api.dropPreview).toMatchObject({ start: 10, insertRow: 1 });
+ expect(view.api.dropPreview).toEqual({ start: 10, track: 1 });
+ act(() => view.api.handleAssetDrop(dragEvent(transfer, 400, y)));
+ expect(onAssetDrop).toHaveBeenCalledWith("assets/a.png", { start: 10, track: 1 });
+ act(() => view.root.unmount());
+ });
+
+ it("opens a new track for an asset released in the empty space above the first row", () => {
+ const onAssetDrop = vi.fn();
+ const view = renderHarness(onAssetDrop);
+ const transfer = assetTransfer(JSON.stringify({ path: "assets/a.png" }));
+ const y = getTimelineRowTop(0) - 4;
+
+ act(() => view.api.handleAssetDragOver(dragEvent(transfer, 400, y)));
act(() => view.api.handleAssetDrop(dragEvent(transfer, 400, y)));
expect(onAssetDrop).toHaveBeenCalledWith(
"assets/a.png",
expect.objectContaining({
start: 10,
- insertRow: 1,
+ insertRow: 0,
trackOrder: Array.from({ length: 100 }, (_, index) => index),
}),
);
diff --git a/packages/studio/src/player/components/timelineDragDrop.ts b/packages/studio/src/player/components/timelineDragDrop.ts
index f3169f2e43..3b50756142 100644
--- a/packages/studio/src/player/components/timelineDragDrop.ts
+++ b/packages/studio/src/player/components/timelineDragDrop.ts
@@ -5,8 +5,7 @@ import {
TIMELINE_COMPOSITION_MIME,
} from "../../utils/timelineCompositionDrop";
import {
- getTimelineInsertBoundaryBand,
- getTimelineRowPositionFromY,
+ getTimelineRowFromY,
resolveTimelineAssetDrop,
type TimelineRowGeometry,
} from "./timelineLayout";
@@ -52,17 +51,17 @@ function canInsertTrackFor(types: readonly string[]): boolean {
return types.includes("Files") || types.includes(TIMELINE_ASSET_MIME);
}
-/** The row boundary a pointer at `contentY` arms for a new track, or null over a lane's middle. */
+/** The row boundary a pointer at `contentY` opens a new track at, or null over a row. */
export function resolveDropInsertRow(
contentY: number,
rowHeights: readonly number[] | undefined,
trackCount: number,
): number | null {
if (trackCount === 0) return null;
- const { rowFloat, rowHeight } = getTimelineRowPositionFromY(contentY, rowHeights);
+ const rowFloat = getTimelineRowFromY(contentY, rowHeights);
// Past the last lane the drop already appends a track (getDefaultDroppedTrack).
if (rowFloat >= trackCount) return null;
- return resolveInsertRow(rowFloat, trackCount, getTimelineInsertBoundaryBand(rowHeight));
+ return resolveInsertRow(rowFloat, trackCount);
}
function placeDrop(
@@ -118,10 +117,9 @@ function applyTypedJsonDrop(
}
/**
- * Dropping an asset/file/block/composition onto the timeline places it at the
- * exact time and track it was dropped on, like CapCut (pointer placement on
- * every track but the magnetic main track). Supersedes the prior playhead
- * decision (#2291); playhead adds stay available, see useAddAssetAtPlayhead.
+ * Dropping an asset/file/block/composition onto the timeline places it on the row
+ * and at the time it was dropped on; an asset moves to that row's nearest free time.
+ * Supersedes the prior playhead decision (#2291); see useAddAssetAtPlayhead.
*/
export function useTimelineAssetDrop({
scrollRef,
diff --git a/packages/studio/src/player/components/timelineDragLanding.ts b/packages/studio/src/player/components/timelineDragLanding.ts
index 880c003e7e..845434e6ca 100644
--- a/packages/studio/src/player/components/timelineDragLanding.ts
+++ b/packages/studio/src/player/components/timelineDragLanding.ts
@@ -1,12 +1,7 @@
import type { TimelineElement } from "../store/playerStore";
import type { DragCommitDeps } from "./timelineClipDragCommit";
-import type { DraggedClipState } from "./timelineClipDragTypes";
import { classifyZone, normalizeToZones } from "./timelineZones";
-import { resolveMainTrackDropStart } from "./timelineCollision";
-import { isAudioTimelineElement } from "../../utils/timelineInspector";
-import { resolveExpandedHostAlias } from "./timelineAuthoredMoveTarget";
import { sameSourceFile } from "./timelineAuthoredTrack";
-import { round3 } from "./timelineGaps";
const keyOf = (e: TimelineElement) => e.key ?? e.id;
@@ -58,47 +53,3 @@ export function layoutAfterTrackInsert(
);
return { normalized, targetTrack, writable };
}
-
-/** The start a solo clip lands at, for both the ghost and the commit: 0 on an empty
- * main track, judged on the final lane (after the renumber and the host alias).
- * Returned in the dragged clip's own frame. */
-export function resolveDragLandingStart(
- drag: DraggedClipState,
- deps: Pick<DragCommitDeps, "elements" | "trackOrder" | "selectedKeys">,
-): number {
- const alias = resolveExpandedHostAlias(drag, deps);
- const target = alias?.drag ?? drag;
- const keys = alias?.selectedKeys ?? deps.selectedKeys;
- const element = target.element;
- const key = keyOf(element);
- if (keys && keys.size > 1 && keys.has(key)) return drag.previewStart;
-
- let landingTrack = target.previewTrack;
- let renumbered = new Map<string, number>();
- if (target.insertRow != null) {
- const layout = layoutAfterTrackInsert(
- element,
- target.previewStart,
- target.insertRow,
- null,
- deps,
- );
- if (layout) {
- renumbered = new Map(layout.normalized.map((n) => [keyOf(n), n.track]));
- landingTrack = renumbered.get(key) ?? layout.targetTrack;
- }
- }
- const others = deps.elements
- .filter((e) => keyOf(e) !== key)
- .map((e) => (renumbered.has(keyOf(e)) ? { ...e, track: renumbered.get(keyOf(e))! } : e));
- const snapped = resolveMainTrackDropStart(
- others,
- element.track,
- landingTrack,
- isAudioTimelineElement(element),
- target.previewStart,
- );
- return snapped === target.previewStart
- ? drag.previewStart
- : round3(drag.previewStart + snapped - target.previewStart);
-}
diff --git a/packages/studio/src/player/components/timelineLayout.test.ts b/packages/studio/src/player/components/timelineLayout.test.ts
index cd0175d567..efd90c92c7 100644
--- a/packages/studio/src/player/components/timelineLayout.test.ts
+++ b/packages/studio/src/player/components/timelineLayout.test.ts
@@ -1,8 +1,5 @@
import { describe, it, expect } from "vitest";
import {
- CLIP_Y,
- INSERT_BOUNDARY_BAND,
- getTimelineInsertBoundaryBand,
RULER_H,
TRACK_H,
LANE_H,
@@ -294,25 +291,3 @@ describe("getTimelineScrubTime", () => {
expect(at(origin + 250, Number.NaN)).toBe(0);
});
});
-
-// The only production hook keeping resolveInsertRow's band aligned with the
-// rendered clip inset once rows can be taller than TRACK_H. Pinned directly so a
-// change to CLIP_Y or the invalid-height fallback can't silently drift it.
-describe("getTimelineInsertBoundaryBand", () => {
- it("matches the fixed band for a plain track row", () => {
- expect(getTimelineInsertBoundaryBand(TRACK_H)).toBe(INSERT_BOUNDARY_BAND);
- expect(getTimelineInsertBoundaryBand(TRACK_H)).toBe(CLIP_Y / TRACK_H);
- });
-
- it("shrinks as the row grows, so the band stays CLIP_Y pixels tall", () => {
- const expanded = TRACK_H + 2 * LANE_H;
- expect(getTimelineInsertBoundaryBand(expanded)).toBeCloseTo(CLIP_Y / expanded, 10);
- expect(getTimelineInsertBoundaryBand(expanded)).toBeLessThan(INSERT_BOUNDARY_BAND);
- });
-
- it("falls back to the plain-track band for a height that is not usable", () => {
- for (const height of [0, -10, Number.NaN]) {
- expect(getTimelineInsertBoundaryBand(height)).toBe(INSERT_BOUNDARY_BAND);
- }
- });
-});
diff --git a/packages/studio/src/player/components/timelineLayout.ts b/packages/studio/src/player/components/timelineLayout.ts
index 5b7f6f0f74..7b8c55247c 100644
--- a/packages/studio/src/player/components/timelineLayout.ts
+++ b/packages/studio/src/player/components/timelineLayout.ts
@@ -54,11 +54,6 @@ export function getTimelineBeatEntries(
export function getTimelineLaneTop(laneIndex: number): number {
return TRACK_H + Math.max(0, Math.trunc(laneIndex)) * LANE_H;
}
-/**
- * Collapsed-row characterization value for the new-track INSERT band. Runtime
- * hit-testing uses getTimelineInsertBoundaryBand with the concrete row height.
- */
-export const INSERT_BOUNDARY_BAND = CLIP_Y / TRACK_H;
/**
* Breathing room INSIDE the scroll area (CapCut-style), threaded through every
* track-row y computation via {@link getTimelineRowTop} — never inline a magic
@@ -263,17 +258,6 @@ export function getTimelineRowFromY(
return getTimelineRowGeometry(rowHeights).getRowFromY(contentY);
}
-export function getTimelineRowPositionFromY(
- contentY: number,
- rowHeights: readonly number[] = EMPTY_ROW_HEIGHTS,
-): { rowFloat: number; row: number; fraction: number; rowHeight: number } {
- return getTimelineRowGeometry(rowHeights).getRowPositionFromY(contentY);
-}
-
-/** Fractional insert band for the concrete row under a pointer. */
-export function getTimelineInsertBoundaryBand(rowHeight: number): number {
- return CLIP_Y / validRowHeight(rowHeight);
-}
/**
* While a clip drag is live, the rendered timeline extends this far past the
* ghost's end so the right-edge auto-scroll zone always has room to keep
diff --git a/packages/studio/src/player/components/timelineMultiDragPreview.test.ts b/packages/studio/src/player/components/timelineMultiDragPreview.test.ts
index d76d553962..91c5912a53 100644
--- a/packages/studio/src/player/components/timelineMultiDragPreview.test.ts
+++ b/packages/studio/src/player/components/timelineMultiDragPreview.test.ts
@@ -1,10 +1,12 @@
import { describe, it, expect } from "vitest";
+import type { TimelineElement } from "../store/playerStore";
import {
- clampGroupMoveDelta,
+ groupMoveFloor,
isMultiDragActive,
isMultiDragPassenger,
multiDragDeltaSeconds,
multiDragPassengerOffsetPx,
+ resolveGroupMovers,
type MultiDragPreviewInput,
} from "./timelineMultiDragPreview";
@@ -17,8 +19,6 @@ const base = (over: Partial<MultiDragPreviewInput> = {}): MultiDragPreviewInput
...over,
});
-const starts = (...values: number[]) => values.map((start) => ({ start }));
-
describe("isMultiDragActive", () => {
it("is active when a started drag's clip is part of a 2+ selection", () => {
expect(isMultiDragActive(base())).toBe(true);
@@ -94,36 +94,45 @@ describe("multiDragPassengerOffsetPx (rigid: every passenger shares the delta)",
});
});
-describe("clampGroupMoveDelta (rigid group move)", () => {
- it("passes a rightward delta through unchanged (no right wall)", () => {
- expect(clampGroupMoveDelta(3, starts(2, 5, 9))).toBe(3);
- expect(clampGroupMoveDelta(1000, starts(0, 4))).toBe(1000);
- });
+const at = (id: string, start: number, locked = false): TimelineElement => ({
+ id,
+ key: id,
+ tag: "video",
+ start,
+ duration: 1,
+ track: 0,
+ domId: id,
+ ...(locked ? { timelineLocked: true } : {}),
+});
- it("passes a leftward delta through when no member would cross 0", () => {
- // Leftmost member at 5, moving left by 3 → 2 ≥ 0, so unclamped.
- expect(clampGroupMoveDelta(-3, starts(5, 8, 12))).toBe(-3);
+describe("groupMoveFloor (rigid group move)", () => {
+ it("lets the grabbed clip go as far left as the leftmost mover allows, and no further", () => {
+ expect(groupMoveFloor(at("g", 10), [at("g", 10), at("p", 1), at("q", 4)])).toBe(9);
+ expect(groupMoveFloor(at("g", 5), [at("g", 5), at("p", 8)])).toBe(0); // the grabbed clip is leftmost
});
- it("clamps a leftward delta so the leftmost member stops exactly at 0", () => {
- // Leftmost at 2 → the furthest left the group can move is -2 (that member → 0).
- // A pointer asking for -5 is clamped to -2: the grabbed clip stops with the
- // formation instead of out-running it.
- expect(clampGroupMoveDelta(-5, starts(2, 6, 10))).toBe(-2);
+ it("forbids any leftward move once a mover sits at 0", () => {
+ expect(groupMoveFloor(at("g", 3), [at("g", 3), at("p", 0)])).toBe(3);
});
- it("is bounded by the MOST-constrained (leftmost) member, not the grabbed one", () => {
- // Grabbed clip is at 10; a passenger at 1 is the constraint. Max left = -1.
- expect(clampGroupMoveDelta(-8, starts(10, 1, 4))).toBe(-1);
+ it("stops a nested mover at its host composition's start, and a lone clip at its own host", () => {
+ const nested = { ...at("p", 3), parentCompositionStart: 2 };
+ expect(groupMoveFloor(at("g", 10), [at("g", 10), nested])).toBe(9);
+ expect(groupMoveFloor(nested, [])).toBe(2);
});
+});
+
+describe("resolveGroupMovers (the clips a group drag moves)", () => {
+ const elements = [at("g", 5), at("p", 2), at("locked", 0, true), at("other", 1)];
- it("already-at-0 member forbids any leftward move", () => {
- expect(clampGroupMoveDelta(-4, starts(0, 3, 7))).toBe(0);
- // rightward still allowed
- expect(clampGroupMoveDelta(2, starts(0, 3, 7))).toBe(2);
+ it("is every selected clip that can move, never a locked one or an unselected one", () => {
+ const movers = resolveGroupMovers(elements, new Set(["g", "p", "locked"]), "g");
+ expect(movers?.map((e) => e.id)).toEqual(["g", "p"]);
});
- it("returns the raw delta for an empty formation", () => {
- expect(clampGroupMoveDelta(-9, starts())).toBe(-9);
+ it("is null when the grabbed clip is not part of a multi-selection", () => {
+ expect(resolveGroupMovers(elements, new Set(["g"]), "g")).toBeNull();
+ expect(resolveGroupMovers(elements, new Set(["p", "other"]), "g")).toBeNull();
+ expect(resolveGroupMovers(elements, undefined, "g")).toBeNull();
});
});
diff --git a/packages/studio/src/player/components/timelineMultiDragPreview.ts b/packages/studio/src/player/components/timelineMultiDragPreview.ts
index 43fa740981..80f8bf1ab7 100644
--- a/packages/studio/src/player/components/timelineMultiDragPreview.ts
+++ b/packages/studio/src/player/components/timelineMultiDragPreview.ts
@@ -1,3 +1,7 @@
+import type { TimelineElement } from "../store/playerStore";
+import { clampToHostStart } from "../store/timelineElement";
+import { canMoveTimelineElement } from "./timelineAuthoredMoveTarget";
+
/**
* Pure geometry for the LIVE multi-selection drag preview.
*
@@ -9,11 +13,11 @@
* behind individually — the whole formation moves by one delta, spacing locked.
*
* That single delta is the GRABBED clip's `draggedPreviewStart − draggedOriginStart`.
- * The preview start is ALREADY group-clamped upstream (updateDraggedClipPreview
- * runs clampGroupMoveDelta before setting it), so this delta is the clamped delta:
+ * The preview start is ALREADY group-clamped upstream (computeDragPreview floors it
+ * at groupMoveFloor), so this delta is the clamped delta:
* the instant any member would cross 0 the grabbed clip stops and every passenger
* stops with it — the formation never deforms. On DROP the commit shifts every
- * selected clip by this same delta (see timelineClipDragCommit / useTimelineClipDrag).
+ * moving clip (resolveGroupMovers) by this same delta (see timelineClipDragCommit).
*
* Track changes apply to the grabbed clip only (mirroring the commit); passengers
* keep their lanes, so only their x moves.
@@ -81,29 +85,23 @@ export function multiDragPassengerOffsetPx(
return multiDragDeltaSeconds(input) * pps;
}
-/**
- * Clamp a group move so the WHOLE selection moves as ONE rigid formation.
- *
- * The grabbed clip proposes a raw delta (its desired preview start minus its
- * origin start, after its own snapping). Applied naively, a passenger could be
- * pushed below 0 (or past any other member bound), and the commit's per-clip
- * `Math.max(0, …)` would then deform the formation — the grabbed clip out-runs
- * the group while a passenger sticks at the wall. This ports main's model
- * (useTimelineClipGroupDrag / clampTimelineGroupMoveDelta): the applied delta is
- * bounded by the MOST-CONSTRAINED member, so the grabbed clip STOPS the instant
- * any member hits 0 and the formation never deforms.
- *
- * `memberStarts` are the pre-drag starts of every selected clip (the grabbed clip
- * included). Only the lower bound (start ≥ 0) constrains a move; the timeline has
- * no fixed right wall (the composition grows on commit).
- */
-export function clampGroupMoveDelta(
- rawDelta: number,
- members: readonly { start: number; minStart?: number }[],
+/** The selected clips a group drag moves: a locked clip swept into the selection stays put.
+ * Null when the grabbed clip is not part of a multi-selection. */
+export function resolveGroupMovers(
+ elements: readonly TimelineElement[],
+ selectedKeys: ReadonlySet<string> | null | undefined,
+ dragKey: string,
+): TimelineElement[] | null {
+ if (!selectedKeys || selectedKeys.size <= 1 || !selectedKeys.has(dragKey)) return null;
+ return elements.filter((e) => selectedKeys.has(e.key ?? e.id) && canMoveTimelineElement(e));
+}
+
+/** The lowest start the grabbed clip may take so the whole group moves rigidly and no clip
+ * crosses its own floor, its host composition's start (the commit floors each one there). */
+export function groupMoveFloor(
+ grabbed: TimelineElement,
+ movers: readonly TimelineElement[],
): number {
- if (members.length === 0) return rawDelta;
- // The member nearest its own floor bounds the move: delta ≥ -(start - minStart) for each.
- const room = Math.min(...members.map((m) => m.start - (m.minStart ?? 0)));
- const minDelta = room === 0 ? 0 : -room; // avoid -0
- return rawDelta < minDelta ? minDelta : rawDelta;
+ const room = Math.min(...[grabbed, ...movers].map((e) => e.start - clampToHostStart(e, 0)));
+ return grabbed.start - room;
}
diff --git a/packages/studio/src/player/components/timelineProviderStateBuilders.ts b/packages/studio/src/player/components/timelineProviderStateBuilders.ts
index 5228bd7efa..3930848cd1 100644
--- a/packages/studio/src/player/components/timelineProviderStateBuilders.ts
+++ b/packages/studio/src/player/components/timelineProviderStateBuilders.ts
@@ -5,23 +5,26 @@ import type {
} from "./TimelineProvider";
import type { ResizingClipState } from "./useTimelineClipDrag";
import type { DraggedClipState } from "./timelineClipDragTypes";
-import type { MultiDragPreviewInput } from "./timelineMultiDragPreview";
+import { resolveGroupMovers, type MultiDragPreviewInput } from "./timelineMultiDragPreview";
import { getTimelineElementIdentity } from "../lib/timelineElementHelpers";
+import type { TimelineElement } from "../store/playerStore";
export function resolveMultiDragPreview(
draggedClip: DraggedClipState | null,
selectedKeys: ReadonlySet<string>,
+ elements: readonly TimelineElement[],
): MultiDragPreviewInput | null {
- // The dragged clip is a free ghost; selected companions follow the same
- // clamped delta so the formation stays rigid at the lane boundary.
+ // The dragged clip is a free ghost; the clips that move with it follow the same
+ // clamped delta so the formation stays rigid. A locked selected clip stays put.
if (!draggedClip?.started) return null;
const draggedKey = getTimelineElementIdentity(draggedClip.element);
+ const movers = resolveGroupMovers(elements, selectedKeys, draggedKey);
return {
dragStarted: true,
draggedKey,
draggedOriginStart: draggedClip.element.start,
draggedPreviewStart: draggedClip.previewStart,
- selectedKeys,
+ selectedKeys: movers ? new Set(movers.map(getTimelineElementIdentity)) : selectedKeys,
};
}
diff --git a/packages/studio/src/player/components/timelineShellMeta.tsx b/packages/studio/src/player/components/timelineShellMeta.tsx
new file mode 100644
index 0000000000..fb8a6677ec
--- /dev/null
+++ b/packages/studio/src/player/components/timelineShellMeta.tsx
@@ -0,0 +1,99 @@
+import type { MutableRefObject, PointerEvent } from "react";
+import type {
+ TimelineContainerProps,
+ TimelineMeta,
+ TimelineViewportProps,
+} from "./TimelineProvider";
+import {
+ buildTimelineMeta,
+ shouldIgnoreTimelinePointerDown,
+} from "./timelineProviderStateBuilders";
+import { TimelineRazorGuideOverlay } from "./TimelineRazorInteraction";
+import { LABEL_COL_W } from "./timelineLayout";
+import type { TimelineTheme } from "./timelineTheme";
+
+type ViewportHandlers = Pick<
+ TimelineViewportProps,
+ "onDragOver" | "onDragLeave" | "onDrop" | "onPointerMove" | "onPointerUp" | "onPointerCancel"
+>;
+
+export interface TimelineShellMetaInputs {
+ isDragOver: boolean;
+ hasFileDrop: boolean;
+ drop: Pick<ViewportHandlers, "onDragOver" | "onDragLeave" | "onDrop">;
+ pointer: Pick<ViewportHandlers, "onPointerMove" | "onPointerUp" | "onPointerCancel"> & {
+ onPointerDown: TimelineViewportProps["onPointerDown"];
+ };
+ setContainerRef: TimelineContainerProps["ref"];
+ setScrollRef: TimelineViewportProps["ref"];
+ focusProps: Pick<TimelineViewportProps, "onFocus" | "onBlur">;
+ elementCount: number;
+ activeTool: string;
+ shiftHeld: boolean;
+ labelMode: boolean;
+ contentOrigin: number;
+ zoomMode: "fit" | "manual";
+ theme: Pick<TimelineTheme, "shellBackground" | "shellBorder">;
+ razor: {
+ razorGuideX: number | null;
+ updateRazorGuide: TimelineContainerProps["onMouseMove"];
+ clearRazorGuide: () => void;
+ splitAllAtPointer: (event: PointerEvent<HTMLDivElement>) => boolean;
+ };
+ lastScrollLeftRef: MutableRefObject<number>;
+ recordTimelineScroll: (scroll: HTMLDivElement) => void;
+ syncScrollViewport: (scroll: HTMLDivElement, isScrolling?: boolean) => void;
+}
+
+/** The timeline shell's container and scroll viewport props: drop, pointer, scroll and razor wiring. */
+export function buildTimelineShellMeta(input: TimelineShellMetaInputs): TimelineMeta {
+ const { drop, pointer, razor, theme, activeTool } = input;
+ return buildTimelineMeta({
+ emptyState: { isDragOver: input.isDragOver, onFileDrop: input.hasFileDrop, ...drop },
+ container: {
+ ref: input.setContainerRef,
+ "aria-label": "Timeline track view",
+ "data-timeline-element-count": input.elementCount,
+ isDragOver: input.isDragOver,
+ activeTool,
+ shiftHeld: input.shiftHeld,
+ accentClass: "ring-1 ring-inset ring-studio-accent/60",
+ onMouseMove: razor.updateRazorGuide,
+ onMouseLeave: razor.clearRazorGuide,
+ style: {
+ touchAction: "pan-x pan-y",
+ background: theme.shellBackground,
+ borderColor: theme.shellBorder,
+ },
+ },
+ viewport: {
+ ref: input.setScrollRef,
+ tabIndex: -1,
+ labelMode: input.labelMode,
+ contentOrigin: input.contentOrigin,
+ zoomMode: input.zoomMode,
+ onScroll: (e) => {
+ input.lastScrollLeftRef.current = e.currentTarget.scrollLeft;
+ input.recordTimelineScroll(e.currentTarget);
+ input.syncScrollViewport(e.currentTarget, true);
+ },
+ ...input.focusProps,
+ ...drop,
+ onPointerDown: (e) => {
+ if (shouldIgnoreTimelinePointerDown(e.target)) return;
+ if (razor.splitAllAtPointer(e)) return;
+ pointer.onPointerDown(e);
+ },
+ onPointerMove: pointer.onPointerMove,
+ onPointerUp: pointer.onPointerUp,
+ onPointerCancel: pointer.onPointerCancel,
+ onLostPointerCapture: pointer.onPointerCancel,
+ },
+ elementCount: input.elementCount,
+ labelColumnWidth: LABEL_COL_W,
+ razorGuide:
+ activeTool === "razor" && razor.razorGuideX !== null ? (
+ <TimelineRazorGuideOverlay x={razor.razorGuideX} />
+ ) : null,
+ });
+}
diff --git a/packages/studio/src/player/components/useTimelineDragPreviewState.ts b/packages/studio/src/player/components/useTimelineDragPreviewState.ts
new file mode 100644
index 0000000000..daf82fc091
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineDragPreviewState.ts
@@ -0,0 +1,34 @@
+import { useCallback, useMemo } from "react";
+import type { TimelineElement } from "../store/playerStore";
+import type { DraggedClipState } from "./timelineClipDragTypes";
+import type { ResizingClipState } from "./useTimelineClipDrag";
+import {
+ resolveMultiDragPreview,
+ resolveResizingElementIds,
+} from "./timelineProviderStateBuilders";
+import { getTimelinePreviewElement } from "./timelineViewModel";
+import { resolveSnapGuide } from "./timelineSnapping";
+
+/** What the lanes draw for a live move or trim: the ghost, the clips riding along, the snap guide. */
+export function useTimelineDragPreviewState(
+ draggedClip: DraggedClipState | null,
+ resizingClip: ResizingClipState | null,
+ selectedElementIds: ReadonlySet<string>,
+ timelineElements: readonly TimelineElement[],
+) {
+ const getPreviewElement = useCallback(
+ (element: TimelineElement): TimelineElement => getTimelinePreviewElement(element, resizingClip),
+ [resizingClip],
+ );
+ const multiDragPreview = useMemo(
+ () => resolveMultiDragPreview(draggedClip, selectedElementIds, timelineElements),
+ [draggedClip, selectedElementIds, timelineElements],
+ );
+ return {
+ resizingElementIds: resolveResizingElementIds(resizingClip),
+ getPreviewElement,
+ draggedElement: draggedClip?.element ?? null,
+ multiDragPreview,
+ snapGuide: resolveSnapGuide(draggedClip, resizingClip),
+ };
+}
diff --git a/packages/studio/src/player/components/useTimelineProviderState.tsx b/packages/studio/src/player/components/useTimelineProviderState.tsx
index e02696b3c7..fb865d1636 100644
--- a/packages/studio/src/player/components/useTimelineProviderState.tsx
+++ b/packages/studio/src/player/components/useTimelineProviderState.tsx
@@ -1,6 +1,6 @@
import { useRef, useMemo, useCallback, useState } from "react";
import { useAdjustedBeatAnalysis, useMusicBeatAnalysis } from "../../hooks/useMusicBeatAnalysis";
-import { usePlayerStore, type TimelineElement } from "../store/playerStore";
+import { usePlayerStore } from "../store/playerStore";
import { defaultTimelineTheme } from "./timelineTheme";
import { useTimelinePlayhead } from "./useTimelinePlayhead";
import { useTimelineZoom } from "./useTimelineZoom";
@@ -8,18 +8,14 @@ import { useTimelineAssetDrop } from "./timelineDragDrop";
import { type KeyframeDiamondContextMenuState } from "./KeyframeDiamondContextMenu";
import { useTimelineClipDrag } from "./useTimelineClipDrag";
import type { ClipContextMenuState, TimelineContextValue } from "./TimelineProvider";
-import {
- buildTimelineMeta,
- resolveMultiDragPreview,
- resolveResizingElementIds,
- shouldIgnoreTimelinePointerDown,
-} from "./timelineProviderStateBuilders";
+import { buildTimelineShellMeta } from "./timelineShellMeta";
+import { useTimelineDragPreviewState } from "./useTimelineDragPreviewState";
import { useTimelineOverlaysState } from "./useTimelineOverlaysState";
import { useTimelineEditPinning } from "./useTimelineEditPinning";
import { useTimelineStackingSync } from "./useTimelineStackingSync";
import { useTimelineGeometry } from "./useTimelineGeometry";
import { useAutoExpandKeyframedClips } from "./useAutoExpandKeyframedClips";
-import { GUTTER, LABEL_COL_W } from "./timelineLayout";
+import { GUTTER } from "./timelineLayout";
import { useTimelineLabelColumn } from "./useTimelineLabelColumn";
import { useTimelineKeyframeData } from "./useTimelineKeyframeData";
import { useTimelineScrollViewport } from "./useTimelineScrollViewport";
@@ -33,9 +29,9 @@ import {
} from "./useTimelineTrackLayout";
import { useTimelineKeyframeHandlers } from "./useTimelineKeyframeHandlers";
import { useTimelineGapHighlights } from "./useTimelineGapHighlights";
-import { TimelineRazorGuideOverlay, useTimelineRazorInteraction } from "./TimelineRazorInteraction";
+import { useTimelineRazorInteraction } from "./TimelineRazorInteraction";
import { useTimelinePerformanceTelemetry } from "./useTimelinePerformanceTelemetry";
-import { getEffectiveTimelineDuration, getTimelinePreviewElement } from "./timelineViewModel";
+import { getEffectiveTimelineDuration } from "./timelineViewModel";
import { useTimelineShiftModifier } from "./useTimelineShiftModifier";
import { useTimelineTicks } from "./useTimelineTicks";
import { getTimelineElementIdentity } from "../lib/timelineElementHelpers";
@@ -44,7 +40,6 @@ import { useTimelineActiveClips } from "./useTimelineActiveClips";
import { useTimelineLaneMoveRefresh } from "./useTimelineLaneMoveRefresh";
import { useTimelineLogicalFocus } from "./useTimelineLogicalFocus";
import { useTimelineEditContextOptional } from "../../contexts/TimelineEditContext";
-import { resolveSnapGuide } from "./timelineSnapping";
export function useTimelineProviderState({
onSeek,
onDrillDown,
@@ -222,7 +217,8 @@ export function useTimelineProviderState({
sessionEpoch,
});
const displayLayout = useTimelineDisplayLayout(draggedClip, trackOrder, rowGeometry);
- const resizingElementIds = resolveResizingElementIds(resizingClip);
+ const { resizingElementIds, getPreviewElement, draggedElement, multiDragPreview, snapGuide } =
+ useTimelineDragPreviewState(draggedClip, resizingClip, selectedElementIds, timelineElements);
const { recordTimelineScroll } = useTimelinePerformanceTelemetry({
totalClipCount: timelineElements.length,
totalRowCount: displayLayout.displayTrackOrder.length,
@@ -421,12 +417,6 @@ export function useTimelineProviderState({
timeDisplayMode,
timelineFocus.rowVirtualizationActive ? renderTimeRange : undefined,
);
- const getPreviewElement = useCallback(
- (element: TimelineElement): TimelineElement => getTimelinePreviewElement(element, resizingClip),
- [resizingClip],
- );
- const draggedElement = draggedClip?.element ?? null;
- const multiDragPreview = resolveMultiDragPreview(draggedClip, selectedElementIds);
const canvasProps = {
major,
minor,
@@ -501,7 +491,7 @@ export function useTimelineProviderState({
onMoveElement,
beatDragging,
draggedElement,
- snapGuide: resolveSnapGuide(draggedClip, resizingClip),
+ snapGuide,
multiDragPreview,
onToggleTrackHidden: editContext.onToggleTrackHidden,
onTogglePropertyGroupKeyframe: editContext.onTogglePropertyGroupKeyframe,
@@ -519,61 +509,34 @@ export function useTimelineProviderState({
)),
[holdNewClipContent, renderClipContent],
);
- const timelineMeta = buildTimelineMeta({
- emptyState: {
- isDragOver: assetDrop.isDragOver,
- onFileDrop: !!onFileDrop,
+ const timelineMeta = buildTimelineShellMeta({
+ isDragOver: assetDrop.isDragOver,
+ hasFileDrop: !!onFileDrop,
+ drop: {
onDragOver: assetDrop.handleAssetDragOver,
onDragLeave: assetDrop.handleAssetDragLeave,
onDrop: assetDrop.handleAssetDrop,
},
- container: {
- ref: setContainerRef,
- "aria-label": "Timeline track view",
- "data-timeline-element-count": timelineElements.length,
- isDragOver: assetDrop.isDragOver,
- activeTool,
- shiftHeld,
- accentClass: "ring-1 ring-inset ring-studio-accent/60",
- onMouseMove: updateRazorGuide,
- onMouseLeave: clearRazorGuide,
- style: {
- touchAction: "pan-x pan-y",
- background: theme.shellBackground,
- borderColor: theme.shellBorder,
- },
- },
- viewport: {
- ref: setScrollRef,
- tabIndex: -1,
- labelMode,
- contentOrigin,
- zoomMode,
- onScroll: (e) => {
- lastScrollLeftRef.current = e.currentTarget.scrollLeft;
- recordTimelineScroll(e.currentTarget);
- syncScrollViewport(e.currentTarget, true);
- },
- ...timelineFocus.timelineFocusProps,
- onDragOver: assetDrop.handleAssetDragOver,
- onDragLeave: assetDrop.handleAssetDragLeave,
- onDrop: assetDrop.handleAssetDrop,
- onPointerDown: (e) => {
- if (shouldIgnoreTimelinePointerDown(e.target)) return;
- if (splitAllAtPointer(e)) return;
- handlePointerDown(e);
- },
+ pointer: {
+ onPointerDown: handlePointerDown,
onPointerMove: handlePointerMove,
onPointerUp: handlePointerUp,
onPointerCancel: handlePointerCancel,
- onLostPointerCapture: handlePointerCancel,
},
+ setContainerRef,
+ setScrollRef,
+ focusProps: timelineFocus.timelineFocusProps,
elementCount: timelineElements.length,
- labelColumnWidth: LABEL_COL_W,
- razorGuide:
- activeTool === "razor" && razorGuideX !== null ? (
- <TimelineRazorGuideOverlay x={razorGuideX} />
- ) : null,
+ activeTool,
+ shiftHeld,
+ labelMode,
+ contentOrigin,
+ zoomMode,
+ theme,
+ razor: { razorGuideX, updateRazorGuide, clearRazorGuide, splitAllAtPointer },
+ lastScrollLeftRef,
+ recordTimelineScroll,
+ syncScrollViewport,
});
const contextValue: TimelineContextValue = {
state: {
diff --git a/packages/studio/src/utils/timelineDropTrackInsert.test.ts b/packages/studio/src/utils/timelineDropTrackInsert.test.ts
index d8bea4ee83..874d77b684 100644
--- a/packages/studio/src/utils/timelineDropTrackInsert.test.ts
+++ b/packages/studio/src/utils/timelineDropTrackInsert.test.ts
@@ -99,6 +99,54 @@ describe("applyTrackRenumbers", () => {
});
describe("resolveDropTrack", () => {
+ // Title shows on row 0; Music is written on track 0 too but shows on audio row 1.
+ const shown = (
+ id: string,
+ tag: string,
+ row: number,
+ track: number,
+ start: number,
+ length: number,
+ ) => ({
+ ...clip(id, row, start),
+ tag,
+ duration: length,
+ authoredTrack: track,
+ });
+ const title = shown("title", "div", 0, 0, 0, 10);
+ const music = shown("music", "audio", 1, 0, 2, 3);
+ const song = { id: "song", tag: "audio", start: 2, duration: 3 };
+ const drop = (elements: TimelineElement[], row: number, dropped = song) =>
+ resolveDropTrack({ source, elements, placement: { track: row }, dropped });
+
+ it("joins an audio row's file track at the nearest free time, not a new track", () => {
+ expect(drop([title, music], 1)).toMatchObject({ track: 0, start: 5 });
+ });
+
+ it("keeps an audio file dropped on a visual row off the audio clip on the track it is written to", () => {
+ expect(drop([title, music], 0)).toMatchObject({ track: 0, start: 5 });
+ });
+
+ it("writes a drop on a shown row to that row's file track and checks the clips there", () => {
+ const top = shown("top", "div", 0, 0, 0, 4);
+ const lower = shown("lower", "div", 1, 2, 0, 4); // file track 2, shown as row 1
+ const image = { id: "image", tag: "img", start: 1, duration: 3 };
+ expect(drop([top, lower], 1, image)).toMatchObject({ track: 2, start: 4 });
+ });
+
+ it("lets only clips of the dropped file's kind block it on the row", () => {
+ const title = clip("title", 0, 0);
+ const music = { ...clip("music", 0, 0), tag: "audio" };
+ const song = { id: "song", tag: "audio", start: 1, duration: 3 };
+ // An audio file shows in the audio rows wherever it is written, so a visual clip never blocks it.
+ expect(
+ resolveDropTrack({ source, elements: [title], placement: { track: 0 }, dropped: song }).start,
+ ).toBe(1);
+ expect(
+ resolveDropTrack({ source, elements: [music], placement: { track: 0 }, dropped: song }).start,
+ ).toBe(2);
+ });
+
it("keeps the aimed lane and the source when no insert is asked for", () => {
const out = resolveDropTrack({
source,
@@ -106,7 +154,17 @@ describe("resolveDropTrack", () => {
placement: { track: 2 },
dropped,
});
- expect(out).toEqual({ source, track: 2 });
+ expect(out).toEqual({ source, track: 2, start: 5 });
+ });
+
+ it("moves a drop on an occupied row to that row's nearest free time, with no new track", () => {
+ const out = resolveDropTrack({
+ source,
+ elements,
+ placement: { track: 1 },
+ dropped: { ...dropped, start: 1 },
+ });
+ expect(out).toEqual({ source, track: 1, start: 2 });
});
it("returns the new lane and the source with the lanes below pushed down", () => {
@@ -117,6 +175,7 @@ describe("resolveDropTrack", () => {
dropped,
});
expect(out.track).toBe(1);
+ expect(out.start).toBe(5);
expect(out.source).toContain('id="b" data-start="0" data-track-index="2"');
});
diff --git a/packages/studio/src/utils/timelineDropTrackInsert.ts b/packages/studio/src/utils/timelineDropTrackInsert.ts
index ed2cc2bfc3..f47532a3ff 100644
--- a/packages/studio/src/utils/timelineDropTrackInsert.ts
+++ b/packages/studio/src/utils/timelineDropTrackInsert.ts
@@ -1,6 +1,9 @@
import type { TimelineElement } from "../player";
import { layoutAfterTrackInsert } from "../player/components/timelineDragLanding";
import { canMoveTimelineElement } from "../player/components/timelineAuthoredMoveTarget";
+import { resolveNearestFreeStart } from "../player/components/timelineCollision";
+import { authoredTrackForLane } from "../player/components/timelineAuthoredTrack";
+import { isAudioTimelineElement } from "./timelineInspector";
import type { TimelineDropPlacement } from "../player/components/timelineCallbacks";
import { applyPatchByTarget, readAttributeByTarget } from "./sourcePatcher";
import { buildPatchTarget } from "../hooks/timelineEditingHelpers";
@@ -67,17 +70,45 @@ export function applyTrackRenumbers(source: string, plan: DropTrackInsertPlan):
return out;
}
-/** The lane a dropped clip is written on and the source with any lanes pushed down to make room. */
+type DroppedClip = Pick<TimelineElement, "id" | "tag" | "start" | "duration">;
+
+/** The file track a drop on display row `lane` is written to, and its nearest free start there.
+ * The timeline's own clips decide the track; `placed` clips only block, like same-kind clips there. */
+function resolveRowDrop(
+ elements: TimelineElement[],
+ placed: readonly TimelineElement[],
+ lane: number,
+ dropped: DroppedClip,
+): { track: number; start: number } {
+ const audio = isAudioTimelineElement(dropped);
+ const row = elements.filter((e) => e.track === lane);
+ const otherKindRow = row.length > 0 && !row.some((e) => isAudioTimelineElement(e) === audio);
+ const asClip = { ...dropped, key: dropped.id, track: lane, sourceFile: elements[0]?.sourceFile };
+ const track = otherKindRow ? lane : authoredTrackForLane(lane, elements, asClip);
+ const onTrack = [...elements, ...placed]
+ .filter((e) => isAudioTimelineElement(e) === audio && (e.authoredTrack ?? e.track) === track)
+ .map((e) => ({ ...e, track }));
+ return {
+ track,
+ start: resolveNearestFreeStart(onTrack, track, dropped.start, dropped.duration, null),
+ };
+}
+
+/** Where a dropped clip is written: the aimed row's file track at its nearest free time, or a new track. */
export function resolveDropTrack(input: {
source: string;
elements: TimelineElement[];
+ /** Clips this drop gesture already wrote, which `elements` does not hold yet. */
+ placed?: readonly TimelineElement[];
placement: TimelineDropPlacement;
- dropped: Pick<TimelineElement, "id" | "tag" | "start" | "duration">;
-}): { source: string; track: number } {
+ dropped: DroppedClip;
+}): { source: string; track: number; start: number } {
const { source, elements, placement, dropped } = input;
- if (placement.insertRow == null) return { source, track: placement.track };
+ if (placement.insertRow == null) {
+ return { source, ...resolveRowDrop(elements, input.placed ?? [], placement.track, dropped) };
+ }
const { insertRow, trackOrder } = placement;
const plan = planDropTrackInsert({ elements, trackOrder, insertRow, dropped });
if (!plan) throw new Error("Cannot open a new track here: a locked clip would have to move.");
- return { source: applyTrackRenumbers(source, plan), track: plan.track };
+ return { source: applyTrackRenumbers(source, plan), track: plan.track, start: dropped.start };
}