← 中文资源

简体中文版本

撤销栈与快照历史

每次修改前先把文档快照压入撤销栈:undo 弹出回到上一版,redo 保留未来版本,新的编辑会清空重做栈——编辑器历史机制一个数组对就能实现。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

after edits: notes v2 - first, second, third
undo: true -> notes - first, second, third
undo: true -> notes - first, second
undo exhausted: false
redo: true -> notes - first, second, third

实现说明

逻辑集中在函数 snapshot、edit、undo、redo里。 返回值是携带 title 的对象。

使用要点

  • 守卫 !previous 满足时靠提前的 return 短路流程。
  • 跑完文件,输出里会留下标记——after edits:、undo:、undo exhausted:。

常见问题

snapshot 会修改传入的参数吗?

入参保持不变;拿回来的是新建的值。

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件在加载时定义 snapshot、edit、undo。

主要签名是 function snapshot(state: DocState)

核心语句

function edit(mutate: (draft: DocState) => void): void {
  undoStack.push(snapshot(doc));
  redoStack.length = 0; // a new edit invalidates the redo future
  mutate(doc);
}
return { title: state.title, lines: [...state.lines] };
edit((draft) => (draft.title = 'notes v2'));

代码示例

interface DocState {
  title: string;
  lines: string[];
}

// Undo/redo: push a snapshot before each mutation; undo pops back,
// redo keeps the future until a new edit discards it
const doc: DocState = { title: 'notes', lines: ['first', 'second'] };
const undoStack: DocState[] = [];
const redoStack: DocState[] = [];

function snapshot(state: DocState): DocState {
  // copy the container; string elements need nothing deeper
  return { title: state.title, lines: [...state.lines] };
}

function edit(mutate: (draft: DocState) => void): void {
  undoStack.push(snapshot(doc));
  redoStack.length = 0; // a new edit invalidates the redo future
  mutate(doc);
}

// restore the popped snapshot into the live document
function undo(): boolean {
  const previous = undoStack.pop();
  if (!previous) return false;
  redoStack.push(snapshot(doc));
  Object.assign(doc, previous);
  return true;
}

function redo(): boolean {
  const next = redoStack.pop();
  if (!next) return false;
  undoStack.push(snapshot(doc));
  Object.assign(doc, next);
  return true;
}

edit((draft) => draft.lines.push('third'));
edit((draft) => (draft.title = 'notes v2'));
console.log('after edits:', doc.title, '-', doc.lines.join(', '));

console.log('undo:', undo(), '->', doc.title, '-', doc.lines.join(', '));
console.log('undo:', undo(), '->', doc.title, '-', doc.lines.join(', '));
console.log('undo exhausted:', undo());

console.log('redo:', redo(), '->', doc.title, '-', doc.lines.join(', '));