Commands with undo

Defining named commands with reverts on a zustand store, and dispatching, undoing and redoing them.

@voidhash/mimic/zustand-commander is a command layer for a zustand store that holds a document. You define each user action once as a command, optionally with a function that reverts it, and the layer keeps undo and redo stacks of the commands that ran. This page shows how to define, dispatch and undo commands.

Setting up

Create a commander typed with your store's state and your document schema, and add its middleware around the mimic middleware:

import { create } from "zustand";
import { mimic, type MimicSlice } from "@voidhash/mimic/zustand";
import { createCommander, type CommanderSlice } from "@voidhash/mimic/zustand-commander";

type BoardState = MimicSlice<typeof BoardDocument> & {
  selectedCardId: string | null;
} & CommanderSlice;

export const commander = createCommander<BoardState, typeof BoardDocument>();

export const useBoardStore = create(
  commander.middleware(mimic(document, () => ({ selectedCardId: null as string | null }))),
);

document is the client document from Creating a client. The samples on this page use a board whose Column nodes have a name and whose Card nodes have a title and an optional description.

The middleware adds a _commander slice with the undo stack, the redo stack and the active draft.

Defining commands

A command is a function of a context and its parameters. The context gives it the document's root proxy, a transaction function, the store's getState and setState, and dispatch for running other commands.

commander.action defines a command that is not undoable:

export const selectCard = commander.action<{ cardId: string | null }>((ctx, params) => {
  ctx.setState({ selectedCardId: params.cardId });
});

commander.undoableAction takes the command and its revert. The command returns whatever the revert needs to undo it:

export const renameColumn = commander.undoableAction<
  { columnId: string; name: string },
  { previousName: string }
>(
  (ctx, params) => {
    const column = ctx.root.findByIdAcrossTree(params.columnId)?.as(Column);
    if (!column) return { previousName: "" };

    const previousName = column.data.name.get();
    column.data.name.set(params.name);
    return { previousName };
  },
  (ctx, params, result) => {
    ctx.root.findByIdAcrossTree(params.columnId)?.as(Column).data.name.set(result.previousName);
  },
);

Use ctx.transaction when a command makes several writes that must be one transaction:

export const updateCard = commander.undoableAction<
  { cardId: string; title: string; description: string },
  { previousTitle: string; previousDescription: string }
>(
  (ctx, params) => {
    const card = ctx.root.findByIdAcrossTree(params.cardId)?.as(Card);
    if (!card) return { previousTitle: "", previousDescription: "" };

    const previousTitle = card.data.title.get();
    const previousDescription = card.data.description.get() ?? "";
    ctx.transaction(() => {
      card.data.title.set(params.title);
      card.data.description.set(params.description);
    });
    return { previousTitle, previousDescription };
  },
  (ctx, params, result) => {
    const card = ctx.root.findByIdAcrossTree(params.cardId)?.as(Card);
    if (!card) return;
    ctx.transaction(() => {
      card.data.title.set(result.previousTitle);
      card.data.description.set(result.previousDescription);
    });
  },
);

Dispatching

useCommander(store) returns a dispatch function. Dispatching is curried: pass the command, then its parameters.

import { useCommander } from "@voidhash/mimic/zustand-commander";

function ColumnHeader({ columnId, name }: { columnId: string; name: string }) {
  const dispatch = useCommander(useBoardStore);
  return (
    <input
      defaultValue={name}
      onBlur={(event) => dispatch(renameColumn)({ columnId, name: event.target.value })}
    />
  );
}

Every undoable command that runs is pushed onto the undo stack and clears the redo stack. The undo stack keeps the most recent 100 entries. Outside React, createDocumentDispatch(store) returns the same dispatch function.

Undo and redo

import { useUndoRedo, useUndoRedoKeyboard } from "@voidhash/mimic/zustand-commander";

function Toolbar() {
  const { canUndo, canRedo, undo, redo } = useUndoRedo(useBoardStore);
  useUndoRedoKeyboard(useBoardStore);

  return (
    <>
      <button disabled={!canUndo} onClick={undo}>
        Undo
      </button>
      <button disabled={!canRedo} onClick={redo}>
        Redo
      </button>
    </>
  );
}

useUndoRedo returns canUndo, canRedo, undoCount, redoCount, undo, redo and clear. useUndoRedoKeyboard binds Ctrl+Z to undo and Ctrl+Shift+Z or Ctrl+Y to redo, with Cmd in place of Ctrl on macOS; pass { enableUndo: false } or { enableRedo: false } to turn one off.

Undo runs the latest entry's revert with the parameters and result of the original run. Redo runs the command again and stores its new result, so a later undo reverts what the redo actually did (for example, a node with a newly generated id).

If a revert or a re-run throws, the entry is removed from the history and the error is rethrown, so older entries stay reachable.

Outside React, use performUndo(store), performRedo(store) and clearUndoHistory(store).

Commands and drafts

Commands dispatched through useCommander always write to the document. To stage a gesture's commands in a draft instead, use the dispatch that useDraft returns:

const { begin, commit, dispatch } = useDraft(store);

// While dragging: staged in the draft, no undo entries.
dispatch(moveCard)({ cardId, destinationColumnId, destinationIndex });

Commands dispatched into a draft record no undo entries, and neither does committing the draft. If the gesture should be undoable, discard the draft and dispatch one undoable command for the final result instead.

Undo and redo do nothing while a draft is active.

Next