History
@syncstate/history
is a SyncState plugin which provides Undo and Redo functionality out of the box.
Installation
# NPM
npm install @syncstate/history --save
# Yarn
yarn add @syncstate/history
Basic usage
import { createDocStore } from "@syncstate/syncstate";
import history from "@syncstate/history";
const store = createDocStore({ todos: [], filter: "all" }, [
history.createInitializer(),
]);
// Undo last applied JSON patch
store.dispatch(history.undo());
// Redo next JSON patch from redo stack
store.dispatch(history.redo());
Breakpoints
You have the option of inserting breakpoints in the history using which you can undo till a specific point in state.
// User actions before breakpoint
store.dispatch(history.insertUndoBreakpoint());
// User actions after breakpoint
// This will undo all actions after breakpoint
store.dispatch(history.undoTillBreakpoint());
// This will redo all actions after breakpoint
store.dispatch(history.redoTillBreakpoint());
Advanced
By default, this plugin will automatically work for the root document which means any change to the document is recorded and performing undo or redo actions will work with those changes.
If you want to maintain separate undo/redo stack for different parts of the document, you can use history.enable
for a path inside document.
store.dispatch(history.enable("/todos"));
store.dispatch(history.undoPath("/todos"));
store.dispatch(history.redoPath("/todos"));
store.dispatch(history.insertUndoBreakpoint("/todos"));
store.dispatch(history.undoPathTillBreakpoint("/todos"));
store.dispatch(history.redoPathTillBreakpoint("/todos"));
How it works
- SyncState stores
inversePatches
which means the opposite ofpatches
generated against user actions. An inversePatch can be applied to reverse the operation of a corresponding patch. - SyncState history plugin adds a middleware to SyncState's internal Redux store and listens to changes and stores patches and inversePatches in an undo stack. It also maintains a redo stack.
- To Undo and Redo, it simply picks up the patches from Undo and Redo stacks and applied them to SyncState store.
Differences with redux-undo
- It doesn't replace with the entire snapshot of the app. Instead it applies a patch on the document from the Undo / Redo stack.