# 撤销和重做

> 给编辑器加上 Fabric.js 撤销重做：每个用户操作一步，代码改动用事务记录，支持键盘快捷键，历史记录始终很快。

Source: https://fabricjs-document-engine.jscrate.dev/zh/docs/guides/undo-redo
Last updated: 2026-09-28

Fabric.js 本身没有撤销功能。用这个包，创建引擎后 Fabric.js 撤销重做就已经开启。每个用户操作是一步，你只要调用 `undo()` 和 `redo()`，就能回到上一步或下一步。

```tsx
"use client";

import { bindKeyboardShortcuts } from "fabricjs-document-engine";
import {
  useDocumentEngine,
  useDocumentState,
} from "fabricjs-document-engine/react";
import {
  CircleIcon,
  PaletteIcon,
  Redo2Icon,
  SquareIcon,
  Undo2Icon,
} from "lucide-react";
import { useTranslations } from "next-intl";
import { useEffect, useRef } from "react";

import {
  COLORS,
  DemoCanvas,
  DemoFrame,
  newShape,
  seedShapes,
  Status,
  Toolbar,
  ToolButton,
} from "./demo-ui";
import { useFabricCanvas } from "./use-fabric-canvas";

export default function UndoRedoDemo() {
  const t = useTranslations("demos");
  const { elementRef, canvas } = useFabricCanvas();
  const engine = useDocumentEngine(canvas);
  const state = useDocumentState(engine);
  const demoRef = useRef<HTMLDivElement>(null);

  // Start from a small drawing, with an empty history.
  useEffect(() => {
    if (!engine) return;
    engine.canvas.add(...seedShapes());
    engine.clearHistory();
  }, [engine]);

  // Ctrl/Cmd+Z and Ctrl/Cmd+Shift+Z, while focus is inside this demo.
  useEffect(() => {
    if (!engine || !demoRef.current) return;
    return bindKeyboardShortcuts(engine, { target: demoRef.current });
  }, [engine]);

  function recolor() {
    const target = canvas?.getActiveObject() ?? canvas?.getObjects().at(-1);
    if (!engine || !target) return;

    const next =
      COLORS[(COLORS.indexOf(String(target.fill)) + 1) % COLORS.length];
    // Fabric fires no event for `set`, so record it as one labelled step.
    engine.transaction("Recolor", () => target.set("fill", next));
    canvas?.requestRenderAll();
  }

  return (
    <DemoFrame ref={demoRef} tabIndex={-1}>
      <DemoCanvas elementRef={elementRef} label={t("canvas")} />

      <Toolbar>
        <ToolButton
          icon={SquareIcon}
          label={t("square")}
          onClick={() => canvas?.add(newShape("square"))}
        />
        <ToolButton
          icon={CircleIcon}
          label={t("circle")}
          onClick={() => canvas?.add(newShape("circle"))}
        />
        <ToolButton icon={PaletteIcon} label={t("recolor")} onClick={recolor} />
        <span className="ml-auto flex gap-1.5">
          <ToolButton
            icon={Undo2Icon}
            label={t("undo")}
            iconOnly
            disabled={!state?.canUndo}
            onClick={() => void engine?.undo()}
          />
          <ToolButton
            icon={Redo2Icon}
            label={t("redo")}
            iconOnly
            disabled={!state?.canRedo}
            onClick={() => void engine?.redo()}
          />
        </span>
      </Toolbar>

      <Status tone={state?.canUndo ? "ok" : "idle"}>
        {state?.canUndo
          ? t("undoRedo.steps", {
              count: engine?.getHistory().undo.length ?? 0,
            })
          : t("undoRedo.empty")}
      </Status>
    </DemoFrame>
  );
}
```

