Skip to content

Write HTML. Render video. Built for agents.

feat(studio): the first clip on an empty main track starts at 0 (#4099)

Miguel Ángel707f9a44c352
diff --git a/packages/studio/src/player/components/timelineClipDragCommit.test.ts b/packages/studio/src/player/components/timelineClipDragCommit.test.ts
index d0c465c93e..eb87017be5 100644
--- a/packages/studio/src/player/components/timelineClipDragCommit.test.ts
+++ b/packages/studio/src/player/components/timelineClipDragCommit.test.ts
@@ -1223,6 +1223,120 @@ describe("commitDraggedClipMove", () => {
expect(onStackingPatches).not.toHaveBeenCalled();
});
});
+
+ 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.
+ 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);
+ });
+
+ it("a plain lane change onto the empty main track snaps its committed start to 0", () => {
+ 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 });
+ });
+
+ 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", () => {
+ const oldMain = el("old", 0, 0, 3);
+ const dragged = el("v1", 2, 0, 5);
+ const { onMoveElements } = runClipMove(
+ drag(dragged, { previewStart: 8, previewTrack: 2, insertRow: 0 }),
+ { elements: [oldMain, dragged], trackOrder: [0, 2] },
+ );
+ const map = editMap(onMoveElements.mock.calls[0][0]);
+ expect(map.old.track).toBe(1);
+ expect(map.v1).toEqual({ start: 0, track: 0 });
+ });
+
+ it("an expanded child dragged with its host commits the HOST at 0", () => {
+ for (const [hostStart, childStart] of [
+ [30, 32],
+ [20, 22],
+ ]) {
+ const host = el("host", 1, hostStart, 10);
+ const child: TimelineElement = {
+ ...el("child", 2, childStart, 4),
+ expandedHostKey: "host",
+ expandedParentStart: hostStart,
+ };
+ const { onMoveElements } = runClipMove(
+ drag(child, { previewStart: childStart, previewTrack: 0 }),
+ {
+ elements: [host, child],
+ trackOrder: [0, 1, 2],
+ selectedKeys: new Set(["host", "child"]),
+ },
+ );
+ expect(editMap(onMoveElements.mock.calls[0][0]).host).toEqual({ start: 0, track: 0 });
+ }
+ });
+
+ it("a multi-selection top-gutter insert does NOT snap (siblings key off the unsnapped start)", () => {
+ const dragged = el("v1", 1, 0, 5);
+ const sibling = el("v2", 1, 10, 5);
+ const elements = [dragged, sibling];
+ const { onMoveElements } = runClipMove(
+ drag(dragged, { previewStart: 8, previewTrack: 1, insertRow: 0 }),
+ { 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
+ });
+ });
});
describe("commitZMirrorLaneMove", () => {
diff --git a/packages/studio/src/player/components/timelineClipDragCommit.ts b/packages/studio/src/player/components/timelineClipDragCommit.ts
index 7a28f8f164..30aea90075 100644
--- a/packages/studio/src/player/components/timelineClipDragCommit.ts
+++ b/packages/studio/src/player/components/timelineClipDragCommit.ts
@@ -3,7 +3,8 @@ import type { DraggedClipState } from "./useTimelineClipDrag";
// Type-only: erased at runtime, so the timelineZMirror → timelineClipDragCommit
// value-import edge stays acyclic.
import type { ZMirrorLaneMove } from "./timelineZMirror";
-import { classifyZone, normalizeToZones } from "./timelineZones";
+import { classifyZone } from "./timelineZones";
+import { layoutAfterTrackInsert, resolveDragLandingStart } from "./timelineDragLanding";
import { computeStackingPatches, type StackingPatch } from "./timelineStackingSync";
import {
canMoveTimelineElement as canMoveElement,
@@ -16,7 +17,7 @@ import {
} from "./timelineOptimisticRevision";
import { runLaneZGesture } from "../../components/nle/zLaneGesture";
import { refreshAfterDurableLaneMove } from "./timelineLaneMoveRefresh";
-import { authoredTrackForLane, sameSourceFile } from "./timelineAuthoredTrack";
+import { authoredTrackForLane } from "./timelineAuthoredTrack";
type StartTrack = Pick<TimelineElement, "start" | "track">;
export interface TimelineMoveEdit {
@@ -172,19 +173,6 @@ export function persistMoveEdits(
);
}
-/**
- * A fractional track value for a NEW lane inserted at boundary `insertRow` in
- * `trackOrder` (0 = above the top, `length` = below the bottom). normalizeToZones
- * then compacts it to a distinct integer lane between its neighbours, and the
- * clips at/below the insert shift down by one — the sanctioned index-renumber.
- */
-function insertTrackValue(trackOrder: number[], insertRow: number): number {
- if (trackOrder.length === 0) return 0;
- if (insertRow <= 0) return trackOrder[0] - 0.5;
- if (insertRow >= trackOrder.length) return trackOrder[trackOrder.length - 1] + 0.5;
- return (trackOrder[insertRow - 1] + trackOrder[insertRow]) / 2;
-}
-
/**
* Build the time-shift resolver for a multi-selection drag: every member of the
* selection moves by the dragged clip's delta (clamped ≥ 0); non-members are
@@ -231,7 +219,8 @@ function resolveMultiSelection(
* permitted multi-clip write) via a whole-set re-normalize; persisted atomically.
*/
// fallow-ignore-next-line complexity
-export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDeps): void {
+export function commitDraggedClipMove(rawDrag: DraggedClipState, deps: DragCommitDeps): void {
+ const drag = { ...rawDrag, previewStart: resolveDragLandingStart(rawDrag, deps) };
const hostAlias = resolveExpandedHostAlias(drag, deps);
if (hostAlias) {
commitDraggedClipMove(hostAlias.drag, { ...deps, selectedKeys: hostAlias.selectedKeys });
@@ -353,36 +342,11 @@ function buildTrackInsertEdits(
} | null,
deps: DragCommitDeps,
): { candidate: TimelineElement[]; edits: TimelineMoveEdit[] } | null {
- const { elements, trackOrder } = deps;
+ const { elements } = deps;
const editKey = keyOf(element);
- // Expanded-child rows are synthetic host lanes, not source-file topology.
- if (element.expandedParentStart != null) return null;
- const targetTrack = insertTrackValue(trackOrder, insertRow);
- const candidate = elements.map((e) => {
- if (keyOf(e) === editKey) return { ...e, start: previewStart, track: targetTrack };
- if (multi?.keys.has(keyOf(e))) return { ...e, start: multi.movedStart(e) };
- return e;
- });
- // Foreign display rows and the opposite zone must not affect this topology.
- const writableZone = classifyZone(element);
- const writable = (src: TimelineElement): boolean =>
- sameSourceFile(src, element) &&
- classifyZone(src) === writableZone &&
- src.expandedParentStart == null;
- const topologyOrder = [...new Set(elements.filter(writable).map((e) => e.track))].sort(
- (a, b) => a - b,
- );
- const topologyInsertRow = topologyOrder.filter((track) => track < targetTrack).length;
- const topologyTargetTrack = insertTrackValue(topologyOrder, topologyInsertRow);
- const normalized = normalizeToZones(
- elements.filter(writable).map((e) => {
- if (keyOf(e) === editKey) {
- return { ...e, start: previewStart, track: topologyTargetTrack };
- }
- if (multi?.keys.has(keyOf(e))) return { ...e, start: multi.movedStart(e) };
- return e;
- }),
- );
+ const layout = layoutAfterTrackInsert(element, previewStart, insertRow, multi, deps);
+ if (!layout) return null;
+ const { normalized, targetTrack, writable } = layout;
const bySrc = new Map(elements.map((e) => [keyOf(e), e]));
// A partial zone renumber creates collisions; refuse a shifted locked row.
for (const norm of normalized) {
@@ -399,6 +363,11 @@ function buildTrackInsertEdits(
return null;
}
}
+ const candidate = elements.map((e) => {
+ if (keyOf(e) === editKey) return { ...e, start: previewStart, track: targetTrack };
+ if (multi?.keys.has(keyOf(e))) return { ...e, start: multi.movedStart(e) };
+ return e;
+ });
const edits: TimelineMoveEdit[] = [];
if (multi) {
for (const src of elements) {
@@ -415,10 +384,10 @@ function buildTrackInsertEdits(
for (const norm of normalized) {
const src = bySrc.get(keyOf(norm));
if (!src || !canMoveElement(src)) continue;
- const start =
- keyOf(norm) === editKey || multi?.keys.has(keyOf(norm))
- ? (multi?.movedStart(src) ?? previewStart)
- : src.start;
+ const normKey = keyOf(norm);
+ let start = src.start;
+ if (normKey === editKey) start = previewStart;
+ else if (multi?.keys.has(normKey)) start = multi.movedStart(src);
edits.push({ element: src, updates: { start, track: norm.track } });
}
return { candidate, edits };
diff --git a/packages/studio/src/player/components/timelineClipDragPreview.test.ts b/packages/studio/src/player/components/timelineClipDragPreview.test.ts
index d14fb1f7bb..346770f9d0 100644
--- a/packages/studio/src/player/components/timelineClipDragPreview.test.ts
+++ b/packages/studio/src/player/components/timelineClipDragPreview.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import type { TimelineElement } from "../store/playerStore";
import {
computeDragPreview,
@@ -7,6 +7,7 @@ import {
type DragPreviewContext,
} from "./timelineClipDragPreview";
import type { DraggedClipState } from "./timelineClipDragTypes";
+import { commitDraggedClipMove } from "./timelineClipDragCommit";
import { LANE_H, RULER_H, TRACKS_TOP_PAD, TRACK_H } from "./timelineLayout";
// ─────────────────────────────────────────────────────────────────────────────
@@ -198,6 +199,72 @@ describe("computeDragPreview — plain horizontal drag never arms a phantom inse
});
});
+describe("computeDragPreview — magnetic first clip on an empty main track", () => {
+ // v-lower sits alone on lane 1; lane 0 (the main track) is empty.
+ const vLower = clip("v-lower", 1, 10, 4, 5);
+
+ // Grab v-lower mid-body on lane 1, aim at `targetRowFloat` (same x — no
+ // horizontal move), against the given sibling elements and selection.
+ function dragUpToMainTrack(
+ elements: TimelineElement[],
+ targetRowFloat = 0.5,
+ selectedKeys: ReadonlySet<string> = new Set(),
+ ) {
+ const originClientY = yForRow(1.5);
+ const drag: DraggedClipState = {
+ pointerId: 0,
+ element: vLower,
+ originClientX: 800,
+ originClientY,
+ originScrollLeft: 0,
+ originScrollTop: 0,
+ pointerClientX: 800,
+ pointerClientY: originClientY,
+ pointerOffsetX: 0,
+ pointerOffsetY: 0,
+ previewStart: vLower.start,
+ previewTrack: vLower.track,
+ insertRow: null,
+ snapTime: null,
+ snapType: null,
+ started: true,
+ };
+ return computeDragPreview(drag, 800, yForRow(targetRowFloat), {
+ ...ctx(undefined, elements),
+ trackOrder: [0, 1],
+ selectedKeys,
+ });
+ }
+
+ it("dragging straight up onto the empty main track snaps the preview start to 0", () => {
+ const next = dragUpToMainTrack([vLower]);
+ expect(next.previewTrack).toBe(0);
+ expect(next.insertRow).toBeNull();
+ expect(next.previewStart).toBe(0);
+ });
+
+ it("does not touch the start once the main track already holds a clip", () => {
+ const vMain = clip("v-main", 0, 0, 3, 5);
+ const next = dragUpToMainTrack([vLower, vMain]);
+ 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", () => {
+ const next = dragUpToMainTrack([vLower], -0.6);
+ expect(next.insertRow).toBe(0);
+ expect(next.previewStart).toBe(0);
+ });
+
+ it("does not retime the rest of a multi-selection when the 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);
+ // The grabbed clip's OWN vertical-only move must not force a horizontal
+ // shift that resolveMultiSelection would then apply to v-other.
+ expect(next.previewStart).toBe(10);
+ });
+});
+
describe("computeResizePreview — composition source continuity", () => {
it("seeds a legacy composition offset and advances it at playback rate", () => {
const element = {
@@ -254,3 +321,108 @@ describe("getTimelineDragOverlayPosition", () => {
expect(getTimelineDragOverlayPosition(drag, null)).toBeNull();
});
});
+
+describe("computeDragPreview — the ghost start is the committed start", () => {
+ function preview(
+ element: TimelineElement,
+ elements: TimelineElement[],
+ originRow: number,
+ targetRowFloat: number,
+ selectedKeys: ReadonlySet<string> = new Set(),
+ ): DraggedClipState {
+ const originClientY = yForRow(originRow + 0.5);
+ const drag: DraggedClipState = {
+ pointerId: 0,
+ element,
+ originClientX: 800,
+ originClientY,
+ originScrollLeft: 0,
+ originScrollTop: 0,
+ pointerClientX: 800,
+ pointerClientY: originClientY,
+ pointerOffsetX: 0,
+ pointerOffsetY: 0,
+ previewStart: element.start,
+ previewTrack: element.track,
+ insertRow: null,
+ snapTime: null,
+ snapType: null,
+ started: true,
+ };
+ return computeDragPreview(drag, 800, yForRow(targetRowFloat), {
+ ...ctx(undefined, elements),
+ trackOrder: [0, 1, 2],
+ selectedKeys,
+ });
+ }
+
+ function committedStart(
+ ghost: DraggedClipState,
+ committed: TimelineElement,
+ elements: TimelineElement[],
+ selectedKeys: ReadonlySet<string> = new Set(),
+ ): number | undefined {
+ const onMoveElement = vi.fn();
+ const onMoveElements = vi.fn();
+ commitDraggedClipMove(ghost, {
+ elements,
+ trackOrder: [0, 1, 2],
+ updateElement: vi.fn(),
+ onMoveElement,
+ onMoveElements,
+ selectedKeys,
+ });
+ const edits = onMoveElements.mock.calls[0]?.[0] as
+ | Array<{ element: TimelineElement; updates: { start: number } }>
+ | undefined;
+ const single = onMoveElement.mock.calls[0];
+ if (single) return single[1].start;
+ return edits?.find((e) => e.element.id === committed.id)?.updates.start;
+ }
+
+ const lower = clip("lower", 1, 10, 4, 5);
+
+ it("plain move onto the empty main track", () => {
+ const ghost = preview(lower, [lower], 1, 0.5);
+ expect(ghost.previewStart).toBe(0);
+ 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", () => {
+ 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", () => {
+ for (const [hostStart, childStart] of [
+ [30, 32],
+ [20, 22],
+ ]) {
+ const host = clip("host", 1, hostStart, 10, 5);
+ const child: TimelineElement = {
+ ...clip("child", 2, childStart, 4, 5),
+ expandedHostKey: "host",
+ expandedParentStart: hostStart,
+ };
+ const elements = [host, child];
+ 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);
+ }
+ });
+});
diff --git a/packages/studio/src/player/components/timelineClipDragPreview.ts b/packages/studio/src/player/components/timelineClipDragPreview.ts
index 935878205d..a0b2b342dd 100644
--- a/packages/studio/src/player/components/timelineClipDragPreview.ts
+++ b/packages/studio/src/player/components/timelineClipDragPreview.ts
@@ -20,6 +20,7 @@ import {
} from "./timelineGroupEditing";
import { clampGroupMoveDelta } from "./timelineMultiDragPreview";
import type { DraggedClipState, ResizingClipState } from "./timelineClipDragTypes";
+import { resolveDragLandingStart } from "./timelineDragLanding";
/** Snap-target builder closure supplied by the hook (closes over refs + store). */
type BuildSnapTargets = (
@@ -200,12 +201,18 @@ export function computeDragPreview(
nextMove.track,
ctx,
);
+ const placed = { ...drag, previewStart, previewTrack, insertRow };
+ const snappedStart = resolveDragLandingStart(placed, {
+ elements,
+ trackOrder,
+ selectedKeys,
+ });
return {
...drag,
started: true,
pointerClientX: clientX,
pointerClientY: clientY,
- previewStart,
+ previewStart: snappedStart,
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.
diff --git a/packages/studio/src/player/components/timelineCollision.test.ts b/packages/studio/src/player/components/timelineCollision.test.ts
index c4fd2548c3..328c875708 100644
--- a/packages/studio/src/player/components/timelineCollision.test.ts
+++ b/packages/studio/src/player/components/timelineCollision.test.ts
@@ -5,6 +5,7 @@ import {
isInsertAllowedForZone,
isLaneFree,
resolveInsertRow,
+ resolveMainTrackDropStart,
resolvePlacement,
resolveZoneDropPlacement,
timeRangesOverlap,
@@ -493,3 +494,25 @@ describe("resolveZoneDropPlacement (the whole drop decision, no same-track overl
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 c4f4c728e4..ab24667610 100644
--- a/packages/studio/src/player/components/timelineCollision.ts
+++ b/packages/studio/src/player/components/timelineCollision.ts
@@ -1,5 +1,6 @@
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
@@ -140,6 +141,32 @@ export function resolveZoneDropPlacement(input: {
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;
+}
+
/**
* 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
diff --git a/packages/studio/src/player/components/timelineDragLanding.ts b/packages/studio/src/player/components/timelineDragLanding.ts
new file mode 100644
index 0000000000..d463f5f4b9
--- /dev/null
+++ b/packages/studio/src/player/components/timelineDragLanding.ts
@@ -0,0 +1,108 @@
+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;
+
+/** A fractional track for a new lane at boundary `insertRow` (0 = above the top);
+ * normalizeToZones compacts it to an integer lane and shifts the clips below. */
+function insertTrackValue(trackOrder: number[], insertRow: number): number {
+ if (trackOrder.length === 0) return 0;
+ if (insertRow <= 0) return trackOrder[0] - 0.5;
+ if (insertRow >= trackOrder.length) return trackOrder[trackOrder.length - 1] + 0.5;
+ return (trackOrder[insertRow - 1] + trackOrder[insertRow]) / 2;
+}
+
+/** The source-file lane layout after inserting `element` at boundary `insertRow`:
+ * the whole-set renumber both the commit and the drag preview read. */
+export function layoutAfterTrackInsert(
+ element: TimelineElement,
+ previewStart: number,
+ insertRow: number,
+ multi: {
+ keys: ReadonlySet<string>;
+ movedStart: (e: TimelineElement) => number;
+ } | null,
+ deps: Pick<DragCommitDeps, "elements" | "trackOrder">,
+): {
+ normalized: TimelineElement[];
+ targetTrack: number;
+ writable: (src: TimelineElement) => boolean;
+} | null {
+ const { elements, trackOrder } = deps;
+ const editKey = keyOf(element);
+ // Expanded-child rows are synthetic host lanes, not source-file topology.
+ if (element.expandedParentStart != null) return null;
+ const targetTrack = insertTrackValue(trackOrder, insertRow);
+ // Foreign display rows and the opposite zone must not affect this topology.
+ const writableZone = classifyZone(element);
+ const writable = (src: TimelineElement): boolean =>
+ sameSourceFile(src, element) &&
+ classifyZone(src) === writableZone &&
+ src.expandedParentStart == null;
+ const topologyOrder = [...new Set(elements.filter(writable).map((e) => e.track))].sort(
+ (a, b) => a - b,
+ );
+ const topologyInsertRow = topologyOrder.filter((track) => track < targetTrack).length;
+ const topologyTargetTrack = insertTrackValue(topologyOrder, topologyInsertRow);
+ const normalized = normalizeToZones(
+ elements.filter(writable).map((e) => {
+ if (keyOf(e) === editKey) {
+ return { ...e, start: previewStart, track: topologyTargetTrack };
+ }
+ if (multi?.keys.has(keyOf(e))) return { ...e, start: multi.movedStart(e) };
+ return e;
+ }),
+ );
+ 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);
+}