diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx index d6242a3be2..a98abd941f 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx +++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx @@ -7,6 +7,7 @@ import { applyRippleShifts, useTimelineDeleteOps } from "./useTimelineDeleteOps" import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness"; import { useTrackPendingTimelineEdit } from "./useTrackPendingTimelineEdit"; import { flushStudioPendingEdits } from "../utils/studioPendingEdits"; +import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator"; installReactActEnvironment(); @@ -63,19 +64,23 @@ describe("useTimelineDeleteOps: ripple undo label", () => { handleTimelineGroupMove: DeleteOpsOptions["handleTimelineGroupMove"]; showToast?: DeleteOpsOptions["showToast"]; recordEdit?: DeleteOpsOptions["recordEdit"]; + editQueueRef?: DeleteOpsOptions["editQueueRef"]; + writeProjectFile?: DeleteOpsOptions["writeProjectFile"]; }) { const elements = [el("hf-a", 0, 2), el("hf-b", 2, 2), el("hf-c", 4, 2)]; + const editQueueRef = overrides.editQueueRef ?? { current: Promise.resolve() }; + usePlayerStore.getState().setElements(elements); let hook: ReturnType | null = null; function Harness() { hook = useTimelineDeleteOps({ projectIdRef: { current: "test-project" }, activeCompPath: "index.html", - timelineElements: elements, showToast: overrides.showToast ?? vi.fn(), - writeProjectFile: vi.fn().mockResolvedValue(undefined), + writeProjectFile: overrides.writeProjectFile ?? vi.fn().mockResolvedValue(undefined), recordEdit: overrides.recordEdit ?? vi.fn().mockResolvedValue(undefined), reloadPreview: vi.fn(), previewIframeRef: { current: null }, + editQueueRef, handleTimelineGroupMove: overrides.handleTimelineGroupMove, }); return null; @@ -89,8 +94,7 @@ describe("useTimelineDeleteOps: ripple undo label", () => { const handleTimelineGroupMove = vi.fn( () => new Promise((resolve) => (finishRipple = resolve)), ); - const { elements, b, getHook } = mountDeleteHarness({ handleTimelineGroupMove }); - usePlayerStore.getState().setElements(elements); + const { b, getHook } = mountDeleteHarness({ handleTimelineGroupMove }); let deleting = Promise.resolve(); await act(async () => { @@ -139,6 +143,51 @@ describe("useTimelineDeleteOps: ripple undo label", () => { ); }); + // fails without the fix: the second delete saved between the first delete and its ripple. + it("saves a delete made right after another after the first one's ripple", async () => { + const writes: string[] = []; + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input).includes("/file-mutations/remove-elements/")) { + const { targets } = JSON.parse(String(init?.body)) as { targets: Array<{ id: string }> }; + writes.push(`delete ${targets.map((t) => t.id).join(",")}`); + } + return new Response(JSON.stringify({ content: html }), { status: 200 }); + }), + ); + // Stands in for the editor's group move: it joins the edit queue, then writes the file. + const editQueueRef = { current: Promise.resolve() }; + const writeProjectFile = vi.fn().mockResolvedValue(undefined); + const handleTimelineGroupMove: DeleteOpsOptions["handleTimelineGroupMove"] = ( + changes, + options, + ) => { + const run = editQueueRef.current.then(async () => { + await options?.beforeTiming; + await serializeStudioFileMutations(writeProjectFile, ["index.html"], async () => { + writes.push(`move ${changes.map((c) => c.element.id).join(",")}`); + }); + }); + editQueueRef.current = run.catch(() => undefined); + return run; + }; + const { elements, getHook } = mountDeleteHarness({ + handleTimelineGroupMove, + editQueueRef, + writeProjectFile, + }); + + await act(async () => { + const first = getHook().handleTimelineElementDelete(elements[0]); + const shiftedB = usePlayerStore.getState().elements.find((e) => e.id === "hf-b")!; + await Promise.all([first, getHook().handleTimelineElementDelete(shiftedB)]); + }); + + expect(writes).toEqual(["delete hf-a", "move hf-b,hf-c", "delete hf-b", "move hf-c"]); + expect(usePlayerStore.getState().elements).toEqual([el("hf-c", 0, 2)]); + }); + it("removes a multi-clip selection with one request, however many clips it holds", async () => { const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined); const { elements, getHook } = mountDeleteHarness({ handleTimelineGroupMove }); @@ -274,6 +323,7 @@ describe("useTimelineDeleteOps: undo race", () => { function mountRaceHarness() { const elements = [el("hf-a", 0, 2), el("hf-b", 2, 2), el("hf-c", 4, 2)]; + usePlayerStore.getState().setElements(elements); const gate = deferred(); const recordEdit = vi.fn(() => gate.promise); let tracked: ((elements: TimelineElement[]) => Promise) | null = null; @@ -282,12 +332,12 @@ describe("useTimelineDeleteOps: undo race", () => { const hook = useTimelineDeleteOps({ projectIdRef: { current: "test-project" }, activeCompPath: "index.html", - timelineElements: elements, showToast: vi.fn(), writeProjectFile: vi.fn().mockResolvedValue(undefined), recordEdit, reloadPreview: vi.fn(), previewIframeRef: { current: null }, + editQueueRef: { current: Promise.resolve() }, handleTimelineGroupMove: vi.fn().mockResolvedValue(undefined), }); tracked = track(hook.handleTimelineElementsDelete); @@ -378,17 +428,18 @@ describe("useTimelineDeleteOps: live preview", () => { sourceFile: "index.html", }); const elements = [clip("hf-a", 0), clip("hf-b", 2)]; + usePlayerStore.getState().setElements(elements); let hook: ReturnType | null = null; function Harness() { hook = useTimelineDeleteOps({ projectIdRef: { current: "test-project" }, activeCompPath: "index.html", - timelineElements: elements, showToast: vi.fn(), writeProjectFile: vi.fn().mockResolvedValue(undefined), recordEdit: vi.fn().mockResolvedValue(undefined), reloadPreview: vi.fn(), previewIframeRef: { current: iframe }, + editQueueRef: { current: Promise.resolve() }, handleTimelineGroupMove: vi.fn().mockResolvedValue(undefined), }); return null; diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts index f4c0ec41bb..50ea2e35b7 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.ts +++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts @@ -45,7 +45,6 @@ export function applyRippleShifts( interface UseTimelineDeleteOpsOptions { projectIdRef: MutableRefObject; activeCompPath: string | null; - timelineElements: TimelineElement[]; showToast: (message: string, tone?: "error" | "info") => void; writeProjectFile: (path: string, content: string, expectedContent?: string) => Promise; recordEdit: (input: RecordEditInput) => Promise; @@ -53,6 +52,7 @@ interface UseTimelineDeleteOpsOptions { isRecordingRef?: MutableRefObject; forceReloadSdkSession?: () => void; previewIframeRef: RefObject; + editQueueRef: MutableRefObject>; /** The same atomic multi-clip move commit the track-gap menu uses, reused * to ripple the main track after a delete, folded into the delete's own * undo entry via a shared coalesceKey. */ @@ -70,7 +70,6 @@ function unlinkInSource(source: string, survivors: readonly TimelineElement[]): export function useTimelineDeleteOps({ projectIdRef, activeCompPath, - timelineElements, showToast, writeProjectFile, recordEdit, @@ -78,6 +77,7 @@ export function useTimelineDeleteOps({ isRecordingRef, forceReloadSdkSession, previewIframeRef, + editQueueRef, handleTimelineGroupMove, }: UseTimelineDeleteOpsOptions) { // First-use-per-session notice for the ripple. Plain info toast: Studio's @@ -110,8 +110,25 @@ export function useTimelineDeleteOps({ // Shared with the ripple move below so a folded ripple is one undo step with the delete. const step = timingGestureStep("main-track-ripple-delete"); const deleteHistoryLabel = "Delete timeline clip"; + const deletedKeys = new Set(sameFile.map((te) => te.key ?? te.id)); + const { elements } = usePlayerStore.getState(); + const survivors = elements.filter((te) => !deletedKeys.has(te.key ?? te.id)); + + // Ripple: close the gap the delete left on the main track. Pure decision + // first (resolveMainTrackDeleteRippleShifts — off, no main-track clip + // deleted, already gapless, or a locked survivor all resolve to null), + // then the one write, folded into the delete's undo entry below. + const rippleShifts = resolveMainTrackDeleteRippleShifts( + survivors, + sameFile, + usePlayerStore.getState().rippleEditEnabled, + ); + const rippleChanges = rippleShifts ? resolveShiftedElements(survivors, rippleShifts) : null; + // Timeline and preview follow at once, so the next edit starts from this result. + usePlayerStore.getState().setElements(applyRippleShifts(survivors, rippleChanges)); + removeIframeTimelineElements(previewIframeRef.current, sameFile, activeCompPath); let rollbackDuration = () => {}; - try { + const deleted = editQueueRef.current.then(async () => { await saveServerRewriteWithHistory({ projectId: pid, path: targetPath, @@ -163,40 +180,35 @@ export function useTimelineDeleteOps({ return { disk: removedContent, after: patchedContent }; }, }); + }); + editQueueRef.current = deleted.catch(() => undefined); + // One call queues both, so no later edit can land between the delete and its shift. + const shifted = + rippleChanges && + handleTimelineGroupMove(rippleChanges, { + beforeTiming: deleted, + coalesceKey: step.coalesceKey, + // Coalescing keeps the LAST entry's label; without this the undo + // toast reads "Undid Move timeline clips" after a delete, naming + // the ripple's mechanics instead of what the user actually did. + label: deleteHistoryLabel, + // This call gets its own, more specific failure toast below — + // the generic one would tell the user about one action twice. + suppressFailureToast: true, + }); + try { + await deleted; } catch (error) { rollbackDuration(); + usePlayerStore.getState().setElements(elements); + void shifted?.catch(() => undefined); + reloadPreview(); throw error; } - - removeIframeTimelineElements(previewIframeRef.current, sameFile, activeCompPath); - const deletedKeys = new Set(sameFile.map((te) => te.key ?? te.id)); - const survivors = timelineElements.filter((te) => !deletedKeys.has(te.key ?? te.id)); - - // Ripple: close the gap the delete left on the main track. Pure decision - // first (resolveMainTrackDeleteRippleShifts — off, no main-track clip - // deleted, already gapless, or a locked survivor all resolve to null), - // then the one write, folded into the delete's undo entry above. - const rippleShifts = resolveMainTrackDeleteRippleShifts( - survivors, - sameFile, - usePlayerStore.getState().rippleEditEnabled, - ); - const rippleChanges = rippleShifts ? resolveShiftedElements(survivors, rippleShifts) : null; - // The timeline follows the delete's write at once, as the owner of the ripple's optimistic update. - usePlayerStore.getState().setElements(applyRippleShifts(survivors, rippleChanges)); let rippleFailed = false; - if (rippleChanges) { + if (shifted) { try { - await handleTimelineGroupMove(rippleChanges, { - coalesceKey: step.coalesceKey, - // Coalescing keeps the LAST entry's label; without this the undo - // toast reads "Undid Move timeline clips" after a delete, naming - // the ripple's mechanics instead of what the user actually did. - label: deleteHistoryLabel, - // This call gets its own, more specific failure toast below — - // the generic one would tell the user about one action twice. - suppressFailureToast: true, - }); + await shifted; } catch (error) { // The delete already committed; a failed ripple leaves the gap the // toggle-off behaviour would have left anyway — not worth undoing @@ -238,12 +250,12 @@ export function useTimelineDeleteOps({ projectIdRef, recordEdit, showToast, - timelineElements, writeProjectFile, reloadPreview, isRecordingRef, forceReloadSdkSession, previewIframeRef, + editQueueRef, handleTimelineGroupMove, ], ); diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts index 5ab9840b33..02515e14c9 100644 --- a/packages/studio/src/hooks/useTimelineEditing.ts +++ b/packages/studio/src/hooks/useTimelineEditing.ts @@ -170,7 +170,6 @@ export function useTimelineEditing({ const { handleTimelineElementsDelete } = useTimelineDeleteOps({ projectIdRef, activeCompPath, - timelineElements, showToast, writeProjectFile, recordEdit, @@ -178,6 +177,7 @@ export function useTimelineEditing({ isRecordingRef, forceReloadSdkSession, previewIframeRef, + editQueueRef, handleTimelineGroupMove: groupEditing.handleTimelineGroupMove, });