```tsx
import { Canvas } from "fabric";
import { useLayoutEffect, useRef, useState } from "react";

/**
 * The page every demo draws on. The document keeps this size; CSS scales the
 * canvas down to fit its card, so saved documents and exports never depend on
 * the screen.
 */
export const PAGE = { width: 480, height: 300 };

// Selection handles in the site's style. Fabric does not save these.
const SELECTION = {
  borderColor: "#6f00ff",
  borderScaleFactor: 1.5,
  borderOpacityWhenMoving: 0.5,
  cornerStyle: "circle",
  cornerSize: 11,
  cornerColor: "#ffffff",
  cornerStrokeColor: "#6f00ff",
  transparentCorners: false,
} as const;

export function styleSelection(canvas: Canvas) {
  canvas.set({
    selectionColor: "rgba(111, 0, 255, 0.06)",
    selectionBorderColor: "#6f00ff",
    selectionLineWidth: 1,
  });
  const style = () => canvas.getActiveObject()?.set(SELECTION);
  canvas.on("selection:created", style);
  canvas.on("selection:updated", style);
}

/**
 * Creates a Fabric.js canvas once the `<canvas>` element exists, and disposes
 * it on unmount. The engine is created from the returned `canvas`.
 */
export function useFabricCanvas({ width, height } = PAGE) {
  const elementRef = useRef<HTMLCanvasElement>(null);
  const [canvas, setCanvas] = useState<Canvas | null>(null);

  // A layout effect creates the canvas before the first paint.
  useLayoutEffect(() => {
    const created = new Canvas(elementRef.current!, {
      width,
      height,
      backgroundColor: "#ffffff",
    });
    styleSelection(created);
    setCanvas(created);

    return () => {
      // Dispose after the engine's own cleanup, so its last recovery copy
      // still sees the objects.
      setTimeout(() => created.dispose().catch(() => undefined));
    };
  }, [width, height]);

  return { elementRef, canvas };
}
```

```tsx
import { Circle, type FabricObject, Rect, Triangle } from "fabric";
import type { LucideIcon } from "lucide-react";

import { cn } from "@/lib/utils";

import { PAGE } from "./use-fabric-canvas";

export const COLORS = ["#f2836f", "#5fe6c4", "#7ad9ec", "#6f00ff", "#ffd666"];

// Demo shapes are placed by their top-left corner, like a design tool.
const CORNER = { originX: "left", originY: "top" } as const;

/** A new shape at a random spot on the page. */
export function newShape(kind: "square" | "circle", fill?: string) {
  const left = 40 + Math.random() * (PAGE.width - 160);
  const top = 30 + Math.random() * (PAGE.height - 120);
  const color = fill ?? COLORS[Math.floor(Math.random() * COLORS.length)];
  return kind === "square"
    ? new Rect({
        ...CORNER,
        left,
        top,
        width: 88,
        height: 64,
        rx: 10,
        ry: 10,
        fill: color,
      })
    : new Circle({ ...CORNER, left, top, radius: 34, fill: color });
}

/** A small composed drawing, so no demo starts on an empty page. */
export function seedShapes(): FabricObject[] {
  return [
    new Rect({
      ...CORNER,
      left: 48,
      top: 56,
      width: 176,
      height: 124,
      rx: 16,
      ry: 16,
      fill: COLORS[4],
    }),
    new Circle({ ...CORNER, left: 268, top: 44, radius: 58, fill: COLORS[0] }),
    new Rect({
      ...CORNER,
      left: 256,
      top: 196,
      width: 176,
      height: 52,
      rx: 26,
      ry: 26,
      fill: COLORS[1],
    }),
    new Triangle({
      ...CORNER,
      left: 96,
      top: 196,
      width: 72,
      height: 60,
      fill: COLORS[3],
    }),
  ];
}

export function DemoFrame({
  className,
  ...props
}: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "flex w-full max-w-md flex-col gap-3 text-left outline-none",
        className
      )}
      {...props}
    />
  );
}

/**
 * Scales the fixed-size Fabric canvas to the frame's width. The rules are
 * `!important` because Fabric writes its sizes as inline styles.
 */
export function DemoCanvas({
  elementRef,
  label,
  page = PAGE,
  children,
}: {
  elementRef: React.Ref<HTMLCanvasElement>;
  label: string;
  page?: { width: number; height: number };
  children?: React.ReactNode;
}) {
  return (
    <div
      className="relative overflow-hidden rounded-lg border bg-white shadow-xs [&_.canvas-container]:aspect-(--page)! [&_.canvas-container]:h-auto! [&_.canvas-container]:w-full! [&_canvas]:h-full! [&_canvas]:w-full!"
      style={
        { "--page": `${page.width} / ${page.height}` } as React.CSSProperties
      }
    >
      <div>
        <canvas ref={elementRef} aria-label={label} />
      </div>
      {children}
    </div>
  );
}

export function Toolbar({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("flex flex-wrap items-center gap-1.5", className)}
      {...props}
    />
  );
}

export function ToolButton({
  icon: Icon,
  label,
  iconOnly = false,
  primary = false,
  className,
  ...props
}: React.ComponentProps<"button"> & {
  icon: LucideIcon;
  label: string;
  iconOnly?: boolean;
  primary?: boolean;
}) {
  return (
    <button
      type="button"
      title={label}
      aria-label={iconOnly ? label : undefined}
      className={cn(
        "inline-flex h-8 min-w-0 items-center justify-center gap-1.5 rounded-md border px-2.5 text-[13px] font-medium whitespace-nowrap transition-colors disabled:pointer-events-none disabled:opacity-40 [&_svg]:size-3.5 [&_svg]:shrink-0",
        primary
          ? "border-transparent bg-foreground text-background hover:bg-foreground/85"
          : "bg-background hover:bg-muted",
        iconOnly && "w-8 px-0",
        className
      )}
      {...props}
    >
      <Icon aria-hidden />
      {!iconOnly && <span className="truncate">{label}</span>}
    </button>
  );
}

const TONES = {
  idle: "bg-zinc-400",
  busy: "bg-amber-400",
  ok: "bg-emerald-500",
  error: "bg-red-500",
};

/** One line of status text. Its height never changes, so the card never jumps. */
export function Status({
  tone = "idle",
  children,
}: {
  tone?: keyof typeof TONES;
  children: React.ReactNode;
}) {
  return (
    <p
      role="status"
      className="flex h-5 min-w-0 items-center gap-2 text-[13px] text-muted-foreground"
    >
      <span
        aria-hidden
        className={cn("size-1.5 shrink-0 rounded-full", TONES[tone])}
      />
      <span className="truncate">{children}</span>
    </p>
  );
}
```

