diff --git a/packages/studio/src/hooks/timelineEditQueue.test.tsx b/packages/studio/src/hooks/timelineEditQueue.test.tsx
index 4d673a120b..7368dae2c7 100644
--- a/packages/studio/src/hooks/timelineEditQueue.test.tsx
+++ b/packages/studio/src/hooks/timelineEditQueue.test.tsx
@@ -1,9 +1,17 @@
-import { describe, expect, it } from "vitest";
+// @vitest-environment happy-dom
+
+import { StrictMode, act } from "react";
+import { describe, expect, it, vi } from "vitest";
import {
enqueueTimelineEdit,
refuseWithEarlier,
+ useTimelineEditQueue,
+ whileShown,
type TimelineEditQueue,
} from "./timelineEditQueue";
+import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness";
+
+installReactActEnvironment();
function deferred() {
let reject: (error: Error) => void = () => {};
@@ -16,7 +24,7 @@ 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 queue: TimelineEditQueue = { current: Promise.resolve(), projectId: "project" };
const a = deferred();
const b = deferred();
const writes: string[] = [];
@@ -36,3 +44,78 @@ describe("enqueueTimelineEdit", () => {
expect(writes).toEqual([]);
});
});
+
+describe("useTimelineEditQueue", () => {
+ // fails without the fix: StrictMode's mount, cleanup and remount left the shown project's queue closed.
+ it("keeps the shown project's queue open under StrictMode, so its live steps run", () => {
+ let queue: TimelineEditQueue | null = null;
+ function Harness({ projectId }: { projectId: string }) {
+ queue = useTimelineEditQueue(projectId);
+ return null;
+ }
+ const root = mountReactHarness(
+
+
+ ,
+ );
+ const liveStep = vi.fn();
+
+ whileShown(queue!, liveStep);
+
+ expect(liveStep).toHaveBeenCalledOnce();
+ act(() => root.unmount());
+ });
+
+ // fails without the fix: back in A, A's next edit ran beside A's held save, which then wrote over it.
+ it("keeps one order across a switch away and back, so a held save is never written over", async () => {
+ const files: Record = { A: "" };
+ let queue: TimelineEditQueue | null = null;
+ function Harness({ projectId }: { projectId: string }) {
+ queue = useTimelineEditQueue(projectId);
+ return null;
+ }
+ const root = mountReactHarness();
+ let release: () => void = () => {};
+ const held = new Promise((done) => (release = done));
+ const first = enqueueTimelineEdit(queue!, async (pid) => {
+ const before = files[pid];
+ await held;
+ files[pid] = `${before}1`;
+ });
+ act(() => root.render());
+ act(() => root.render());
+ const second = enqueueTimelineEdit(queue!, async (pid) => {
+ files[pid] = `${files[pid]}2`;
+ });
+
+ release();
+ await Promise.all([first, second]);
+
+ expect(files.A).toBe("12");
+ act(() => root.unmount());
+ });
+
+ // fails without the fix: the old project's refused delete refused the new project's ripple.
+ it("gives a new project its own queue, so a refusal in the old one never touches it", async () => {
+ let queue: TimelineEditQueue | null = null;
+ function Harness({ projectId }: { projectId: string }) {
+ queue = useTimelineEditQueue(projectId);
+ return null;
+ }
+ const root = mountReactHarness();
+ const oldSave = deferred();
+ const refused = enqueueTimelineEdit(queue!, () => oldSave.promise);
+ act(() => root.render());
+ const writes: string[] = [];
+
+ const ripple = enqueueTimelineEdit(queue!, async () => void writes.push("ripple"), {
+ ifEarlierRefused: refuseWithEarlier,
+ });
+ oldSave.reject(new Error("refused"));
+
+ await expect(refused).rejects.toThrow("refused");
+ await expect(ripple).resolves.toBeUndefined();
+ expect(writes).toEqual(["ripple"]);
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/studio/src/hooks/timelineEditQueue.ts b/packages/studio/src/hooks/timelineEditQueue.ts
index 5a5799dcc7..c185900ef2 100644
--- a/packages/studio/src/hooks/timelineEditQueue.ts
+++ b/packages/studio/src/hooks/timelineEditQueue.ts
@@ -1,9 +1,54 @@
-import type { MutableRefObject } from "react";
+import { useLayoutEffect, useRef, type MutableRefObject, type RefObject } from "react";
+import type { PublishSdkSession } from "../utils/sdkCutover";
+import { forgetTimelineOptimisticGestures } from "../player/components/timelineOptimisticRevision";
/** 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> {
+ /** Per project, a promise that rejects when an edit of that project still pending is refused. */
placed?: Map>;
+ readonly projectId: string | null;
+ readonly shownProjectId?: { readonly current: string | null };
+}
+
+export function useTimelineEditQueue(projectId: string | null): TimelineEditQueue {
+ const shownProjectId = useRef(projectId);
+ shownProjectId.current = projectId;
+ const owner = useRef(null);
+ if (owner.current?.projectId !== projectId) {
+ const { current = Promise.resolve(), placed = new Map() } = owner.current ?? {};
+ owner.current = { current, placed, projectId, shownProjectId };
+ }
+ useLayoutEffect(() => () => forgetTimelineOptimisticGestures(), [projectId]);
+ return owner.current;
+}
+
+export const isClosed = (queue: TimelineEditQueue) =>
+ queue.shownProjectId !== undefined && queue.shownProjectId.current !== queue.projectId;
+
+/** Runs a queued edit's live-preview or timeline-store side only while its project is shown. */
+export function whileShown(queue: TimelineEditQueue, effect: () => void): void {
+ if (!isClosed(queue)) effect();
+}
+
+/** A queued edit's way to the live preview, inert once its project is no longer shown. */
+export function shownPreview(
+ queue: TimelineEditQueue,
+ live: {
+ iframeRef: RefObject;
+ reloadPreview: () => void;
+ publishSdkSession?: PublishSdkSession;
+ },
+) {
+ const publish = live.publishSdkSession;
+ return {
+ iframe: () => (isClosed(queue) ? null : live.iframeRef.current),
+ reload: () => whileShown(queue, live.reloadPreview),
+ publish:
+ publish &&
+ ((publication: Parameters[0]) =>
+ isClosed(queue) ? ("rejected-inactive-target" as const) : publish(publication)),
+ };
}
export const refuseWithEarlier = (error: unknown): never => {
@@ -14,11 +59,11 @@ export const refuseWithEarlier = (error: unknown): never => {
* refused, `ifEarlierRefused` runs first, and throwing refuses this edit too. */
export function enqueueTimelineEdit(
queue: TimelineEditQueue,
- run: () => Promise,
+ run: (projectId: string) => Promise,
{
label,
ifEarlierRefused,
- projectId = null,
+ projectId = queue.projectId,
}: {
label?: string;
ifEarlierRefused?: (error: unknown) => void;
@@ -29,7 +74,8 @@ export function enqueueTimelineEdit(
const earlier = byProject.get(projectId) ?? Promise.resolve();
const task = queue.current.then(async () => {
if (ifEarlierRefused) await earlier.catch(ifEarlierRefused);
- return run();
+ if (!projectId) throw new Error("No project to save this edit to");
+ return run(projectId);
});
const placed = Promise.allSettled([earlier, task]).then((settled) => {
for (const result of settled) if (result.status === "rejected") throw result.reason;
diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx
index aedec0b3e9..6323627b78 100644
--- a/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx
+++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx
@@ -6,7 +6,11 @@ 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 {
+ enqueueTimelineEdit,
+ useTimelineEditQueue,
+ type TimelineEditQueue,
+} from "./timelineEditQueue";
import { useTimelineClipTimingEditing } from "./useTimelineClipTimingEditing";
import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness";
@@ -30,9 +34,9 @@ const sdkWrites = vi.mocked(sdkTimingPersist);
const fileWrites = vi.mocked(persistTimelineEdit);
const gsapSyncs = vi.mocked(finishClipTimingFallback);
-function mountClipTiming(projectIdRef = { current: "project" as string | null }) {
+function mountClipTiming() {
usePlayerStore.getState().setDuration(10);
- const queue: TimelineEditQueue = { current: Promise.resolve() };
+ const queue: TimelineEditQueue = { current: Promise.resolve(), projectId: "project" };
let hook: ReturnType | null = null;
function Harness() {
hook = useTimelineClipTimingEditing({
@@ -46,7 +50,6 @@ function mountClipTiming(projectIdRef = { current: "project" as string | null })
pendingTimelineEditPathRef: { current: new Set() },
sdkSession: {} as never,
editQueueRef: queue,
- projectIdRef,
});
return null;
}
@@ -97,26 +100,44 @@ describe.each<[string, CutoverResult]>([
});
});
-describe("a single-clip SDK trim queued behind another save", () => {
+describe("a single-clip trim queued before a project switch", () => {
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 () => {
+ // fails without the fix: the queued SDK trim read index.html from the newly opened project.
+ it("reads and writes only the project it was queued in", async () => {
+ usePlayerStore.getState().setDuration(10);
sdkWrites.mockResolvedValue({ status: "committed", version: "1", before: "", after: "" });
- const projectIdRef = { current: "old" as string | null };
- const { queue, getHook, unmount } = mountClipTiming(projectIdRef);
+ let hook: ReturnType | null = null;
+ let queue: TimelineEditQueue | null = null;
+ function Harness({ projectId }: { projectId: string }) {
+ queue = useTimelineEditQueue(projectId);
+ 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,
+ });
+ return null;
+ }
+ const root = mountReactHarness();
let release: () => void = () => {};
const held = new Promise((done) => (release = done));
- void enqueueTimelineEdit(queue, () => held);
- const trim = getHook().handleTimelineElementResize(clipB, { start: 2, duration: 3 });
+ void enqueueTimelineEdit(queue!, () => held);
+ const trim = hook!.handleTimelineElementResize(clipB, { start: 2, duration: 3 });
- projectIdRef.current = "new";
+ act(() => root.render());
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();
+ act(() => root.unmount());
});
});
diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts
index 243a759f52..3de067741b 100644
--- a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts
+++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts
@@ -1,4 +1,4 @@
-import { useCallback, type MutableRefObject } from "react";
+import { useCallback } from "react";
import type { TimelineElement } from "../player";
import { toAuthoredStart, toCompositionTime } from "../player/store/timelineElement";
import {
@@ -30,6 +30,9 @@ import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics";
import {
enqueueTimelineEdit,
refuseWithEarlier,
+ isClosed,
+ shownPreview,
+ whileShown,
type TimelineEditQueue,
} from "./timelineEditQueue";
@@ -51,7 +54,6 @@ type UseTimelineClipTimingEditingOptions = Pick<
| "handleDomZIndexReorderCommitRef"
> & {
editQueueRef: TimelineEditQueue;
- projectIdRef: MutableRefObject;
};
/** One clip's move and resize: the timing write, then its tween rewrite, as one undo step. */
@@ -71,7 +73,6 @@ export function useTimelineClipTimingEditing({
invalidateGsapCache,
handleDomZIndexReorderCommitRef,
editQueueRef,
- projectIdRef,
}: UseTimelineClipTimingEditingOptions) {
const enqueueEdit = useCallback(
(
@@ -84,19 +85,18 @@ export function useTimelineClipTimingEditing({
trySdk,
}: {
ifEarlierRefused?: (error: unknown) => void;
- trySdk?: () => Promise;
+ trySdk?: (projectId: string) => Promise;
} = {},
): Promise => {
if (isRecordingRef?.current) {
showToast("Cannot edit timeline while recording", "error");
return Promise.resolve(undefined);
}
- const pid = projectIdRef.current;
- if (!pid) return Promise.resolve(undefined);
+ if (!editQueueRef.projectId) return Promise.resolve(undefined);
return enqueueTimelineEdit(
editQueueRef,
- async () => {
- const sdk = await trySdk?.();
+ async (pid) => {
+ const sdk = await trySdk?.(pid);
if (sdk && cutoverCommittedOrThrow(sdk)) return sdk;
await persistTimelineEdit({
projectId: pid,
@@ -106,13 +106,15 @@ export function useTimelineClipTimingEditing({
buildPatches,
writeProjectFile,
recordEdit,
- pendingTimelineEditPathRef,
+ pendingTimelineEditPathRef: isClosed(editQueueRef)
+ ? { current: new Set() }
+ : pendingTimelineEditPathRef,
...step,
});
- forceReloadSdkSession?.();
+ whileShown(editQueueRef, () => forceReloadSdkSession?.());
return undefined;
},
- { label, ifEarlierRefused, projectId: pid },
+ { label, ifEarlierRefused },
);
},
[
@@ -124,13 +126,11 @@ export function useTimelineClipTimingEditing({
isRecordingRef,
forceReloadSdkSession,
editQueueRef,
- projectIdRef,
],
);
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";
@@ -180,12 +180,17 @@ export function useTimelineClipTimingEditing({
);
};
const step = timingGestureStep("timeline-move");
+ const shown = shownPreview(editQueueRef, {
+ iframeRef: previewIframeRef,
+ reloadPreview,
+ publishSdkSession,
+ });
const finishMoveGsapSync = (sdkGsap?: ReturnType) =>
// One GSAP sync per edit: the SDK commit's own (sdkGsap), else the server rewrite here.
finishClipTimingFallback({
- iframe: previewIframeRef.current,
- reloadPreview,
- projectId,
+ iframe: shown.iframe(),
+ reloadPreview: shown.reload,
+ projectId: editQueueRef.projectId,
targetPath,
domId: element.domId,
label: "Move timeline clip",
@@ -194,12 +199,12 @@ export function useTimelineClipTimingEditing({
writeProjectFile,
edit: { kind: "shift", delta: updates.start - element.start },
sdkGsap,
- }).finally(() => invalidateGsapCache?.());
+ }).finally(() => whileShown(editQueueRef, () => invalidateGsapCache?.()));
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
- ? () =>
+ ? (projectId: string) =>
sdkTimingPersist(
hfId,
targetPath,
@@ -208,12 +213,12 @@ export function useTimelineClipTimingEditing({
{
editHistory: { recordEdit },
writeProjectFile,
- reloadPreview,
+ reloadPreview: shown.reload,
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,
+ readProjectFile: (path) => readFileContent(projectId, path),
+ publishSession: shown.publish,
},
{ label: "Move timeline clip", ...step, skipRefresh: true },
)
@@ -225,7 +230,7 @@ export function useTimelineClipTimingEditing({
.then((sdk) => finishMoveGsapSync(sdk && sdkTimingGsapSync(sdk)))
.catch((error) => {
// Failed persist: revert the optimistic duration readout + live root.
- rollbackDuration();
+ whileShown(editQueueRef, rollbackDuration);
showToast(getStudioSaveErrorMessage(error), "error");
throw error;
});
@@ -245,7 +250,7 @@ export function useTimelineClipTimingEditing({
handleDomZIndexReorderCommitRef,
showToast,
invalidateGsapCache,
- projectIdRef,
+ editQueueRef,
],
);
@@ -255,7 +260,6 @@ 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)],
@@ -285,11 +289,16 @@ export function useTimelineClipTimingEditing({
// script (timing-only resize) — same no-flash path as move; full reload is
// the fallback.
const step = timingGestureStep("timeline-resize");
+ const shown = shownPreview(editQueueRef, {
+ iframeRef: previewIframeRef,
+ reloadPreview,
+ publishSdkSession,
+ });
const finishResizeGsapSync = (sdkGsap?: ReturnType) =>
finishClipTimingFallback({
- iframe: previewIframeRef.current,
- reloadPreview,
- projectId,
+ iframe: shown.iframe(),
+ reloadPreview: shown.reload,
+ projectId: editQueueRef.projectId,
targetPath,
domId: element.domId,
label: "Resize timeline clip",
@@ -302,11 +311,11 @@ export function useTimelineClipTimingEditing({
to: { start: toCompositionTime(element, updates.start), duration: updates.duration },
},
sdkGsap,
- }).finally(() => invalidateGsapCache?.());
+ }).finally(() => whileShown(editQueueRef, () => invalidateGsapCache?.()));
const hfId = element.hfId;
const sdkResize =
sdkSession && hfId && !element.link && !hasPbsAdjustment && !needsExtension
- ? () =>
+ ? (projectId: string) =>
sdkTimingPersist(
hfId,
targetPath,
@@ -315,12 +324,12 @@ export function useTimelineClipTimingEditing({
{
editHistory: { recordEdit },
writeProjectFile,
- reloadPreview,
+ reloadPreview: shown.reload,
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,
+ readProjectFile: (path) => readFileContent(projectId, path),
+ publishSession: shown.publish,
},
{ label: "Resize timeline clip", ...step, skipRefresh: true },
)
@@ -331,7 +340,7 @@ export function useTimelineClipTimingEditing({
}).then((sdk) => finishResizeGsapSync(sdk && sdkTimingGsapSync(sdk)));
return persistDone.catch((error) => {
// Failed persist: revert the optimistic duration readout + live root.
- rollbackDuration();
+ whileShown(editQueueRef, rollbackDuration);
showToast(getStudioSaveErrorMessage(error), "error");
throw error;
});
@@ -347,7 +356,7 @@ export function useTimelineClipTimingEditing({
reloadPreview,
showToast,
invalidateGsapCache,
- projectIdRef,
+ editQueueRef,
],
);
diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx
index a3bd405e64..f92f40f8c1 100644
--- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx
+++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx
@@ -72,12 +72,14 @@ describe("useTimelineDeleteOps: ripple undo label", () => {
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() };
+ const editQueueRef = overrides.editQueueRef ?? {
+ current: Promise.resolve(),
+ projectId: "test-project",
+ };
usePlayerStore.getState().setElements(elements);
let hook: ReturnType | null = null;
function Harness() {
hook = useTimelineDeleteOps({
- projectIdRef: { current: "test-project" },
activeCompPath: "index.html",
showToast: overrides.showToast ?? vi.fn(),
writeProjectFile: overrides.writeProjectFile ?? vi.fn().mockResolvedValue(undefined),
@@ -171,7 +173,10 @@ describe("useTimelineDeleteOps: ripple undo label", () => {
}),
);
// Stands in for the editor's group commits: each joins the edit queue, then writes the file.
- const editQueueRef: TimelineEditQueue = { current: Promise.resolve() };
+ const editQueueRef: TimelineEditQueue = {
+ current: Promise.resolve(),
+ projectId: "test-project",
+ };
const writeProjectFile = vi.fn().mockResolvedValue(undefined);
const save = (write: string, options?: TimelineGroupCommitOptions) =>
enqueueTimelineEdit(
@@ -204,6 +209,7 @@ describe("useTimelineDeleteOps: ripple undo label", () => {
handleTimelineGroupMove,
showToast: vi.fn(),
reloadPreview: vi.fn(),
+ editQueueRef,
});
},
});
@@ -434,14 +440,13 @@ describe("useTimelineDeleteOps: undo race", () => {
function Harness() {
const track = useTrackPendingTimelineEdit();
const hook = useTimelineDeleteOps({
- projectIdRef: { current: "test-project" },
activeCompPath: "index.html",
showToast: vi.fn(),
writeProjectFile: vi.fn().mockResolvedValue(undefined),
recordEdit,
reloadPreview: vi.fn(),
previewIframeRef: { current: null },
- editQueueRef: { current: Promise.resolve() },
+ editQueueRef: { current: Promise.resolve(), projectId: "test-project" },
handleTimelineGroupMove: vi.fn().mockResolvedValue(undefined),
});
tracked = track(hook.handleTimelineElementsDelete);
@@ -536,14 +541,13 @@ describe("useTimelineDeleteOps: live preview", () => {
let hook: ReturnType | null = null;
function Harness() {
hook = useTimelineDeleteOps({
- projectIdRef: { current: "test-project" },
activeCompPath: "index.html",
showToast: vi.fn(),
writeProjectFile: vi.fn().mockResolvedValue(undefined),
recordEdit: vi.fn().mockResolvedValue(undefined),
reloadPreview: vi.fn(),
previewIframeRef: { current: iframe },
- editQueueRef: { current: Promise.resolve() },
+ editQueueRef: { current: Promise.resolve(), projectId: "test-project" },
handleTimelineGroupMove: vi.fn().mockResolvedValue(undefined),
});
return null;
diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts
index ca2a1b75c2..63a5d37fb0 100644
--- a/packages/studio/src/hooks/useTimelineDeleteOps.ts
+++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts
@@ -28,6 +28,8 @@ import { studioApiFetch } from "../utils/studioApiFetch";
import { countOf } from "../utils/countOf";
import {
enqueueTimelineEdit,
+ isClosed,
+ whileShown,
refuseWithEarlier,
type TimelineEditQueue,
} from "./timelineEditQueue";
@@ -63,7 +65,6 @@ function undoRippleShift(changes: TimelineGroupMoveChange[] | null, restore: Tim
}
interface UseTimelineDeleteOpsOptions {
- projectIdRef: MutableRefObject;
activeCompPath: string | null;
showToast: (message: string, tone?: "error" | "info") => void;
writeProjectFile: (path: string, content: string, expectedContent?: string) => Promise;
@@ -88,7 +89,6 @@ function unlinkInSource(source: string, survivors: readonly TimelineElement[]):
}
export function useTimelineDeleteOps({
- projectIdRef,
activeCompPath,
showToast,
writeProjectFile,
@@ -112,8 +112,7 @@ export function useTimelineDeleteOps({
showToast("Cannot edit timeline while recording", "error");
return;
}
- const pid = projectIdRef.current;
- if (!pid) throw new Error("No active project");
+ if (!editQueueRef.projectId) throw new Error("No active project");
const [element] = selection;
if (!element) return;
const label =
@@ -148,9 +147,7 @@ export function useTimelineDeleteOps({
usePlayerStore.getState().setElements(applyRippleShifts(survivors, rippleChanges));
removeIframeTimelineElements(previewIframeRef.current, sameFile, activeCompPath);
let rollbackDuration = () => {};
- const inThisProject = (run: () => Promise) =>
- enqueueTimelineEdit(editQueueRef, run, { projectId: pid });
- const deleted = inThisProject(async () => {
+ const deleted = enqueueTimelineEdit(editQueueRef, async (pid) => {
await saveServerRewriteWithHistory({
projectId: pid,
path: targetPath,
@@ -195,10 +192,12 @@ export function useTimelineDeleteOps({
const patchedContent = unlinkInSource(synced.source, alsoUnlink);
// Optimistically reflect the shrunk length in the readout/seek bar,
// rolling it back if the persist below fails (see captureDurationRollback).
- rollbackDuration = captureDurationRollback(previewIframeRef.current);
- if (synced.contentEnd > 0 && targetPath === (activeCompPath || "index.html")) {
- usePlayerStore.getState().setDuration(synced.contentEnd);
- }
+ whileShown(editQueueRef, () => {
+ rollbackDuration = captureDurationRollback(previewIframeRef.current);
+ if (synced.contentEnd > 0 && targetPath === (activeCompPath || "index.html")) {
+ usePlayerStore.getState().setDuration(synced.contentEnd);
+ }
+ });
return { disk: removedContent, after: patchedContent };
},
});
@@ -221,10 +220,12 @@ export function useTimelineDeleteOps({
try {
await deleted;
} catch (error) {
- rollbackDuration();
- undoRippleShift(rippleChanges, sameFile);
void shifted?.catch(() => undefined);
- reloadPreview();
+ whileShown(editQueueRef, () => {
+ rollbackDuration();
+ undoRippleShift(rippleChanges, sameFile);
+ reloadPreview();
+ });
throw error;
}
let rippleFailed = false;
@@ -236,12 +237,13 @@ export function useTimelineDeleteOps({
// toggle-off behaviour would have left anyway — not worth undoing
// an otherwise-successful delete over.
rippleFailed = true;
- undoRippleShift(rippleChanges, []);
+ whileShown(editQueueRef, () => undoRippleShift(rippleChanges, []));
console.error("[Timeline] ripple-edit failed to persist after delete", error);
showToast("Clip deleted, but the gap could not be closed.", "error");
}
}
+ if (isClosed(editQueueRef)) return;
usePlayerStore.getState().setSelectedElementId(null);
usePlayerStore.getState().setSelectedElementIds(new Set());
forceReloadSdkSession?.();
@@ -269,7 +271,6 @@ export function useTimelineDeleteOps({
},
[
activeCompPath,
- projectIdRef,
recordEdit,
showToast,
writeProjectFile,
diff --git a/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx b/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx
new file mode 100644
index 0000000000..f42b07a729
--- /dev/null
+++ b/packages/studio/src/hooks/useTimelineEditing.projectSwitch.test.tsx
@@ -0,0 +1,170 @@
+// @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 { jsonResponse, requestUrl } from "./fetchStubTestUtils";
+import { useTimelineEditing } from "./useTimelineEditing";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(() => {
+ document.body.innerHTML = "";
+ usePlayerStore.getState().reset();
+ vi.unstubAllGlobals();
+});
+
+const clip = (id: string, start: number): TimelineElement => ({
+ id,
+ key: `index.html#${id}`,
+ domId: id,
+ tag: "div",
+ start,
+ duration: 2,
+ track: 0,
+ sourceFile: "index.html",
+});
+const SOURCE = ["a", "b", "c", "d"]
+ .map(
+ (id, i) =>
+ ``,
+ )
+ .join("\n");
+
+/** Every request to project "new" is a leak; project "old" answers like a server. */
+function stubFetch(leaks: string[]) {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: Parameters[0]) => {
+ const url = requestUrl(input);
+ if (url.includes("/projects/new/")) {
+ leaks.push(url);
+ return jsonResponse({}, 500);
+ }
+ if (url.includes("/remove-elements/")) return jsonResponse({ content: SOURCE });
+ 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 });
+ }
+ if (url.includes("/files/")) return jsonResponse({ content: SOURCE });
+ throw new Error(`Unexpected fetch: ${url}`);
+ }),
+ );
+}
+
+/** An iframe stand-in that records every way anyone reaches into it, `instanceof` included. */
+function spyIframe(touched: string[]): HTMLIFrameElement {
+ return new Proxy({} as HTMLIFrameElement, {
+ get: (_, property) => {
+ touched.push(`get ${String(property)}`);
+ return undefined;
+ },
+ has: (_, property) => {
+ touched.push(`has ${String(property)}`);
+ return false;
+ },
+ getPrototypeOf: () => {
+ touched.push("getPrototypeOf");
+ return null;
+ },
+ });
+}
+
+describe.each(["lands", "is refused"])(
+ "edits queued in one project while its first save %s, then a project switch",
+ (outcome) => {
+ // fails without the fix: the old project's queued edits patched and reloaded the new preview.
+ it("never touch the new project's preview, timeline store, files or history", async () => {
+ const leaks: string[] = [];
+ stubFetch(leaks);
+ const store = usePlayerStore.getState();
+ store.setRippleEditEnabled(true);
+ store.setDuration(10);
+ store.setElements([clip("a", 0), clip("b", 2), clip("c", 4), clip("d", 6)]);
+
+ let releaseFirstSave: (error?: Error) => void = () => {};
+ const firstSave = new Promise((done, fail) => {
+ releaseFirstSave = (error) => (error ? fail(error) : done());
+ });
+ const oldWrite = vi.fn().mockReturnValueOnce(firstSave).mockResolvedValue(undefined);
+ const newProject = { write: vi.fn(), recordEdit: vi.fn() };
+ const shared = {
+ reloadPreview: vi.fn(),
+ forceReloadSdkSession: vi.fn(),
+ invalidateGsapCache: vi.fn(),
+ pending: { current: new Set() },
+ };
+ const oldIframe = document.createElement("iframe");
+ document.body.append(oldIframe);
+ const previewIframeRef: { current: HTMLIFrameElement | null } = { current: oldIframe };
+
+ let hook: ReturnType | null = null;
+ function Harness({ projectId }: { projectId: "old" | "new" }) {
+ const own = projectId === "old" ? { write: oldWrite, recordEdit: vi.fn() } : newProject;
+ hook = useTimelineEditing({
+ projectId,
+ activeCompPath: "index.html",
+ timelineElements: usePlayerStore.getState().elements,
+ showToast: vi.fn(),
+ writeProjectFile: own.write,
+ recordEdit: own.recordEdit,
+ reloadPreview: shared.reloadPreview,
+ previewIframeRef,
+ pendingTimelineEditPathRef: shared.pending,
+ uploadProjectFiles: vi.fn(),
+ forceReloadSdkSession: shared.forceReloadSdkSession,
+ invalidateGsapCache: shared.invalidateGsapCache,
+ });
+ return null;
+ }
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ act(() => root.render());
+
+ const [a, b, c, d] = usePlayerStore.getState().elements;
+ const queued: Array> = [];
+ act(() => {
+ queued.push(Promise.resolve(hook!.handleTimelineElementsDelete([b!])));
+ queued.push(
+ Promise.resolve(hook!.handleTimelineElementResize(a!, { start: 0, duration: 1 })),
+ );
+ queued.push(Promise.resolve(hook!.handleTimelineGroupMove([{ element: c!, start: 7 }])));
+ queued.push(Promise.resolve(hook!.handleTimelineElementMove(d!, { start: 9, track: 0 })));
+ });
+
+ const touchedIframe: string[] = [];
+ const newElements = [clip("x", 0), clip("y", 2)];
+ act(() => {
+ previewIframeRef.current = spyIframe(touchedIframe);
+ usePlayerStore.getState().setElements(newElements);
+ root.render();
+ });
+ for (const spy of Object.values(shared)) if (typeof spy === "function") spy.mockClear();
+ shared.pending.current.clear();
+ const storeChanges = vi.fn();
+ const stopWatching = usePlayerStore.subscribe(storeChanges);
+
+ await act(async () => {
+ releaseFirstSave(outcome === "lands" ? undefined : new Error("refused"));
+ await Promise.allSettled(queued);
+ });
+ stopWatching();
+
+ expect(touchedIframe).toEqual([]);
+ expect(shared.reloadPreview).not.toHaveBeenCalled();
+ expect(shared.forceReloadSdkSession).not.toHaveBeenCalled();
+ expect(shared.invalidateGsapCache).not.toHaveBeenCalled();
+ expect([...shared.pending.current]).toEqual([]);
+ expect(storeChanges).not.toHaveBeenCalled();
+ expect(usePlayerStore.getState().elements).toEqual(newElements);
+ expect(newProject.write).not.toHaveBeenCalled();
+ expect(newProject.recordEdit).not.toHaveBeenCalled();
+ expect(leaks).toEqual([]);
+ if (outcome === "lands") expect(oldWrite.mock.calls.length).toBeGreaterThan(1);
+ act(() => root.unmount());
+ });
+ },
+);
diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts
index 6de351c915..1554f77e52 100644
--- a/packages/studio/src/hooks/useTimelineEditing.ts
+++ b/packages/studio/src/hooks/useTimelineEditing.ts
@@ -24,6 +24,7 @@ import {
import { useTimelineGroupEditing } from "./useTimelineGroupEditing";
import { useTimelineClipTimingEditing } from "./useTimelineClipTimingEditing";
import { useTimelineTrimRipple } from "./useTimelineTrimRipple";
+import { useTimelineEditQueue } from "./timelineEditQueue";
import { useBlockedTimelineEditToast } from "./useBlockedTimelineEditToast";
import { useTimelineEditGate, type TimelineEditOutcome } from "./timelineEditPermission";
import type { UseTimelineEditingOptions } from "./useTimelineEditingTypes";
@@ -50,7 +51,7 @@ export function useTimelineEditing({
}: UseTimelineEditingOptions) {
const projectIdRef = useRef(projectId);
projectIdRef.current = projectId;
- const editQueueRef = useRef(Promise.resolve());
+ const editQueueRef = useTimelineEditQueue(projectId);
const track = useTrackPendingTimelineEdit();
const checkEditable = useTimelineEditGate(canEdit, showToast);
const guard = useTimelineEditGuard(canEdit, showToast);
@@ -63,7 +64,6 @@ export function useTimelineEditing({
isRecordingRef,
pendingTimelineEditPathRef,
previewIframeRef,
- projectIdRef,
recordEdit,
reloadPreview,
sdkSession,
@@ -87,7 +87,6 @@ export function useTimelineEditing({
invalidateGsapCache,
handleDomZIndexReorderCommitRef,
editQueueRef,
- projectIdRef,
});
const { handleTrimElement, handleTrimElements } = useTimelineTrimRipple({
@@ -96,6 +95,7 @@ export function useTimelineEditing({
handleTimelineGroupMove: groupEditing.handleTimelineGroupMove,
showToast,
reloadPreview,
+ editQueueRef,
});
const handleToggleTrackHidden = useTimelineTrackVisibilityEditing({
@@ -169,7 +169,6 @@ export function useTimelineEditing({
});
const { handleTimelineElementsDelete } = useTimelineDeleteOps({
- projectIdRef,
activeCompPath,
showToast,
writeProjectFile,
diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx
index e13dcd54b9..83e197d66d 100644
--- a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx
+++ b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx
@@ -46,10 +46,9 @@ describe("useTimelineGroupEditing: handleTimelineGroupMove suppressFailureToast"
function Harness() {
hook = useTimelineGroupEditing({
activeCompPath: "index.html",
- editQueueRef: { current: Promise.resolve() },
+ editQueueRef: { current: Promise.resolve(), projectId: null },
pendingTimelineEditPathRef: { current: new Set() },
previewIframeRef: { current: null },
- projectIdRef: { current: null },
recordEdit: vi.fn().mockResolvedValue(undefined),
reloadPreview: vi.fn(),
showToast,
@@ -115,10 +114,9 @@ it.each([false, true])(
function Harness() {
hook = useTimelineGroupEditing({
activeCompPath: "index.html",
- editQueueRef: { current: Promise.resolve() },
+ editQueueRef: { current: Promise.resolve(), projectId: "fixture" },
pendingTimelineEditPathRef: { current: new Set() },
previewIframeRef: { current: iframe },
- projectIdRef: { current: "fixture" },
recordEdit,
writeProjectFile,
reloadPreview: vi.fn(),
@@ -166,11 +164,9 @@ 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 editQueueRef: TimelineEditQueue = { current: Promise.resolve(), projectId: "fixture" };
+ const earlier = enqueueTimelineEdit(editQueueRef, () =>
+ Promise.reject(new Error("delete refused")),
);
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ content: "" })));
vi.stubGlobal("fetch", fetchMock);
@@ -181,7 +177,6 @@ function mountBehindRefusedEdit(showToast = vi.fn()) {
editQueueRef,
pendingTimelineEditPathRef: { current: new Set() },
previewIframeRef: { current: null },
- projectIdRef: { current: "fixture" },
recordEdit: vi.fn(),
reloadPreview: vi.fn(),
showToast,
@@ -266,10 +261,9 @@ it("undoes each group move with its GSAP rewrite in one step, however long the r
editHistory = usePersistentEditHistory({ projectId: "demo" });
editing = useTimelineGroupEditing({
activeCompPath: "index.html",
- editQueueRef: { current: Promise.resolve() },
+ editQueueRef: { current: Promise.resolve(), projectId: "demo" },
pendingTimelineEditPathRef: { current: new Set() },
previewIframeRef: { current: null },
- projectIdRef: { current: "demo" },
recordEdit: editHistory.recordEdit,
reloadPreview: vi.fn(),
showToast: vi.fn(),
diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts
index 6a43d0d330..79cc622c90 100644
--- a/packages/studio/src/hooks/useTimelineGroupEditing.ts
+++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts
@@ -36,6 +36,9 @@ import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics";
import {
enqueueTimelineEdit,
refuseWithEarlier,
+ isClosed,
+ shownPreview,
+ whileShown,
type TimelineEditQueue,
} from "./timelineEditQueue";
@@ -77,7 +80,6 @@ interface UseTimelineGroupEditingOptions {
isRecordingRef?: RefObject;
pendingTimelineEditPathRef: MutableRefObject>;
previewIframeRef: RefObject;
- projectIdRef: MutableRefObject;
recordEdit: (input: RecordEditInput) => Promise;
reloadPreview: () => void;
sdkSession?: Composition | null;
@@ -125,7 +127,6 @@ export function useTimelineGroupEditing({
isRecordingRef,
pendingTimelineEditPathRef,
previewIframeRef,
- projectIdRef,
recordEdit,
reloadPreview,
sdkSession,
@@ -143,16 +144,14 @@ export function useTimelineGroupEditing({
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`));
+ if (!editQueueRef.projectId) return Promise.reject(new Error(`${label}: no active project`));
// The raw (rejecting) promise lets the gesture owner roll back on a real failure.
- return enqueueTimelineEdit(editQueueRef, () => operation(projectId), {
+ return enqueueTimelineEdit(editQueueRef, operation, {
label,
ifEarlierRefused,
- projectId,
});
},
- [editQueueRef, isRecordingRef, projectIdRef, showToast],
+ [editQueueRef, isRecordingRef, showToast],
);
const persistServerBatch = useCallback(
@@ -170,14 +169,17 @@ export function useTimelineGroupEditing({
changes: batchChanges,
writeProjectFile,
recordEdit,
- pendingTimelineEditPathRef,
+ pendingTimelineEditPathRef: isClosed(editQueueRef)
+ ? { current: new Set() }
+ : pendingTimelineEditPathRef,
coalesceKey,
coalesceMs,
});
- forceReloadSdkSession?.();
+ whileShown(editQueueRef, () => forceReloadSdkSession?.());
},
[
activeCompPath,
+ editQueueRef,
forceReloadSdkSession,
pendingTimelineEditPathRef,
recordEdit,
@@ -191,6 +193,7 @@ export function useTimelineGroupEditing({
// server syncs) when it handled the edit; null → caller falls through to the server.
const trySdkBatchPersist = useCallback(
async (input: {
+ projectId: string;
changes: readonly { element: TimelineElement }[];
sdkChanges: Array<{
hfId: string;
@@ -209,6 +212,11 @@ export function useTimelineGroupEditing({
input.eligible &&
input.sdkChanges.every((change) => change !== null);
if (!canUseSdk) return null;
+ const shown = shownPreview(editQueueRef, {
+ iframeRef: previewIframeRef,
+ reloadPreview,
+ publishSdkSession,
+ });
const result = await sdkTimingBatchPersist(
input.sdkChanges.filter((change): change is NonNullable => change !== null),
sharedPath,
@@ -216,10 +224,10 @@ export function useTimelineGroupEditing({
{
editHistory: { recordEdit },
writeProjectFile,
- reloadPreview,
+ reloadPreview: shown.reload,
compositionPath: activeCompPath,
- readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),
- publishSession: publishSdkSession,
+ readProjectFile: (path) => readFileContent(input.projectId, path),
+ publishSession: shown.publish,
},
{
label: input.label,
@@ -232,7 +240,8 @@ export function useTimelineGroupEditing({
},
[
activeCompPath,
- projectIdRef,
+ editQueueRef,
+ previewIframeRef,
publishSdkSession,
recordEdit,
reloadPreview,
@@ -276,6 +285,7 @@ export function useTimelineGroupEditing({
// Snapshot the duration BEFORE the optimistic updates below so a failed
// persist can roll the readout + live root back (see captureDurationRollback).
const rollbackDuration = captureDurationRollback(previewIframeRef.current);
+ const shown = shownPreview(editQueueRef, { iframeRef: previewIframeRef, reloadPreview });
// needsExtension gates the SDK path (setTiming can't grow the root duration),
// so read the store BEFORE the readout sync below optimistically updates it.
// Track-only batches leave every clip end unchanged, so both this and the
@@ -290,6 +300,7 @@ export function useTimelineGroupEditing({
return enqueueGroupOperation(label, options?.ifEarlierRefused, async (projectId) => {
await options?.beforeTiming;
const sdk = await trySdkBatchPersist({
+ projectId,
changes,
sdkChanges: toSdkTimingChanges(changes, (change) => ({
start: toAuthoredStart(change.element, change.start),
@@ -333,8 +344,8 @@ export function useTimelineGroupEditing({
try {
await finishGroupTimingGsapFallback({
projectId,
- iframe: previewIframeRef.current,
- reloadPreview,
+ iframe: shown.iframe(),
+ reloadPreview: shown.reload,
label,
errorLabel: "Failed to shift GSAP positions",
coalesceKey,
@@ -348,12 +359,12 @@ export function useTimelineGroupEditing({
shiftGsapMutation(change.element.domId, change.start - change.element.start),
});
} finally {
- invalidateGsapCache?.();
+ whileShown(editQueueRef, () => invalidateGsapCache?.());
}
}).catch((error) => {
// Failed persist: revert the optimistic duration readout + live root
// alongside the gesture owner's store rollback.
- rollbackDuration();
+ whileShown(editQueueRef, rollbackDuration);
if (options?.suppressFailureToast) {
console.error("[Timeline] group move failed to persist", error);
} else {
@@ -364,6 +375,7 @@ export function useTimelineGroupEditing({
},
[
activeCompPath,
+ editQueueRef,
enqueueGroupOperation,
persistServerBatch,
previewIframeRef,
@@ -398,6 +410,7 @@ export function useTimelineGroupEditing({
// Snapshot the duration BEFORE the optimistic updates below so a failed
// persist can roll the readout + live root back (see captureDurationRollback).
const rollbackDuration = captureDurationRollback(previewIframeRef.current);
+ const shown = shownPreview(editQueueRef, { iframeRef: previewIframeRef, reloadPreview });
// needsExtension gates the SDK path (setTiming can't grow the root duration),
// so read the store BEFORE the readout sync below optimistically updates it.
const needsExtension = extendRootDurationIfNeeded(maxEnd);
@@ -409,6 +422,7 @@ export function useTimelineGroupEditing({
return enqueueGroupOperation("Resize timeline clips", derivedStarts, async (projectId) => {
await options?.beforeTiming;
const sdk = await trySdkBatchPersist({
+ projectId,
changes,
sdkChanges: toSdkTimingChanges(changes, (change) => ({
start: toAuthoredStart(change.element, change.start),
@@ -442,8 +456,8 @@ export function useTimelineGroupEditing({
try {
await finishGroupTimingGsapFallback({
projectId,
- iframe: previewIframeRef.current,
- reloadPreview,
+ iframe: shown.iframe(),
+ reloadPreview: shown.reload,
label: "Resize timeline clips",
errorLabel: "Failed to scale GSAP positions",
coalesceKey,
@@ -463,18 +477,19 @@ export function useTimelineGroupEditing({
),
});
} finally {
- invalidateGsapCache?.();
+ whileShown(editQueueRef, () => invalidateGsapCache?.());
}
}).catch((error) => {
// Failed persist: revert the optimistic duration readout + live root
// alongside the gesture owner's store rollback.
- rollbackDuration();
+ whileShown(editQueueRef, rollbackDuration);
showToast(getStudioSaveErrorMessage(error), "error");
throw error;
});
},
[
activeCompPath,
+ editQueueRef,
enqueueGroupOperation,
persistServerBatch,
previewIframeRef,
diff --git a/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx b/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx
index 72d8d89013..3f639eab40 100644
--- a/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx
+++ b/packages/studio/src/hooks/useTimelineTrimRipple.test.tsx
@@ -50,6 +50,7 @@ function mountTrimRipple(rippleOn: boolean, elements: TimelineElement[]) {
handleTimelineGroupMove,
showToast: vi.fn(),
reloadPreview,
+ editQueueRef: { current: Promise.resolve(), projectId: "project" },
});
return null;
}
diff --git a/packages/studio/src/hooks/useTimelineTrimRipple.ts b/packages/studio/src/hooks/useTimelineTrimRipple.ts
index 823bf4ac1e..548a47fa84 100644
--- a/packages/studio/src/hooks/useTimelineTrimRipple.ts
+++ b/packages/studio/src/hooks/useTimelineTrimRipple.ts
@@ -3,7 +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 { isClosed, refuseWithEarlier, type TimelineEditQueue } from "./timelineEditQueue";
import type {
TimelineGroupCommitOptions,
TimelineGroupMoveChange,
@@ -24,6 +24,7 @@ interface UseTimelineTrimRippleOptions {
) => Promise;
showToast: (message: string, tone?: "error" | "info") => void;
reloadPreview: () => void;
+ editQueueRef: TimelineEditQueue;
}
function setStarts(changes: ReadonlyArray<{ element: TimelineElement; start: number }>) {
@@ -41,6 +42,7 @@ export function useTimelineTrimRipple({
handleTimelineGroupMove,
showToast,
reloadPreview,
+ editQueueRef,
}: UseTimelineTrimRippleOptions) {
const persistWithRipple = useCallback(
async (
@@ -54,6 +56,7 @@ export function useTimelineTrimRipple({
if (!ripple) return persistTrimAlone();
const { coalesceKey } = timingGestureStep("timeline-resize", given);
const undoRipple = () => {
+ if (isClosed(editQueueRef)) return;
const now = new Map(usePlayerStore.getState().elements.map((e) => [e.key ?? e.id, e]));
setStarts(
ripple.map(({ element, start }) => ({
@@ -89,7 +92,7 @@ export function useTimelineTrimRipple({
showToast("Clip trimmed, but the gap could not be closed.", "error");
}
},
- [handleTimelineGroupResize, handleTimelineGroupMove, showToast, reloadPreview],
+ [handleTimelineGroupResize, handleTimelineGroupMove, showToast, reloadPreview, editQueueRef],
);
const handleTrimElement = useCallback(
diff --git a/packages/studio/src/player/components/timelineOptimisticRevision.ts b/packages/studio/src/player/components/timelineOptimisticRevision.ts
index ea6dbecae6..857ad634f6 100644
--- a/packages/studio/src/player/components/timelineOptimisticRevision.ts
+++ b/packages/studio/src/player/components/timelineOptimisticRevision.ts
@@ -3,7 +3,11 @@ import { batchElementUpdates } from "../store/batchElementUpdates";
type UpdateElement = (key: string, updates: Partial) => void;
type RevisionScope = "timing" | "membership";
-const revisionsByUpdater = new WeakMap>>();
+let revisionsByUpdater = new WeakMap>>();
+
+export function forgetTimelineOptimisticGestures(): void {
+ revisionsByUpdater = new WeakMap();
+}
export function beginTimelineOptimisticGesture(
updateElement: UpdateElement,