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. 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 agent reads a document as blocks
with ids and answers "replace b7" or "delete b9", and those operations
must find the right block after the document was saved, reloaded or edited
by someone else.
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.
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, every element and decorator child of the root. Nested blocks
are opt-in through $isIdentifiedBlock, which is evaluated when a node is
marked dirty, so it should depend only on the node and its ancestors:
import {$defaultIsIdentifiedBlock, BlockIdExtension} from '@lexical/extension';
import {$isListItemNode} from '@lexical/list';
import {$isTableCellNode} from '@lexical/table';
import {configExtension} from 'lexical';
configExtension(BlockIdExtension, {
$isIdentifiedBlock: node =>
$defaultIsIdentifiedBlock(node) ||
$isListItemNode(node) ||
$isTableCellNode(node),
});
Blocks inside slots get ids when the predicate
identifies them (for example, any non-inline element whose parent has a slot
host, $getSlotHost(parent) !== null). Replacing a slot value with
$setSlot keeps the replaced block's id, like replace.
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, quote or list, and back | The new block keeps the id of the block it replaced |
node.replace(newNode) with a node that has no id | 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 ids (converting paragraphs to a list gives
the items the paragraphs' ids). $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 the id before the update wins over a copy (so a reference never jumps to a copy, even one placed above the original); between blocks that all had it before (copies collaborators made concurrently), the earliest in document order wins; between 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 collaboration 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 the blocks it creates get random ids.
Positional ids are only unique within a document: if you index ids across
documents, key the 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; the others receive it.
- 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, and converge.
- 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 characters of the base64url alphabet (126 random bits, fromcrypto.getRandomValues). It throws wherecrypto.getRandomValuesis missing (React Native without a polyfill), so configure your own there. A replacement must return a non-empty string of at most 128 characters and stay 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, so an app that stores its own ids there can switch by using the exportedblockIdStateinstead of its owncreateState('blockId', ...).
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
.. With the default predicate it is the block's index among the root's children ("0","1", …); with list items identified, the second item of a list at index 3 is"3.1". - 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, every reader must register the same nodes. A node class whose compact JSON changes changes the key of documents that contain it, until the document is first written with its ids.