From c99cbbe44d92deca1345aac73729fa29828757c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 10:07:54 +0000 Subject: [PATCH] fix(studio): a drag behind a refused edit is refused only when it would land on a clip (#8456) * fix(studio): a refused delete no longer brings back another delete still saving A refused delete, or a ripple shift that fails after its delete, now moves back only the clips that delete shifted, on the timeline as it is now, instead of restoring the timeline from before it. * fix(studio): a refused delete also refuses the ripple shifts queued behind it A delete's ripple shift saves absolute starts worked out with every earlier pending delete applied. When one of those is refused, the shifts queued behind it are refused too and leave their gap, so the saved file never puts a clip on top of the restored one. * fix(studio): a ripple shift queued behind a refused edit is refused before it writes The timeline's edit queue now has one owner. It knows when an edit still pending is refused, and a ripple shift (after a delete or a trim) queued behind it is refused instead of saving starts that assumed that edit. The trim ripple's rollback moves clips back by its own shift only. Drags, single-clip timing and link edits are unchanged. * fix(studio): a drag queued behind a refused edit is refused only if it would overlap A drop is where the user put it, so a drag queued behind an edit that is then refused still saves, unless it would now land on a clip in its lane, such as the one a refused delete puts back. Then it is refused with the same "Clips on the same track can't overlap." notice a refused drop shows, and the clip returns to where it was. The lane overlap check is shared with the insert-on-drop partner check. * fix(studio): a trim behind a refused edit follows the drag rule, and both notices show as info A trim queued behind an edit that is then refused is kept unless it now overlaps a clip in its lane, the same rule as a drag. A refused drag or trim shows "Clips on the same track can't overlap." in the same info tone as a refused drop: the notice's owner now holds its words and its tone. * fix(studio): a refused edit refuses trims behind it, per project, until every save settles - A queued save stays tracked until it settles, so a later failure still refuses the ripple queued behind it. - A trim's own resize is refused behind a refused edit too: its start and duration were read from the timeline that edit left. - Each project gets its own queue. - A refused trim shift reloads the preview, as a refused delete does. * test(studio): the project-switch case keeps the old project's save pending * fix(studio): a single-clip SDK timing save waits its turn in the edit queue The SDK move and resize now run inside the queued edit, with the file-write fallback in the same entry, so the earlier-refusal check guards both paths and later edits see these saves. * test(studio): give the clip-timing tests a 10 s timeline so every case can use the SDK path * fix(studio): a single-clip drag behind a refused edit is refused only when it lands on a clip * fix(studio): a queued timeline edit reads and writes only the project it was queued in Each edit queue now carries the project it was made for and hands that id to every queued edit, so the SDK readers, the file writes and the tween rewrite never follow a project switch that happens while an edit waits. * test(studio): hold the old project's save from the start in the project-switch case * revert(studio): leave project isolation of queued edits to its own change Takes out the per-project queue and the project binding of queued edits. Main already lets a queued edit follow a project switch, through more handles than the project id (preview, timeline store, history), so that fix moves to one change that covers every handle. * fix(studio): a queued single-clip SDK save reads the project it was made in Main read the project as the save started, right away; queued, it read it when its turn came. The move and resize now take the project when the gesture queues them, for the SDK reader and the tween rewrite. * fix(studio): a refused edit refuses only later edits of its own project Each queued edit carries the project it was queued in, and the queue tracks refusals per project, so a refusal left behind by a project the editor has moved away from never refuses an edit in the one now open. * test(studio): the switch matrix's stand-in SDK session finds no element, like an unknown target * fix(studio): a refused drag takes back only its own shift With Ripple on, a drag behind a refused delete was rolled back to its rippled start, on top of the clip the delete put back. Both drag rollbacks now move the clip from where it is by this drag's own shift, the rule the delete and trim rollbacks follow. The overlap check no longer takes a lane it never reads. * test(studio): the drag-overlap test's earlier refused edit belongs to the hook's project * refactor(studio): track-insert edits live beside the track-insert layout buildTrackInsertEdits moves unchanged from the drag commit into timelineDragLanding, next to layoutAfterTrackInsert, whose layout it turns into edits. Both the drag and the canvas z-order mirror still call it. * fix(studio): a drag behind a refusal in a project no longer shown is refused The drag's overlap check reads the timeline on screen. Once the editor shows another project, that timeline is not the drag's own, so the check could keep a drag that lands on the clip its refused delete put back. A queue whose project is not shown now refuses an edit behind a refusal outright, before any policy reads live state. * test(studio): the group-drag row carries the policy the move adapter gives it --- .../studio/src/hooks/timelineEditQueue.ts | 25 ++++- .../src/hooks/timelineMoveAdapter.test.ts | 31 +++--- .../studio/src/hooks/timelineMoveAdapter.ts | 28 +++--- .../useTimelineClipTimingEditing.test.tsx | 45 ++++++++- .../src/hooks/useTimelineClipTimingEditing.ts | 12 ++- .../src/hooks/useTimelineDeleteOps.test.tsx | 67 +++++++++++-- .../useTimelineEditing.projectSwitch.test.tsx | 67 +++++++++++++ .../hooks/useTimelineGroupEditing.test.tsx | 26 ++++- .../src/hooks/useTimelineGroupEditing.ts | 6 +- .../player/components/TimelineProvider.tsx | 3 +- .../components/timelineClipDragCommit.test.ts | 47 ++++++++- .../components/timelineClipDragCommit.ts | 95 ++++--------------- .../player/components/timelineCollision.ts | 34 +++++++ .../player/components/timelineDragLanding.ts | 74 ++++++++++++++- .../components/timelineMainTrackInsert.ts | 19 +--- .../studio/src/utils/studioSaveDiagnostics.ts | 4 + 16 files changed, 437 insertions(+), 146 deletions(-) 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;