From 56e0d6fbd7fbaa4f668ac940b95089347d1f274e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 07:30:46 +0000 Subject: [PATCH] fix(studio): a ripple shift queued behind a refused edit is refused before it writes (#8443) * 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 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 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 --- .../src/hooks/timelineEditQueue.test.tsx | 38 ++++ .../studio/src/hooks/timelineEditQueue.ts | 50 ++++++ .../useTimelineClipTimingEditing.test.tsx | 122 +++++++++++++ .../src/hooks/useTimelineClipTimingEditing.ts | 162 ++++++++++-------- .../src/hooks/useTimelineDeleteOps.test.tsx | 109 +++++++++--- .../studio/src/hooks/useTimelineDeleteOps.ts | 25 ++- .../useTimelineEditing.switchMatrix.test.tsx | 157 +++++++++++++++++ .../studio/src/hooks/useTimelineEditing.ts | 1 + .../hooks/useTimelineGroupEditing.test.tsx | 73 ++++++++ .../src/hooks/useTimelineGroupEditing.ts | 36 ++-- .../src/hooks/useTimelineTrimRipple.test.tsx | 15 ++ .../studio/src/hooks/useTimelineTrimRipple.ts | 18 +- 12 files changed, 676 insertions(+), 130 deletions(-) create mode 100644 packages/studio/src/hooks/timelineEditQueue.test.tsx create mode 100644 packages/studio/src/hooks/timelineEditQueue.ts create mode 100644 packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx create mode 100644 packages/studio/src/hooks/useTimelineEditing.switchMatrix.test.tsx diff --git a/packages/studio/src/hooks/timelineEditQueue.test.tsx b/packages/studio/src/hooks/timelineEditQueue.test.tsx new file mode 100644 index 0000000000..4d673a120b --- /dev/null +++ b/packages/studio/src/hooks/timelineEditQueue.test.tsx @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { + enqueueTimelineEdit, + refuseWithEarlier, + type TimelineEditQueue, +} from "./timelineEditQueue"; + +function deferred() { + let reject: (error: Error) => void = () => {}; + const promise = new Promise((_, fail) => (reject = fail)); + return { promise, reject }; +} + +const settle = () => new Promise((resolve) => setImmediate(resolve)); + +describe("enqueueTimelineEdit", () => { + // fails without the fix: A's failure cleared the tracking of B's save still in flight. + it("refuses a ripple queued during a save that then fails, after an earlier save already failed", async () => { + const queue: TimelineEditQueue = { current: Promise.resolve() }; + const a = deferred(); + const b = deferred(); + const writes: string[] = []; + const first = enqueueTimelineEdit(queue, () => a.promise); + const second = enqueueTimelineEdit(queue, () => b.promise); + a.reject(new Error("A refused")); + await expect(first).rejects.toThrow("A refused"); + await settle(); + + const ripple = enqueueTimelineEdit(queue, async () => void writes.push("ripple"), { + ifEarlierRefused: refuseWithEarlier, + }); + b.reject(new Error("B refused")); + + await expect(second).rejects.toThrow("B refused"); + await expect(ripple).rejects.toThrow("refused"); + expect(writes).toEqual([]); + }); +}); diff --git a/packages/studio/src/hooks/timelineEditQueue.ts b/packages/studio/src/hooks/timelineEditQueue.ts new file mode 100644 index 0000000000..5a5799dcc7 --- /dev/null +++ b/packages/studio/src/hooks/timelineEditQueue.ts @@ -0,0 +1,50 @@ +import type { MutableRefObject } from "react"; + +/** 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. */ +export interface TimelineEditQueue extends MutableRefObject> { + placed?: Map>; +} + +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. */ +export function enqueueTimelineEdit( + queue: TimelineEditQueue, + run: () => Promise, + { + label, + ifEarlierRefused, + projectId = null, + }: { + label?: string; + ifEarlierRefused?: (error: unknown) => void; + projectId?: string | null; + } = {}, +): Promise { + 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); + return run(); + }); + const placed = Promise.allSettled([earlier, task]).then((settled) => { + for (const result of settled) if (result.status === "rejected") throw result.reason; + }); + byProject.set(projectId, placed); + queue.current = task.then( + () => undefined, + (error) => { + if (label) console.error(`[Timeline] Failed to persist: ${label}`, error); + }, + ); + void placed + .catch(() => undefined) + .then(() => { + if (byProject.get(projectId) === placed) byProject.delete(projectId); + }); + return task; +} diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx new file mode 100644 index 0000000000..aedec0b3e9 --- /dev/null +++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx @@ -0,0 +1,122 @@ +// @vitest-environment happy-dom + +import { act } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { usePlayerStore, type TimelineElement } from "../player"; +import { sdkTimingPersist, type CutoverResult } from "../utils/sdkCutover"; +import { persistTimelineEdit } from "./timelineEditingHelpers"; +import { finishClipTimingFallback } from "./timelineTimingSync"; +import { enqueueTimelineEdit, type TimelineEditQueue } from "./timelineEditQueue"; +import { useTimelineClipTimingEditing } from "./useTimelineClipTimingEditing"; +import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness"; + +vi.mock("../utils/sdkCutover", async (original) => ({ + ...(await original()), + sdkTimingPersist: vi.fn(), +})); +vi.mock("./timelineEditingHelpers", async (original) => ({ + ...(await original()), + persistTimelineEdit: vi.fn(async () => undefined), +})); +vi.mock("./timelineTimingSync", async (original) => ({ + ...(await original()), + finishClipTimingFallback: vi.fn(async () => undefined), + readFileContent: vi.fn(async (projectId: string, path: string) => `${projectId}:${path}`), +})); + +installReactActEnvironment(); + +const sdkWrites = vi.mocked(sdkTimingPersist); +const fileWrites = vi.mocked(persistTimelineEdit); +const gsapSyncs = vi.mocked(finishClipTimingFallback); + +function mountClipTiming(projectIdRef = { current: "project" as string | null }) { + usePlayerStore.getState().setDuration(10); + const queue: TimelineEditQueue = { current: Promise.resolve() }; + let hook: ReturnType | null = null; + function Harness() { + hook = useTimelineClipTimingEditing({ + activeCompPath: "index.html", + timelineElements: [], + showToast: vi.fn(), + writeProjectFile: vi.fn(), + recordEdit: vi.fn(), + reloadPreview: vi.fn(), + previewIframeRef: { current: null }, + pendingTimelineEditPathRef: { current: new Set() }, + sdkSession: {} as never, + editQueueRef: queue, + projectIdRef, + }); + return null; + } + const root = mountReactHarness(); + return { queue, getHook: () => hook!, unmount: () => act(() => root.unmount()) }; +} + +const clipB: TimelineElement = { + id: "b", + hfId: "hf-b", + tag: "div", + start: 2, + duration: 2, + track: 0, +}; + +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) => { + afterEach(() => vi.clearAllMocks()); + + it("saves when nothing queued before it was refused", async () => { + sdkWrites.mockResolvedValue(sdkResult); + const { getHook, unmount } = mountClipTiming(); + await act(() => getHook().handleTimelineElementResize(clipB, { start: 2, duration: 3 })); + expect(sdkWrites).toHaveBeenCalledOnce(); + expect(fileWrites).toHaveBeenCalledTimes(sdkResult.status === "committed" ? 0 : 1); + unmount(); + }); + + // fails without the fix: the SDK trim wrote B at its provisional 2 s start after the move to 2 s was refused. + it("is refused before it writes when a move queued before it is refused", async () => { + sdkWrites.mockResolvedValue(sdkResult); + const { queue, getHook, unmount } = mountClipTiming(); + let refuseMove: (error: Error) => void = () => {}; + const moveSave = new Promise((_, fail) => (refuseMove = fail)); + const move = enqueueTimelineEdit(queue, () => moveSave, { projectId: "project" }); + await act(async () => { + const trim = getHook().handleTimelineElementResize(clipB, { start: 2, duration: 3 }); + refuseMove(new Error("move refused")); + await expect(move).rejects.toThrow("move refused"); + await expect(trim).rejects.toThrow("move refused"); + }); + expect(sdkWrites).not.toHaveBeenCalled(); + expect(fileWrites).not.toHaveBeenCalled(); + unmount(); + }); +}); + +describe("a single-clip SDK trim queued behind another save", () => { + afterEach(() => vi.clearAllMocks()); + + // fails without the fix: after a project switch the queued trim read the newly opened project's file. + it("reads the project it was made in, as it did before it joined the queue", async () => { + sdkWrites.mockResolvedValue({ status: "committed", version: "1", before: "", after: "" }); + const projectIdRef = { current: "old" as string | null }; + const { queue, getHook, unmount } = mountClipTiming(projectIdRef); + let release: () => void = () => {}; + const held = new Promise((done) => (release = done)); + void enqueueTimelineEdit(queue, () => held); + const trim = getHook().handleTimelineElementResize(clipB, { start: 2, duration: 3 }); + + projectIdRef.current = "new"; + release(); + await act(() => trim); + + const sdkDeps = sdkWrites.mock.calls[0]?.[4]; + await expect(sdkDeps?.readProjectFile?.("index.html")).resolves.toBe("old:index.html"); + expect(gsapSyncs.mock.calls.map(([sync]) => sync.projectId)).toEqual(["old"]); + unmount(); + }); +}); diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts index ca550ccf00..243a759f52 100644 --- a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts +++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts @@ -22,9 +22,16 @@ import { timingGestureStep, } from "./timelineTimingSync"; import { serializeZLaneGesture } from "../components/nle/zLaneGesture"; -import { cutoverCommittedOrThrow, sdkTimingPersist } from "../utils/sdkCutover"; +import { cutoverCommittedOrThrow, sdkTimingPersist, type CutoverResult } from "../utils/sdkCutover"; + +type SdkCommit = Extract; import type { TimelineMoveUpdates, UseTimelineEditingOptions } from "./useTimelineEditingTypes"; import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics"; +import { + enqueueTimelineEdit, + refuseWithEarlier, + type TimelineEditQueue, +} from "./timelineEditQueue"; type UseTimelineClipTimingEditingOptions = Pick< UseTimelineEditingOptions, @@ -43,7 +50,7 @@ type UseTimelineClipTimingEditingOptions = Pick< | "invalidateGsapCache" | "handleDomZIndexReorderCommitRef" > & { - editQueueRef: MutableRefObject>; + editQueueRef: TimelineEditQueue; projectIdRef: MutableRefObject; }; @@ -72,16 +79,26 @@ export function useTimelineClipTimingEditing({ label: string, buildPatches: PersistTimelineEditInput["buildPatches"], step: ReturnType, - ): Promise => { + { + ifEarlierRefused, + trySdk, + }: { + ifEarlierRefused?: (error: unknown) => void; + trySdk?: () => Promise; + } = {}, + ): Promise => { if (isRecordingRef?.current) { showToast("Cannot edit timeline while recording", "error"); - return Promise.resolve(); + return Promise.resolve(undefined); } const pid = projectIdRef.current; - if (!pid) return Promise.resolve(); - const queued = editQueueRef.current - .then(() => - persistTimelineEdit({ + if (!pid) return Promise.resolve(undefined); + return enqueueTimelineEdit( + editQueueRef, + async () => { + const sdk = await trySdk?.(); + if (sdk && cutoverCommittedOrThrow(sdk)) return sdk; + await persistTimelineEdit({ projectId: pid, element, activeCompPath, @@ -91,15 +108,12 @@ export function useTimelineClipTimingEditing({ recordEdit, pendingTimelineEditPathRef, ...step, - }), - ) - .then(() => { + }); forceReloadSdkSession?.(); - }); - editQueueRef.current = queued.catch((error) => { - console.error(`[Timeline] Failed to persist: ${label}`, error); - }); - return queued; + return undefined; + }, + { label, ifEarlierRefused, projectId: pid }, + ); }, [ activeCompPath, @@ -116,6 +130,7 @@ export function useTimelineClipTimingEditing({ const handleTimelineElementMove = useCallback( // fallow-ignore-next-line complexity (element: TimelineElement, updates: TimelineMoveUpdates) => { + const projectId = projectIdRef.current; // fallow-ignore-next-line complexity const commitMove = () => { const targetPath = element.sourceFile || activeCompPath || "index.html"; @@ -170,7 +185,7 @@ export function useTimelineClipTimingEditing({ finishClipTimingFallback({ iframe: previewIframeRef.current, reloadPreview, - projectId: projectIdRef.current, + projectId, targetPath, domId: element.domId, label: "Move timeline clip", @@ -180,37 +195,34 @@ export function useTimelineClipTimingEditing({ edit: { kind: "shift", delta: updates.start - element.start }, sdkGsap, }).finally(() => invalidateGsapCache?.()); - const moveFallback = () => - enqueueEdit(element, "Move timeline clip", buildMovePatches, step).then(() => - finishMoveGsapSync(), - ); + const hfId = element.hfId; + // SDK setTiming writes start only; a lane change needs the fallback's track patch. + const sdkMove = + sdkSession && hfId && !element.link && !needsExtension && !trackChanged + ? () => + sdkTimingPersist( + hfId, + targetPath, + { start: authoredStart }, + sdkSession, + { + editHistory: { recordEdit }, + writeProjectFile, + reloadPreview, + compositionPath: activeCompPath, + // Capture on-disk bytes as the undo `before` so undoing a timing move + // restores the file verbatim, not a normalized full-DOM re-emit. + readProjectFile: (path) => readFileContent(projectId ?? "", path), + publishSession: publishSdkSession, + }, + { label: "Move timeline clip", ...step, skipRefresh: true }, + ) + : undefined; return reorderDone - .then(() => { - // SDK setTiming writes start only; a lane change needs the fallback's track patch. - if (sdkSession && element.hfId && !element.link && !needsExtension && !trackChanged) { - return sdkTimingPersist( - element.hfId, - targetPath, - { start: authoredStart }, - sdkSession, - { - editHistory: { recordEdit }, - writeProjectFile, - reloadPreview, - compositionPath: activeCompPath, - // Capture on-disk bytes as the undo `before` so undoing a timing move - // restores the file verbatim, not a normalized full-DOM re-emit. - readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path), - publishSession: publishSdkSession, - }, - { label: "Move timeline clip", ...step, skipRefresh: true }, - ).then((result) => { - if (!cutoverCommittedOrThrow(result)) return moveFallback(); - return finishMoveGsapSync(sdkTimingGsapSync(result)); - }); - } - return moveFallback(); - }) + .then(() => + enqueueEdit(element, "Move timeline clip", buildMovePatches, step, { trySdk: sdkMove }), + ) + .then((sdk) => finishMoveGsapSync(sdk && sdkTimingGsapSync(sdk))) .catch((error) => { // Failed persist: revert the optimistic duration readout + live root. rollbackDuration(); @@ -243,6 +255,7 @@ export function useTimelineClipTimingEditing({ element: TimelineElement, updates: Pick, ) => { + const projectId = projectIdRef.current; const authoredStart = toAuthoredStart(element, updates.start); const liveAttrs: Array<[string, string]> = [ ["data-start", formatTimelineAttributeNumber(authoredStart)], @@ -276,7 +289,7 @@ export function useTimelineClipTimingEditing({ finishClipTimingFallback({ iframe: previewIframeRef.current, reloadPreview, - projectId: projectIdRef.current, + projectId, targetPath, domId: element.domId, label: "Resize timeline clip", @@ -290,33 +303,32 @@ export function useTimelineClipTimingEditing({ }, sdkGsap, }).finally(() => invalidateGsapCache?.()); - const resizeFallback = () => - enqueueEdit(element, "Resize timeline clip", buildResizePatches, step).then(() => - finishResizeGsapSync(), - ); - const persistDone = - sdkSession && element.hfId && !element.link && !hasPbsAdjustment && !needsExtension - ? sdkTimingPersist( - element.hfId, - targetPath, - { start: authoredStart, duration: updates.duration }, - sdkSession, - { - editHistory: { recordEdit }, - writeProjectFile, - reloadPreview, - compositionPath: activeCompPath, - // Capture on-disk bytes as the undo `before` so undoing a timing - // resize restores the file verbatim, not a normalized full-DOM re-emit. - readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path), - publishSession: publishSdkSession, - }, - { label: "Resize timeline clip", ...step, skipRefresh: true }, - ).then((result) => { - if (!cutoverCommittedOrThrow(result)) return resizeFallback(); - return finishResizeGsapSync(sdkTimingGsapSync(result)); - }) - : resizeFallback(); + const hfId = element.hfId; + const sdkResize = + sdkSession && hfId && !element.link && !hasPbsAdjustment && !needsExtension + ? () => + sdkTimingPersist( + hfId, + targetPath, + { start: authoredStart, duration: updates.duration }, + sdkSession, + { + editHistory: { recordEdit }, + writeProjectFile, + reloadPreview, + compositionPath: activeCompPath, + // Capture on-disk bytes as the undo `before` so undoing a timing + // resize restores the file verbatim, not a normalized full-DOM re-emit. + readProjectFile: (path) => readFileContent(projectId ?? "", path), + publishSession: publishSdkSession, + }, + { label: "Resize timeline clip", ...step, skipRefresh: true }, + ) + : undefined; + const persistDone = enqueueEdit(element, "Resize timeline clip", buildResizePatches, step, { + ifEarlierRefused: refuseWithEarlier, + trySdk: sdkResize, + }).then((sdk) => finishResizeGsapSync(sdk && sdkTimingGsapSync(sdk))); return persistDone.catch((error) => { // Failed persist: revert the optimistic duration readout + live root. rollbackDuration(); diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx index 5b6321fb1e..a3bd405e64 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx +++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx @@ -8,6 +8,9 @@ import { installReactActEnvironment, mountReactHarness } from "./domSelectionTes import { useTrackPendingTimelineEdit } from "./useTrackPendingTimelineEdit"; import { flushStudioPendingEdits } from "../utils/studioPendingEdits"; import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator"; +import { enqueueTimelineEdit, type TimelineEditQueue } from "./timelineEditQueue"; +import type { TimelineGroupCommitOptions } from "./useTimelineGroupEditing"; +import { useTimelineTrimRipple } from "./useTimelineTrimRipple"; installReactActEnvironment(); @@ -66,6 +69,7 @@ describe("useTimelineDeleteOps: ripple undo label", () => { recordEdit?: DeleteOpsOptions["recordEdit"]; editQueueRef?: DeleteOpsOptions["editQueueRef"]; writeProjectFile?: DeleteOpsOptions["writeProjectFile"]; + alsoMount?: () => void; }) { const elements = [el("hf-a", 0, 2), el("hf-b", 2, 2), el("hf-c", 4, 2)]; const editQueueRef = overrides.editQueueRef ?? { current: Promise.resolve() }; @@ -83,6 +87,7 @@ describe("useTimelineDeleteOps: ripple undo label", () => { editQueueRef, handleTimelineGroupMove: overrides.handleTimelineGroupMove, }); + overrides.alsoMount?.(); return null; } mountReactHarness(); @@ -143,58 +148,78 @@ describe("useTimelineDeleteOps: ripple undo label", () => { ); }); - // Deletes hf-a, then hf-b once hf-a's ripple slid it to 0, both saving through one edit queue. - async function deleteTwoInARow(refuseOnce?: string) { + // Deletes, trims and moves sharing one edit queue; `writes` is the save order, with each move's starts. + function mountQueuedEdits(refuseOnce?: string) { const writes: string[] = []; let refused = refuseOnce; + const refuses = (write: string) => { + writes.push(write); + if (write !== refused) return false; + refused = undefined; + return true; + }; 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 }> }; - const write = `delete ${targets.map((t) => t.id).join(",")}`; - writes.push(write); - if (write === refused) { - refused = undefined; + if (refuses(`delete ${targets.map((t) => t.id).join(",")}`)) { return new Response("{}", { status: 500 }); } } 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() }; + // Stands in for the editor's group commits: each joins the edit queue, then writes the file. + const editQueueRef: TimelineEditQueue = { current: Promise.resolve() }; const writeProjectFile = vi.fn().mockResolvedValue(undefined); + const save = (write: string, options?: TimelineGroupCommitOptions) => + enqueueTimelineEdit( + editQueueRef, + async () => { + await options?.beforeTiming; + await serializeStudioFileMutations(writeProjectFile, ["index.html"], async () => { + if (refuses(write)) throw new Error("refused"); + }); + }, + { ifEarlierRefused: options?.ifEarlierRefused, projectId: "test-project" }, + ); const handleTimelineGroupMove: DeleteOpsOptions["handleTimelineGroupMove"] = ( changes, options, - ) => { - const run = editQueueRef.current.then(async () => { - await options?.beforeTiming; - await serializeStudioFileMutations(writeProjectFile, ["index.html"], async () => { - const write = `move ${changes.map((c) => `${c.element.id}@${c.start}`).join(",")}`; - writes.push(write); - if (write === refused) { - refused = undefined; - throw new Error("refused"); - } - }); - }); - editQueueRef.current = run.catch(() => undefined); - return run; - }; + ) => save(`move ${changes.map((c) => `${c.element.id}@${c.start}`).join(",")}`, options); + let trimRipple: ReturnType | null = null; const { elements, getHook } = mountDeleteHarness({ handleTimelineGroupMove, editQueueRef, writeProjectFile, + alsoMount: () => { + trimRipple = useTimelineTrimRipple({ + handleTimelineElementResize: vi.fn(), + handleTimelineGroupResize: (changes, options) => + save( + `resize ${changes.map((c) => `${c.element.id}+${c.duration}`).join(",")}`, + options, + ), + handleTimelineGroupMove, + showToast: vi.fn(), + reloadPreview: vi.fn(), + }); + }, }); + return { writes, elements, getHook, getTrim: () => trimRipple!, handleTimelineGroupMove }; + } + // Deletes hf-a, then hf-b once hf-a's ripple slid it to 0. + async function deleteTwoInARow(refuseOnce?: string) { + const queued = mountQueuedEdits(refuseOnce); + const { elements, getHook } = queued; 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)]); }); - return { writes, getHook }; + return queued; } // fails without the fix: the second delete saved between the first delete and its ripple. @@ -231,6 +256,42 @@ describe("useTimelineDeleteOps: ripple undo label", () => { expect(usePlayerStore.getState().elements).toEqual([el("hf-c", 2, 2)]); }); + // fails without the fix: the trim's shift saved hf-c at 1, placed as if hf-b's refused delete had happened. + it("a trim ripple queued behind a refused delete is refused before it writes, and only its shift rolls back", async () => { + const { writes, elements, getHook, getTrim } = mountQueuedEdits("delete hf-b"); + const [a, b] = elements; + + await act(async () => { + const deleting = getHook().handleTimelineElementDelete(b); + const trim = getTrim().handleTrimElement(a, { + start: 0, + duration: 1, + playbackStart: undefined, + }); + await Promise.all([deleting, trim]); + }); + + expect(writes).toEqual(["delete hf-b", "resize hf-a+1"]); + expect(usePlayerStore.getState().elements).toEqual([ + el("hf-a", 0, 2), + el("hf-c", 4, 2), + el("hf-b", 2, 2), + ]); + }); + + // 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"); + + 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 }])]); + }); + + expect(writes).toEqual(["delete hf-a", "move hf-c@8"]); + }); + 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 }); diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts index 40b90aad95..ca2a1b75c2 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.ts +++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts @@ -26,6 +26,11 @@ import type { } from "./useTimelineGroupEditing"; import { studioApiFetch } from "../utils/studioApiFetch"; import { countOf } from "../utils/countOf"; +import { + enqueueTimelineEdit, + refuseWithEarlier, + type TimelineEditQueue, +} from "./timelineEditQueue"; import { createStudioSaveHttpError } from "../utils/studioSaveDiagnostics"; /** Apply already-resolved ripple changes to the surviving elements for the @@ -67,7 +72,7 @@ interface UseTimelineDeleteOpsOptions { isRecordingRef?: MutableRefObject; forceReloadSdkSession?: () => void; previewIframeRef: RefObject; - editQueueRef: MutableRefObject>; + editQueueRef: TimelineEditQueue; /** 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. */ @@ -99,8 +104,6 @@ export function useTimelineDeleteOps({ // toast system has no action buttons, so Undo and the toggle location are // named in words instead. const rippleNoticeShownRef = useRef(false); - // Rejects once a pending delete or its shift is refused: shifts queued behind it were placed after it. - const placedRef = useRef>(Promise.resolve()); // fallow-ignore-next-line complexity const handleTimelineElementsDelete = useCallback( // fallow-ignore-next-line complexity @@ -145,7 +148,9 @@ export function useTimelineDeleteOps({ usePlayerStore.getState().setElements(applyRippleShifts(survivors, rippleChanges)); removeIframeTimelineElements(previewIframeRef.current, sameFile, activeCompPath); let rollbackDuration = () => {}; - const deleted = editQueueRef.current.then(async () => { + const inThisProject = (run: () => Promise) => + enqueueTimelineEdit(editQueueRef, run, { projectId: pid }); + const deleted = inThisProject(async () => { await saveServerRewriteWithHistory({ projectId: pid, path: targetPath, @@ -198,13 +203,12 @@ export function useTimelineDeleteOps({ }, }); }); - editQueueRef.current = deleted.catch(() => undefined); // One call queues both, so no later edit can land between the delete and its shift. - const placed = Promise.all([deleted, placedRef.current]).then(() => undefined); const shifted = rippleChanges && handleTimelineGroupMove(rippleChanges, { - beforeTiming: placed, + beforeTiming: deleted, + ifEarlierRefused: refuseWithEarlier, coalesceKey: step.coalesceKey, // Coalescing keeps the LAST entry's label; without this the undo // toast reads "Undid Move timeline clips" after a delete, naming @@ -214,13 +218,6 @@ export function useTimelineDeleteOps({ // the generic one would tell the user about one action twice. suppressFailureToast: true, }); - const mine = shifted ?? placed; - placedRef.current = mine; - void mine - .catch(() => undefined) - .then(() => { - if (placedRef.current === mine) placedRef.current = Promise.resolve(); - }); try { await deleted; } catch (error) { diff --git a/packages/studio/src/hooks/useTimelineEditing.switchMatrix.test.tsx b/packages/studio/src/hooks/useTimelineEditing.switchMatrix.test.tsx new file mode 100644 index 0000000000..bf8d687d8f --- /dev/null +++ b/packages/studio/src/hooks/useTimelineEditing.switchMatrix.test.tsx @@ -0,0 +1,157 @@ +// @vitest-environment happy-dom + +import React, { act } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { usePlayerStore, type TimelineElement } from "../player"; +import { sdkTimingPersist, type CutoverResult } from "../utils/sdkCutover"; +import { jsonResponse, requestUrl } from "./fetchStubTestUtils"; +import { useTimelineEditing } from "./useTimelineEditing"; + +vi.mock("../utils/sdkCutover", async (original) => ({ + ...(await original()), + sdkTimingPersist: vi.fn(), +})); + +(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +afterEach(() => { + document.body.innerHTML = ""; + usePlayerStore.getState().reset(); + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +const clip = (id: string, start: number): TimelineElement => ({ + id, + key: `index.html#${id}`, + domId: id, + hfId: `hf-${id}`, + tag: "div", + start, + duration: 2, + track: 0, + sourceFile: "index.html", +}); +const SOURCE = ["a", "b", "c", "x", "y", "z"] + .map((id) => `
`) + .join("\n"); + +function stubFetch() { + vi.stubGlobal( + "fetch", + vi.fn(async (input: Parameters[0]) => { + const url = requestUrl(input); + if (url.includes("/gsap-mutation-capabilities")) { + return jsonResponse({ atomicOwnershipPairs: true }); + } + if (url.includes("/gsap-mutations")) { + return jsonResponse({ mutated: false, scriptText: null, before: SOURCE, after: SOURCE }); + } + return jsonResponse({ content: SOURCE }); + }), + ); +} + +type Editing = ReturnType; +type Elements = Record<"x" | "y" | "z", TimelineElement>; + +// Every edit kind this queue touches, made in the newly opened project. +const NEW_PROJECT_EDITS: Array<[string, (hook: Editing, el: Elements) => Promise]> = [ + ["a ripple delete", (hook, el) => hook.handleTimelineElementsDelete([el.y])], + [ + "a ripple trim", + (hook, el) => hook.handleTimelineElementResize(el.x, { start: 0, duration: 1 }), + ], + ["a group move", (hook, el) => hook.handleTimelineGroupMove([{ element: el.z, start: 7 }])], + [ + "a single-clip move", + (hook, el) => hook.handleTimelineElementMove(el.z, { start: 7, track: 0 }), + ], + [ + "a single-clip trim", + (hook, el) => hook.handleTimelineElementResize(el.z, { start: 4, duration: 1 }), + ], +]; + +describe.each<[string, CutoverResult]>([ + ["the SDK path", { status: "committed", version: "1", before: "

", after: "

" }], + ["the file-write fallback", { status: "declined", reason: "feature_disabled" }], +])("saving through %s", (_path, sdkResult) => { + describe.each(["lands", "is refused"])( + "while the old project's ripple delete is held, then %s", + (outcome) => { + // fails without the fix: the old project's refusal refused the new project's ripple and trims. + it.each(NEW_PROJECT_EDITS)( + "%s in the new project completes and saves, as on main", + async (_kind, makeEdit) => { + stubFetch(); + vi.mocked(sdkTimingPersist).mockResolvedValue(sdkResult); + const store = usePlayerStore.getState(); + store.setRippleEditEnabled(true); + store.setDuration(20); + store.setElements([clip("a", 0), clip("b", 2), clip("c", 4)]); + + let releaseOldSave: (error?: Error) => void = () => {}; + const oldSave = new Promise((done, fail) => { + releaseOldSave = (error) => (error ? fail(error) : done()); + }); + const projects = { + old: { + write: vi.fn().mockReturnValueOnce(oldSave).mockResolvedValue(undefined), + toast: vi.fn(), + }, + new: { write: vi.fn().mockResolvedValue(undefined), toast: vi.fn() }, + }; + let hook: Editing | null = null; + function Harness({ projectId }: { projectId: "old" | "new" }) { + hook = useTimelineEditing({ + projectId, + activeCompPath: "index.html", + timelineElements: usePlayerStore.getState().elements, + showToast: projects[projectId].toast, + writeProjectFile: projects[projectId].write, + recordEdit: vi.fn(), + reloadPreview: vi.fn(), + previewIframeRef: { current: null }, + pendingTimelineEditPathRef: { current: new Set() }, + uploadProjectFiles: vi.fn(), + sdkSession: { getElement: () => null } as never, + }); + return null; + } + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + act(() => root.render()); + const oldDelete = hook!.handleTimelineElementsDelete([ + usePlayerStore.getState().elements[1]!, + ]); + + const el = { x: clip("x", 0), y: clip("y", 2), z: clip("z", 4) }; + act(() => { + usePlayerStore.getState().setElements([el.x, el.y, el.z]); + root.render(); + }); + vi.mocked(sdkTimingPersist).mockClear(); + let newEdit: Promise = Promise.resolve(); + act(() => { + newEdit = Promise.resolve(makeEdit(hook!, el)); + }); + + await act(async () => { + releaseOldSave(outcome === "lands" ? undefined : new Error("refused")); + await oldDelete; + await newEdit; + }); + + const saves = + projects.new.write.mock.calls.length + vi.mocked(sdkTimingPersist).mock.calls.length; + expect(saves).toBeGreaterThan(0); + expect(projects.new.toast.mock.calls.filter(([, tone]) => tone !== "info")).toEqual([]); + act(() => root.unmount()); + }, + ); + }, + ); +}); diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts index 02515e14c9..6de351c915 100644 --- a/packages/studio/src/hooks/useTimelineEditing.ts +++ b/packages/studio/src/hooks/useTimelineEditing.ts @@ -95,6 +95,7 @@ export function useTimelineEditing({ handleTimelineGroupResize: groupEditing.handleTimelineGroupResize, handleTimelineGroupMove: groupEditing.handleTimelineGroupMove, showToast, + reloadPreview, }); const handleToggleTrackHidden = useTimelineTrackVisibilityEditing({ diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx index 9ec6dc9aff..e13dcd54b9 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx @@ -14,6 +14,11 @@ import type { Root } from "react-dom/client"; import type { TimelineElement } from "../player"; import { persistTimelineMoveEditsAtomically } from "./timelineMoveAdapter"; import { useTimelineGroupEditing } from "./useTimelineGroupEditing"; +import { + enqueueTimelineEdit, + refuseWithEarlier, + type TimelineEditQueue, +} from "./timelineEditQueue"; import { usePersistentEditHistory } from "./usePersistentEditHistory"; import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness"; @@ -159,6 +164,74 @@ it.each([false, true])( }, ); +// The real group commits on a queue whose first edit was refused. +function mountBehindRefusedEdit(showToast = vi.fn()) { + const editQueueRef: TimelineEditQueue = { current: Promise.resolve() }; + const earlier = enqueueTimelineEdit( + editQueueRef, + () => Promise.reject(new Error("delete refused")), + { projectId: "fixture" }, + ); + const fetchMock = vi.fn(async () => new Response(JSON.stringify({ content: "" }))); + vi.stubGlobal("fetch", fetchMock); + let hook: ReturnType; + function Harness() { + hook = useTimelineGroupEditing({ + activeCompPath: "index.html", + editQueueRef, + pendingTimelineEditPathRef: { current: new Set() }, + previewIframeRef: { current: null }, + projectIdRef: { current: "fixture" }, + recordEdit: vi.fn(), + reloadPreview: vi.fn(), + showToast, + writeProjectFile: vi.fn(), + }); + return null; + } + const root = mountReactHarness(); + const unmount = () => { + act(() => root.unmount()); + vi.unstubAllGlobals(); + }; + return { earlier, fetchMock, getHook: () => hook!, unmount }; +} + +// fails without the fix: the shift ran and wrote though the edit queued before it was refused. +it("refuses a ripple shift before it writes when an edit queued before it is refused", async () => { + const { earlier, fetchMock, getHook, unmount } = mountBehindRefusedEdit(); + try { + await act(async () => { + const shift = getHook().handleTimelineGroupMove([{ element: el("a", 2, 2), start: 0 }], { + ifEarlierRefused: refuseWithEarlier, + suppressFailureToast: true, + }); + await expect(earlier).rejects.toThrow("delete refused"); + await expect(shift).rejects.toThrow("delete refused"); + }); + expect(fetchMock.mock.calls).toEqual([]); + } finally { + unmount(); + } +}); + +// 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(); + try { + await act(async () => { + const trim = getHook().handleTimelineGroupResize([ + { element: el("b", 0, 2), start: 0, duration: 1 }, + ]); + await expect(earlier).rejects.toThrow("delete refused"); + await expect(trim).rejects.toThrow("delete refused"); + }); + expect(fetchMock.mock.calls).toEqual([]); + } finally { + unmount(); + } +}); + const SLOWER_THAN_THE_DEFAULT_WINDOW_MS = 400; it("undoes each group move with its GSAP rewrite in one step, however long the rewrite takes", async () => { diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts index 19b98415c7..6a43d0d330 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.ts +++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts @@ -33,6 +33,11 @@ import { } from "./timelineTimingSync"; import type { GsapMutationStatus } from "./gsapMutationClient"; import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics"; +import { + enqueueTimelineEdit, + refuseWithEarlier, + type TimelineEditQueue, +} from "./timelineEditQueue"; export interface TimelineGroupMoveChange { element: TimelineElement; @@ -50,6 +55,8 @@ export interface TimelineGroupResizeChange { export interface TimelineGroupCommitOptions { beforeTiming?: Promise; + /** Runs before writing when an edit queued earlier was refused; throwing refuses this one. */ + ifEarlierRefused?: (error: unknown) => void; coalesceKey?: string; /** Overrides the default "Move timeline clips" undo-history label. Coalescing * keeps the LAST entry's label (editHistory.ts), so a mechanical follow-up @@ -64,7 +71,7 @@ export interface TimelineGroupCommitOptions { interface UseTimelineGroupEditingOptions { activeCompPath: string | null; - editQueueRef: MutableRefObject>; + editQueueRef: TimelineEditQueue; forceReloadSdkSession?: () => void; invalidateGsapCache?: () => void; isRecordingRef?: RefObject; @@ -127,23 +134,23 @@ export function useTimelineGroupEditing({ writeProjectFile, }: UseTimelineGroupEditingOptions) { const enqueueGroupOperation = useCallback( - (label: string, operation: (projectId: string) => Promise): Promise => { + ( + label: string, + ifEarlierRefused: ((error: unknown) => void) | undefined, + operation: (projectId: string) => Promise, + ): Promise => { if (isRecordingRef?.current) { showToast("Cannot edit timeline while recording", "error"); return Promise.reject(new Error(`${label}: blocked while recording`)); } const projectId = projectIdRef.current; if (!projectId) return Promise.reject(new Error(`${label}: no active project`)); - const run = editQueueRef.current.then(() => operation(projectId)); - // Keep the shared edit queue from wedging on a rejection, but return the raw - // (rejecting) promise so the gesture owner can roll back on a real failure. - editQueueRef.current = run.then( - () => undefined, - (error) => { - console.error(`[Timeline] Failed to persist: ${label}`, error); - }, - ); - return run; + // The raw (rejecting) promise lets the gesture owner roll back on a real failure. + return enqueueTimelineEdit(editQueueRef, () => operation(projectId), { + label, + ifEarlierRefused, + projectId, + }); }, [editQueueRef, isRecordingRef, projectIdRef, showToast], ); @@ -280,7 +287,7 @@ export function useTimelineGroupEditing({ syncPreviewContentDuration(previewIframeRef.current); const { coalesceKey, coalesceMs } = timingGestureStep("timeline-group-move", options); const label = options?.label ?? "Move timeline clips"; - return enqueueGroupOperation(label, async (projectId) => { + return enqueueGroupOperation(label, options?.ifEarlierRefused, async (projectId) => { await options?.beforeTiming; const sdk = await trySdkBatchPersist({ changes, @@ -398,7 +405,8 @@ export function useTimelineGroupEditing({ // the just-patched live DOM. See syncPreviewContentDuration. syncPreviewContentDuration(previewIframeRef.current); const { coalesceKey, coalesceMs } = timingGestureStep("timeline-group-resize", options); - return enqueueGroupOperation("Resize timeline clips", async (projectId) => { + const derivedStarts = refuseWithEarlier; + return enqueueGroupOperation("Resize timeline clips", derivedStarts, async (projectId) => { await options?.beforeTiming; const sdk = await trySdkBatchPersist({ changes, diff --git a/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx b/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx index 96317d0856..72d8d89013 100644 --- a/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx +++ b/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx @@ -41,6 +41,7 @@ function mountTrimRipple(rippleOn: boolean, elements: TimelineElement[]) { (changes: Array<{ element: TimelineElement }>, options?: { beforeTiming?: Promise }) => enqueue(`move ${ids(changes)}`, options?.beforeTiming), ); + const reloadPreview = vi.fn(); let hook: ReturnType | null = null; function Harness() { hook = useTimelineTrimRipple({ @@ -48,6 +49,7 @@ function mountTrimRipple(rippleOn: boolean, elements: TimelineElement[]) { handleTimelineGroupResize, handleTimelineGroupMove, showToast: vi.fn(), + reloadPreview, }); return null; } @@ -60,6 +62,7 @@ function mountTrimRipple(rippleOn: boolean, elements: TimelineElement[]) { handleTimelineElementResize, handleTimelineGroupResize, handleTimelineGroupMove, + reloadPreview, }; } @@ -94,6 +97,18 @@ describe("useTimelineTrimRipple", () => { expect(h.writes).toEqual(["resize a", "move b", "resize b"]); }); + // fails without the fix: the timeline put b back at 4 while the preview kept it at 3. + it("a refused shift puts the clips back and reloads the preview to match", async () => { + const a = el("a", 0, 4); + const h = mountTrimRipple(true, [a, el("b", 4, 2)]); + h.handleTimelineGroupMove.mockImplementationOnce(() => Promise.reject(new Error("refused"))); + + await act(() => h.trim(a, 0, 3)); + + expect(startOf("b")).toBe(4); + expect(h.reloadPreview).toHaveBeenCalledOnce(); + }); + it("leaves the gap and moves nothing with Ripple off", async () => { const a = el("a", 0, 4); const h = mountTrimRipple(false, [a, el("b", 4, 2)]); diff --git a/packages/studio/src/hooks/useTimelineTrimRipple.ts b/packages/studio/src/hooks/useTimelineTrimRipple.ts index 64a788fb52..823bf4ac1e 100644 --- a/packages/studio/src/hooks/useTimelineTrimRipple.ts +++ b/packages/studio/src/hooks/useTimelineTrimRipple.ts @@ -3,6 +3,7 @@ import { usePlayerStore, type TimelineElement } from "../player"; import { batchElementUpdates } from "../player/store/batchElementUpdates"; import { resolveMainTrackTrimRipple } from "../player/components/timelineGapCommit"; import { timingGestureStep } from "./timelineTimingSync"; +import { refuseWithEarlier } from "./timelineEditQueue"; import type { TimelineGroupCommitOptions, TimelineGroupMoveChange, @@ -22,6 +23,7 @@ interface UseTimelineTrimRippleOptions { options?: TimelineGroupCommitOptions, ) => Promise; showToast: (message: string, tone?: "error" | "info") => void; + reloadPreview: () => void; } function setStarts(changes: ReadonlyArray<{ element: TimelineElement; start: number }>) { @@ -38,6 +40,7 @@ export function useTimelineTrimRipple({ handleTimelineGroupResize, handleTimelineGroupMove, showToast, + reloadPreview, }: UseTimelineTrimRippleOptions) { const persistWithRipple = useCallback( async ( @@ -50,14 +53,23 @@ export function useTimelineTrimRipple({ const ripple = resolveMainTrackTrimRipple(elements, trims, rippleEditEnabled); if (!ripple) return persistTrimAlone(); const { coalesceKey } = timingGestureStep("timeline-resize", given); - const undoRipple = () => - setStarts(ripple.map(({ element }) => ({ element, start: element.start }))); + const undoRipple = () => { + const now = new Map(usePlayerStore.getState().elements.map((e) => [e.key ?? e.id, e])); + setStarts( + ripple.map(({ element, start }) => ({ + element, + start: (now.get(element.key ?? element.id)?.start ?? start) + element.start - start, + })), + ); + reloadPreview(); + }; setStarts(ripple); // Both join the edit queue in this call, so no later edit can land between the trim and // its shift and be overwritten by it. const trimmed = handleTimelineGroupResize(trims, { ...given, coalesceKey }); const shifted = handleTimelineGroupMove(ripple, { beforeTiming: trimmed, + ifEarlierRefused: refuseWithEarlier, coalesceKey, label, suppressFailureToast: true, @@ -77,7 +89,7 @@ export function useTimelineTrimRipple({ showToast("Clip trimmed, but the gap could not be closed.", "error"); } }, - [handleTimelineGroupResize, handleTimelineGroupMove, showToast], + [handleTimelineGroupResize, handleTimelineGroupMove, showToast, reloadPreview], ); const handleTrimElement = useCallback(