@lexical/y
Experimental. Every export is @experimental, and @y/y (Yjs 14) is a
release candidate. The document layout carries a version: a client that
meets a newer layout goes read only instead of writing to it. Guide:
Collaboration with Yjs 14.
A collaboration binding for Lexical on Yjs 14
(@y/y). It is a separate package from @lexical/yjs (Yjs 13), which is
unchanged: the two use different Yjs libraries and different document
layouts, and an app uses one or the other.
Install
@y/y is a peer dependency pinned to a release candidate (npm's latest tag
points at an older one):
npm i @lexical/y @y/y@14.0.0-rc.29
The release candidate's own type declarations do not type-check on their own
(an upstream issue): projects that type-check with tsc need
skipLibCheck: true. @lexical/y's own declarations are clean.
Entries
@lexical/y:YBinding(framework independent, no DOM requirement; itseditor,doc,root,status,pinsandundoManagerare read-only getters),YCollabExtension(a Lexical extension: binding plus collaborative undo),describeStorage,LAYOUT_VERSION,DEFAULT_ROOT_NAME('lexical-y'), and the typesYBindingOptions,YBindingStatus,YCollabConfig,YCursor,YWarning,YWarningCode,ClientIDRange,StorageKind.@lexical/y/server:inspectUpdateRoots(the roots an update writes to),LAYOUT_VERSION,DEFAULT_ROOT_NAMEand the typeUpdateRoots. No editor dependencies.@lexical/y/migrateis reserved for a converter from the Yjs 13 layouts.
Usage
import {
buildEditorFromExtensions,
getExtensionDependencyFromEditor,
} from '@lexical/extension';
import {YCollabExtension} from '@lexical/y';
import {configExtension, defineExtension} from 'lexical';
const editor = buildEditorFromExtensions(
defineExtension({
dependencies: [configExtension(YCollabExtension, {doc})],
name: 'app',
}),
);
// After the provider's first sync:
getExtensionDependencyFromEditor(editor, YCollabExtension).output.binding.initialize();
The editor stays read only until the document's layout record has been read
(the extension's status signal: pending, then active or readonly).
initialize() marks an empty layout root with the layout version and writes
the editor's content, with a client id derived from the target shared type
and the exact items written (two clients initializing the same content into
the same root at once write it once; different roots or content never share
an id) and outside the undo history. It refuses when an older layout's root
(root, root-v2) has content: the binding goes read only (warning
'unsupported-layout'), and such a document is converted instead (a binding
with convert: true writes the layout root next to the old one). A document
marked with a newer layout is read only.
The binding owns the formatting cleanup of its own types: it opts its
containers out of Yjs' remote formatting cleanup, which rescans a whole type
after a remote format change (the document's cleanupFormatting flag and the
app's other types are untouched).
In development (and in production with selfCheck: true, optionally sampled
with selfCheckSample), every local write is read back from Yjs and compared
with the editor; mismatches are reported through the binding's onWarn with
the code 'self-check' (never through the editor's onWarn, which throws in
development, inside a Yjs observer). After a remote change, a mismatch also
makes the binding read those containers again. Each
line a write touches is checked; a structural change also compares a fresh
read of the whole container, every time for containers of up to 256 lines and
nodes and sampled in proportion for bigger ones (a 2,000-block root is
checked on about one structural edit in eight), so Enter and Backspace stay
fast in development. YCollabExtension takes the same selfCheck,
selfCheckSample and convert options as YBinding; selfCheck: false
turns the check off. The self-check is off in production unless enabled.
Warnings
onWarn receives {code, message} (default: console.warn of the message
outside production). The codes are stable; new ones may be added:
| Code | Meaning |
|---|---|
'unsupported-layout' | The layout version is missing, newer than this version supports or malformed, or an older layout's root has content. Read only. |
'unknown-node-types' | The document has node types the editor does not register. Read only, so that content is never hidden and then deleted. |
'storage-mismatch' | The document stores a node type in a way this editor's class cannot (another storage kind or group identity). Read only. |
'self-check' | The self-check found the editor and the document different. |
'recovered-read' | A remote change could not be read; the editor was rebuilt from the document. |
'recovered-write' | A local change could not be written; every container was rewritten (a diff, so nothing a peer wrote is lost). |
Servers
-
Clients of the Yjs 13 bindings (
@lexical/yjs) read and writerootorroot-v2, never this root, so they cannot edit this layout (they show an empty document). A server that wants to refuse their writes can check the roots an update writes to withinspectUpdateRoots(update, doc)from@lexical/y/server(pass the server's document so nested items and deletions resolve). -
yrs before 0.28 (y-crdt relays and servers, e.g. on yrs 0.23) reads client ids as 32-bit numbers, while Yjs 14 draws 53-bit ones. Symptoms seen with Yjs 14's default ids:
- with a ywasm 0.23.5 relay, the server stores an author's content under a truncated id, and the author receives its own content back as another client's on reconnect, duplicating it;
- with a yrs 0.23 server, reconnect fails ("the awareness update is malformed") and edits made offline are lost.
yrs/ywasm 0.28 handles 53-bit ids. For an older server, keep client ids in 32 bits: pass
clientIDRange: 'uint32'to the binding (also onYCollabExtension). It also corrects the id when Yjs draws a new one. The default,'uint53', leaves Yjs 14's ids as they are. The ids the binding derives from content (the initial content, repairs) are in the same range: 53-bit hashes under'uint53', 32-bit under'uint32', so every client of a document must use the same range.The binding does not create or own the awareness. An awareness takes the document's client id when it is created, so give the document a 32-bit id before you create it (and the provider), for example
doc.clientID = crypto.getRandomValues(new Uint32Array(1))[0] || 1.clientIDRange: 'uint32'applies when the binding starts, so an awareness created before that keeps the id it had.
Layout
The shared root is doc.get('lexical-y') (a new root name, so a client of an
older layout never edits this content), with attribute lexical-y = layout
version.
Every container (the root, and every node stored as its own Y.Node) holds
one sequence of children:
-
text, with formats: the text node's type (
t, when nottext), one key per format (f:bold), its JSON fields (p:<field>), NodeState (s:<key>), a segment key (k) for nodes Lexical would not merge, and one key per format wrapper (an inline element withmergeAdjacent,w:link, whose value holds the link's fields); -
¶markers: a line (a block withchildren: 'inline') is its inline content followed by its marker, aY.Nodewhose attributes are the line's type (t, left out for a paragraph), schema fields, NodeState, and for an item of a group (a block listing line classes aschildren, withmergeAdjacent: a list) the group's type, its fields and the item's level; groups are told apart by theirmergeAdjacent.byfields. Groups are rebuilt from consecutive items; -
¦run terminators: inline content that belongs to the container itself; -
b:<type>children: any other block (tables, rows, cells, block decorators, undeclared or not schema-complete classes), with the node's JSON as attributes and, for an element, its own sequence and its content kind (c:bblocks oriinline content, from its declaredchildrenor decided when it is created, never changed); -
i:<type>children: any other node inside inline content (inline decorators, inline elements that are not formats, a block inside a line). Withu= 1 such a node is a unit of its container, like ab:<type>child: a block a peer wrote inside a line, lifted out of it in place (the line's content splits around it). -
↷children: move records. Moving units of a container keeps their items where they are and inserts a record where they now show. Its attributes name a range of the same sequence by item id (s: the item before the range, or none for the start;e: the range's last item, inclusive) and a priority (p). Items inserted later inside the range (a peer typing in the moved line, an Enter in it) belong to it too. An item shows with the record of highest priority (then client, then clock) whose range holds it; a record inside its own range, directly or through other records, shows nothing (two peers moving ranges into each other). This is computed when reading, from the document alone, so nothing is repaired. A record shows its units before the line its item is in (text typed next to it concurrently stays in its line). Formats stay positional, as in Yjs: a format item applies to what follows it in the sequence, so a moved range keeps its formats. A container without records costs nothing more to read or write.A record with
j= 1 is inline: it shows its range in its place, inside the line around it. It is written for a join of two lines that live in different ranges (one of them moved): the joined line is the first line's text, an inline record of the second line's range, and the first line's marker; the second line's marker is deleted and its text keeps its items, so a peer typing in it keeps typing in the joined line. Two peers making the same join write two records of one range: one shows it, the other shows nothing. A line can therefore start inside an inline range (an Enter in the second part of a joined line).
The root's layout attribute is 1 for a new document and becomes 2 when the
first move record or lifted block (u) is written: a client that only knows
layout 1 goes read only instead of misreading them.
Storage is derived from general facts node classes declare in $config()
(inline, children, mergeAdjacent, derived), with one fixed rule, first
match wins: a block with children: 'inline' is a line; an inline element
with mergeAdjacent is a format; a block listing classes that are all lines
as children, with mergeAdjacent, is a group (a line holding its own group,
a list item holding a list, is the only nesting); anything else is nested.
The first three also need the class's data to be fully in its schema and
NodeState. describeStorage(editor) returns the result per type. The first
write of a type records its kind (k:<type> on the root): a later client
whose class derives another kind uses the recorded one when it can store the
class that way, and opens read only otherwise. The binding registers the
normalization NodeStructureExtension performs, so every peer writes the
normalized tree the declarations describe (see
What changes when collaboration is on).
Wire format: layout 1
Layout 1 is frozen: these names are stored in documents and do not change. A change to any of them is a new layout version, which older clients open read only. Layout 2 (below) keeps everything here and adds move records and lifted blocks.
- Root: the top-level type
lexical-y(or therootoption). Root attributes:lexical-y= the layout version (an integer,1), andk:<type>= the storage kind recorded for each element type on its first write:line,nested,group|<field>,…orformat|<field>,…(the group's or format's identity fields). - Children of a container (the root and every node stored as its own
Y.Node), in order:- text (
Ystrings) with formats; ¶(U+00B6) nodes: line markers. A line is the inline content before its marker;¦(U+00A6) nodes: run terminators, ending inline content that belongs to the container itself;b:<type>nodes: blocks stored as nodes (a unit of the container);i:<type>nodes: nodes inside inline content.
- text (
- Container attribute:
c='b'(holds blocks) or'i'(holds inline content), fixed when the node is created. - Node and marker attributes:
t= the type (on a marker, left out for a paragraph; on a stored node, only when it was replaced in place by another type),p:<field>= a schema field,s:<key>= a NodeState value,pad=trueon a table cell a repair added to pad a row. - Group items (markers of a group's items, such as list items):
g= the group type,g:<field>= the group's identity fields,l= the level (0 for top level),o= for a nested item, the identity fields of each outer level, outermost first, with@holding the fields of a level's wrapper item. - Text formats:
t= the text node type (left out fortext),f:<format>=trueper text format,p:<field>,s:<key>,k= a segment key that keeps text nodes Lexical would not merge apart, andw:<type>= a format wrapper (an inline element stored as a format, such as a link), whose value is an object of its fields and NodeState, with#telling apart two adjacent wrappers with equal fields. - Values: primitives as they are; any other JSON value as
\u0000followed by its JSON with sorted keys.
Wire format: layout 2
Layout 2 is layout 1 plus the following, and is frozen the same way. A
document is marked 2 (lexical-y = 2 on the root) by the first client
that writes one of them; a client that only reads layout 1 opens it read
only.
-
Move records:
↷(U+21B7) children of a container. Attributes:s: the id[client, clock]of the item right before the range, ornullfor the start of the container;e: the id of the range's last item (inclusive);p: the priority, a non-negative integer;o: optional, the id of the record this one was written again from (it keeps that record's rank among records of equal priority);j: optional,1for a join record (below).
Ids name items of the same container. Ownership is computed when reading, never stored: an item belongs to the record whose range holds it positionally (items inserted later inside a range included) that ranks first: highest
p, then highest client and then clock ofo(the record's own id when it has none), then of the record's own id; otherwise to the container. A record that sits inside its own range, directly or through the records that show it, is inactive (it shows nothing). A record whose ids are not received yet waits for them. A block record (noj) shows its range's units right before the line its item is in. -
Join records: a move record with
j=1shows its range inline, at its own position inside the line around it: a walk of the line enters the range at the record and goes on after the record past the range's last item. A join of two lines in different ranges is written as the first line's text, one join record per piece of the second line (a piece is a run of the line's items in one range, in order), and the first line's marker; the second line's marker is deleted. A line can start or end inside a range a join record shows. A line moved while it spans ranges gets one join record per piece but its last, written at the start of that last piece, and a block record over that last piece. -
Lifted blocks:
u=1on ani:<type>node (see Layout).
Recovery and repairs
- If writing a local change throws, every container is rewritten from the
editor (a diff against the shared content) in a fresh transaction, and the
failure is reported through
onWarn. - If reading a remote change throws, the editor is rebuilt from the shared
content (what every fresh reader shows) and the failure is reported
through
onWarn. When the self-check finds the editor different from the shared content after a remote change, those containers are read again. - Concurrent edits can leave shapes Lexical would normalize: a ragged table (row insert ‖ column insert) and two equal lists side by side inside a list item. Every client that sees one repairs it, so the repair happens whoever is online. A repair is a pure function of the shared content (it never reads the editor), and its client id is derived from a repair version, its inputs described independently of how items are split, and its output encoded on a scratch document: clients with the same inputs write the same items once, and clients with different inputs never share an id. Repairs wait while the editor is composing or has a pending update, and are not part of the undo history. Cells added to pad a row are marked, and an empty padding cell is removed again when its column goes away (an undo of the column insert).
- Content that the normalization would change (a block inside a paragraph,
inline content directly in a table cell, adjacent equal links) can reach a
peer from a client that wrote it without the normalization (an update with
skipTransforms, an older client) or from concurrent edits (text typed into a paragraph a peer removed from a table cell). Every peer normalizes it right after reading it (the author too, right after writing it), one repair per write, and writes each repair under a client id derived from exactly what that repair writes: the binding runs the write on a copy of the document first and hashes the inserted items (content, parent and neighbours by id). Peers that would write the same items use the same id, so Yjs keeps one copy. A block lifted out of the line it was written in keeps its shared node where it is (it is marked a unit of the container,u, layout 2) and the line's parts get markers: nothing is copied, so a peer typing in the block or next to it keeps its text, and peers lifting the same block from different surroundings (one holds an edit next to it that the other has not received) keep the one block. Lexical replacing such a block by a new one of its type (Enter at its start) keeps the shared node too. Merges of adjacent equal lists inside a list item are left to the list repair above. Repairs wait while the editor is composing, and are not part of the undo history. - A line written inside a line (a heading a client wrote inside a list item without the normalization) is stored as the lines the normalization leaves, never as a node of its own inside the line: the holder's inline content is split around it, each part a line with the holder's marker, and the held line follows with its own marker. Readers never see the nested shape, the author's normalization then only changes markers, and a later Enter in the held line, a block put inside it or a type change of it keeps its text's items (a node of its own holds one line only, so each of those would copy its text), so it is never lifted in place as a node. A shadow root that is a line class (a quote that is a shadow root) keeps the lines it holds as nodes.
What changes when collaboration is on
YCollabExtension depends on NodeStructureExtension, so the editor
enforces the structure its node classes declare in $config() (children,
mergeAdjacent, placement). Editors without @lexical/y are not affected.
With it, the shape of some documents changes, on the first update that marks
the nodes dirty and for content that arrives from peers:
- A block inside inline content is lifted out. A paragraph, heading, quote, code block or list item holding a block (a table, a block decorator such as a horizontal rule, a custom block, another paragraph) is split around it, and the block becomes a sibling between the two halves; a block that is the holder's only child replaces it. A heading inside a link becomes a heading holding the link. A paragraph inside a quote or a list item (as a paste can leave) is unwrapped into its own copy of that quote or item, so the formatting stays (one quote per paragraph). A block decorator inside a list item splits the list around it.
- Inline content directly in a block holder is wrapped in a paragraph (text directly in a table cell).
- A list wraps what it may not hold in a list item, as
ListNodealready does. - Adjacent equal siblings merge: two adjacent links with equal URL,
target, rel and title merge into one (
LinkNode#shouldMergeAdjacentLinkdecides), also in editors withoutLinkExtension(a headless markdown import of[a](x)[b](x)gives one link); adjacent autolinks never merge. Two adjacent lists of one type merge, whatever theirstart. - An element that becomes a block inside a paragraph (a class whose
isInline()changes with a field) is lifted out like any block. - Unchanged: shadow roots (table cells, a quote that is a shadow root)
keep their blocks,
OverflowNodestays in its paragraph (it declaresplacement: 'inline'), and classes that declare nothing are left alone. - The repairs only move content, never delete it.
Limits
- A move inside one container (the root, a table, a row, a cell, a collapsible's content, a list) keeps the moved items: a peer's concurrent typing, formatting, retyping, indenting and Enter inside the moved blocks stay with them, and two peers moving the same block show it once. A move to another container (a paragraph into a table cell or a box) is still a delete and a reinsert, with the old limit: text a peer types into the moved block at the same time lands where it was.
- A join of a moved line with the line it now follows (or the reverse) keeps both lines' items (join records, see Layout): two peers making the same join show the text once, and a peer's concurrent typing, Enter or formatting in either part stays in the joined line. This holds when the second line is not one range too (a block moved away from between its parts, or it starts inside a joined range): one join record per piece. A line that spans ranges (split off a joined line, or joined across a moved range) moves with its pieces' items as well. Still copied: a join that also changes other text in the same update, and a join whose record would show inside its own range through other records (joins of joins across moves made concurrently); two peers making that same edit at once both copy the second line's text. Follow-up writes that every peer makes (repairs, list renumbering) never write join records.
- Concurrent moves into the same place keep both, in an order the clients agree on.
- A container deleted by one peer takes what another peer typed into it concurrently (delete wins), as does unwrapping a container (a removal and a reinsertion of its lines). A join ‖ removal of the joined line also joins the next line (nothing deleted comes back).
- A block other than a line held by a line (a table or a box written inside a list item or a paragraph without the normalization) is stored as a node inside the line until the normalization lifts it out: a Backspace or range delete that removes it meanwhile takes what a peer types into it at the same time (delete wins). A line held by a line is stored as lines (see Recovery and repairs).
- Lexical restructures written as moves (a list created from a paragraph inside a container that is not a shadow root, indenting or pasting list items that hold blocks) lose a peer's concurrent typing in the moved paragraph, or show an item twice when two peers indent it at once. Two peers pulling the same text across a container edge both copy it.
- Properties a node class keeps outside its
$config()schema and NodeState are not synced (the binding warns, and stores such classes as nodes). Lexical itself drops them when it clones such a node (its generated clone copies schema fields only), so they cannot be kept in any case. - MarkNode is an element with its own content: wrapping a range moves the text into it, and concurrent typing in that range stays outside. Store comments as NodeState instead (MarkStateExtension).
- Set-valued NodeState (
createState(key, {collab: 'set'}), which MarkStateExtension uses for its mark ids) is stored as one value per text run, not one entry per member: two peers changing the set of the same text at once (two comments added to the same words) keep one writer's set. Every peer converges and nothing throws. Storing one entry per member is planned before the first release that publishes@lexical/y. - A split racing a type change gives the first half the splitter's type; text typed into a line a peer removed joins the next line.
- Slots are not synchronized; a link's fields merge as a whole (last writer wins). Bold ‖ bold on adjacent ranges of one line can leave part unformatted (Yjs format semantics, the same on Yjs 13).
- Editor instances (nested caption editors) are not synchronized; JSON snapshots of them are.
- Undo never deletes a container another client has put content in: it is
kept whole. Undo of a removal restores the text as new items (Yjs
semantics): two peers that both remove the same text and both undo the
removal each restore their own copy, so it shows twice, as with two
Y.Textundo managers (2 of 2,000 sessions of the block id moves fuzz; no move is needed). After two peers' lists inside one list item are merged, undoing either addition keeps the merged list; undoing the addition of the list a peer is merging away does nothing, and a later redo adds it again, so its items show twice. Two clients that repair the same shape from different content (one has an edit in one of the lists the other has not received yet) both apply their repair, so the moved list's items can show twice. A list that ends up right before a line of an equal nested list (a peer deleted the text between them) is shown inside that line's item rather than merged with its list (every client shows the same). - The list merge copies the second list's content into the first and deletes the second, so text anyone types into the second list (its author included) before the merge reaches them is lost.
- A peer's repair can move the line the editor is composing in (IME): the development self-check may warn until the composition ends (it then converges), and composed text in the moved line follows the move ‖ typing limit above.
- Repair detection walks every container a remote change touched (linear; about 27 ms at 320,000 items in one container, some 8% of receiving a keystroke).
- Two clients initializing with different content at once both keep their content (converged). "The same content" means the same JSON, NodeState included: an extension that gives every new block a random id (block ids) makes two clients' initial content differ, so two clients initializing an empty room at once both write it and it shows twice. Seed new documents in one place (on the server) or give the initial blocks fixed ids. (An initial-content gate, writing nothing until the first real edit as y-prosemirror does, would not remove this case: two clients that both edit before they sync still write both contents.)
- Several edits to one line in a single update are written as one replace (a peer's caret inside it moves to the edge).
- Receiving a move, its undo or redo, or a structural edit (Enter, a join, a deletion across lines) in a container that holds move records reads only the moved range and the lines next to the records whose ownership changed (about 0.1 s end to end per move at 10,000 blocks with 100 earlier moves, a third more than a move written as a delete and a re-insert, which loses concurrent typing; Enter and Backspace there cost as much as a move). A format change there (bold, a link), a change in a container that holds an inline record (a join across moved ranges), and records that name items not received yet still read the whole container on the receiving side, which grows with the container and its records.
- Structural edits in a large list cost time proportional to the list on both sides (regrouping and renumbering).
- The layout version must be an integer from 1 to
LAYOUT_VERSION; anything else is read only. - With Yjs 14's default 53-bit client ids, servers on yrs before 0.28 duplicate content or lose offline edits on reconnect (see Servers).
- A node whose
isInline()changes (a class may compute it from a field) is written again in its new form: text a peer types inside it at the same time lands next to it, as with a move. As a block inside a paragraph it is then lifted out (see What changes when collaboration is on). - A node's NodeState keys keep the order of its author's local history in the author's editor (values are equal everywhere).
- Relies on @y/y internals (item and type fields), pinned to the tested release candidate.