## 自动记录的内容

引擎监听 Fabric.js 事件，自动记录：

- 添加和删除对象（同一时刻的多个改动合并为一步）；
- 用鼠标移动、缩放和旋转（Fabric 的 `object:modified`）；
- 完成的文本编辑。

每一步都有一个标签，比如 `Add rect` 或 `Move circle`，可以显示在按钮上。

```ts
await engine.undo();
await engine.redo();

engine.canUndo();
engine.getHistory(); // { undo: ["Move circle", "Add rect"], redo: [] }
```

调用会按顺序执行，快速按三次撤销，就会撤销三步。

## 代码做的改动

`object.set("fill", "red")` 或 `canvas.bringObjectForward(object)` 不会触发任何 Fabric.js 事件。把这类改动包在事务里，它们就成为带标签的一步：

```ts
engine.transaction("Arrange furniture", () => {
  chair.set({ left: 120, top: 80 });
  table.set("fill", "oak");
  canvas.bringObjectToFront(table);
});
```

或者先改，再调用 `commit`：

```ts
canvas.sendObjectBackwards(rug);
engine.commit("Send rug backwards");
```

- 事务可以嵌套，使用最外层的标签。
- 事务可以是异步的：`await engine.transaction("Import", async () => { /* ... */ })`。
- 编组和取消编组是对对象列表的改动。把移除和添加放在同一个事务里，就是一步撤销。

## 键盘快捷键

```ts
import { bindKeyboardShortcuts } from "fabricjs-document-engine";

const unbind = bindKeyboardShortcuts(engine);
```

Ctrl+Z 或 Cmd+Z 撤销。Ctrl+Shift+Z、Cmd+Shift+Z 和 Ctrl+Y 重做。用户在输入框、文本域、contenteditable 元素或 Fabric.js 文本里打字时，快捷键会被忽略，原生的文本撤销照常工作。传入 `{ target: element }` 可以只在某个元素上监听，而不是 `window`。

## 工具栏状态

```ts
engine.on("history:change", ({ canUndo, canRedo, undoLabel }) => {
  undoButton.disabled = !canUndo;
  redoButton.disabled = !canRedo;
  undoButton.textContent = undoLabel ? `Undo ${undoLabel}` : "Undo";
});
```

## 保存 id，而不是对象

撤销和重做会根据保存的状态重建改动过的对象。它们会以新的 Fabric.js 实例回来，id 不变。保存 id，再重新查找对象：

```ts
const id = shape.get("id") as string;
await engine.undo();
const current = engine.getObjectById(id);
```

## 历史记录的大小

每一步只存改动过的对象，所以大图里的一步也很小。默认情况下 Fabric.js 撤销重做的历史记录保留 100 步，最多 64 MB，超出时先丢最旧的步骤：

```ts
createDocumentEngine({
  canvas,
  history: { limit: 50, maxBytes: 32 * 1024 * 1024 },
});
```

撤销只覆盖本次会话里最近的编辑。想长期保留某个状态，请用[版本](https://fabricjs-document-engine.jscrate.dev/zh/docs/guides/versions)。
