Undo and redo

A per-user undo history for a collaborative document, and how it behaves when other people edit in between.

createHistory from @voidhash/mimic/history adds undo and redo to a client document. In a collaborative document, undo cannot mean "go back to the previous state", because that would take back other people's work. This page explains what it means instead and how to use the history.

What undo means here

  • Only your own edits are recorded. Edits from other users never enter your undo stack. Their edits also do not clear your redo stack; a new edit of your own does.
  • Undo applies the reverse of your edit as a new transaction. It changes only what your edit changed. If someone else has since edited a different field of the same object, their edit stays.
  • Undo skips what no longer exists. If the thing your edit touched was deleted by someone else, that part of the step is skipped. A step that would change nothing at all is skipped entirely, so pressing undo always does something while older steps remain.
  • Redo returns to the present. The redo step is captured from what the undo actually replaced, at the moment of undoing. Undoing and then redoing back leaves the document as it was, even if others edited in between.

Creating a history

import { createHistory } from "@voidhash/mimic/history";

const history = createHistory({ document });

document.transaction((root) => root.title.set("Roadmap"), { label: "Rename" });

history.undo(); // true: the title is back
history.redo(); // true: "Roadmap" again

Every local transaction with origin user becomes one step. undo() and redo() return whether a step was applied.

NameTypeDefaultDescription
document *ClientDocument—The document whose local writes are recorded.
captureSelection() => TSelection—Reads the current selection, to store with each step.
restoreSelection(selection: TSelection) => void—Restores a stored selection after undo or redo.
mergeWindowMsnumber1000How close together batches with the same merge key must be to merge.
limitnumber200How many steps are kept; the oldest are forgotten first.

Grouping writes into steps

One user action often makes several transactions. batch records everything written inside it as one step:

history.batch({ label: "Align left" }, () => {
  for (const id of selectedIds) {
    document.transaction((root) => {
      root.findByIdAcrossTree(id)?.update({ x: 0 });
    });
  }
});

Nested batches join the outermost one. If the function throws, the writes it already made are reverted and nothing is recorded.

Consecutive batches with the same mergeKey that follow each other within the merge window become one step. Use it for typing into a field or nudging with the arrow keys:

history.batch({ label: "Edit title", mergeKey: `title:${cardId}` }, () => {
  document.transaction((root) => {
    root.findByIdAcrossTree(cardId)?.update({ title });
  });
});

Writes made inside ignore are not recorded at all. Use it for repairs and imports that the user should not be able to undo:

history.ignore(() => {
  document.transaction((root) => root.layoutVersion.set(2), { origin: "system" });
});

Selection

If you pass captureSelection and restoreSelection, the history stores the selection before and after each step and restores it on undo and redo. Changing the selection is never a step of its own and does not clear redo.

Reading the state

const { canUndo, canRedo, undoLabel, redoLabel } = history.getState();

const unsubscribe = history.subscribe(() => {
  updateToolbar(history.getState());
});

getState() returns the same object until the state changes, so it can be used with useSyncExternalStore. clear() empties both stacks, and dispose() detaches the history from the document.

Rejected edits

A transaction that the server refuses, or that it evaluated without any effect, is removed from the history, so undo never tries to reverse something that did not happen.

When the document's collection is migrated to a new schema version, both stacks are cleared: their steps address the old schema.

Edits made on your behalf

adoptSubject(sub, label) records the transactions written with a document token for the subject sub as one step of your history. It is meant for an agent that this user started: your backend mints the agent a token whose subject names it (see Issuing document tokens), the agent edits with it from the backend, and the user can undo what it did. Adopting the same subject again starts the next step, so each turn of an agent is a step of its own.

A subject is whatever the token's issuer named, so adopt only a subject your own backend minted for this user's agent run (agent:<user>:<run>, say), never one that other users' agents write with too. releaseSubject(sub) ends the adoption; the steps it recorded stay.

Next