Lab

undo-history

Undo and redo as a value: a pure history of any document, with bursts (a drag is one entry), redo that drops on a new change, and a depth limit

pnpm dlx shadcn@latest add @audio-ui/undo-history
import { HISTORY_LIMIT, emptyHistory, canUndo, canRedo, beginChange, /* … */ } from "@/lib/undo-history";
Fileslib/undo-history.ts
Depends onNothing
npmNothing
Used byhistory, use-arrangement, use-undo-history
ExportKindWhat it is
HistoryinterfaceUndo and redo as a value: every function takes the present and hands back the present, and holds no state of its own.
HistoryStepinterface
HISTORY_LIMITconstHow many entries a history keeps: deep, not infinite.
emptyHistoryfunction
canUndofunction
canRedofunction
beginChangefunctionOpens a burst, or joins the one already open.
settleChangefunctionCloses a burst: everything it did becomes one entry on past.
recordChangefunctionA change made in one go: a burst opened and closed.
undofunctionTakes back the latest change, or returns null when there is none.
redofunctionPuts back what undo took, or returns null when there is nothing to put back.

Usage

Undo and redo of any value, as a value: the steps behind it and after it, a gesture recorded as one step, and the last 100 kept.

import { canUndo, emptyHistory, recordChange, redo, undo } from "@/lib/undo-history";

let history = emptyHistory<Note[]>();
history = recordChange(history, notesBefore); // before an edit
const step = undo(history, notesNow); // { history, present } to go back to, null with nothing to undo

beginChange and settleChange make a drag one step. In React, useUndoHistory holds it for you; the arrangement's undo is built on it.

Built by Ouest Labs, the source code is available on GitHub.
RSS