feat(studio): dropping a clip onto main-track clips can insert it there (#8397)

* feat(studio): dropping a clip onto main-track clips can insert it there

* fix(studio): say why a dropped clip went back, from the timeline's own notice

* fix(studio): keep the drag commit file under the line cap

* fix(studio): an insert never puts a linked clip on top of another clip in its lane
This commit is contained in:
Miguel Ángel
2026-11-21 23:03:01 +00:00
committed by GitHub
parent b008e37b46
commit 08bd7fc126
12 changed files with 228 additions and 5 deletions
+4
View File
@@ -1070,6 +1070,10 @@
// useColorGradingController.ts: the hook's complexity is inherited; the sealed-preview
// status read adds no branch to it, but its import lines shift the hook's fingerprint.
"packages/studio/src/components/editor/useColorGradingController.ts",
// The timeline drag hooks' complexity is inherited; passing the drop options through
// adds no branch to them, but any edit re-flags the whole hook.
"packages/studio/src/player/components/useTimelineProviderState.tsx",
"packages/studio/src/player/components/useTimelineClipDrag.ts",
],
},
}
@@ -32,8 +32,10 @@ import { useTimelineProviderState } from "./useTimelineProviderState";
import { TimelineReadOnlyContext } from "./timelineReadOnly";
import {
TimelineEditProvider,
useTimelineEditContextOptional,
useTimelineEditContextValue,
} from "../../contexts/TimelineEditContext";
import { useStudioShellContextOptional } from "../../contexts/StudioContext";
export type TimelineCanvasState = Omit<
TimelineLaneBaseProps,
@@ -212,7 +214,11 @@ export function TimelineProvider({
}
function TimelineProviderState({ children, ...props }: TimelineProps & { children: ReactNode }) {
const value = useTimelineProviderState(props);
const shell = useStudioShellContextOptional();
const { onNotice } = useTimelineEditContextOptional();
const notice = shell?.showToast ?? onNotice;
const onDropRefused = notice && (() => notice("Clips on the same track can't overlap.", "info"));
const value = useTimelineProviderState({ ...props, onDropRefused });
return <TimelineContext.Provider value={value}>{children}</TimelineContext.Provider>;
}
@@ -50,4 +50,5 @@ export interface TimelineProps
trackPadding?: TimelineTrackPadding;
readOnly?: boolean;
onReadOnlyPress?: () => void;
insertOnClipDrop?: boolean;
}
@@ -1628,3 +1628,44 @@ describe("persistMoveEdits convergence", () => {
expect(updateElement).toHaveBeenCalledTimes(2);
});
});
describe("commitDraggedClipMove: drop onto main-track clips", () => {
const elements = [el("a", 0, 0, 2), el("b", 0, 2, 2), el("c", 0, 4, 2)];
// The full main track sends the dragged clip back to its own start.
const backHome = { ...drag(elements[2]!, { previewStart: 4, previewTrack: 0 }), aimStart: 0 };
it("inserts the clip and moves the others right when drops insert", () => {
const onDropRefused = vi.fn();
const { onMoveElements } = runClipMove(backHome, {
elements,
trackOrder: [0],
insertOnClipDrop: true,
onDropRefused,
});
const [edits] = onMoveElements.mock.calls[0] as [TimelineMoveEdit[]];
expect(editMap(edits)).toEqual({
c: { start: 0, track: 0 },
a: { start: 2, track: 0 },
b: { start: 4, track: 0 },
});
expect(onDropRefused).not.toHaveBeenCalled();
});
it("moves nothing and says why when drops do not insert", () => {
const onDropRefused = vi.fn();
const { onMoveElement, onMoveElements } = runClipMove(backHome, {
elements,
trackOrder: [0],
onDropRefused,
});
expect(onMoveElement).not.toHaveBeenCalled();
expect(onMoveElements).not.toHaveBeenCalled();
expect(onDropRefused).toHaveBeenCalledWith(elements[2]);
});
it("says nothing when the clip was put back where it was", () => {
const onDropRefused = vi.fn();
runClipMove({ ...backHome, aimStart: 4 }, { elements, trackOrder: [0], onDropRefused });
expect(onDropRefused).not.toHaveBeenCalled();
});
});
@@ -27,6 +27,7 @@ import { authoredTrackForLane } from "./timelineAuthoredTrack";
import { resolveGroupMovers } from "./timelineMultiDragPreview";
import { beginStudioPendingEdit } from "../../utils/studioPendingEdits";
import { batchElementUpdates } from "../store/batchElementUpdates";
import { resolveMainTrackInsertEdits } from "./timelineMainTrackInsert";
type StartTrack = TimelineAtomicMoveUpdates;
export interface TimelineMoveEdit extends TimelineAtomicMoveEdit {
@@ -81,12 +82,19 @@ export interface DragCommitDeps {
onStackingPatches?: (patches: StackingPatch[], coalesceKey?: string) => Promise<unknown> | void;
/** Converge the preview manifest after the complete lane + z transaction. */
refreshAfterLaneMove?: () => void;
/** A drop onto other main-track clips inserts there instead of landing in free space. */
insertOnClipDrop?: boolean;
/** The drop aimed somewhere else but the clip went back where it was. */
onDropRefused?: (element: TimelineElement) => void;
}
const keyOf = (e: TimelineElement) => e.key ?? e.id;
const round3 = (v: number) => Math.round(v * 1000) / 1000;
// One deterministic coalesce key shared by both records in a lane-change gesture.
let laneChangeGestureSeq = 0;
let clipInsertGestureSeq = 0;
// Studio saves starts to the centisecond, so a smaller aim is the clip's own place.
const REFUSED_DROP_MIN_S = 0.01;
function moveStoreUpdates(edit: TimelineMoveEdit) {
const writtenTrack =
@@ -276,8 +284,17 @@ export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDe
// ── Pure time-move (dragged clip keeps its lane, no insert) ─────────────────
if (!isInsert && !laneChanged) {
const insert = deps.insertOnClipDrop && resolveMainTrackInsertEdits(drag, deps, multi?.keys);
if (insert) {
void persistMoveEdits(insert, deps, `clip-insert:${clipInsertGestureSeq++}`);
return;
}
const delta = drag.previewStart - drag.element.start;
if (delta === 0) return;
if (delta === 0) {
const aimedAway = Math.abs((drag.aimStart ?? drag.element.start) - drag.element.start);
if (aimedAway >= REFUSED_DROP_MIN_S) deps.onDropRefused?.(drag.element);
return;
}
if (multi) {
const edits: TimelineMoveEdit[] = elements
.filter((e) => multi.keys.has(keyOf(e)))
@@ -80,6 +80,7 @@ interface TimelineClipDragGestureLifecycleInput {
((patches: StackingPatch[]) => Promise<unknown> | void) | undefined
>;
refreshAfterLaneMoveRef: RefObject<(() => void) | undefined>;
dropOptionsRef?: RefObject<Pick<DragCommitDeps, "insertOnClipDrop" | "onDropRefused">>;
}
export function mountTimelineClipDragGestureLifecycle({
@@ -118,6 +119,7 @@ export function mountTimelineClipDragGestureLifecycle({
readZIndexRef,
onStackingPatchesRef,
refreshAfterLaneMoveRef,
dropOptionsRef,
}: TimelineClipDragGestureLifecycleInput): () => void {
const clearSuppressedClick = () => {
requestAnimationFrame(() => {
@@ -308,6 +310,7 @@ export function mountTimelineClipDragGestureLifecycle({
readZIndex: readZIndexRef.current,
onStackingPatches: onStackingPatchesRef.current,
refreshAfterLaneMove: refreshAfterLaneMoveRef.current,
...dropOptionsRef?.current,
});
unlinkAltEdited(drag);
};
@@ -280,6 +280,7 @@ export function computeDragPreview(
pointerClientX: clientX - (floored - previewStart) * pps,
pointerClientY: clientY,
previewStart: placement.start,
aimStart: previewStart,
previewTrack,
// 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.
@@ -23,6 +23,7 @@ export interface DraggedClipState {
* allowed) from a horizontal drag. Absent: the commit falls back to `previewTrack`.
*/
desiredTrack?: number;
aimStart?: number;
/**
* When non-null, the drop inserts a NEW track at this visual row boundary
* (0 = above the top lane, trackOrder.length = below the bottom) instead of
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import type { TimelineElement } from "../store/playerStore";
import { resolveMainTrackInsert } from "./timelineMainTrackInsert";
function el(id: string, start: number, duration: number, track = 0): TimelineElement {
return { id, tag: "video", start, duration, track, domId: id };
}
const starts = (moves: ReturnType<typeof resolveMainTrackInsert>) =>
Object.fromEntries((moves ?? []).map((m) => [m.element.id, m.start]));
describe("resolveMainTrackInsert", () => {
const a = el("a", 0, 2);
const b = el("b", 2, 2);
const c = el("c", 4, 2);
it("puts a clip dropped onto the first clip's spot first and moves the others right", () => {
expect(starts(resolveMainTrackInsert([a, b, c], c, 0.05, true))).toEqual({ c: 0, a: 2, b: 4 });
});
it("puts a clip dropped onto a later clip's spot before it and closes the gap it left", () => {
expect(starts(resolveMainTrackInsert([a, b, c], a, 4, true))).toEqual({ b: 0, a: 2 });
});
it("moves a linked partner with its clip", () => {
const cLinked = { ...c, link: "l1" };
const cAudio = { ...el("c-audio", 4, 2, 1), tag: "audio", link: "l1" };
const moves = resolveMainTrackInsert([a, b, cLinked, cAudio], cLinked, 0, true);
expect(starts(moves)).toEqual({ c: 0, a: 2, b: 4, "c-audio": 0 });
});
it("is null when the drop overlaps no clip, and empty when the order stays the same", () => {
expect(resolveMainTrackInsert([a, el("far", 8, 2)], a, 4, true)).toBeNull();
expect(resolveMainTrackInsert([a, b, c], b, 2.5, true)).toEqual([]);
});
it("is null when a linked partner would land on a clip that stays in its lane", () => {
const cLinked = { ...c, link: "l1" };
const cAudio = { ...el("c-audio", 4, 2, 1), tag: "audio", link: "l1" };
const music = { ...el("music", 0, 2, 1), tag: "audio" };
expect(resolveMainTrackInsert([a, b, cLinked, cAudio, music], cLinked, 0, true)).toBeNull();
});
it("is null when a clip that would move is locked", () => {
const lockedA = { ...a, timelineLocked: true };
expect(resolveMainTrackInsert([lockedA, b, c], c, 0, true)).toBeNull();
});
});
@@ -0,0 +1,90 @@
import type { TimelineElement } from "../store/playerStore";
import type { DragCommitDeps, TimelineMoveEdit } from "./timelineClipDragCommit";
import type { DraggedClipState } from "./timelineClipDragTypes";
import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences";
import { sharesLinkGroup } from "./audioClipLink";
import { timeRangesOverlap } from "./timelineCollision";
import { getTimelineEditCapabilities } from "./timelineEditing";
import { round3, TRACK_GAP_EPSILON_S } from "./timelineGaps";
import { isMainTrackElement } from "./timelineZones";
const keyOf = (e: TimelineElement) => e.key ?? e.id;
// A main-track clip dropped over others goes before the first one whose middle is past its left
// edge; that one and the rest move right by its length, and its old gap closes. Null: no overlap
// or a locked clip would move; empty: nothing moves.
export function resolveMainTrackInsert(
elements: readonly TimelineElement[],
dragged: TimelineElement,
aimStart: number,
linked: boolean,
): Array<{ element: TimelineElement; start: number }> | null {
if (!isMainTrackElement(dragged)) return null;
const others = elements
.filter((e) => keyOf(e) !== keyOf(dragged) && isMainTrackElement(e))
.sort((a, b) => a.start - b.start);
const aimEnd = aimStart + dragged.duration;
const hit = others.some((e) =>
timeRangesOverlap(aimStart, aimEnd, e.start, e.start + e.duration),
);
const last = others.at(-1);
if (!hit || !last) return null;
const at = others.findIndex((e) => e.start + e.duration / 2 > aimStart);
const firstPushed = at < 0 ? others.length : at;
const boundary = others[at]?.start ?? last.start + last.duration;
const lift = (time: number) => (time > dragged.start ? dragged.duration : 0);
const main = [
{ element: dragged, start: round3(boundary - lift(boundary)) },
...others.map((e, i) => ({
element: e,
start: round3(e.start - lift(e.start) + (i >= firstPushed ? dragged.duration : 0)),
})),
].filter((m) => Math.abs(m.start - m.element.start) > TRACK_GAP_EPSILON_S);
const partners = elements.flatMap((partner) => {
if (!linked || isMainTrackElement(partner)) return [];
const lead = main.find((m) => sharesLinkGroup(m.element, partner));
if (!lead) return [];
return [{ element: partner, start: round3(partner.start + lead.start - lead.element.start) }];
});
const moves = [...main, ...partners];
const moving = new Set(moves.map((m) => keyOf(m.element)));
// A partner may not land on a clip that stays put in its lane; main-track moves only reorder, so they cannot.
const lands = partners.some(({ element, start }) =>
elements.some(
(other) =>
other.track === element.track &&
!moving.has(keyOf(other)) &&
timeRangesOverlap(
start,
start + element.duration,
other.start,
other.start + other.duration,
),
),
);
if (lands) return null;
return moves.every((m) => getTimelineEditCapabilities(m.element).canMove) ? moves : null;
}
/** The insert's moves for a finished drag, or null when the drop is not an insert. */
export function resolveMainTrackInsertEdits(
drag: DraggedClipState,
deps: DragCommitDeps,
movingKeys: ReadonlySet<string> | undefined,
): TimelineMoveEdit[] | null {
if (drag.aimStart == null || (drag.desiredTrack ?? drag.previewTrack) !== drag.element.track) {
return null;
}
// A group drag inserts only when the group is the clip and its linked partners.
const groupOfOne = deps.elements.every(
(e) =>
!movingKeys?.has(keyOf(e)) ||
keyOf(e) === keyOf(drag.element) ||
sharesLinkGroup(e, drag.element),
);
if (!groupOfOne) return null;
const linked = isLinkedSelectionOn();
const moves = resolveMainTrackInsert(deps.elements, drag.element, drag.aimStart, linked);
if (!moves) return null;
return moves.map(({ element, start }) => ({ element, updates: { start, track: element.track } }));
}
@@ -64,7 +64,7 @@ export type {
const EMPTY_BEAT_TIMES: number[] = [];
/* ── Hook ───────────────────────────────────────────────────────── */
interface UseTimelineClipDragInput {
interface UseTimelineClipDragInput extends ClipDropOptions {
scrollRef: React.RefObject<HTMLDivElement | null>;
ppsRef: React.RefObject<number>;
durationRef: React.RefObject<number>;
@@ -116,6 +116,8 @@ export function useTimelineClipDrag({
onStackingPatches,
refreshAfterLaneMove,
sessionEpoch = 0,
insertOnClipDrop,
onDropRefused,
}: UseTimelineClipDragInput) {
const getClipCapabilities = useTimelineClipCapabilities();
const commitGestureRef = useRef<() => void>(() => {});
@@ -297,6 +299,8 @@ export function useTimelineClipDrag({
onStackingPatchesRef.current = onStackingPatches;
const refreshAfterLaneMoveRef = useRef(refreshAfterLaneMove);
refreshAfterLaneMoveRef.current = refreshAfterLaneMove;
const dropOptionsRef = useRef({ insertOnClipDrop, onDropRefused });
dropOptionsRef.current = { insertOnClipDrop, onDropRefused };
const clipDragScrollRaf = useRef(0);
const clipDragPointerRef = useRef<{
@@ -461,6 +465,7 @@ export function useTimelineClipDrag({
commitGestureRef,
onStackingPatchesRef,
refreshAfterLaneMoveRef,
dropOptionsRef,
readZIndexRef,
onBlockedEditAttemptRef,
onLinkEditRef,
@@ -588,3 +593,5 @@ export function useTimelineClipDrag({
stopClipDragAutoScroll,
};
}
export type ClipDropOptions = Pick<DragCommitDeps, "insertOnClipDrop" | "onDropRefused">;
@@ -6,7 +6,7 @@ import { useTimelinePlayhead } from "./useTimelinePlayhead";
import { useTimelineZoom } from "./useTimelineZoom";
import { useTimelineAssetDrop } from "./timelineDragDrop";
import { type KeyframeDiamondContextMenuState } from "./KeyframeDiamondContextMenu";
import { useTimelineClipDrag } from "./useTimelineClipDrag";
import { useTimelineClipDrag, type ClipDropOptions } from "./useTimelineClipDrag";
import type { ClipContextMenuState, TimelineContextValue } from "./TimelineProvider";
import { buildTimelineShellMeta } from "./timelineShellMeta";
import { useTimelineDragPreviewState } from "./useTimelineDragPreviewState";
@@ -80,7 +80,9 @@ export function useTimelineProviderState({
sessionEpoch: sessionEpochProp,
previewIframeRef,
onZIndexReorder,
}: TimelineProps = {}): TimelineContextValue {
insertOnClipDrop,
onDropRefused,
}: TimelineProps & ClipDropOptions = {}): TimelineContextValue {
const {
onMoveElement,
onMoveElements,
@@ -229,6 +231,8 @@ export function useTimelineProviderState({
onStackingPatches: zSyncEnabled ? applyStackingPatches : undefined,
refreshAfterLaneMove,
sessionEpoch,
insertOnClipDrop,
onDropRefused,
});
const assetDrop = useTimelineAssetDrop({
scrollRef,