Block IDs
BlockIdExtension and BlockIdHTMLExtension are experimental. Their API may
change in a minor release.
BlockIdExtension (from @lexical/extension) gives blocks stable, unique ids.
Code outside the editor can then address a block by id, and the same id works
wherever the document goes: in a headless process editing stored JSON, in a
single-user editor, and between collaborators.
The main use case is editing by agents. An AI agent reads a document as a list
of blocks with ids, and answers with operations such as "replace block b7",
"insert after b7" or "delete b7". Those operations must find the right
block even after the document was saved, reloaded, edited by someone else, or
synchronized through a collaboration server.
Setup
import {BlockIdExtension, buildEditorFromExtensions} from '@lexical/extension';
import {RichTextExtension} from '@lexical/rich-text';
const editor = buildEditorFromExtensions({
dependencies: [RichTextExtension, BlockIdExtension],
name: 'my-editor',
});
How ids are stored
An id is NodeState under the key blockId
(blockIdState). It is part of the node's JSON:
{
"type": "paragraph",
"$": {"blockId": "Xk3_a9Qz"},
"children": [...]
}
Because it is NodeState, an id:
- round-trips through
exportJSON/importJSONand the Lexical clipboard; - is kept when a node is cloned by an update, and restored by undo and redo;
- is synchronized by any collaboration binding that synchronizes NodeState
(
@lexical/yjsv1 and v2 both do). Ids do not depend on the identity of items in a CRDT, so a document keeps its ids when it is exported from one collaboration session and imported into another, or edited without collaboration at all.
$copyNode does not copy the id (the state is declared with
resetOnCopyNode), so a node split off another one starts without an id
rather than with a duplicate.
Which blocks get ids
By default, every element and decorator child of the root. Nested blocks are
opt-in through $isIdentifiedBlock:
import {$defaultIsIdentifiedBlock, BlockIdExtension} from '@lexical/extension';
import {configExtension} from 'lexical';
import {$isListItemNode} from '@lexical/list';
import {$isTableCellNode} from '@lexical/table';
configExtension(BlockIdExtension, {
$isIdentifiedBlock: node =>
$defaultIsIdentifiedBlock(node) ||
$isListItemNode(node) ||
$isTableCellNode(node),
});
The predicate is evaluated when a node is marked dirty, so it should depend only on the node and its ancestors.
Ids are generated by generateId. The default makes 8 URL-safe characters (48
random bits). Any function that returns a non-empty string of at most 128
characters works; an id that is already in use is simply retried, so tests can
inject a counter:
let n = 0;
configExtension(BlockIdExtension, {generateId: () => `b${++n}`});
When ids are assigned
An identified block that has no id gets one in the same update that creates
it, whether it was typed, pasted, or produced by importJSON, an HTML import
or a markdown import. No later update is needed, so the first committed state
that contains the block, and anything serialized from it, already carries the
id.
A document loaded without ids (for instance with
editor.setEditorState(editor.parseEditorState(json))) gets them in the update
that loads it. A document that is already in the editor when the extension is
registered, or a state set with setEditorState from an editor without the
extension, gets them in the next update.
Updates that do not run transforms are repaired by a follow-up update that runs right after their commit. That is how changes from collaborators are handled: the collaboration bindings apply remote changes without transforms, and they do not write changes made during those updates back to the shared document.
Uniqueness: the existing block keeps the id
When several identified blocks carry the same id, one keeps it and the others get fresh ids. Duplicates come from pasting copied content, duplicating a block, importing JSON or HTML that contains copies, or concurrent edits. The block that keeps the id is chosen in two steps:
- A block that already had the id before the update keeps it. A block that got the id in this update (a pasted or duplicated block, an imported one, a block whose id was set explicitly) yields and gets a fresh id. A reference held by an agent never jumps to a copy, wherever the copy is placed, even above the original.
- Between blocks that all had the id before, or that all got it in this update, the earliest in document order keeps it. This settles duplicates that no single update created: two copies imported together, or copies that collaborators made concurrently and that only meet when their edits merge.
Telling the two apart costs nothing extra: the extension compares each holder with its own version in the previous editor state.
Cut and paste moves the id: once the cut has removed the original, nothing else carries the id, so the pasted block keeps it.
The tie-break depends only on the document, not on which collaborator made a copy. Collaborators who see the same merged duplicate repair it the same way: all keep the earliest block and give the later one a fresh id. They may generate different fresh ids, but the shared document settles on one of them (it is one NodeState value), and once the ids are unique there is nothing left to repair. A repair never produces a new duplicate, so it cannot oscillate. A copy made locally never reaches the shared document as a duplicate at all, because it is repaired in the update that creates it.
Splits, joins, type changes and moves
The ids 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; the empty block left above gets a fresh id |
| Backspace at the start of a block (join) | The block that absorbs the content keeps its id; the removed block's id is gone |
Paragraph to heading, quote or list ($setBlocksType, INSERT_*_LIST_COMMAND), and back | The new block keeps the id of the block it replaced |
node.replace(newNode) with a new node that has no id | The new node keeps the replaced node's id |
Moving a block (drag and drop, insertAfter/insertBefore of an existing node) | The id moves with the block |
| Copy and paste, duplicate, JSON or HTML import of copied content | The copy keeps the id only if no other block has it; otherwise the copy gets a fresh id and the original keeps it, even when the copy is placed above it |
| Cut and paste | The pasted block keeps the id, since the cut removed the original |
| Undo and redo | Ids are restored exactly |
Lexical's core does not carry NodeState across a type change: $setBlocksType
creates a new element and calls replace. The extension recognizes these
cases from the previous editor state, in the update that makes them: a new
block that took over the children of a removed block, or that sits exactly
where a removed block sat, takes over that block's id. A new block that took
all the children of a block that is now empty takes its id too (Enter at the
start). No core behavior is changed.
With nested ids, the same rules apply inside lists and tables. For example,
Enter in a list item creates a new list item (with $copyNode, so without an
id) and the rules above decide which item keeps the id. Converting paragraphs
to a list gives the list items the paragraphs' ids, because they took over the
paragraphs' content.
Looking blocks up
import {$getBlockById, $getBlockId} from '@lexical/extension';
editor.read(() => {
const block = $getBlockById('b7');
const id = block && $getBlockId(block);
});
$getBlockById uses an index that the extension keeps up to date from the
dirty nodes of each update, so its cost does not grow with the document. Every
result is checked against the active state, so it never returns a removed or
re-keyed block. A block created earlier in the same update is found once that
update has committed.
Headless: assign ids in one write
A server that stores Lexical JSON can assign ids to a document (or to whatever blocks lack one) in a single synchronous load-and-save:
import {BlockIdExtension, buildEditorFromExtensions} from '@lexical/extension';
import {RichTextExtension} from '@lexical/rich-text';
const editor = buildEditorFromExtensions({
$initialEditorState: null,
dependencies: [RichTextExtension, BlockIdExtension],
name: 'docs-pipeline',
});
// Parsing marks every node dirty, so this one commit assigns every missing
// id and repairs every duplicate.
editor.setEditorState(editor.parseEditorState(storedJSON));
const withIds = JSON.stringify(editor.getEditorState().toJSON());
Register the same nodes as the editors that wrote the document. Ids already in the document are kept, so running this again changes nothing.
How agents use this
Give the agent each block's id and content, then apply its operations by id in one update:
import {$getBlockById, $getBlockId, blockIdState} from '@lexical/extension';
import {$convertFromMarkdownString} from '@lexical/markdown';
import {$getRoot, $setState} from 'lexical';
// 1. What the agent reads.
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: report it back to the agent.
}
if (op.op === 'delete') {
block.remove();
} else {
const node = $createParagraphNode().append($createTextNode(op.text));
if (op.op === 'replace') {
// Takes the place of the old block, so it keeps id b7.
block.replace(node);
} 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. To give a new block an id of the agent's
choosing, set it before inserting: $setState(node, blockIdState, 'b7-intro').
If another block already has that id, it keeps it and the new node gets a fresh id.
HTML
Ids are not part of HTML by default. BlockIdHTMLExtension (from
@lexical/html) opts in:
import {BlockIdHTMLExtension} from '@lexical/html';
buildEditorFromExtensions({
dependencies: [RichTextExtension, BlockIdHTMLExtension],
name: 'my-editor',
});
- 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. Imported ids are never trusted: they are validated like any other id and go through the uniqueness rule, so pasting HTML whose ids are already in the document gives the pasted blocks fresh ids. The legacyimportDOMpath does not read the attribute.
Set export: false or import: false in its config to use only one
direction.
Collaboration
The extension works with any collaboration binding that synchronizes NodeState, and needs nothing from the binding beyond that:
- The collaborator who creates a block assigns its id, and the others receive it; they do not assign anything themselves.
- A collaborator who pastes or duplicates a block repairs the copy locally, in the same update, so the copy reaches the others with its own id.
- Duplicates that only appear when concurrent edits merge (two people moving the same block at the same time, which a CRDT can turn into two copies) are repaired by every collaborator with the earliest-in-document-order rule, and converge.
- A shared document written without ids (by clients without the extension) gets ids from the first collaborator who opens it with the extension. If several do so at the same time, the shared document keeps one value per block.
- Ids are generated at random, so two clients that create "the same" initial
content independently produce different content. A binding that merges
identical initial content written by several clients at once can only do so
if the ids match: give such initial blocks fixed ids
(
$setState(node, blockIdState, 'intro')) or let one client bootstrap the document.
Repairs are ordinary local edits. With @lexical/yjs, the Yjs undo manager can
record a repair together with the user's last change, so undoing that change
can also undo the repair; the repair then runs again and assigns another fresh
id.
Disabling
disabled: true (or setting the disabled output signal) stops assigning,
repairing and indexing ids. Ids already in the document are kept. While
disabled, $getBlockById falls back to a scan of the document. Enabling the
extension again assigns and repairs ids for the whole document in one update.