Block IDs
BlockIdExtension and BlockIdHTMLExtension are experimental. Their API may
change in a minor release.
BlockIdExtension (from @lexical/extension) gives blocks stable, unique
ids, so that code outside the editor can address a block by id: in a
headless process editing stored JSON, in a single-user editor, and between
collaborators. The main use case is an agent that reads a document as blocks
with ids and answers "replace b7" or "delete b9", which must find the
right block after the document was saved, reloaded or edited by others.
Setup
import {BlockIdExtension, buildEditorFromExtensions} from '@lexical/extension';
import {RichTextExtension} from '@lexical/rich-text';
const editor = buildEditorFromExtensions({
dependencies: [RichTextExtension, BlockIdExtension],
name: 'my-editor',
});
An id is NodeState under the key blockId
(blockIdState), so it is part of the node's JSON
("$": {"blockId": "V1StGXR8_Z5jdHi6B-myT"}), survives clones, undo and redo
and the Lexical clipboard, and is synchronized by any collaboration binding
that synchronizes NodeState.
Addressing blocks
$getBlockId(node) returns a node's id, and $getBlockById(id) finds a
block through an index, without scanning the document. A block created
earlier in the same update is found once that update has committed.
To let an agent edit a document, give it each block's id and content, then apply its operations by id in one update:
import {$getBlockById, $getBlockId} from '@lexical/extension';
import {$createParagraphNode, $createTextNode, $getRoot} from 'lexical';
// 1. What the agent reads (here, the top-level blocks).
const blocks = editor.read(() =>
$getRoot()
.getChildren()
.map(node => ({id: $getBlockId(node), text: node.getTextContent()})),
);
// 2. What the agent answers, e.g.
// [{op: 'replace', id: 'b7', text: 'New text'},
// {op: 'insertAfter', id: 'b7', text: 'Another paragraph'},
// {op: 'delete', id: 'b9'}]
editor.update(
() => {
for (const op of ops) {
const block = $getBlockById(op.id);
if (block === null) {
continue; // Deleted meanwhile, or a mistyped id: tell the agent.
}
if (op.op === 'delete') {
block.remove();
} else {
const node = $createParagraphNode().append($createTextNode(op.text));
if (op.op === 'replace') {
block.replace(node); // Keeps id b7.
} else {
block.insertAfter(node); // Gets a fresh id in this update.
}
}
}
},
{discrete: true},
);
replace with a node that has no id keeps the replaced block's id, so the
agent can keep referring to b7. Whether a collaborator's concurrent typing
in the replaced block survives depends on the collaboration binding. To give
a new block an id of your choosing, set it before inserting it:
$setState(node, blockIdState, 'b7-intro'). If another block already has
that id, that block keeps it and the new one gets a fresh id.
Headless
A server that stores Lexical JSON can assign ids to a document (or to the blocks that lack one) in one synchronous load and save:
const pipeline = buildEditorFromExtensions({
$initialEditorState: null,
dependencies: [RichTextExtension, BlockIdExtension],
name: 'docs-pipeline',
});
pipeline.setEditorState(pipeline.parseEditorState(storedJSON));
const withIds = JSON.stringify(pipeline.getEditorState().toJSON());
Register the same nodes as the editors that wrote the document. Running it again changes nothing, and the ids it assigns are derived from the document, so a server that only reads gets the same ids without writing first.
Which blocks get ids
By default ($defaultIsIdentifiedBlock): every child of the root (a
top-level list or table included), every nested block that holds text, and
every nested block decorator. A block holds text when its class declares
children: 'inline' (or a list that includes 'inline') in its
node structure: list
items, and paragraphs, headings, quotes and code blocks inside table cells
or other containers. Nested wrappers get no id: nested lists, table rows and
cells, shadow roots, and nested elements whose class declares no
children. Slots count as nested, like
shadow roots.
$isIdentifiedBlock changes the set. It is evaluated when a node is marked
dirty, so it should depend only on the node and its ancestors, and every
reader of a document stored without ids must use the same one, since
positional ids follow from it:
import {
$defaultIsIdentifiedBlock,
$isRootChildBlock,
BlockIdExtension,
} from '@lexical/extension';
import {$isTableCellNode} from '@lexical/table';
import {configExtension} from 'lexical';
// Top-level blocks only.
configExtension(BlockIdExtension, {$isIdentifiedBlock: $isRootChildBlock});
// The default, plus table cells.
configExtension(BlockIdExtension, {
$isIdentifiedBlock: node =>
$defaultIsIdentifiedBlock(node) || $isTableCellNode(node),
});
How ids follow edits
An identified block without an id gets one in the same update that creates
it, whether it was typed, pasted, or produced by importJSON, HTML or
Markdown import. Ids then follow the content the user sees:
| Edit | Result |
|---|---|
| Enter in the middle or at the end of a block | The block keeps its id; the new block after it gets a fresh one |
| Enter at the start of a block | The text moves into the new block below, and the id moves with it |
| Backspace at the start of a block (join) | The block that absorbs the content keeps its id |
| Paragraph to heading or quote, and back | The new block keeps the id of the block it replaced |
| Paragraph to list | The item keeps the paragraph's id; the list gets a fresh one |
node.replace(newNode) with a node that has no id, or $setSlot replacing a slot value | The new node keeps the replaced node's id |
Moving a block (drag and drop, insertAfter of an existing node) | The id moves with the block |
| Copy and paste, duplicate, import of copied content | The copy gets a fresh id unless no other block has the id |
| Cut and paste | The pasted block keeps the id |
| Undo and redo | Ids are restored exactly |
The same rules apply to nested blocks. $copyNode does not copy the id.
Uniqueness
When several identified blocks carry the same id, one keeps it and the others get fresh ids: a block that had it before the update wins over a copy (even one placed above it); among blocks that all had it (copies made concurrently by collaborators), the earliest in document order wins; among blocks that all got it in this update, the first one created wins.
Documents stored without ids
A document stored before it had ids (written by an editor without the extension, by a server, or converted from another format) gets positional ids when it is loaded: derived from the document's content and each block's place in it. Everyone who loads the same document derives the same ids, so an agent can read ids without writing first, a person's first edit keeps the ids the agent read, and collaborators who open the document at the same time assign the same ids.
A load is a state set with setEditorState, the state present when the
extension is registered, the first content an editor gets (an initial state,
an import into a new headless editor, a binding's first sync), and a remote
change that brings blocks without an id or with a repeated id. Everything
else is an edit, and gets random ids. Positional ids are unique within a
document only: key a cross-document index by document too.
HTML
Ids are not part of HTML by default. Add BlockIdHTMLExtension (from
@lexical/html) to the editor's dependencies to opt in:
- Export: every identified block's element gets a
data-block-idattribute, in$generateHtmlFromNodesand in copied HTML. - Import: HTML imported through
DOMImportExtension(for example withClipboardDOMImportExtension) readsdata-block-idback, through the uniqueness rules. The legacyimportDOMpath does not read it.
Set export: false or import: false to use only one direction. Keep the
export off in editors whose HTML must be byte-for-byte deterministic
(snapshot comparisons, content hashing).
Collaboration
The extension works with any collaboration binding that synchronizes NodeState. The collaborator who creates a block assigns its id. A pasted or duplicated block is repaired in the update that creates it, so it reaches the others with its own id. Duplicates that appear only when concurrent edits merge are repaired by every collaborator the same way. Two clients that put the same initial content into empty editors give it the same ids. Repairs are ordinary local edits, so a Yjs undo manager can record one with the user's last change; undoing it re-runs the repair, with the same ids.
Configuration
generateId: makes a new id. The default,generateBlockId, makes 21 base64url characters (126 random bits) withcrypto.getRandomValues, and throws where that is missing (React Native without a polyfill). A replacement must return a non-empty string of at most 128 characters that stays unique across collaborators, who make ids without coordination; tests can use a counter:generateId: () => `b${++n}`.disabled: stops assigning, repairing and indexing ids (also an output signal). Ids already in the document are kept, and$getBlockByIdscans the document. Enabling it again assigns and repairs ids in one update.- Existing ids. Any non-empty string of at most 128 characters under
$.blockIdis adopted as it is: an app that stores its own ids there can switch to the exportedblockIdState.
Id format
Ids that the extension writes are always 21 characters of the base64url
alphabet (A–Z, a–z, 0–9, -, _), random or positional alike.
Positional ids are part of the stored format: every reader of a document
stored without ids must derive the same ones, whatever version of Lexical it
runs.
- The document key. Export the document in compact JSON
(
editorState.toJSON(true)), remove everyblockIdfrom the nodes' NodeState (and a$that held only that), and write it as canonical JSON:JSON.stringifywithout whitespace, of a copy in which every object's keys were inserted in UTF-16 code unit order. The key is the SHA-256 of its UTF-8 bytes. - The block's place. Its index among the identified blocks with the
same nearest identified ancestor (or the root), in document order (a
host's slot values, in canonical slot order, before its children), after
that ancestor's place, joined by
.. A root child's place is its index ("0","1", …); the second item of a list at index 3 is"3.1", and so is the paragraph in the second cell of a one-row table at index 3. - The id. The first 21 characters of the unpadded base64url encoding of SHA-256(key ‖ UTF-8(place)).
The k-th later holder (in document order, from 1) of a repeated id id gets
the first 21 characters of the unpadded base64url encoding of
SHA-256(UTF-8("dup" + U+0000 + id + U+0000 + k)), k in decimal.
Repeated ids are handled in the code unit order of the ids. When a derived
id is already taken, the n-th retry appends #n to the place ("3#1") or
to k ("1#1").
Because the key comes from the nodes' compact JSON and the places from the predicate, every reader must register the same nodes and use the same predicate. A node class whose compact JSON changes changes the key of documents that contain it, until the document is first written with its ids.