Create the editor with its initial document and plugin tuple. Configure editor-wide runtime policy here; configure feature behavior on its owning plugin.
Use createEditor to create a Plate editor, or useCreateEditor in a React component:
import { createEditor } from "platejs/react";
const editor = createEditor({
plugins: [HeadingPlugin],
});import { createEditor } from "platejs/react";
const editor = createEditor({
plugins: [HeadingPlugin],
});Set the initial content of the editor:
const editor = createEditor({
initialValue: [
{
type: "paragraph",
children: [{ text: "Hello, EditorRoot!" }],
},
],
});const editor = createEditor({
initialValue: [
{
type: "paragraph",
children: [{ text: "Hello, EditorRoot!" }],
},
],
});Pass an EditorDocumentValue with children, roots, and persisted meta
when one editor owns content roots or other named regions. Plate publishes the
same complete shape through onValueChange.
Use a synchronous initializer when decoding requires the compiled plugin model:
const editor = createEditor({
plugins: [HtmlPlugin, BoldPlugin, ItalicPlugin],
initialValue: ({ editor }) => {
const result = editor.api.html.parse(
"<p>This is <b>bold</b> and <i>italic</i> text!</p>"
);
if (!result.ok) throw new Error(result.diagnostics[0].message);
return result.document;
},
});const editor = createEditor({
plugins: [HtmlPlugin, BoldPlugin, ItalicPlugin],
initialValue: ({ editor }) => {
const result = editor.api.html.parse(
"<p>This is <b>bold</b> and <i>italic</i> text!</p>"
);
if (!result.ok) throw new Error(result.diagnostics[0].message);
return result.document;
},
});See HTML mappings for custom element and mark conversion.
Plate compiles the document schema from the installed plugins. Omit schema
for ordinary editors. editor.read.schema.identity() returns a derived
identity with the exact compiled fingerprint:
const editor = createEditor({
plugins: [HeadingPlugin],
});
editor.read.schema.identity();
// { kind: 'derived', fingerprint: '...' }const editor = createEditor({
plugins: [HeadingPlugin],
});
editor.read.schema.identity();
// { kind: 'derived', fingerprint: '...' }Put id and version in schema when a document participates in durable
persistence, history serialization, schema migration, or collaboration peer
negotiation. The same object owns application schema overrides and named
lineage. The fingerprint remains tied only to the compiled schema:
const editor = createEditor({
plugins: [HeadingPlugin],
schema: { id: "acme-document", version: 3 },
});
editor.read.schema.identity();
// { kind: 'named', id: 'acme-document', version: 3, fingerprint: '...' }const editor = createEditor({
plugins: [HeadingPlugin],
schema: { id: "acme-document", version: 3 },
});
editor.read.schema.identity();
// { kind: 'named', id: 'acme-document', version: 3, fingerprint: '...' }Bump version whenever the named lineage changes schema semantics. Reusing an
ID and version with a different fingerprint is an identity mismatch.
Omit schema.root for Plate's standard nonempty paragraph root. Declare it
only when the application needs a different top-level grammar.
import { schema } from "platejs";
import { createEditor, definePlugin, ParagraphPlugin } from "platejs/react";
const SectionPlugin = definePlugin("section", {
schema: {
element: {
content: schema.content.element(ParagraphPlugin, { min: 1 }),
},
},
});
const editor = createEditor({
plugins: [SectionPlugin],
schema: {
root: schema.content.element(SectionPlugin, { min: 1 }),
},
});import { schema } from "platejs";
import { createEditor, definePlugin, ParagraphPlugin } from "platejs/react";
const SectionPlugin = definePlugin("section", {
schema: {
element: {
content: schema.content.element(ParagraphPlugin, { min: 1 }),
},
},
});
const editor = createEditor({
plugins: [SectionPlugin],
schema: {
root: schema.content.element(SectionPlugin, { min: 1 }),
},
});root.min is required and must be a positive integer. Root descriptors must
match the installed plugin family: use Plate descriptors with
createEditor and Base descriptors with a headless Base plugin tuple.
For schema.content.elements([...]), the first descriptor constructs the
default root child.
A custom root changes the compiled fingerprint. For a named persisted schema,
increment version and add the document migration before loading documents
that use the earlier root grammar. Generated Value types include every legal
root variant; min and max remain runtime validation rules.
Persist schema identity beside the document, then declare one application-owned migration chain. Convert stored input before creating or replacing an editor value. Target-version steps run in ascending order and the converter returns a complete current envelope.
import { ListPlugin, ParagraphPlugin } from "platejs/react";
import {
defineDocumentMigrations,
migrateListIdentity,
migrateV54,
} from "platejs/migrations";
import { fingerprint as v53Fingerprint } from "./migrations/v54-upgrade-plate/from";
import { fingerprint as v54Fingerprint } from "./migrations/v55-list-identity/from";
export const EditorKit = [ParagraphPlugin, ListPlugin] as const;
export const EditorSchema = {
id: "acme-document",
version: 55,
} as const;
export const EditorMigrations = defineDocumentMigrations({
plugins: EditorKit,
schema: EditorSchema,
sourceFingerprints: { 53: v53Fingerprint, 54: v54Fingerprint },
steps: { 54: migrateV54, 55: migrateListIdentity },
});import { ListPlugin, ParagraphPlugin } from "platejs/react";
import {
defineDocumentMigrations,
migrateListIdentity,
migrateV54,
} from "platejs/migrations";
import { fingerprint as v53Fingerprint } from "./migrations/v54-upgrade-plate/from";
import { fingerprint as v54Fingerprint } from "./migrations/v55-list-identity/from";
export const EditorKit = [ParagraphPlugin, ListPlugin] as const;
export const EditorSchema = {
id: "acme-document",
version: 55,
} as const;
Run the conversion where the app loads the stored document, before any component
renders, then pass its output to the editor. Ordinary editor loading accepts
current input only. applied lists the steps that ran; when it is not empty,
save output back so the next load runs no steps.
import { migrateDocument } from "platejs/migrations";
import { EditorMigrations } from "./editor";
import { readDocument, saveDocument } from "./storage";
export async function loadDocument(id: string) {
const { applied, output } = migrateDocument(await readDocument(id), {
migrations: EditorMigrations,
});
if (applied.length > 0) await saveDocument(id, output);
return output;
}import { migrateDocument } from "platejs/migrations";
import { EditorMigrations } from "./editor";
import { readDocument, saveDocument } from "./storage";
export async function loadDocument(id: string) {
const { applied, output } = migrateDocument(await readDocument(id), {
migrations: EditorMigrations,
});
if (applied.length > 0) await saveDocument(id, output);
return output;
}Keep the conversion out of the component. React runs a component's body on every render, while the editor keeps the value it was created with.
import { EditorRoot, useCreateEditor } from "platejs/react";
import { EditorKit, EditorSchema } from "./editor";
export function DocumentEditor({ initialValue }) {
const editor = useCreateEditor({
initialValue,
plugins: EditorKit,
schema: EditorSchema,
});
return <EditorRoot editor={editor} />;
}import { EditorRoot, useCreateEditor } from "platejs/react";
import { EditorKit, EditorSchema } from "./editor";
export function DocumentEditor({ initialValue }) {
const editor = useCreateEditor({
initialValue,
plugins: EditorKit,
schema: EditorSchema,
});
return <EditorRoot editor={editor} />;
}A version 53 envelope converted by this version 55 definition runs steps 54
and 55. Plate
rejects a missing step, a different schema ID, a future version, or a fingerprint
mismatch. Register every supported historical envelope fingerprint in
sourceFingerprints.
migrateListIdentity gives each list item a listId. The list plugin numbers
items by listId, so the step gives each run of adjacent list items its own id,
or the one id its items already hold, and every number stays the same. The list
plugin's listId and listLevels properties are part of the compiled
fingerprint, so register the step under the first version whose schema has
them. Running it again changes nothing.
Raw historical documents have no source identity. Supply it at that import boundary:
const current = migrateDocument(legacyDocument, {
migrations: EditorMigrations,
source: 53,
}).output;const current = migrateDocument(legacyDocument, {
migrations: EditorMigrations,
source: 53,
}).output;Use source: 'current' only when the raw document already uses the current
schema. With an explicit source, migrateDocument reads its input as a raw
document, so pass a persisted envelope without it.
A step's document holds only children, meta, roots and records. Any other field
stored at the document's top level arrives in legacy. Lift it into meta and
return the remaining fields as legacy; a step that omits legacy passes it on
unchanged. migrateDocument refuses a field that no step lifted.
import type { DocumentMigration } from "platejs/migrations";
const liftTitle: DocumentMigration = ({
document,
legacy: { title, ...legacy },
}) => ({
document:
title === undefined
? document
: { ...document, meta: { ...document.meta, title } },
legacy,
});import type { DocumentMigration } from "platejs/migrations";
const liftTitle: DocumentMigration = ({
document,
legacy: { title, ...legacy },
}) => ({
document:
title === undefined
? document
: { ...document, meta: { ...document.meta, title } },
legacy,
});Document migrations do not rewrite serialized history or a populated Yjs room. Invalidate or migrate stored history offline, and connect upgraded clients to a new schema-versioned room after migrating its snapshot. Do not mix peers from different schema versions.
Comment ranges saved with a revision point into that revision's document. Pass
them as ranges to the call that migrates the document, and save the result's
ranges with its output. Here readCommentRanges reads the ranges your
storage layer saved with the document:
const { output, ranges } = migrateDocument(await readDocument(id), {
migrations: EditorMigrations,
ranges: await readCommentRanges(id),
});const { output, ranges } = migrateDocument(await readDocument(id), {
migrations: EditorMigrations,
ranges: await readCommentRanges(id),
});ranges is a record keyed by thread ID. A range in a nested root, such as a
board note, names that root on both points, and a page range names none. Each
range maps through every step and the final fit in its own root and keeps
covering the same words. A range comes back null when the text it covered is
gone or a step reverses its ends, and when the saved entry is not a range, names
a root the document lacks, covers no text or points outside the document. Save
no entry for it; its thread loads without a highlight.
A step that changes the document carries ranges only through the mapRanges
it returns. It receives the ranges still mapped, in order, and returns one
range or null for each. A range the step moves to another root comes back
null. A step that changes the document without mapRanges
returns null for every range, even when it returns mapSelection, so no
range lands on another block's words. A step that returns the document
unchanged keeps every range. migrateV54 and migrateListIdentity map ranges
exactly. A step that changes only element properties, and leaves every block
and text in place, keeps its ranges with mapRanges: ({ ranges }) => ranges.
Run extractLegacyCommentRanges before loading documents that contain
comment, comment_*, comment_draft, or commentTransient properties. Its
ranges point into the cleaned document, so pass both to one migrateDocument
call:
import {
extractLegacyCommentRanges,
migrateDocument,
} from "platejs/migrations";
const {
document: cleanDocument,
ranges,
report,
} = extractLegacyCommentRanges(legacyDocument, {
threadIds: storedThreads.map((thread) => thread.id),
});
const migrated = migrateDocument(cleanDocument, {
migrations: EditorMigrations,
ranges,
source: 53,
});
console.table(report);import {
extractLegacyCommentRanges,
migrateDocument,
} from "platejs/migrations";
const {
document: cleanDocument,
ranges,
report,
} = extractLegacyCommentRanges(legacyDocument, {
threadIds: storedThreads.map((thread) => thread.id),
});
const migrated = migrateDocument(cleanDocument, {
migrations: EditorMigrations,
ranges,
source: 53,
});
console.table(report);Review every report row, then save migrated.output with the non-null entries
of migrated.ranges as its comment ranges. Each thread gets one range. Empty
texts, voids and inline element edges never split it; visible text without the
mark does, and that thread gets no range and a split-group row that lists
each part's range in order. To keep such a thread, add one range for its ID to
ranges before the migrateDocument call, such as from the first part's
anchor to the last part's focus. Comment marks in a media caption are
removed and reported at the media element's path. A thread's mark there is an
invalid-range row whose reason is caption-text, and a malformed,
anonymous or draft-only mark gets the row it gets in the document body. The
extractor never invents missing thread IDs. Run it offline; the runtime plugin
has no legacy fallback.
Fetch remote content before constructing the editor. The loader owns aborts, stale responses, retries, and errors; the editor receives one synchronous initial document.
import type { Value } from "platejs";
import { EditorRoot, useCreateEditor } from "platejs/react";
function DocumentEditor({ initialValue }: { initialValue: Value }) {
const editor = useCreateEditor({ initialValue });
return (
<EditorRoot editor={editor}>
<EditorContainer>
<Editor />
</EditorContainer>
</EditorRoot>
);
}import type { Value } from "platejs";
import { EditorRoot, useCreateEditor } from "platejs/react";
function DocumentEditor({ initialValue }: { initialValue: Value }) {
const editor = useCreateEditor({ initialValue });
return (
<EditorRoot editor={editor}>
<EditorContainer>
<Editor />
</EditorContainer>
</EditorRoot>
);
}Render DocumentEditor only after your route or data loader resolves the
document. See Controlled Editor Value for an abort-aware
client loader and explicit replacement patterns.
Include plugins in the plugins array:
const editor = createEditor({
plugins: [HeadingPlugin, ListPlugin],
});const editor = createEditor({
plugins: [HeadingPlugin, ListPlugin],
});Raw plugin arrays keep plugin APIs, reads, updates, stores, and individual
element shapes inferred. Use a generated editor contract when the application
also needs one exact recursive Value across the complete plugin graph.
Export the runtime inputs from one source file:
import { HeadingPlugin } from "platejs/react";
import { TablePlugin } from "platejs/table/react";
import { property, schema as s, target } from "platejs";
export const EditorKit = [HeadingPlugin, TablePlugin] as const;
export const EditorSchema = {
id: "app-document",
version: 1,
overrides: [
s.override(HeadingPlugin, {
element: { type: "headingOne" },
}),
],
properties: {
reviewState: s.elementProperty(
property.enum(["draft", "approved"] as const),
{ target: target.element(HeadingPlugin) }
),
},
} as const;import { HeadingPlugin } from "platejs/react";
import { TablePlugin } from "platejs/table/react";
import { property, schema as s, target } from "platejs";
export const EditorKit = [HeadingPlugin, TablePlugin] as const;
export const EditorSchema = {
id: "app-document",
version: 1,
overrides: [
s.override(HeadingPlugin, {
element: { type: "headingOne" },
}),
],
properties: {
reviewState: s.elementProperty(
property.enum
plate generate finds the single exported Plate plugin tuple and optional
application schema by their validated runtime shapes. Their export names belong
to your app, not the compiler contract.
The editor-level schema may remap an element type, content, groups, or an existing property's target, and
it may add application-owned properties. Plugin-owned property keys and value
laws stay fixed; changing one requires a new field and an explicit migration.
Installed code reads final identities from schema handles:
import { schema as generatedSchema } from "./editor.generated";
editor.plugin(HeadingPlugin).schema.type; // 'headingOne'
generatedSchema.properties.reviewState.key; // 'reviewState'import { schema as generatedSchema } from "./editor.generated";
editor.plugin(HeadingPlugin).schema.type; // 'headingOne'
generatedSchema.properties.reviewState.key; // 'reviewState'Generate and commit the TypeScript and JSON contracts:
pnpm add -D @platejs/cli
pnpm exec plate generatepnpm add -D @platejs/cli
pnpm exec plate generateplate generate reads src/editor.ts. Pass entry paths when an app owns
several editor modules. The @plate/editor-plugins registry item installs the
authored plugin module only; it does not copy generated contracts.
Rerun plate generate after you change the editor module. Gate committed
artifacts in CI:
{
"scripts": {
"editor:check": "plate generate --check src/editor.ts"
}
}{
"scripts": {
"editor:check": "plate generate --check src/editor.ts"
}
}The generated TypeScript module exports the exact Value type and static
schema handles. The generated JSON contract carries the compiled schema
fingerprint. Neither artifact owns runtime plugin composition:
import { createEditor, EditorRoot, useCreateEditor } from "platejs/react";
import type { Value } from "./editor.generated";
import { EditorKit, EditorSchema } from "./editor";
export const createDocumentEditor = (initialValue?: Value) =>
createEditor({ plugins: EditorKit, schema: EditorSchema, initialValue });
export type DocumentEditorInstance = ReturnType<typeof createDocumentEditor>;
export function insertDocumentContent(editor: DocumentEditorInstance) {
editor.update.heading.toggle({ level: 1 });
}
export function DocumentEditor({ initialValue }: { initialValue: Value }) {
const editor = useCreateEditor({
plugins: EditorKit,
schema: EditorSchema,
initialValue,
});
return (
<EditorRoot editor={editor}>
<button type="button" onClick={() => insertDocumentContent(editor)}>
Heading
</button>
</EditorRoot>
);
}import { createEditor, EditorRoot, useCreateEditor } from "platejs/react";
import type { Value } from "./editor.generated";
import { EditorKit, EditorSchema } from "./editor";
export const createDocumentEditor = (initialValue?: Value) =>
createEditor({ plugins: EditorKit, schema: EditorSchema, initialValue });
export type DocumentEditorInstance = ReturnType<typeof createDocumentEditor>;
export function insertDocumentContent(editor: DocumentEditorInstance) {
editor.update.heading.toggle({ level: 1 });
}
export
Use the generated Value at static boundaries such as storage and
collaboration. A live editor's document type is the broad Value from
platejs, so a live editor never has the generated Editor type. A helper
that takes the editor uses the factory's return type, as
insertDocumentContent does, or the plain Editor from platejs/react when it
needs only core APIs. Runtime constructors and hooks consume the authored
EditorKit and EditorSchema directly.
The CI command recompiles the authored module and fails when committed generated artifacts are stale.
Create typed application steps with the migration scaffold:
pnpm exec plate migrate new add-captionpnpm exec plate migrate new add-captionPass --entry <path> when the editor module does not use the standard path.
The scaffold contains typed FromValue and ToValue snapshots, their
fingerprints, and the structural diff. Add the completed function to
EditorMigrations.steps under the version it produces, and bind the exported
from fingerprint in sourceFingerprints.
For offline JSON files, the entry module exports its migrations as
EditorMigrations. The runner reads that one export by name, so other exports
in the module never change which migrations run.
pnpm exec plate migrate run --entry src/editor.ts --check documents/*.json
pnpm exec plate migrate run --entry src/editor.ts --write documents/*.json
cat document.json | pnpm exec plate migrate run --entry src/editor.ts --stdinpnpm exec plate migrate run --entry src/editor.ts --check documents/*.json
pnpm exec plate migrate run --entry src/editor.ts --write documents/*.json
cat document.json | pnpm exec plate migrate run --entry src/editor.ts --stdinThe command is a dry run unless --write is present. --check exits nonzero
when any document needs migration. --stdin writes the migrated envelope to
standard output and never mutates storage. Envelope selections are mapped and
preserved through the same document and preparation pipeline.
Raw documents need --from <version> or --from current. With --from, the
command reads every input as a raw document, so run persisted envelopes without it.
Use compileEditor in build tooling that needs schema identity, property
contracts and final plugin bindings. Ordinary editors use createEditor or
useCreateEditor directly.
import { writeFileSync } from "node:fs";
import { compileEditor } from "platejs/compiler";
import { EditorKit, EditorSchema } from "../src/editor";
const artifact = compileEditor({ plugins: EditorKit, schema: EditorSchema });
writeFileSync("editor.schema.json", JSON.stringify(artifact.schema, null, 2));import { writeFileSync } from "node:fs";
import { compileEditor } from "platejs/compiler";
import { EditorKit, EditorSchema } from "../src/editor";
const artifact = compileEditor({ plugins: EditorKit, schema: EditorSchema });
writeFileSync("editor.schema.json", JSON.stringify(artifact.schema, null, 2));The result contains recursively frozen JSON data:
| Field | Content |
|---|---|
schema | Validated schema contract, identity and fingerprint. |
bindings | Installed capability names, final element types and mark keys; authoredToggle identifies an authored toggle command. |
Compilation evaluates configuration, API factories and validators. It does
not activate plugins or generate an initial document. The result contains
no editor, stores or callbacks. schema is optional, as with editor creation.
plate generate also emits exact application types. Its type-only
EditorPropertyTypes and GeneratedEditorTypeProvider imports belong to
advanced tooling and generated files.
Set the maximum length of the editor:
const editor = createEditor({
maxLength: 100,
});const editor = createEditor({
maxLength: 100,
});Set a custom id for the editor:
const editor = createEditor({
id: "my-custom-editor-id",
});const editor = createEditor({
id: "my-custom-editor-id",
});The ID labels the model for application code. Use contextual useEditor() for the selected mounted view, or bind existing controls with <EditorProvider editor={editor}>. See Plate Controller for shared UI.
Every live descendant has an editor-scoped NodeKey. Node keys include
text nodes, survive moves and immutable updates, and disappear when the node is
removed. They never enter JSON, clipboard slices, history, or collaboration
payloads. Use them for selection, drag and drop, temporary UI state, and lazy
path lookup.
const nodeKey = editor.key(element);
const path = editor.read.nodes.path(nodeKey);
editor.update.nodes.remove({ at: nodeKey });const nodeKey = editor.key(element);
const path = editor.read.nodes.path(nodeKey);
editor.update.nodes.remove({ at: nodeKey });Node keys can target nodes across one editor's document roots. Path lookup is root-local: the base editor resolves paths in the main root, while an editor view resolves paths in its own root.
Use ElementIdPlugin only when an element needs an ID that survives storage or
cross-session references. The plugin is opt-in. It assigns persisted string IDs
to block and inline elements, never text nodes.
import { ElementIdPlugin } from "platejs";
const editor = useCreateEditor({
plugins: [
ElementIdPlugin.configure({
initialState: {
generateId: () => crypto.randomUUID(),
},
}),
],
});
const elementId = editor.plugin(ElementIdPlugin);
const key = editor.key(element);
const id = elementId.read.id(key);
const entry = id ? editor.read.nodes.byId(id) : null;import { ElementIdPlugin } from "platejs";
const editor = useCreateEditor({
plugins: [
ElementIdPlugin.configure({
initialState: {
generateId: () => crypto.randomUUID(),
},
}),
],
});
const elementId = editor.plugin(ElementIdPlugin);
const key = editor.key(element);
const id = elementId.read.id(key);
const entry = id ? editor.read.nodes.byId(id) : nulleditor.read.nodes.byId(id), or tx.nodes.byId(id) inside an update, returns
the element's key, node and path, with root when the element lives in
a named root, or null when no element holds the ID. A stored ID addresses an
element; the element's live identity stays its key. Node reads and node
transforms take an { id } target, such as nodes.path({ id }) or
at: { id }:
// A command looks the ID up in the document it runs in.
editor.update.nodes.move({ at: { id: "intro" }, to: [0] });
// A raw update looks the ID up in the stored draft.
editor.update((tx) => tx.nodes.remove({ at: { id: "intro" } }));// A command looks the ID up in the document it runs in.
editor.update.nodes.move({ at: { id: "intro" }, to: [0] });
// A raw update looks the ID up in the stored draft.
editor.update((tx) => tx.nodes.remove({ at: { id: "intro" } }));byId and at: { id } need an editor that stores IDs. An editor stores IDs
when the schema gives every element type a generated, unique string id, as
ElementIdPlugin's default target does, and no content admits undeclared
element types. In any other editor, both throw.
An { id } target names the element that holds the ID. Text,
mark, range and offset targets keep their point or range. A target is an ID
only as an object, not an array, whose one own key is a string id, so a live
element that carries an id stays a node target. When no element holds the
ID, a write changes nothing and a read returns its empty result.
The route decides which document the ID is looked up in:
editor.update, such
as editor.update.nodes.wrap, look it up in the command's document. So do
the one-shots and plugin update methods of a writable view, in the view's
root. Over another author's pending suggestions, the ID of a moved element
reaches the moved copy, and an ID that only a struck original holds changes
nothing. A path in to, after or before, and a child position, still
names a place in the stored document.editor.update((tx) => ...) looks it up in the stored draft, as it
resolves a path or a key. It reaches the struck original.nodes.get({ id }) and
nodes.path({ id }) return nothing for an ID another root holds. A node key
still reads the element in whichever root holds it.The default generator is full-length nanoid(). Loads and moves preserve valid
IDs. Copies, splits, duplicates, and pasted copies receive fresh IDs. No two
elements store one ID. An insert or update that stores an ID another element
holds lands with a fresh one, so read the ID back from the landed element. A
collaboration peer's concurrent edit can change it again the same way. Exact
schema-derived elements expose element.id; use the plugin read at erased or
optionally installed package boundaries. A suggested Enter stores the new
element's ID when it records, so
previews and decisions show that ID.
The compiled schema property target decides which elements receive IDs. When only blocks need persisted identity and the application never finds or targets an element by ID, narrow the target in the application schema:
import { ElementIdPlugin, schema, target } from "platejs";
const editor = useCreateEditor({
plugins: [ElementIdPlugin],
schema: {
overrides: [
schema.override(ElementIdPlugin, {
properties: { id: { target: target.group("block") } },
}),
],
},
});import { ElementIdPlugin, schema, target } from "platejs";
const editor = useCreateEditor({
plugins: [ElementIdPlugin],
schema: {
overrides: [
schema.override(ElementIdPlugin, {
properties: { id: { target: target.group("block") } },
}),
],
},
});A block-only target leaves inline elements without IDs, so nodes.byId and
at: { id } throw in that editor, even for a block's ID.
elementId.read.id(key) and pen marks from platejs/ink keep working.
Current-document admission generates IDs only for matching elements and removes
the plugin-owned id from excluded elements. The block target works while no
element's content admits both a block and an inline element, because the ID is
unique and a type change must not drop it.
Include ElementIdPlugin in EditorMigrations. Raw documents that already use
the current schema can enter through the same detached conversion boundary:
import { migrateDocument } from "platejs/migrations";
const current = migrateDocument(rawCurrentDocument, {
migrations: EditorMigrations,
source: "current",
}).output;
const editor = createEditor({
plugins: [ElementIdPlugin],
initialValue: current,
});import { migrateDocument } from "platejs/migrations";
const current = migrateDocument(rawCurrentDocument, {
migrations: EditorMigrations,
source: "current",
}).output;
const editor = createEditor({
plugins: [ElementIdPlugin],
initialValue: current,
});Current admission keeps valid string IDs and fills missing IDs. An editor load
gives every later copy of a repeated ID a fresh one and keeps the ID on the
first element in document order. migrateDocument refuses a document that
holds one ID twice. Convert numeric IDs, legacy property names and repeated IDs
in the migration step for their historical schema version, where the
application can define an explicit collision policy.
ElementIdPlugin declares its id with unique: true. Declare an
application's own generated element metadata the same way when two equal
values would mean one copied identity:
import { definePlugin, property, schema, target } from "platejs";
const AnchorPlugin = definePlugin("anchor", {
schema: {
properties: {
anchorId: schema.elementProperty(
property.string({ generate: () => crypto.randomUUID() }),
{
role: "metadata",
target: target.group("element"),
typeChange: "preserve-if-allowed",
unique: true,
}
),
},
},
});import { definePlugin, property, schema, target } from "platejs";
const AnchorPlugin = definePlugin("anchor", {
schema: {
properties: {
anchorId: schema.elementProperty(
property.string({ generate: () => crypto.randomUUID() }),
{
role: "metadata",
target: target.group("element"),
typeChange: "preserve-if-allowed",
unique: true,
}
),
},
},
});A generated element property that declares no split rule drops its value on
a split, so the second half generates a fresh one. Declare split: "preserve"
to copy the value instead.
unique sets copy and split to "drop". It requires a generator, the
metadata role, an exact key, a value that is not a set, a target that does
not depend on place, landing: "preserve", and
typeChange: "preserve-if-allowed". A type change keeps an element where it
is. So when an element's or root's content admits a type the target matches,
every type that content admits must match too, including an undeclared type
under unknown: "preserve". The schema rejects any other declaration and names
the content that breaks the rule. A unique key takes one element declaration,
so the schema also rejects a second declaration of that key from any plugin.
A generator that keeps returning held values throws an error that names the
property. Suggesting mode writes a unique value directly, without a suggestion.
When a stored block repeats a value that a stored spare block holds, the
decision that builds that spare block gives it a fresh value.
Adding or removing unique changes the schema fingerprint, so editors that
disagree on it never share a collaboration room, and saved documents need a
migration step. A generated element property that Suggesting supports, such as
ElementIdPlugin's id, sets the schema contract's storage revision to 2,
because suggestions store spare blocks that hold its values. The revision
changes the fingerprint the same way.
Find the element that holds a unique value with
editor.read.unique.holder(property, value), or tx.unique.holder inside an
update. It reads the unique index instead of scanning, in every root, and
returns the holder's key, path and root, or null when no element holds
the value. Inside an update it also finds an element that took the value
earlier in that update. In an editor whose elements store IDs,
holder("id", value) throws: find that element with nodes.byId(id).
const holder = editor.read.unique.holder("anchorId", anchorId);
if (holder) {
editor.update((tx) => tx.nodes.remove({ at: holder.key }));
}const holder = editor.read.unique.holder("anchorId", anchorId);
if (holder) {
editor.update((tx) => tx.nodes.remove({ at: holder.key }));
}Plate's navigation feedback plugin shows "you landed here" feedback after TOC jumps, footnote navigation, search jumps, and custom outline movement.
Navigation feedback is enabled by default. To change the flash duration or
turn the plugin off, configure NavigationFeedbackPlugin in plugins. The
configured plugin replaces the default one.
import { createEditor, NavigationFeedbackPlugin } from 'platejs/react';
const editor = createEditor({
plugins: [
NavigationFeedbackPlugin.configure({ initialState: { duration: 1200 } }),
],
});import { createEditor, NavigationFeedbackPlugin } from 'platejs/react';
const editor = createEditor({
plugins: [
NavigationFeedbackPlugin.configure({ initialState: { duration: 1200 } }),
],
});The NavigationFeedbackPlugin is part of the React editor defaults. List it
in plugins only to change its configuration.
import { createEditor, NavigationFeedbackPlugin } from 'platejs/react';
const editor = createEditor({
plugins: [NavigationFeedbackPlugin.configure({ enabled: false })],
});import { createEditor, NavigationFeedbackPlugin } from 'platejs/react';
const editor = createEditor({
plugins: [NavigationFeedbackPlugin.configure({ enabled: false })],
});Control whether the editor should normalize its content on initialization:
const editor = createEditor({
shouldNormalizeEditor: true,
});const editor = createEditor({
shouldNormalizeEditor: true,
});Normalization may take a few dozen milliseconds for large documents, such as the playground value.
Set where the caret starts:
const editor = createEditor({
initialSelection: 'end', // or 'start', a selection, or null for no caret
});const editor = createEditor({
initialSelection: 'end', // or 'start', a selection, or null for no caret
});The starting caret does not focus the editor. Leave initialSelection out to
keep the caret a persisted initialValue saved.
Bind each component to its owning plugin descriptor:
const editor = createEditor({
plugins: [
ParagraphPlugin.configure({ component: CustomParagraphComponent }),
HeadingPlugin.configure({ component: CustomHeadingComponent }),
],
});const editor = createEditor({
plugins: [
ParagraphPlugin.configure({ component: CustomParagraphComponent }),
HeadingPlugin.configure({ component: CustomHeadingComponent }),
],
});When your app imports the target, configure that descriptor directly:
const AppLinkPlugin = LinkPlugin.configure({
initialState: {
allowedSchemes: ["http", "https"],
},
});
const editor = createEditor({
plugins: [AppLinkPlugin],
});const AppLinkPlugin = LinkPlugin.configure({
initialState: {
allowedSchemes: ["http", "https"],
},
});
const editor = createEditor({
plugins: [AppLinkPlugin],
});A package plugin may need to adapt another installed package without importing it or controlling the consumer's editor kit:
import { PLUGINS } from "platejs";
import { definePlugin } from "platejs/react";
const SingleBlockPlugin = definePlugin(PLUGINS.singleBlock, {
override: {
[PLUGINS.trailingBlock]: {
enabled: false,
},
},
});import { PLUGINS } from "platejs";
import { definePlugin } from "platejs/react";
const SingleBlockPlugin = definePlugin(PLUGINS.singleBlock, {
override: {
[PLUGINS.trailingBlock]: {
enabled: false,
},
},
});The override applies only when the target is installed; a missing target is
ignored. It cannot change name, dependencies, or nest another override.
Direct target configuration wins.
A complete explicit descriptor can replace a lower-precedence core or dependency definition with the same name. Inside one plugin array, terminal configurations derived from the same authored plugin compose in order and later defined values win. Unrelated plugins and divergent authoring branches cannot share a name.
const AppParagraphPlugin = ParagraphPlugin.configure({
component: AppParagraphElement,
});
const editor = createEditor({
plugins: [AppParagraphPlugin],
});const AppParagraphPlugin = ParagraphPlugin.configure({
component: AppParagraphElement,
});
const editor = createEditor({
plugins: [AppParagraphPlugin],
});createEditor derives plugin APIs, reads, updates and stores from the installed
plugin tuple. The editor's document type is Value. TypeScript checks
initialValue against Value, and the starting document never narrows the
editor's type, because the document changes with the first edit.
import { createEditor, LinkPlugin } from 'platejs/react';
import { TablePlugin } from 'platejs/table/react';
const AppKit = [TablePlugin, LinkPlugin] as const;
const editor = createEditor({
plugins: AppKit,
});
// Usage
editor.update((tx) => {
tx.plugin(TablePlugin).insertRow();
});import { createEditor, LinkPlugin } from 'platejs/react';
import { TablePlugin } from 'platejs/table/react';
const AppKit = [TablePlugin, LinkPlugin] as const;
const editor = createEditor({
plugins: AppKit,
});
// Usage
editor.update((tx) => {
tx.plugin(TablePlugin).insertRow();
});Every editor's document type is Value, whatever initialValue holds. Name the
editor type with typeof editor, or with the ReturnType of a factory when
another module needs it.
import { createEditor, LinkPlugin } from "platejs/react";
import { TablePlugin } from "platejs/table/react";
const AppKit = [TablePlugin, LinkPlugin] as const;
const editor = createEditor({
plugins: AppKit,
initialValue: [
{
type: "paragraph",
children: [{ text: "Hello, EditorRoot!" }],
},
],
});
export type MyEditor = typeof editor;import { createEditor, LinkPlugin } from "platejs/react";
import { TablePlugin } from "platejs/table/react";
const AppKit = [TablePlugin, LinkPlugin] as const;
const editor = createEditor({
plugins: AppKit,
initialValue: [
{
type: "paragraph",
children: [{ text: "Hello, EditorRoot!" }],
},
],
});
export type MyEditor = typeof editor;Read a node by its plugin to get its exact type:
const table = editor.read.nodes.get([0], { type: TablePlugin })?.[0];const table = editor.read.nodes.get([0], { type: TablePlugin })?.[0];A helper that takes this editor uses MyEditor. A helper that needs only core
APIs takes the plain Editor from platejs/react. For one exact recursive
Value across the whole plugin graph, use the generated types from
Exact generated editor types at storage and
collaboration boundaries.
A component reads the current editor from context without repeating its plugin tuple:
import { useEditor } from "platejs/react";
import { TablePlugin } from "platejs/table/react";
const editor = useEditor();
const table = editor.plugin(TablePlugin);import { useEditor } from "platejs/react";
import { TablePlugin } from "platejs/table/react";
const editor = useEditor();
const table = editor.plugin(TablePlugin);Use useEditor().plugin(Plugin) when the component needs an exact plugin
capability. Generated application types stay at explicit static boundaries.