An operation-based history implementation for Slate editors providing undo/redo functionality.
npx @tessl/cli install tessl/npm-slate-history@0.115.0Slate History provides a comprehensive undo/redo history implementation for Slate rich text editors through operation-based state tracking. It seamlessly integrates with Slate editors to track all document operations in undo and redo stacks, enabling users to undo and redo changes while preserving selection state.
npm install slate-historyslate >= 0.114.3import { withHistory, HistoryEditor, History, HISTORY, SAVING, MERGING, SPLITTING_ONCE } from "slate-history";For CommonJS:
const { withHistory, HistoryEditor, History, HISTORY, SAVING, MERGING, SPLITTING_ONCE } = require("slate-history");Most Common Usage:
import { withHistory, HistoryEditor, History } from "slate-history";Required Slate Types:
// These types from slate are used in the API signatures
import { Editor, BaseEditor, Operation, Range } from "slate";import { createEditor } from "slate";
import { withHistory } from "slate-history";
// Create an editor with history functionality
const editor = withHistory(createEditor());
// Use undo and redo methods
editor.undo();
editor.redo();
// Check if editor has history functionality
if (HistoryEditor.isHistoryEditor(editor)) {
console.log("Editor has history support");
}With React:
import { withReact } from "slate-react";
import { withHistory } from "slate-history";
import { createEditor } from "slate";
const editor = withReact(withHistory(createEditor()));Slate History is built around several key components:
The core plugin that adds undo/redo functionality to Slate editors through operation tracking and batch management.
function withHistory<T extends Editor>(editor: T): T & HistoryEditor;Helper methods for controlling history behavior, checking editor state, and managing operation batching.
interface HistoryEditor extends BaseEditor {
history: History;
undo: () => void;
redo: () => void;
writeHistory: (stack: 'undos' | 'redos', batch: any) => void;
}The core data structure and utilities for managing undo/redo operation stacks.
interface History {
redos: Batch[];
undos: Batch[];
}
// Internal batch structure (not exported)
interface Batch {
operations: Operation[];
selectionBefore: Range | null;
}
// Static methods
namespace History {
function isHistory(value: any): value is History;
}interface HistoryEditor extends BaseEditor {
history: History;
undo: () => void;
redo: () => void;
writeHistory: (stack: 'undos' | 'redos', batch: any) => void;
}
interface History {
redos: Batch[];
undos: Batch[];
}
// Internal batch structure (not exported)
interface Batch {
operations: Operation[];
selectionBefore: Range | null;
}
// WeakMap exports for advanced usage
const HISTORY: WeakMap<Editor, History>;
const SAVING: WeakMap<Editor, boolean | undefined>;
const MERGING: WeakMap<Editor, boolean | undefined>;
const SPLITTING_ONCE: WeakMap<Editor, boolean | undefined>;