Plate tracks local undo and redo batches by default. Each batch preserves a canonical document change, effects, and selection.
Saving a document revision and its comment ranges does not save local undo. Ordinary reload creates a fresh editor with empty undo and redo stacks. Application version history and pending authored proposals have separate lifetimes from this session history.
import { createEditor } from "platejs";
const editor = createEditor();
const canUndo = editor.read.history.hasUndo();
const pending = editor.read.history.pending();
import { createEditor } from "platejs";
const editor = createEditor();
const canUndo = editor.read.history.hasUndo();
const pending = editor.read.history.pending();
editor.api.history.undo();
editor.update({ history: "skip" }).text.insert("draft");undo() and redo() replay their next batch in call order and return its
result. A document batch has applied when the call returns. A batch with a
live-session effect returns { status: "pending", settled } and publishes its
pending direction while its external owner finishes. Editing, selection, and
remote collaboration continue during that wait.
Wait for settled only when you need the final outcome:
const result = editor.api.history.undo();
const outcome = result.status === "pending" ? await result.settled : result;const result = editor.api.history.undo();
const outcome = result.status === "pending" ? await result.settled : result;Use useEditorHistory for undo and redo controls in
the interface. A control that names no editor or root is off while its next undo
changes a root that no shown, writable view can edit, and the undo shortcut
inside an editor refuses that change. A control that names an editor or a root skips that check. So do a
button that calls editor.api.history.undo() and a live-session owner's own
writes while it replays. Read hasUndo(), hasRedo(), and pending() for the
history's own state. Inspect editor.read.history() when you need the full
immutable stacks.
Configure retention and automatic grouping on HistoryPlugin:
import { createEditor, HistoryPlugin } from "platejs";
const editor = createEditor({
plugins: [
HistoryPlugin.configure({
initialState: { maxDepth: 100, newBatchDelay: 750 },
}),
],
});import { createEditor, HistoryPlugin } from "platejs";
const editor = createEditor({
plugins: [
HistoryPlugin.configure({
initialState: { maxDepth: 100, newBatchDelay: 750 },
}),
],
});maxDepth defaults to 100. newBatchDelay defaults to 500 milliseconds.
The configured values apply to the next accepted update or replay.
An otherwise-compatible automatic native edit that arrives after the newBatchDelay idle window starts a new batch. Explicit tx.history.merge() and tx.history.newBatch() decide grouping without the idle window: newBatch() always starts a new batch, and merge() joins the previous batch when the two are compatible. Authored text input outside composition still needs the window. History JSON stores no timing metadata.
Use one local effect when undo or redo must replay state outside the document.
The history value owns its replay callback, so a replayable effect cannot be
declared without the code that settles it.
import { createEditor, defineEffect, definePlugin } from "platejs";
type Transition = Readonly<{ previous: string; value: string }>;
const externalValue = { current: "" };
const externalValueEffect = defineEffect<Transition>({
history: {
replay: (_editor, transition) => {
if (externalValue.current !== transition.previous) {
return { reason: "external-value-changed", status: "blocked" };
}
externalValue.current = transition.value;
return { status: "applied", value: transition };
},
},
invert: ({ previous, value }) => ({ previous: value, value: previous }),
key: "external-value.set",
});
const ExternalValuePlugin = definePlugin("externalValue", {
effectTypes: [externalValueEffect],
});
const editor = createEditor({ plugins: [ExternalValuePlugin] });
const previous = externalValue.current;
externalValue.current = "saved";
editor.update((tx) => {
tx.effects.emit(externalValueEffect, { previous, value: "saved" });
});import { createEditor, defineEffect, definePlugin } from "platejs";
type Transition = Readonly<{ previous: string; value: string }>;
const externalValue = { current: "" };
const externalValueEffect = defineEffect<Transition>({
history: {
replay: (_editor, transition) => {
if (externalValue.current !== transition.previous) {
return { reason: "external-value-changed", status: "blocked" };
}
externalValue.current = transition.value;
The effect is local, effect-only, excluded from serialized History, and never
merged with another batch. Return { status: "blocked", reason } when the
external owner cannot apply the transition. An applied result returns the exact
transition the owner applied, including any canonical value returned by that
owner.
import type {
DocumentChange,
EditorEffect,
EditorSchemaIdentity,
Selection,
} from "platejs";
export interface History {
readonly redos: readonly Batch[];
readonly revision: number;
readonly schema: EditorSchemaIdentity;
readonly undos: readonly Batch[];
}
interface Batch {
readonly change: DocumentChange;
readonly effects: readonly EditorEffect[];
readonly selectionAfter: Selection;
readonly selectionAfterRoot?: string;
readonly selectionBefore: Selection;
readonly selectionBeforeRoot?: string;
readonly unsettle?: DocumentChange;
readonly rest?: DocumentChange;
readonly carried?: readonly CarriedRun[];
}
interface CarriedRun {
readonly at: number;
readonly length: number;
readonly root: string;
readonly source: number;
}import type {
DocumentChange,
EditorEffect,
EditorSchemaIdentity,
Selection,
} from "platejs";
export interface History {
readonly redos: readonly Batch[];
readonly revision: number;
readonly schema: EditorSchemaIdentity;
readonly undos: readonly Batch[];
}
interface Batch {
readonly change: DocumentChange;
readonly effects: readonly EditorEffect[];
unsettle appears only on an undo step whose commit stored a value that a
pending suggestion had kept an element from storing, such as a unique ID. It
takes that write back, so undoing the step and redoing it decides the value
again.
unsettle also appears, with rest, on an undo step whose commit accepted a
suggested deletion of text. The step's change is unsettle then rest.
unsettle puts back the text the accept removed, and rest undoes everything
else the commit did. Redoing the step replays only the inverse of rest, so
the accept settles again against the document the redo finds.
carried appears on an undo step whose commit moved content earlier across
element edges and nothing else, such as a line merged into the last line of
a quote before it, or a line in one quote merged into a line of the quote
before it, and on each step an undo or redo of it pushes. Each run
names length tokens the step deletes at source in the document before it
and inserts at at in the document after it, so a teammate's edit inside a
run moves with the run.
Returns true if the passed in value is a History object and acts as a
type guard.
Encode the installed undo and redo stacks as validated JSON at version 7. The
envelope records the editor's schema identity, and each batch stores its id,
canonical DocumentChange, registered effects, selection envelopes, and
unsettle, rest, carried and record when it has them. record lists
what the batch's change moved, split and joined in each root, or is null
when that is unknown. A redo batch can also store a fallback batch with no
id. History applies the fallback from the same document when a guard refuses
the redo.
A batch keeps its id through undo, redo, a merge into it, History.fromJSON
and tx.history.restore. Two editors that restore the same saved history get
the same ids.
This advanced API serializes local document history. It does not serialize the native anchor recovery data or live-session effects needed to restore exact comment coverage and undo local comment creation. Load Comments revisions into a fresh editor with empty local history.
Compatible typing and same-node property updates coalesce from canonical change classifications and changed ranges. Grouping fingerprints are runtime-only; loading persisted history starts a fresh automatic group.
Decode and validate history without mutating the editor. Effect codecs are
discovered from installed editor-plugin resources, including state fields
and standalone effects. Install the returned immutable value through
tx.history.restore(...).
Decoding fails before reading any batch when the persisted schema identity does not match the editor. A matching schema ID and version with a different fingerprint means the schema semantics need a version bump.
import { History } from "platejs/history";
const json = History.toJSON(editor);
localStorage.setItem("editor.history", JSON.stringify(json));
const decoded = History.fromJSON(
editor,
JSON.parse(localStorage.getItem("editor.history")!)
);
editor.update((tx) => {
tx.history.restore(decoded);
});import { History } from "platejs/history";
const json = History.toJSON(editor);
localStorage.setItem("editor.history", JSON.stringify(json));
const decoded = History.fromJSON(
editor,
JSON.parse(localStorage.getItem("editor.history")!)
);
editor.update((tx) => {
tx.history.restore(decoded);
});Schema identity is always derived or named; null is invalid in memory and in
history JSON. Decoding reads versions 4 to 7. A batch saved before version 7
loads with an unknown record. A batch saved without an id gets a fresh one.
Decoding refuses an id that is empty or not a string, an id on a
fallback, and two batches that share one id. Schema identity, codec
versions, effect keys, built-in selection payloads, and JSON values are
validated during decoding. Failed decoding leaves editor state untouched.
Read the current undo and redo stacks.
Return whether the undo branch has a surviving mapped batch.
Return whether the redo branch has a surviving mapped batch.
Return the live-session replay direction currently waiting for its external owner. Pending state belongs to this editor's runtime and is absent from History JSON, snapshots, and collaboration.
Replay the current undo batch.
Replay the current redo batch.
Both methods return { status: "applied" } after a replay and
{ status: "empty" } when no surviving batch exists. A replay requested while
another live-session replay is pending returns { status: "busy" } without
claiming another batch.
A live-session batch returns { status: "pending", settled } while its
external owner works, unless the owner answers synchronously.
settled resolves to HistorySettlement and never rejects:
{ status: "applied" } after the owner applied the transition.{ status: "blocked", reason } when its external state changed or the owner
refused.{ status: "failed" } when the owner or the settlement threw. The editor
reports the error to its lifecycleErrorSink. With no sink, it uses
reportError, or console.error where reportError does not exist.A blocked or failed live-session replay leaves the same batch at the branch
head. A document replay that throws while it resolves or applies its batch,
for example because the schema rejects the restored document, reports the
error the same way, drops that batch and returns { status: "failed" }, so
the next call replays the batch below. A batch below the head that can no
longer map onto the document is dropped and reported the same way. The batch
right below a dropped batch maps by comparing documents, so it can drop too
when the comparison cannot place it, such as a letter typed beside an equal
letter that another change deleted. An error
raised when the replay commits, such as a Yjs admission error, also reports and
returns { status: "failed" }, but the batch stays at the head. Errors in the call itself, such as a replay
inside editor.update(...), still throw.
Call these services outside editor.read(...) and editor.update(...). A
history batch can cover several document roots; replay always applies the
complete batch. Live-session batches are effect-only, local to the current
session, excluded from serialized History, and never merged with another
batch.
Replace both history branches when the surrounding update commits. Commit and snapshot subscribers observe the restored revision through that one update.
Do not save the current transaction to history.
Merge the current transaction into the previous compatible undo batch.
Start a fresh undo batch for the current transaction.
Run one update without saving it to history.
Run one update that merges into the previous compatible undo batch.
Run one update where the first write starts a fresh history batch, then the rest of the callback merges into that batch.
For one direct write, configure the update facade instead:
editor.update({ history: "skip" }).text.insert("draft");editor.update({ history: "skip" }).text.insert("draft");Restore decoded history as one direct update.
Install AuthoredPlugin when the document needs review proposals. It shares Plate's existing History:
import { AuthoredPlugin } from "platejs/authored";
const editor = createEditor({
plugins: [AuthoredPlugin],
userId: session.user.id,
});import { AuthoredPlugin } from "platejs/authored";
const editor = createEditor({
plugins: [AuthoredPlugin],
userId: session.user.id,
});Undo and redo reverse local interaction batches, including the review marks and mapped selection recorded with that batch. An accept or reject decision made as a local document action can be undone. Undo is not a substitute for choosing a review decision through Authored.
Use editor.plugin(AuthoredPlugin).update.decide(...) for review decisions.
Persist History with History.toJSON only when the application needs local undo stacks after reload. editor.read.value() separately persists pending proposals, as review marks on its nodes and review records in its records.
See Authored Changes.
Document undo maps comment attachments without rewinding conversation data. Replies, message edits, resolution, reopening, and explicit deletion stay outside document undo. Undoing a suggestion decision preserves its discussion and locates it through the same Authored change ID.
Save editor.read.value() with editor.plugin(CommentsPlugin).api.ranges() under
one application revision, and keep thread rows in your tables. Loading the
document creates a fresh editor with initialComments: { ranges, threads } and
an empty local undo stack.
For an old-version preview, load the current thread rows with the selected revision's saved ranges. Threads without a range in that revision are unavailable; currently deleted threads remain absent. A version restore creates a new application revision under a document-head check, then opens a fresh editor. It is not a local undo or an in-place document replacement. See Comments for the target join.
Saved comment ranges do not support a changed Yjs baseline. A state vector alone cannot map missed edits through restored targets, and Yjs admission does not support persisted local undo.
Render ephemeral previews from local state, decorations, or sidecar UI until the user commits them. Do not mutate document content for a preview and then try to make that preview history later.
Use a local defineStateField without a persistence codec and with
history: 'skip' for preview state. Cancel by clearing that field. Accept by
clearing the preview and applying the real document edit in one normal update.
const previewReplacement = defineStateField<string | null>({
key: "local.preview.replacement",
history: "skip",
initial: () => null,
});
editor.update((tx) => {
tx.setField(previewReplacement, null);
tx.text.delete({ at: selectedRange });
tx.text.insert(acceptedText);
});const previewReplacement = defineStateField<string | null>({
key: "local.preview.replacement",
history: "skip",
initial: () => null,
});
editor.update((tx) => {
tx.setField(previewReplacement, null);
tx.text.delete({ at: selectedRange });
tx.text.insert(acceptedText);
});Undo then restores the document content without resurrecting preview UI.