Aller au contenu principal

createReactiveCommandStack()

createReactiveCommandStack<S>(options): object

Creates a reactive command stack with undo/redo support.

Unlike createCommandStack (imperative, mutation-based), this variant manages state internally and notifies via onChange on every transition. Commands are pure functions from state to state, making it naturally compatible with React, Vue, Angular, or any reactive framework.


Type Parameters

S: S


Parameters

options: ReactiveCommandStackOptions<S>

Initial state and onChange callback


Returns

Stack with execute, undo, redo, canUndo, canRedo, clear, state

execute(): (cmd) => void

Execute a state command. Clears redo stack.

cmd: UndoableStateCommand<S>
Returns: void

undo(): () => boolean

Undo the last command. Returns false if nothing to undo.

Returns: boolean

redo(): () => boolean

Redo the last undone command. Returns false if nothing to redo.

Returns

boolean

state: #### Get Signature: > get state(): S

Current state.

Returns

S

canUndo

Get Signature: > *get canUndo*(): boolean

Returns

boolean

canRedo

Get Signature: > *get canRedo*(): boolean

Returns: boolean

clear(): () => void

Reset to initial state and clear all history.

Returns: void


Since

2.5.0


Example

// React
const [board, setBoard] = useState(INITIAL);
const stack = useRef(createReactiveCommandStack({
initial: INITIAL,
onChange: setBoard,
}));

stack.current.execute(undoableState(
(b) => moveTask(b, "todo", "done", task),
(b) => moveTask(b, "done", "todo", task),
));
// setBoard is called automatically with the new state

stack.current.undo(); // setBoard called with previous state
stack.current.redo(); // setBoard called with next state

ReactiveCommandStackOptions<S>

Interface

Options for createReactiveCommandStack.


Since

2.5.0


Type Parameters

S: S


Properties

initial: S

The initial state.

onChange(): (state) => void

Called after every state change (execute, undo, redo, clear).

state: S
Returns: void