diff --git a/packages/studio/src/hooks/timelineEditQueue.ts b/packages/studio/src/hooks/timelineEditQueue.ts index c185900ef2..e990fd8b6c 100644 --- a/packages/studio/src/hooks/timelineEditQueue.ts +++ b/packages/studio/src/hooks/timelineEditQueue.ts @@ -1,6 +1,12 @@ import { useLayoutEffect, useRef, type MutableRefObject, type RefObject } from "react"; import type { PublishSdkSession } from "../utils/sdkCutover"; import { forgetTimelineOptimisticGestures } from "../player/components/timelineOptimisticRevision"; +import { usePlayerStore } from "../player"; +import { + landsOnLaneClip, + laneOverlapRefusal, + type LaneLanding, +} from "../player/components/timelineCollision"; /** The editor's one timeline edit queue. `placed` holds, per project, a promise that rejects * when an edit of that project still pending is refused. */ @@ -55,8 +61,20 @@ export const refuseWithEarlier = (error: unknown): never => { throw error; }; -/** Runs `run` after every edit queued before it. When one of those, in the same project, was - * refused, `ifEarlierRefused` runs first, and throwing refuses this edit too. */ +/** For an edit the user placed, such as a drop: kept unless it now overlaps a lane clip. */ +export const keepUnlessItOverlaps = + (changes: ReadonlyArray>) => () => { + const { elements } = usePlayerStore.getState(); + const shown = new Map(elements.map((e) => [e.key ?? e.id, e])); + const placed = changes.map(({ element, start }) => ({ + element: shown.get(element.key ?? element.id) ?? element, + start, + })); + if (landsOnLaneClip(elements, placed)) throw laneOverlapRefusal(); + }; + +/** Runs `run` after every edit queued before it. When one in its project was refused, `ifEarlierRefused` + * decides (throw to refuse too); with that project no longer shown, the edit is refused outright. */ export function enqueueTimelineEdit( queue: TimelineEditQueue, run: (projectId: string) => Promise, @@ -73,7 +91,8 @@ export function enqueueTimelineEdit( const byProject = (queue.placed ??= new Map()); const earlier = byProject.get(projectId) ?? Promise.resolve(); const task = queue.current.then(async () => { - if (ifEarlierRefused) await earlier.catch(ifEarlierRefused); + if (ifEarlierRefused) + await earlier.catch(isClosed(queue) ? refuseWithEarlier : ifEarlierRefused); if (!projectId) throw new Error("No project to save this edit to"); return run(projectId); }); diff --git a/packages/studio/src/hooks/timelineMoveAdapter.test.ts b/packages/studio/src/hooks/timelineMoveAdapter.test.ts index 74ea16ee94..497883c4e8 100644 --- a/packages/studio/src/hooks/timelineMoveAdapter.test.ts +++ b/packages/studio/src/hooks/timelineMoveAdapter.test.ts @@ -23,6 +23,12 @@ const movedPair = (edits: MoveArgs[0]) => [ { element: edits[1].element, start: 3, track: 2 }, ]; +// Every drag carries its policy for an earlier refused edit. +const commitOptions = (coalesceKey: string | undefined) => ({ + coalesceKey, + ifEarlierRefused: expect.any(Function), +}); + const runMove = async (edits: MoveArgs[0], coalesceKey: MoveArgs[1], intent: MoveArgs[2]) => { const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined); await persistTimelineMoveEditsAtomically(edits, coalesceKey, intent, { @@ -36,17 +42,19 @@ describe("persistTimelineMoveEditsAtomically", () => { const edits = twoLaneEdits(1); const handleTimelineGroupMove = await runMove(edits, "clip-lane-move:7", "track-insert"); expect(handleTimelineGroupMove).toHaveBeenCalledTimes(1); - expect(handleTimelineGroupMove).toHaveBeenCalledWith(movedPair(edits), { - coalesceKey: "clip-lane-move:7", - }); + expect(handleTimelineGroupMove).toHaveBeenCalledWith( + movedPair(edits), + commitOptions("clip-lane-move:7"), + ); }); it("omits track attrs for plain timing moves (keeps the SDK fast path eligible)", async () => { const edit = { element: element("a", 0), updates: { start: 1, track: 0 } }; const handleTimelineGroupMove = await runMove([edit], undefined, "timing"); - expect(handleTimelineGroupMove).toHaveBeenCalledWith([{ element: edit.element, start: 1 }], { - coalesceKey: undefined, - }); + expect(handleTimelineGroupMove).toHaveBeenCalledWith( + [{ element: edit.element, start: 1 }], + commitOptions(undefined), + ); }); it("persists the track attr for a single lane reorder (stable track lanes)", async () => { @@ -56,16 +64,17 @@ describe("persistTimelineMoveEditsAtomically", () => { const handleTimelineGroupMove = await runMove([edit], "clip-lane-move:7", "lane-reorder"); expect(handleTimelineGroupMove).toHaveBeenCalledWith( [{ element: edit.element, start: 1, track: 1 }], - { coalesceKey: "clip-lane-move:7" }, + commitOptions("clip-lane-move:7"), ); }); it("persists track attrs for a multi-selection lane drag (stable track lanes)", async () => { const edits = twoLaneEdits(2); const handleTimelineGroupMove = await runMove(edits, "clip-lane-move:7", "lane-reorder"); - expect(handleTimelineGroupMove).toHaveBeenCalledWith(movedPair(edits), { - coalesceKey: "clip-lane-move:7", - }); + expect(handleTimelineGroupMove).toHaveBeenCalledWith( + movedPair(edits), + commitOptions("clip-lane-move:7"), + ); }); it("carries explicit detachment through the atomic move", async () => { @@ -76,7 +85,7 @@ describe("persistTimelineMoveEditsAtomically", () => { const handle = await runMove([edit], "move", "track-insert"); expect(handle).toHaveBeenCalledWith( [{ element: edit.element, start: 1, track: 0, audioGroup: null }], - { coalesceKey: "move" }, + commitOptions("move"), ); }); diff --git a/packages/studio/src/hooks/timelineMoveAdapter.ts b/packages/studio/src/hooks/timelineMoveAdapter.ts index 30e1ec860d..a31b4eff51 100644 --- a/packages/studio/src/hooks/timelineMoveAdapter.ts +++ b/packages/studio/src/hooks/timelineMoveAdapter.ts @@ -1,5 +1,6 @@ import { useCallback } from "react"; import type { TimelineElement } from "../player"; +import { keepUnlessItOverlaps } from "./timelineEditQueue"; import type { TimelineGroupCommitOptions, TimelineGroupMoveChange, @@ -35,19 +36,20 @@ export function persistTimelineMoveEditsAtomically( operation: TimelineMoveOperation, deps: AtomicMoveDeps, ): Promise { - return deps.handleTimelineGroupMove( - edits.map(({ element, updates }) => ({ - element, - start: updates.start, - audioGroup: updates.audioGroup, - // Stable track lanes: a lane is the authored data-track-index, so every - // vertical gesture (lane-reorder AND track-insert) must persist the track; - // z is paint order only and is synced separately. Plain horizontal moves - // ("timing") omit it so they stay eligible for the SDK fast path. - track: operation === "timing" ? undefined : updates.track, - })), - { coalesceKey }, - ); + const changes = edits.map(({ element, updates }) => ({ + element, + start: updates.start, + audioGroup: updates.audioGroup, + // Stable track lanes: a lane is the authored data-track-index, so every + // vertical gesture (lane-reorder AND track-insert) must persist the track; + // z is paint order only and is synced separately. Plain horizontal moves + // ("timing") omit it so they stay eligible for the SDK fast path. + track: operation === "timing" ? undefined : updates.track, + })); + return deps.handleTimelineGroupMove(changes, { + coalesceKey, + ifEarlierRefused: keepUnlessItOverlaps(changes), + }); } export function useTimelineMoveEditsHandler( diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx index 6323627b78..c8ae538cc3 100644 --- a/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx @@ -11,6 +11,7 @@ import { useTimelineEditQueue, type TimelineEditQueue, } from "./timelineEditQueue"; +import { LANE_OVERLAP_NOTICE } from "../player/components/timelineCollision"; import { useTimelineClipTimingEditing } from "./useTimelineClipTimingEditing"; import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness"; @@ -37,12 +38,13 @@ const gsapSyncs = vi.mocked(finishClipTimingFallback); function mountClipTiming() { usePlayerStore.getState().setDuration(10); const queue: TimelineEditQueue = { current: Promise.resolve(), projectId: "project" }; + const showToast = vi.fn(); let hook: ReturnType | null = null; function Harness() { hook = useTimelineClipTimingEditing({ activeCompPath: "index.html", timelineElements: [], - showToast: vi.fn(), + showToast, writeProjectFile: vi.fn(), recordEdit: vi.fn(), reloadPreview: vi.fn(), @@ -54,7 +56,7 @@ function mountClipTiming() { return null; } const root = mountReactHarness(); - return { queue, getHook: () => hook!, unmount: () => act(() => root.unmount()) }; + return { queue, showToast, getHook: () => hook!, unmount: () => act(() => root.unmount()) }; } const clipB: TimelineElement = { @@ -69,7 +71,7 @@ const clipB: TimelineElement = { describe.each<[string, CutoverResult]>([ ["the SDK path", { status: "committed", version: "1", before: "

", after: "

" }], ["the file-write fallback", { status: "declined", reason: "feature_disabled" }], -])("a single-clip trim saved through %s", (_path, sdkResult) => { +])("a single-clip edit saved through %s", (_path, sdkResult) => { afterEach(() => vi.clearAllMocks()); it("saves when nothing queued before it was refused", async () => { @@ -98,6 +100,43 @@ describe.each<[string, CutoverResult]>([ expect(fileWrites).not.toHaveBeenCalled(); unmount(); }); + + // Moves B to `to` while a move queued before it is held, then refuses that move with A back at 0-2. + async function dragBehindRefusedMove(to: number) { + usePlayerStore.getState().setElements([{ ...clipB, id: "a", hfId: "hf-a", start: 0 }, clipB]); + sdkWrites.mockResolvedValue(sdkResult); + const h = mountClipTiming(); + let refuseMove: (error: Error) => void = () => {}; + const moveSave = new Promise((_, fail) => (refuseMove = fail)); + const move = enqueueTimelineEdit(h.queue, () => moveSave, { projectId: "project" }); + const onlyTheMove = h.queue.current; + let drag: Promise = Promise.resolve(); + await act(async () => { + drag = h.getHook().handleTimelineElementMove(clipB, { start: to, track: 0 }) ?? drag; + await vi.waitFor(() => expect(h.queue.current).not.toBe(onlyTheMove)); + refuseMove(new Error("move refused")); + await expect(move).rejects.toThrow("move refused"); + await drag.catch(() => undefined); + }); + h.unmount(); + usePlayerStore.getState().setElements([]); + return { drag, showToast: h.showToast }; + } + + // fails without the fix: a single-clip drag saved B at 1 s over the restored A. + it("refuses a single-clip drag that would land on a restored clip, with the refused-drop notice", async () => { + const { drag, showToast } = await dragBehindRefusedMove(1); + await expect(drag).rejects.toThrow(LANE_OVERLAP_NOTICE); + expect(sdkWrites).not.toHaveBeenCalled(); + expect(fileWrites).not.toHaveBeenCalled(); + expect(showToast.mock.calls).toEqual([[LANE_OVERLAP_NOTICE, "info"]]); + }); + + it("keeps a single-clip drag that stays clear of a restored clip", async () => { + const { drag } = await dragBehindRefusedMove(6); + await expect(drag).resolves.toBeUndefined(); + expect(sdkWrites).toHaveBeenCalledOnce(); + }); }); describe("a single-clip trim queued before a project switch", () => { diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts index 3de067741b..da84705dcd 100644 --- a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts +++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts @@ -26,9 +26,10 @@ import { cutoverCommittedOrThrow, sdkTimingPersist, type CutoverResult } from ". type SdkCommit = Extract; import type { TimelineMoveUpdates, UseTimelineEditingOptions } from "./useTimelineEditingTypes"; -import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics"; +import { getStudioSaveErrorMessage, getStudioSaveErrorTone } from "../utils/studioSaveDiagnostics"; import { enqueueTimelineEdit, + keepUnlessItOverlaps, refuseWithEarlier, isClosed, shownPreview, @@ -225,13 +226,16 @@ export function useTimelineClipTimingEditing({ : undefined; return reorderDone .then(() => - enqueueEdit(element, "Move timeline clip", buildMovePatches, step, { trySdk: sdkMove }), + enqueueEdit(element, "Move timeline clip", buildMovePatches, step, { + ifEarlierRefused: keepUnlessItOverlaps([{ element, start: updates.start }]), + trySdk: sdkMove, + }), ) .then((sdk) => finishMoveGsapSync(sdk && sdkTimingGsapSync(sdk))) .catch((error) => { // Failed persist: revert the optimistic duration readout + live root. whileShown(editQueueRef, rollbackDuration); - showToast(getStudioSaveErrorMessage(error), "error"); + showToast(getStudioSaveErrorMessage(error), getStudioSaveErrorTone(error)); throw error; }); }; @@ -341,7 +345,7 @@ export function useTimelineClipTimingEditing({ return persistDone.catch((error) => { // Failed persist: revert the optimistic duration readout + live root. whileShown(editQueueRef, rollbackDuration); - showToast(getStudioSaveErrorMessage(error), "error"); + showToast(getStudioSaveErrorMessage(error), getStudioSaveErrorTone(error)); throw error; }); }, diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx index f92f40f8c1..b0c6161089 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx +++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx @@ -11,6 +11,9 @@ import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordin import { enqueueTimelineEdit, type TimelineEditQueue } from "./timelineEditQueue"; import type { TimelineGroupCommitOptions } from "./useTimelineGroupEditing"; import { useTimelineTrimRipple } from "./useTimelineTrimRipple"; +import { persistTimelineMoveEditsAtomically } from "./timelineMoveAdapter"; +import { persistMoveEdits, type DragCommitDeps } from "../player/components/timelineClipDragCommit"; +import { LANE_OVERLAP_NOTICE } from "../player/components/timelineCollision"; installReactActEnvironment(); @@ -285,17 +288,63 @@ describe("useTimelineDeleteOps: ripple undo label", () => { ]); }); - // A drag's start is where the user dropped it, so it saves as before; it does not opt in. - it("a plain move queued behind a refused delete still saves", async () => { - const { writes, elements, getHook, handleTimelineGroupMove } = mountQueuedEdits("delete hf-a"); + // Deletes hf-b with Ripple off, then drags hf-a to `to` while the delete is still saving. + async function dragBehindRefusedDelete(to: number) { + usePlayerStore.setState({ rippleEditEnabled: false }); + const queued = mountQueuedEdits("delete hf-b"); + const [a, b] = queued.elements; + let refusal: Promise = Promise.resolve(); + const onMoveElements: DragCommitDeps["onMoveElements"] = (edits, coalesceKey) => { + const moved = persistTimelineMoveEditsAtomically(edits, coalesceKey, "timing", { + handleTimelineGroupMove: queued.handleTimelineGroupMove, + }); + refusal = moved.then( + () => null, + (error: Error) => error.message, + ); + return moved; + }; + try { + await act(async () => { + const deleting = queued.getHook().handleTimelineElementDelete(b); + const { elements, updateElement } = usePlayerStore.getState(); + const drag = persistMoveEdits([{ element: a, updates: { start: to, track: 0 } }], { + elements, + trackOrder: [0], + updateElement, + onMoveElements, + }); + await Promise.all([deleting, drag]); + }); + } finally { + usePlayerStore.setState({ rippleEditEnabled: true }); + } + return { writes: queued.writes, refused: await refusal }; + } - await act(async () => { - const deleting = getHook().handleTimelineElementDelete(elements[0]); - const c = usePlayerStore.getState().elements.find((e) => e.id === "hf-c")!; - await Promise.all([deleting, handleTimelineGroupMove([{ element: c, start: 8 }])]); - }); + it("a drag queued behind a refused delete that stays clear of the restored clip still saves", async () => { + const { writes, refused } = await dragBehindRefusedDelete(6.5); - expect(writes).toEqual(["delete hf-a", "move hf-c@8"]); + expect(refused).toBeNull(); + expect(writes).toEqual(["delete hf-b", "move hf-a@6.5"]); + expect(usePlayerStore.getState().elements).toEqual([ + el("hf-a", 6.5, 2), + el("hf-c", 4, 2), + el("hf-b", 2, 2), + ]); + }); + + // fails without the fix: the drag saved hf-a at 2.5, on top of hf-b, which the refused delete put back. + it("a drag queued behind a refused delete that would land on the restored clip is refused and rolls back", async () => { + const { writes, refused } = await dragBehindRefusedDelete(2.5); + + expect(refused).toBe(LANE_OVERLAP_NOTICE); + expect(writes).toEqual(["delete hf-b"]); + expect(usePlayerStore.getState().elements).toEqual([ + el("hf-a", 0, 2), + el("hf-c", 4, 2), + el("hf-b", 2, 2), + ]); }); it("removes a multi-clip selection with one request, however many clips it holds", async () => { diff --git a/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx b/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx index f42b07a729..a824944f5d 100644 --- a/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx +++ b/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx @@ -5,6 +5,7 @@ import { createRoot } from "react-dom/client"; import { afterEach, describe, expect, it, vi } from "vitest"; import { usePlayerStore, type TimelineElement } from "../player"; import { jsonResponse, requestUrl } from "./fetchStubTestUtils"; +import { keepUnlessItOverlaps } from "./timelineEditQueue"; import { useTimelineEditing } from "./useTimelineEditing"; (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -168,3 +169,69 @@ describe.each(["lands", "is refused"])( }); }, ); + +describe.each< + [string, (hook: ReturnType, c: TimelineElement) => unknown] +>([ + ["a single-clip drag", (hook, c) => hook.handleTimelineElementMove(c, { start: 2.5, track: 0 })], + [ + "a group drag, with the policy the move adapter gives it", + (hook, c) => { + const changes = [{ element: c, start: 2.5 }]; + return hook.handleTimelineGroupMove(changes, { + ifEarlierRefused: keepUnlessItOverlaps(changes), + }); + }, + ], +])("%s queued behind a delete that is refused after a project switch", (_kind, drag) => { + // fails without the fix: the drag was checked against the shown project's clips, kept, and saved + // on top of the restored clip in its own project. + it("is refused with the delete, since its own project's timeline is not shown", async () => { + stubFetch([]); + usePlayerStore.getState().setDuration(10); + usePlayerStore.getState().setElements([clip("a", 0), clip("b", 2), clip("c", 4)]); + let refuseDelete: (error: Error) => void = () => {}; + const deleteSave = new Promise((_, fail) => (refuseDelete = fail)); + const oldWrite = vi.fn().mockReturnValueOnce(deleteSave).mockResolvedValue(undefined); + let hook: ReturnType | null = null; + function Harness({ projectId }: { projectId: "old" | "new" }) { + hook = useTimelineEditing({ + projectId, + activeCompPath: "index.html", + timelineElements: usePlayerStore.getState().elements, + showToast: vi.fn(), + writeProjectFile: projectId === "old" ? oldWrite : vi.fn(), + recordEdit: vi.fn(), + reloadPreview: vi.fn(), + previewIframeRef: { current: null }, + pendingTimelineEditPathRef: { current: new Set() }, + uploadProjectFiles: vi.fn(), + }); + return null; + } + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + act(() => root.render()); + const [, b, c] = usePlayerStore.getState().elements; + let deleted: Promise = Promise.resolve(); + let dragged: Promise = Promise.resolve(); + act(() => { + deleted = Promise.resolve(hook!.handleTimelineElementsDelete([b!])); + dragged = Promise.resolve(drag(hook!, c!)); + }); + act(() => { + usePlayerStore.getState().setElements([clip("a", 0)]); + root.render(); + }); + + await act(async () => { + refuseDelete(new Error("refused")); + await Promise.allSettled([deleted, dragged]); + }); + + await expect(dragged).rejects.toThrow("refused"); + expect(oldWrite).toHaveBeenCalledOnce(); + act(() => root.unmount()); + }); +}); diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx index 83e197d66d..e360107e25 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx @@ -11,7 +11,8 @@ import { } from "@hyperframes/studio-server"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { Root } from "react-dom/client"; -import type { TimelineElement } from "../player"; +import { usePlayerStore, type TimelineElement } from "../player"; +import { LANE_OVERLAP_NOTICE } from "../player/components/timelineCollision"; import { persistTimelineMoveEditsAtomically } from "./timelineMoveAdapter"; import { useTimelineGroupEditing } from "./useTimelineGroupEditing"; import { @@ -210,6 +211,29 @@ it("refuses a ripple shift before it writes when an edit queued before it is ref } }); +// fails without the fix: the refused drag said the same words as a refused drop, but as an error. +it("a drag refused for landing on a restored clip shows the refused-drop notice, as info", async () => { + usePlayerStore.getState().setElements([el("restored", 0, 2)]); + const showToast = vi.fn(); + const { earlier, getHook, unmount } = mountBehindRefusedEdit(showToast); + try { + await act(async () => { + const drag = persistTimelineMoveEditsAtomically( + [{ element: el("a", 4, 2), updates: { start: 1, track: 0 } }], + undefined, + "timing", + { handleTimelineGroupMove: getHook().handleTimelineGroupMove }, + ); + await expect(earlier).rejects.toThrow("delete refused"); + await expect(drag).rejects.toThrow(LANE_OVERLAP_NOTICE); + }); + expect(showToast.mock.calls).toEqual([[LANE_OVERLAP_NOTICE, "info"]]); + } finally { + unmount(); + usePlayerStore.getState().setElements([]); + } +}); + // fails without the fix: a trim of B, shifted to 0 by a delete that was then refused, wrote B at 0. it("refuses a trim before it writes when an edit queued before it is refused, so the clip keeps its start", async () => { const { earlier, fetchMock, getHook, unmount } = mountBehindRefusedEdit(); diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts index 79cc622c90..378cb1dd39 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.ts +++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts @@ -32,7 +32,7 @@ import { syncPreviewContentDuration, } from "./timelineTimingSync"; import type { GsapMutationStatus } from "./gsapMutationClient"; -import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics"; +import { getStudioSaveErrorMessage, getStudioSaveErrorTone } from "../utils/studioSaveDiagnostics"; import { enqueueTimelineEdit, refuseWithEarlier, @@ -368,7 +368,7 @@ export function useTimelineGroupEditing({ if (options?.suppressFailureToast) { console.error("[Timeline] group move failed to persist", error); } else { - showToast(getStudioSaveErrorMessage(error), "error"); + showToast(getStudioSaveErrorMessage(error), getStudioSaveErrorTone(error)); } throw error; }); @@ -483,7 +483,7 @@ export function useTimelineGroupEditing({ // Failed persist: revert the optimistic duration readout + live root // alongside the gesture owner's store rollback. whileShown(editQueueRef, rollbackDuration); - showToast(getStudioSaveErrorMessage(error), "error"); + showToast(getStudioSaveErrorMessage(error), getStudioSaveErrorTone(error)); throw error; }); }, diff --git a/packages/studio/src/player/components/TimelineProvider.tsx b/packages/studio/src/player/components/TimelineProvider.tsx index 476e585c75..396a63b460 100644 --- a/packages/studio/src/player/components/TimelineProvider.tsx +++ b/packages/studio/src/player/components/TimelineProvider.tsx @@ -30,6 +30,7 @@ import type { TimelineEditCallbacks } from "./timelineCallbacks"; import type { KeyframeDiamondContextMenuState } from "./KeyframeDiamondContextMenu"; import { useTimelineProviderState } from "./useTimelineProviderState"; import { TimelineReadOnlyContext } from "./timelineReadOnly"; +import { LANE_OVERLAP_NOTICE, LANE_OVERLAP_TONE } from "./timelineCollision"; import { TimelineEditProvider, useTimelineEditContextOptional, @@ -217,7 +218,7 @@ function TimelineProviderState({ children, ...props }: TimelineProps & { childre 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 onDropRefused = notice && (() => notice(LANE_OVERLAP_NOTICE, LANE_OVERLAP_TONE)); const value = useTimelineProviderState({ ...props, onDropRefused }); return {children}; } diff --git a/packages/studio/src/player/components/timelineClipDragCommit.test.ts b/packages/studio/src/player/components/timelineClipDragCommit.test.ts index 9ec5d8437e..a776d45dbb 100644 --- a/packages/studio/src/player/components/timelineClipDragCommit.test.ts +++ b/packages/studio/src/player/components/timelineClipDragCommit.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi, type Mock } from "vitest"; -import type { TimelineElement } from "../store/playerStore"; +import { usePlayerStore, type TimelineElement } from "../store/playerStore"; import type { DraggedClipState } from "./useTimelineClipDrag"; import { commitDraggedClipMove, @@ -1669,3 +1669,48 @@ describe("commitDraggedClipMove: drop onto main-track clips", () => { expect(onDropRefused).not.toHaveBeenCalled(); }); }); + +// A delete still saving rippled C from 4 to 2; C is dragged to 2.5; the refused delete's rollback moves C +// back by its ripple to 4.5, and then the drag is refused too. +describe("a refused drag after an earlier edit's rollback moved its clip", () => { + const startOf = (id: string) => + usePlayerStore.getState().elements.find((e) => e.id === id)?.start; + function setUp() { + const store = usePlayerStore.getState(); + store.setElements([el("a", 0, 0, 2), el("c", 0, 2, 2)]); + let refuse: (error: Error) => void = () => {}; + const save = new Promise((_, fail) => (refuse = fail)); + const deps = { + elements: usePlayerStore.getState().elements, + trackOrder: [0], + updateElement: store.updateElement, + }; + const rollBackRipple = () => store.updateElement("c", { start: startOf("c")! + 2 }); + return { c: deps.elements[1]!, save, refuse, deps, rollBackRipple }; + } + + // fails without the fix: C went back to its rippled 2, on top of the restored B. + it("takes back only its own shift on the single-clip path", async () => { + const { c, save, refuse, deps, rollBackRipple } = setUp(); + commitDraggedClipMove(drag(c, { previewStart: 2.5, previewTrack: 0 }), { + ...deps, + onMoveElement: () => save, + }); + rollBackRipple(); + refuse(new Error("lands on B")); + await flushMicrotasks(); + expect(startOf("c")).toBe(4); + }); + + it("takes back only its own shift on the multi-clip path", async () => { + const { c, save, refuse, deps, rollBackRipple } = setUp(); + const moved = persistMoveEdits([{ element: c, updates: { start: 2.5, track: 0 } }], { + ...deps, + onMoveElements: () => save, + }); + rollBackRipple(); + refuse(new Error("lands on B")); + await expect(moved).resolves.toBe(false); + expect(startOf("c")).toBe(4); + }); +}); diff --git a/packages/studio/src/player/components/timelineClipDragCommit.ts b/packages/studio/src/player/components/timelineClipDragCommit.ts index bb800edb98..37e30d3e96 100644 --- a/packages/studio/src/player/components/timelineClipDragCommit.ts +++ b/packages/studio/src/player/components/timelineClipDragCommit.ts @@ -1,17 +1,14 @@ -import type { TimelineElement } from "../store/playerStore"; +import { usePlayerStore, type TimelineElement } from "../store/playerStore"; import { clampToHostStart } from "../store/timelineElement"; 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 } from "./timelineZones"; -import { layoutAfterTrackInsert } from "./timelineDragLanding"; +import { buildTrackInsertEdits } from "./timelineDragLanding"; import type { TimelineTrackInsertLayout } from "./timelineTrackInsertLayout"; import { computeStackingPatches, type StackingPatch } from "./timelineStackingSync"; -import { - canMoveTimelineElement as canMoveElement, - resolveExpandedHostAlias, -} from "./timelineAuthoredMoveTarget"; +import { resolveExpandedHostAlias } from "./timelineAuthoredMoveTarget"; import type { TimelineMoveOperation, TimelineAtomicMoveUpdates, @@ -89,6 +86,12 @@ export interface DragCommitDeps { } const keyOf = (e: TimelineElement) => e.key ?? e.id; + +/** Where `key` sits now, minus this drag's own shift: an earlier edit's rollback may have moved it since. */ +function startBeforeDrag(key: string, from: number, to: number): number { + const now = usePlayerStore.getState().elements.find((e) => keyOf(e) === key)?.start ?? to; + return now - (to - from); +} 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; @@ -191,13 +194,15 @@ export function persistMoveEdits( ? e : { element: e.element, updates: { ...e.updates, track: e.persistTrack } }, ); + const movedTo = new Map(edits.map((e) => [keyOf(e.element), e.updates.start])); const restorePrev = () => batchElementUpdates(() => { for (const p of prev) { const { audioGroup, ...timing } = p.updates; const updates: Partial = {}; if (isLatestTimelineOptimisticGesture(updateElement, revision, p.key)) { - Object.assign(updates, timing); + const to = movedTo.get(p.key) ?? timing.start; + Object.assign(updates, timing, { start: startBeforeDrag(p.key, timing.start, to) }); } if ( isLatestTimelineOptimisticGesture(updateElement, membershipRevision, p.key, "membership") @@ -312,7 +317,10 @@ export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDe updateElement(dragKey, updates); Promise.resolve(onMoveElement?.(drag.element, updates)).catch((error) => { if (isLatestTimelineOptimisticGesture(updateElement, revision, dragKey)) { - updateElement(dragKey, prev); + updateElement(dragKey, { + ...prev, + start: startBeforeDrag(dragKey, prev.start, updates.start), + }); } console.error("[Timeline] Failed to persist clip edit", error); }); @@ -378,77 +386,6 @@ export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDe ).catch(() => undefined); } -/** Build the one sanctioned multi-clip write: atomically insert and compact a - * source-file zone, then let the caller sync the deliberate vertical stacking. */ -// fallow-ignore-next-line complexity -function buildTrackInsertEdits( - element: TimelineElement, - previewStart: number, - insertRow: number, - multi: { - keys: ReadonlySet; - movedStart: (e: TimelineElement) => number; - } | null, - deps: DragCommitDeps, -): { candidate: TimelineElement[]; edits: TimelineMoveEdit[] } | null { - const { elements } = deps; - const editKey = keyOf(element); - 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) { - const src = bySrc.get(keyOf(norm)); - if ( - src && - writable(src) && - !canMoveElement(src) && - norm.track !== (src.authoredTrack ?? src.track) - ) { - console.warn( - `[Timeline] Track insert refused: locked clip ${keyOf(src)} would need renumbering`, - ); - 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) { - const srcKey = keyOf(src); - if (srcKey !== editKey && multi.keys.has(srcKey) && !writable(src) && canMoveElement(src)) { - edits.push({ - element: src, - updates: { start: multi.movedStart(src), track: src.track }, - persistTrack: src.authoredTrack, - }); - } - } - } - for (const norm of normalized) { - const src = bySrc.get(keyOf(norm)); - if (!src || !canMoveElement(src)) continue; - 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, - ...(normKey === editKey && src.audioGroup ? { audioGroup: null } : {}), - }, - }); - } - return { candidate, edits }; -} - function commitTrackInsert( drag: DraggedClipState, deps: DragCommitDeps, diff --git a/packages/studio/src/player/components/timelineCollision.ts b/packages/studio/src/player/components/timelineCollision.ts index 62c995abe2..ef77612241 100644 --- a/packages/studio/src/player/components/timelineCollision.ts +++ b/packages/studio/src/player/components/timelineCollision.ts @@ -217,6 +217,40 @@ export function timeRangesOverlap( return aStart < bEnd && bStart < aEnd; } +export const LANE_OVERLAP_NOTICE = "Clips on the same track can't overlap."; +export const LANE_OVERLAP_TONE = "info"; + +export const laneOverlapRefusal = () => + Object.assign(new Error(LANE_OVERLAP_NOTICE), { tone: LANE_OVERLAP_TONE }); + +export type LaneLanding = { element: TimelineElement; start: number; track?: number }; + +/** True when one of `checked` overlaps another clip in its lane, each clip placed where `moves` puts it. */ +export function landsOnLaneClip( + elements: readonly TimelineElement[], + moves: readonly LaneLanding[], + checked: readonly LaneLanding[] = moves, +): boolean { + const keyOf = (e: TimelineElement) => e.key ?? e.id; + const landed = new Map(moves.map((m) => [keyOf(m.element), m])); + const place = (e: TimelineElement) => { + const move = landed.get(keyOf(e)); + const start = move?.start ?? e.start; + return { start, end: start + e.duration, track: move?.track ?? e.track }; + }; + return checked.some(({ element }) => { + const self = place(element); + return elements.some((other) => { + const at = place(other); + return ( + keyOf(other) !== keyOf(element) && + at.track === self.track && + timeRangesOverlap(self.start, self.end, at.start, at.end) + ); + }); + }); +} + /** * True when no clip on `track` overlaps [start, end) — excluding the clip * identified by `excludeKey` (the one being dragged). diff --git a/packages/studio/src/player/components/timelineDragLanding.ts b/packages/studio/src/player/components/timelineDragLanding.ts index 1fcc243c2e..aa96a34349 100644 --- a/packages/studio/src/player/components/timelineDragLanding.ts +++ b/packages/studio/src/player/components/timelineDragLanding.ts @@ -1,5 +1,6 @@ import type { TimelineElement } from "../store/playerStore"; -import type { DragCommitDeps } from "./timelineClipDragCommit"; +import type { DragCommitDeps, TimelineMoveEdit } from "./timelineClipDragCommit"; +import { canMoveTimelineElement as canMoveElement } from "./timelineAuthoredMoveTarget"; import { classifyZone, normalizeToZones } from "./timelineZones"; import { sameSourceFile } from "./timelineAuthoredTrack"; @@ -67,3 +68,74 @@ export function layoutAfterTrackInsert( ); return { normalized, targetTrack, writable }; } + +/** Build the one sanctioned multi-clip write: atomically insert and compact a + * source-file zone, then let the caller sync the deliberate vertical stacking. */ +// fallow-ignore-next-line complexity +export function buildTrackInsertEdits( + element: TimelineElement, + previewStart: number, + insertRow: number, + multi: { + keys: ReadonlySet; + movedStart: (e: TimelineElement) => number; + } | null, + deps: DragCommitDeps, +): { candidate: TimelineElement[]; edits: TimelineMoveEdit[] } | null { + const { elements } = deps; + const editKey = keyOf(element); + 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) { + const src = bySrc.get(keyOf(norm)); + if ( + src && + writable(src) && + !canMoveElement(src) && + norm.track !== (src.authoredTrack ?? src.track) + ) { + console.warn( + `[Timeline] Track insert refused: locked clip ${keyOf(src)} would need renumbering`, + ); + 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) { + const srcKey = keyOf(src); + if (srcKey !== editKey && multi.keys.has(srcKey) && !writable(src) && canMoveElement(src)) { + edits.push({ + element: src, + updates: { start: multi.movedStart(src), track: src.track }, + persistTrack: src.authoredTrack, + }); + } + } + } + for (const norm of normalized) { + const src = bySrc.get(keyOf(norm)); + if (!src || !canMoveElement(src)) continue; + 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, + ...(normKey === editKey && src.audioGroup ? { audioGroup: null } : {}), + }, + }); + } + return { candidate, edits }; +} diff --git a/packages/studio/src/player/components/timelineMainTrackInsert.ts b/packages/studio/src/player/components/timelineMainTrackInsert.ts index 0f22a1a404..0062c5d0f3 100644 --- a/packages/studio/src/player/components/timelineMainTrackInsert.ts +++ b/packages/studio/src/player/components/timelineMainTrackInsert.ts @@ -3,7 +3,7 @@ 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 { landsOnLaneClip, timeRangesOverlap } from "./timelineCollision"; import { getTimelineEditCapabilities } from "./timelineEditing"; import { round3, TRACK_GAP_EPSILON_S } from "./timelineGaps"; import { isMainTrackElement } from "./timelineZones"; @@ -47,23 +47,8 @@ export function resolveMainTrackInsert( return [{ element: partner, start: round3(partner.start + lead.start - lead.element.start) }]; }); const moves = [...main, ...partners]; - const landed = new Map(moves.map((m) => [keyOf(m.element), m.start])); - const startAfter = (e: TimelineElement) => landed.get(keyOf(e)) ?? e.start; // A partner may not land on a clip in its lane, moved or not, nor start before 0; main-track moves only reorder. - const lands = partners.some(({ element, start }) => - elements.some( - (other) => - other.track === element.track && - keyOf(other) !== keyOf(element) && - timeRangesOverlap( - start, - start + element.duration, - startAfter(other), - startAfter(other) + other.duration, - ), - ), - ); - if (lands || partners.some((p) => p.start < 0)) return null; + if (landsOnLaneClip(elements, moves, partners) || partners.some((p) => p.start < 0)) return null; return moves.every((m) => getTimelineEditCapabilities(m.element).canMove) ? moves : null; } diff --git a/packages/studio/src/utils/studioSaveDiagnostics.ts b/packages/studio/src/utils/studioSaveDiagnostics.ts index bf0d4086fe..0a1e85e429 100644 --- a/packages/studio/src/utils/studioSaveDiagnostics.ts +++ b/packages/studio/src/utils/studioSaveDiagnostics.ts @@ -113,6 +113,10 @@ function attachStudioSaveAttempt(error: unknown, attempt: number): unknown { return error; } +export function getStudioSaveErrorTone(error: unknown): "info" | "error" { + return error instanceof Error && "tone" in error && error.tone === "info" ? "info" : "error"; +} + export function getStudioSaveErrorMessage(error: unknown): string { if (error instanceof Error && error.message) return error.message; if (typeof error === "string" && error.trim()) return error;