History API: undo, redo, and transactions
Control undo and redo for editor operations.
Reaching the editor instance
The methods below run on the editor you created with new Blok(). They are available once editor.isReady resolves.
// You already hold the instance returned by the constructor.
const editor = new Blok({ holder: 'editor' });
await editor.isReady;
// Call any API method on it.
editor.caret.setToLastBlock('end');Methods
history.undo()
voidUndo the last operation. It does nothing while the editor is read-only, the same as Cmd+Z.
When to use
Programmatic Ctrl/Cmd+Z. It does nothing when there is nothing to undo, or while the editor is read-only. Gate custom buttons on canUndo().
// Undo last change
editor.history.undo();
// Undo multiple times
for (let i = 0; i < 3; i++) {
editor.history.undo();
}history.redo()
voidRedo the last undone operation. It does nothing while the editor is read-only, the same as Cmd+Shift+Z.
When to use
Programmatic Ctrl/Cmd+Shift+Z. It does nothing while the editor is read-only. Gate custom UI on canRedo() so the button disables correctly.
// Redo last undone change
editor.history.redo();
// Redo multiple times
for (let i = 0; i < 3; i++) {
editor.history.redo();
}history.canUndo()
booleanCheck if undo is available (there are operations to undo).
When to use
Use it to enable or disable a custom undo button. Pair it with undo().
if (editor.history.canUndo()) {
editor.history.undo();
} else {
console.log('Nothing to undo');
}history.canRedo()
booleanCheck if redo is available (there are undone operations to redo).
When to use
Use it to enable or disable a custom redo button. Pair it with redo().
if (editor.history.canRedo()) {
editor.history.redo();
} else {
console.log('Nothing to redo');
}history.clear()
voidClear all history. Removes all undo/redo entries.
When to use
Drops the entire undo stack. render() already does this, so call it after loading content another way, such as insertMany(). Then users cannot undo back into the previous document.
// render() already clears history.
// Clear it yourself after loading content another way.
editor.blocks.insertMany(loadedBlocks);
editor.history.clear();