Skip to content

Write HTML. Render video. Built for agents.

refactor(studio): one hook owns file undo and redo (#4189)

Miguel Ángelfd6049f35615
diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.ts
index 19d1295b7a..8d1ab9fa68 100644
--- a/packages/studio/src/hooks/useAppHotkeys.ts
+++ b/packages/studio/src/hooks/useAppHotkeys.ts
@@ -3,7 +3,6 @@ import { usePlayerStore } from "../player";
import type { TimelineElement } from "../player";
import type { DomEditSelection } from "../components/editor/domEditing";
import type { LeftSidebarHandle } from "../components/sidebar/LeftSidebar";
-import { STUDIO_MOTION_PATH } from "../components/editor/studioMotion";
import { isTypingTarget } from "../utils/typingTarget";
import { useCaptionStore } from "../captions/store";
import {
@@ -11,13 +10,17 @@ import {
isCaptionPreviewVisible,
} from "../captions/components/CaptionOverlayUtils";
import { shouldIgnoreHistoryShortcut } from "../utils/studioHelpers";
-import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";
import {
type HotkeyCallbacks,
dispatchModifierKey,
dispatchPlainKey,
handleUndoRedoKey,
} from "./appHotkeysDispatch";
+import {
+ useEditHistoryActions,
+ type EditHistoryHandle,
+ type UseEditHistoryActionsOptions,
+} from "./useEditHistoryActions";
function iframeContentWindow(iframe: HTMLIFrameElement | null): Window | null {
try {
@@ -69,28 +72,6 @@ function tryApplyBeatHistory(
// ── Types ──
-interface HistoryResult {
- ok: boolean;
- reason?: string;
- label?: string;
- paths?: string[];
- /** Per-file restored/previous content, used to soft-apply the preview. */
- files?: Record<string, { previous: string; restored: string }>;
-}
-interface HistoryFileCallbacks {
- readFile: (path: string) => Promise<string>;
- writeFile: (path: string, content: string) => Promise<void>;
- serialize?: <T>(paths: readonly string[], task: () => Promise<T>) => Promise<T>;
-}
-interface EditHistoryHandle {
- undo: (cb: HistoryFileCallbacks) => Promise<HistoryResult>;
- redo: (cb: HistoryFileCallbacks) => Promise<HistoryResult>;
- state: {
- undo: ReadonlyArray<{ createdAt: number }>;
- redo: ReadonlyArray<{ createdAt: number }>;
- };
-}
-
interface UseAppHotkeysParams {
handleTimelineElementsDelete: (elements: TimelineElement[]) => Promise<void>;
handleTimelineElementSplit: (element: TimelineElement, splitTime: number) => Promise<void>;
@@ -105,10 +86,7 @@ interface UseAppHotkeysParams {
readProjectFile: (path: string) => Promise<string>;
writeProjectFile: (path: string, content: string) => Promise<void>;
showToast: (message: string, tone?: "error" | "info") => void;
- syncHistoryPreviewAfterApply: (restore: {
- paths?: string[];
- files?: Record<string, { previous: string; restored: string }>;
- }) => Promise<void>;
+ syncHistoryPreviewAfterApply: UseEditHistoryActionsOptions["syncHistoryPreviewAfterApply"];
waitForPendingDomEditSaves: () => Promise<void>;
leftSidebarRef: React.RefObject<LeftSidebarHandle | null>;
handleCopy: () => boolean;
@@ -165,22 +143,18 @@ export function useAppHotkeys({
// ── Undo / Redo ──
- const readHistoryFile = useCallback(
- (path: string): Promise<string> =>
- path === STUDIO_MOTION_PATH ? readOptionalProjectFile(path) : readProjectFile(path),
- [readOptionalProjectFile, readProjectFile],
- );
- const writeHistoryFile = useCallback(
- async (path: string, content: string): Promise<void> => {
- await writeProjectFile(path, content);
- },
- [writeProjectFile],
- );
- const serializeHistoryFiles = useCallback(
- <T>(paths: readonly string[], task: () => Promise<T>) =>
- serializeStudioFileMutations(writeProjectFile, paths, task),
- [writeProjectFile],
- );
+ const fileHistory = useEditHistoryActions({
+ editHistory,
+ readOptionalProjectFile,
+ readProjectFile,
+ writeProjectFile,
+ showToast,
+ syncHistoryPreviewAfterApply,
+ waitForPendingDomEditSaves,
+ onAfterUndoRedo,
+ activeCompPath,
+ forceReloadSdkSession,
+ });
const applyHistory = useCallback(
async (direction: "undo" | "redo") => {
@@ -204,42 +178,9 @@ export function useAppHotkeys({
// Beat edits interleave with file history by timestamp; handle them first.
if (tryApplyBeatHistory(direction, editHistory.state, showToast)) return;
- await waitForPendingDomEditSaves();
- const result = await editHistory[direction]({
- readFile: readHistoryFile,
- writeFile: writeHistoryFile,
- serialize: serializeHistoryFiles,
- });
- if (!result.ok && result.reason === "content-mismatch") {
- showToast(
- `File changed outside Studio. ${direction === "undo" ? "Undo" : "Redo"} history was not applied.`,
- "info",
- );
- return;
- }
- if (result.ok && result.label) {
- onAfterUndoRedo?.();
- // If the active composition was among the written files, force-reload
- // the SDK session so its in-memory doc matches the reverted content.
- if (activeCompPath && result.paths?.includes(activeCompPath)) {
- forceReloadSdkSession?.();
- }
- await syncHistoryPreviewAfterApply({ paths: result.paths, files: result.files });
- showToast(`${direction === "undo" ? "Undid" : "Redid"} ${result.label}`, "info");
- }
+ await fileHistory[direction]();
},
- [
- editHistory,
- readHistoryFile,
- showToast,
- syncHistoryPreviewAfterApply,
- waitForPendingDomEditSaves,
- writeHistoryFile,
- serializeHistoryFiles,
- onAfterUndoRedo,
- activeCompPath,
- forceReloadSdkSession,
- ],
+ [editHistory.state, fileHistory, showToast],
);
const handleUndo = useCallback(() => applyHistory("undo"), [applyHistory]);
diff --git a/packages/studio/src/hooks/useEditHistoryActions.test.tsx b/packages/studio/src/hooks/useEditHistoryActions.test.tsx
new file mode 100644
index 0000000000..104d3471c8
--- /dev/null
+++ b/packages/studio/src/hooks/useEditHistoryActions.test.tsx
@@ -0,0 +1,90 @@
+// @vitest-environment happy-dom
+
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { STUDIO_MOTION_PATH } from "../components/editor/studioMotion";
+import { useEditHistoryActions, type EditHistoryHandle } from "./useEditHistoryActions";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | null = null;
+afterEach(() => act(() => root?.unmount()));
+
+function mount(result: { ok: boolean; reason?: string; label?: string; paths?: string[] }) {
+ const editHistory = {
+ undo: vi.fn<EditHistoryHandle["undo"]>(async (cb) => {
+ if (result.ok) await cb.writeFile("index.html", "before");
+ return result;
+ }),
+ redo: vi.fn<EditHistoryHandle["redo"]>(async () => result),
+ };
+ const deps = {
+ editHistory,
+ readOptionalProjectFile: vi.fn(async () => ""),
+ readProjectFile: vi.fn(async () => ""),
+ writeProjectFile: vi.fn(async () => undefined),
+ showToast: vi.fn(),
+ syncHistoryPreviewAfterApply: vi.fn(async () => undefined),
+ waitForPendingDomEditSaves: vi.fn(async () => undefined),
+ onAfterUndoRedo: vi.fn(),
+ activeCompPath: "index.html",
+ forceReloadSdkSession: vi.fn(),
+ };
+ let actions!: ReturnType<typeof useEditHistoryActions>;
+ function Probe() {
+ actions = useEditHistoryActions(deps);
+ return null;
+ }
+ root = createRoot(document.createElement("div"));
+ act(() => root!.render(createElement(Probe)));
+ return { deps, actions };
+}
+
+describe("useEditHistoryActions", () => {
+ it("undo writes through the host writer, resyncs the preview and toasts the label", async () => {
+ const { deps, actions } = mount({ ok: true, label: "Move clip", paths: ["index.html"] });
+ await act(() => actions.undo());
+ expect(deps.waitForPendingDomEditSaves).toHaveBeenCalled();
+ expect(deps.writeProjectFile).toHaveBeenCalledWith("index.html", "before");
+ expect(deps.onAfterUndoRedo).toHaveBeenCalled();
+ expect(deps.forceReloadSdkSession).toHaveBeenCalled();
+ expect(deps.syncHistoryPreviewAfterApply).toHaveBeenCalled();
+ expect(deps.showToast).toHaveBeenCalledWith("Undid Move clip", "info");
+ });
+
+ it("redo reports the redone label and skips the SDK reload for other files", async () => {
+ const { deps, actions } = mount({ ok: true, label: "Split clip", paths: ["other.html"] });
+ await act(() => actions.redo());
+ expect(deps.forceReloadSdkSession).not.toHaveBeenCalled();
+ expect(deps.showToast).toHaveBeenCalledWith("Redid Split clip", "info");
+ });
+
+ it("explains a refused undo when the file changed on disk", async () => {
+ const { deps, actions } = mount({ ok: false, reason: "content-mismatch" });
+ await act(() => actions.undo());
+ expect(deps.showToast).toHaveBeenCalledWith(
+ "File changed outside Studio. Undo history was not applied.",
+ "info",
+ );
+ expect(deps.syncHistoryPreviewAfterApply).not.toHaveBeenCalled();
+ });
+
+ it("waits for pending saves first and reads the motion file through the optional reader", async () => {
+ const { deps, actions } = mount({ ok: true, label: "Move clip", paths: ["index.html"] });
+ const order: string[] = [];
+ deps.waitForPendingDomEditSaves.mockImplementation(async () => void order.push("wait"));
+ deps.editHistory.undo.mockImplementation(async (cb) => {
+ order.push("undo");
+ await cb.readFile(STUDIO_MOTION_PATH);
+ await cb.readFile("index.html");
+ await cb.serialize?.(["index.html"], async () => order.push("serialized"));
+ return { ok: true };
+ });
+ await act(() => actions.undo());
+ expect(order).toEqual(["wait", "undo", "serialized"]);
+ expect(deps.readOptionalProjectFile).toHaveBeenCalledWith(STUDIO_MOTION_PATH);
+ expect(deps.readProjectFile).toHaveBeenCalledWith("index.html");
+ expect(deps.readProjectFile).not.toHaveBeenCalledWith(STUDIO_MOTION_PATH);
+ });
+});
diff --git a/packages/studio/src/hooks/useEditHistoryActions.ts b/packages/studio/src/hooks/useEditHistoryActions.ts
new file mode 100644
index 0000000000..26efd28c95
--- /dev/null
+++ b/packages/studio/src/hooks/useEditHistoryActions.ts
@@ -0,0 +1,106 @@
+// fallow-ignore-file complexity
+import { useCallback, useMemo } from "react";
+import { STUDIO_MOTION_PATH } from "../components/editor/studioMotion";
+import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";
+
+interface HistoryResult {
+ ok: boolean;
+ reason?: string;
+ label?: string;
+ paths?: string[];
+ /** Per-file restored/previous content, used to soft-apply the preview. */
+ files?: Record<string, { previous: string; restored: string }>;
+}
+interface HistoryFileCallbacks {
+ readFile: (path: string) => Promise<string>;
+ writeFile: (path: string, content: string) => Promise<void>;
+ serialize?: <T>(paths: readonly string[], task: () => Promise<T>) => Promise<T>;
+}
+export interface EditHistoryHandle {
+ undo: (cb: HistoryFileCallbacks) => Promise<HistoryResult>;
+ redo: (cb: HistoryFileCallbacks) => Promise<HistoryResult>;
+ state: {
+ undo: ReadonlyArray<{ createdAt: number }>;
+ redo: ReadonlyArray<{ createdAt: number }>;
+ };
+}
+
+export interface UseEditHistoryActionsOptions {
+ editHistory: Pick<EditHistoryHandle, "undo" | "redo">;
+ readOptionalProjectFile: (path: string) => Promise<string>;
+ readProjectFile: (path: string) => Promise<string>;
+ writeProjectFile: (path: string, content: string) => Promise<void>;
+ showToast: (message: string, tone?: "error" | "info") => void;
+ syncHistoryPreviewAfterApply: (restore: Pick<HistoryResult, "paths" | "files">) => Promise<void>;
+ waitForPendingDomEditSaves: () => Promise<void>;
+ onAfterUndoRedo?: () => void;
+ /** Active composition path — decides whether undo/redo must resync the SDK session. */
+ activeCompPath?: string | null;
+ /** Reloads the SDK session after a revert of the active comp, past the self-write suppress window. */
+ forceReloadSdkSession?: () => void;
+}
+
+/** Applies one persisted file-history step: the single owner of undo/redo over project files. */
+export function useEditHistoryActions({
+ editHistory,
+ readOptionalProjectFile,
+ readProjectFile,
+ writeProjectFile,
+ showToast,
+ syncHistoryPreviewAfterApply,
+ waitForPendingDomEditSaves,
+ onAfterUndoRedo,
+ activeCompPath,
+ forceReloadSdkSession,
+}: UseEditHistoryActionsOptions) {
+ const readHistoryFile = useCallback(
+ (path: string): Promise<string> =>
+ path === STUDIO_MOTION_PATH ? readOptionalProjectFile(path) : readProjectFile(path),
+ [readOptionalProjectFile, readProjectFile],
+ );
+ const serializeHistoryFiles = useCallback(
+ <T>(paths: readonly string[], task: () => Promise<T>) =>
+ serializeStudioFileMutations(writeProjectFile, paths, task),
+ [writeProjectFile],
+ );
+
+ const apply = useCallback(
+ async (direction: "undo" | "redo") => {
+ const [noun, verb] = direction === "undo" ? ["Undo", "Undid"] : ["Redo", "Redid"];
+ await waitForPendingDomEditSaves();
+ const result = await editHistory[direction]({
+ readFile: readHistoryFile,
+ writeFile: writeProjectFile,
+ serialize: serializeHistoryFiles,
+ });
+ if (!result.ok && result.reason === "content-mismatch") {
+ showToast(`File changed outside Studio. ${noun} history was not applied.`, "info");
+ return;
+ }
+ if (result.ok && result.label) {
+ onAfterUndoRedo?.();
+ if (activeCompPath && result.paths?.includes(activeCompPath)) {
+ forceReloadSdkSession?.();
+ }
+ await syncHistoryPreviewAfterApply({ paths: result.paths, files: result.files });
+ showToast(`${verb} ${result.label}`, "info");
+ }
+ },
+ [
+ editHistory,
+ readHistoryFile,
+ showToast,
+ syncHistoryPreviewAfterApply,
+ waitForPendingDomEditSaves,
+ writeProjectFile,
+ serializeHistoryFiles,
+ onAfterUndoRedo,
+ activeCompPath,
+ forceReloadSdkSession,
+ ],
+ );
+
+ const undo = useCallback(() => apply("undo"), [apply]);
+ const redo = useCallback(() => apply("redo"), [apply]);
+ return useMemo(() => ({ undo, redo }), [undo, redo]);
+}