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": "V1StGXR8_Z5jdHi6B-myT"},
"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.
Adopting blockIdState in an existing app
blockId is the one key the extension reads and writes. An app that already
stores its own block ids under $.blockId can switch to the extension without
migrating documents: replace its own createState('blockId', ...) with the
exported blockIdState (two state configs with the same key would both claim
the same JSON field), and every stored id that is a non-empty string of at
most 128 characters, such as a UUID, is adopted as it is. Only missing,
invalid and duplicate ids are replaced.
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 (a slot value's ancestors run through its host).
Blocks in slots
Blocks inside slots get ids when the predicate identifies them, and everything the extension walks (the index, the repair of duplicates, removals of a host with its slots, the lookup while disabled) visits slot values as well as children. For example, to identify the blocks inside slot containers as well as the root's children:
import {$defaultIsIdentifiedBlock, BlockIdExtension} from '@lexical/extension';
import {$getSlotHost, $isElementNode, configExtension} from 'lexical';
configExtension(BlockIdExtension, {
$isIdentifiedBlock: node => {
if ($defaultIsIdentifiedBlock(node)) {
return true;
}
const parent = node.getParent();
return (
$isElementNode(node) &&
!node.isInline() &&
parent !== null &&
$getSlotHost(parent) !== null
);
},
});
Where the rules below speak of document order, a host's slot values (in its
canonical slot order) come before its children, as $dfsWithSlots visits
them. Replacing a slot value with $setSlot in one update keeps the replaced
block's id, like replace.
Id format
Ids are generated by generateId. The default, generateBlockId, makes 21
URL-safe characters: 126 random bits, more than the 122 random bits of a
version 4 UUID.
Ids are made by every collaborator and by servers that edit stored JSON, with
no coordination between them. An id that is already in the editor is retried,
but ids made concurrently by two peers cannot see each other, so the size
alone has to make a collision practically impossible: with 126 bits, a
document with a million blocks has less than a 10-26 chance of holding
any two equal random ids. Shorter ids made unique by a per-peer prefix and a
counter would need a prefix of about 72 bits anyway (peers have no shared
identity outside a collaboration session, and their random prefixes collide
too), would save only about 6 characters per block, and would make ids
sequential: a model that mistypes …-17 as …-18 would silently edit another
block, where a mistyped random id names no block and the edit fails visibly.
Any function that returns a non-empty string of at most 128 characters works. A replacement must stay unique across peers (for instance a per-peer prefix plus a counter); tests can inject a plain counter:
let n = 0;
configExtension(BlockIdExtension, {generateId: () => `b${++n}`});
If the ids are too long for a prompt, map them to short aliases (b1, b2,
…) when building the prompt and back when applying the model's answer.
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, the earliest in document order keeps it. This settles duplicates that no single update created, such as copies that collaborators made concurrently and that only meet when their edits merge. Every collaborator that sees such a duplicate repairs it, so the rule must give all of them the same answer: it depends only on the document.
- Between blocks that all got the id in this update, the first one created keeps it (for instance the first of two copies imported together). Only the editor that makes this update decides, and the others receive the result, so creation order (Lexical's node keys, which only increase) is enough and cheap.
Telling these apart costs nothing extra: the extension compares each holder with its own version in the previous editor state. Node keys cannot replace document order in rule 2: each collaborator numbers the nodes it receives in its own order, so with key order every collaborator would keep its own copy and give the other copy a fresh id, and the merged document would lose the id altogether.
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. A replace_block operation is therefore one
line: $getBlockById(id)?.replace(newBlock). That holds on every binding.
Whether a collaborator's concurrent typing in the replaced block survives is up
to the binding: @lexical/y keeps it, @lexical/yjs v2 keeps it when the new
block has the same type, and @lexical/yjs v1 drops it. 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.
The attribute changes exported HTML. Keep BlockIdHTMLExtension out of editors
whose HTML export must be byte-for-byte deterministic (a strict HTML codec,
snapshot comparisons, content hashing), or set export: false there.
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.
- Ids are random and long enough that ids made concurrently by different collaborators do not collide (see Id format).
- 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. Known case:
@lexical/ydeduplicates deterministic initial content, so two clients that initialize the same empty room with the same content get it twice when the extension is on. Seed the document on the server (or let one client bootstrap it), or give the initial blocks fixed ids ($setState(node, blockIdState, 'intro')).
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.