Yjs 14 (@lexical/y)
@lexical/y is experimental: every export is marked @experimental, and
@y/y (Yjs 14) is itself a release candidate. Pin both versions. The
document layout carries a version, so a client that meets a newer layout
opens the document read only instead of misreading it.
@lexical/y is a collaboration binding for Lexical on Yjs 14 (the @y/y
package). It is separate from @lexical/yjs, the Yjs 13 binding that the
React guide uses: the two use different Yjs libraries and
different document layouts, and a document uses one or the other.
When to use it
Use @lexical/y for a new collaborative editor that can run Yjs 14 on
every client and on its server:
- Concurrent edits keep each other's text. A paragraph, heading or list item is stored as its characters followed by a marker, and a link as a format over the characters it wraps. Splitting or joining a paragraph, changing its type, indenting a list item, or linking text keeps the characters, so what a collaborator types at the same time is not lost.
- Smaller documents. Enter, Backspace, heading and list changes write only a marker or its attributes.
- No React or DOM requirement. The binding is a Lexical extension, so it works with any framework and in a headless editor.
Stay on @lexical/yjs when you have documents stored in its layouts (see
Moving from @lexical/yjs), when your server or
other clients cannot move to Yjs 14, or when you need the
LexicalCollaborationPlugin React API.
Install
npm i @lexical/y @lexical/extension lexical @y/y@14.0.0-rc.29
@y/y is a peer dependency pinned to the release candidate @lexical/y is
tested with; npm's latest tag points at an older one, so name the version.
The type declarations @y/y ships do not type-check on their own (an
upstream issue): if you run tsc, set skipLibCheck: true.
Set up an editor
YCollabExtension connects an editor to a Yjs document. It also provides
collaborative undo (UNDO_COMMAND and REDO_COMMAND undo only this
client's changes), so leave out HistoryExtension: the two conflict. Any
Yjs 14 provider can carry the document; this example uses @y/websocket.
import {
buildEditorFromExtensions,
getExtensionDependencyFromEditor,
} from '@lexical/extension';
import {ListExtension} from '@lexical/list';
import {RichTextExtension} from '@lexical/rich-text';
import {YCollabExtension} from '@lexical/y';
import {WebsocketProvider} from '@y/websocket';
import * as Y from '@y/y';
import {configExtension, defineExtension} from 'lexical';
const doc = new Y.Doc();
const editor = buildEditorFromExtensions(
defineExtension({
dependencies: [
RichTextExtension,
ListExtension,
configExtension(YCollabExtension, {doc}),
],
name: 'my-app/editor',
}),
);
editor.setRootElement(document.getElementById('editor'));
const {binding, status} = getExtensionDependencyFromEditor(
editor,
YCollabExtension,
).output;
const provider = new WebsocketProvider('wss://example.com', 'my-room', doc);
provider.once('sync', () => {
// Writes the editor's content if the document is new; otherwise the
// editor shows the shared content.
binding.initialize();
});
- The editor stays read only until the document's layout record has
been read.
statusis a signal:'pending', then'active', or'readonly'when the binding cannot write the document safely (a newer layout, a node type this editor does not register; a warning says why). Register the same node classes on every client. binding.initialize(), called after the provider's first sync, writes the editor's content into an empty document (aneditor.update()still pending is part of it). Two clients that initialize the same content in a new document at once write it once. It does nothing on a document that already has content, and it refuses a document whose@lexical/yjsroots hold content.- Pass
synced: trueinstead when the document is already loaded (a test, an editor bound to a stored state): the extension initializes as soon as it registers. - While the binding writes, an
editor.update()that changes content commits at once, as withdiscrete: true, instead of in a microtask: a remote change the provider applies in the same task then never finds a local update waiting to be written. A single update costs the same as before, but several updates made in one task are no longer batched into one commit: each is reconciled, written and sent on its own. In a 10,000-block document (headless, a peer's read included), one keystroke took about 60 ms either way, and a task of 10 updates took 590 ms instead of 78 ms. Make related changes in oneeditor.update(). - To seed or convert a document on a server, use
seedYState(see Server-side editing).
| Option | Default | |
|---|---|---|
doc | (required) | The Yjs document. |
root | doc.get('lexical-y') | The shared root to bind. |
synced | false | Initialize as soon as the extension registers. |
captureTimeout | 500 | Undo capture timeout in ms; null turns collaborative undo off. |
clientIDRange | 'uint53' | 'uint32' for servers on yrs before 0.28, see Servers. |
selfCheck | false | Reads every local write (and every container a remote change rebuilt) back from Yjs and compares it with the editor; a mismatch is a '@lexical/y/self-check' warning. A debugging aid: turn it on in tests and development builds. |
selfCheckSample | 1 | The fraction of changes the self-check samples: local writes, and remote changes (where a sampled check that finds the editor differing from the shared content also reads those containers again). |
convert | false | Initialize even when a @lexical/yjs root has content. |
Only a client's own edits are written. Some updates follow a commit on
every client that has it, and are no one's edit: the binding's refresh of
list numbering, the update that names the blocks a remote change brings
(with BlockIdExtension), and the update
Lexical makes when a transform is registered while a document is open (it
runs the transform over the whole document, as a plugin that mounts once the
editor is editable does). Such an update may set attributes or delete;
anything else it changes is not written, and the binding reads that content
again, so the editor keeps showing what is stored (a development warning
names the change). Every client's editor shows the document: the binding
reads remote changes without running transforms, and a transform never
rewrites what a client read.
YCollabExtension configures BlockIdExtension with
repairTransforms: false, so that its naming update sets ids and nothing
else. With true (the extension's default, which an editor that uses
YBinding directly gets unless it sets the option), the naming update would
also run transforms over what a remote change brought, and what they derive
(the start of a list they split) can disagree between clients, which would
then show different content. So the binding fails closed: when it finds
repairTransforms: true, it writes nothing, is read only and warns
(@lexical/y/unsupported-config). Set it to false there too. An update
another listener queues in the same listener phase as the naming update is
committed with it and counts as part of it: what it inserts is not written,
and the editor reads it back as stored.
A line that concurrent edits leave without its marker (text typed into a paragraph a collaborator removed) has no stored id: every client derives the same one from the document (the Yjs id of its first character), and the edit that next changes the line stores it.
Without the extension API, new YBinding(editor, doc, options) does the
same: call binding.start() to connect it, binding.initialize() after the
first sync, and binding.undo() / binding.redo() for undo. An undo puts
back the selection from before the step it undoes (as HistoryExtension
does), and a redo the one from when it was undone. Called while the editor
is updating (from a command handler, an update or its $onUpdate), it runs
right after that update commits, in an update of its own.
binding.getCursor() and binding.$resolveCursor() convert the selection
to and from Yjs relative positions for an awareness-based cursor UI; the
binding does not render remote cursors itself.
Warnings
The binding reports to the editor's onWarn (set it on your root
extension, see Errors and warnings).
Each warning is a LexicalWarning with a stable code, a message for
people and data for programs. The codes are exported as constants from
@lexical/y, and their union as the YWarningCode type:
code | Constant | Reported when | data |
|---|---|---|---|
'@lexical/y/unsupported-layout' | UNSUPPORTED_LAYOUT_WARNING | The document's layout version is newer than this version, missing or malformed, or a @lexical/yjs root has content. The binding is read only. | {layout, legacyRoots} |
'@lexical/y/unknown-node-types' | UNKNOWN_NODE_TYPES_WARNING | The document has node types the editor does not register. The binding is read only. | {types} |
'@lexical/y/storage-mismatch' | STORAGE_MISMATCH_WARNING | The document stores a node type in a way this editor's class cannot. The binding is read only. | {types} |
'@lexical/y/self-check' | SELF_CHECK_WARNING | The self-check (selfCheck) found the editor and the document disagree. | {problems, remote} |
'@lexical/y/recovered-read' | RECOVERED_READ_WARNING | A remote change could not be read; the editor was rebuilt from the document. | {error} |
'@lexical/y/recovered-write' | RECOVERED_WRITE_WARNING | A local change could not be written; the document was rewritten. | {error} |
'@lexical/y/nested-fallback' | NESTED_FALLBACK_WARNING | A class declares a line, format or group, but something it does prevents that (see How content is stored); it is stored as a node of its own. Once per binding, class and reason. | {type} |
'@lexical/y/unsynced-value' | UNSYNCED_VALUE_WARNING | A property or NodeState value is not plain JSON, so it is not synchronized. Once per binding and property. | {property} |
'@lexical/y/unsupported-config' | UNSUPPORTED_CONFIG_WARNING | The editor is configured in a way the binding cannot write safely: BlockIdExtension with repairTransforms: true (see Set up an editor). Nothing is written, and the binding is read only. | {options} |
'@lexical/y/unsupported-slots' | UNSUPPORTED_SLOTS_WARNING | A node holds named slots where the document cannot store them (a slot set on a paragraph, a link, a list or the root). The change is not written, and the binding is read only. | {types} |
import {LexicalWarning} from 'lexical';
defineExtension({
// ...
onWarn(error) {
if (error instanceof LexicalWarning) {
reportWarning(error.code, error.message, error.data);
} else {
console.warn(error);
}
},
});
- Warnings arrive once a change has been applied in full: never from inside a Yjs observer or transaction. A handler that throws does not affect syncing; its error is rethrown in a microtask.
- Without a handler, Lexical's default
onWarnapplies: it throws in development (each warning shows up as an uncaught error) and callsconsole.warnin production. - Codes are never renamed or reused; new ones may be added, so a
switchover them needs adefault.
How content is stored
@lexical/y does not copy the Lexical tree node for node. Each container
(the root, a table cell, a collapsible's content) is one Yjs sequence of
characters, ¶ markers and nested nodes. Splitting a paragraph, changing its
type or linking a word then only writes a marker or an attribute, and the
characters a collaborator is typing into stay where they are. Three rules
decide how a node is stored.
1. A block that holds text is its text followed by a ¶ marker. The
marker carries the block's type, fields and NodeState; text formats are
attributes of the characters.
The heading and the paragraph above, as one sequence.
2. Lists and links have no node of their own. A list is rebuilt from its items, whose markers carry the list's type and the item's level, and a link is an attribute over the characters it wraps.
A nested list: the second item's marker says level 1.
A link: the characters carry its URL.
3. Everything else is a node of its own, with its fields as attributes: tables, rows and cells, decorators, custom containers. An element holds its own sequence.
A table: the table, its rows and its cells are nodes of their own, and each cell holds a sequence.
Named slots go with the node that holds them. A block decorator or
custom container that holds content in named slots
($setSlot, as a callout's body or a figure's caption) keeps each slot on
its own node, under the slot's name. The slot's node is a node of its own
too, holding its content as a sequence (a slot that holds one paragraph holds
its text), so collaborators typing in one slot merge as in any container.
A callout with two slots: its body holds a paragraph, its title one line.
Only a node of its own can hold slots: a slot set on a paragraph, heading or
list item (stored as a marker), a link (a format) or a list (rebuilt from its
items) cannot be stored, so the binding writes nothing of that change, warns
(@lexical/y/unsupported-slots) and goes read only rather than drop it. A
class that declares slots in $config() is always stored as a node of its
own.
Moving blocks within a container keeps their characters where they are and adds a move record that shows them in their new place, so what a collaborator types in them at the same time moves with them (see Wire format).
Custom nodes follow the same rules, from the
node structure their class declares: a
block that declares children: 'inline' is stored like a paragraph, an
inline element that declares inline: true and mergeAdjacent like a link,
and anything else as a node of its own. Properties a class keeps outside its
$config schema and NodeState are not synchronized (the binding warns).
describeStorage(editor) lists how each node type is stored. The first write
of a type records its kind, so a later client whose class declares something
else keeps the recorded kind or opens read only.
Wire format
The diagrams below use the stored names. The package README specifies them exactly: layout 1 and layout 2.
Layout 1. A container's sequence holds characters, ¶ markers and
nodes of their own. A marker holds the line's type in t (left out for a
paragraph), its fields as p:<field> and its NodeState as s:<key>. Text
formats are ranges over the characters: f:<format> for a text format, and
w:<type> for an inline element stored as a format, such as a link. A node
of its own is a b:<type> child that holds its own sequence (c: b when it
holds blocks), and each of its named slots as an attribute slot:<name>
whose value is the slot's b:<type> node. The root also records the layout
versions the document needs
(lexical-y:1, a record that only grows) and, per type, the storage kind its
first write chose (k:<type>).
A heading, a paragraph with a link, a bold word and a NodeState value, and
a custom container (callout) that holds a paragraph, in layout 1.
Layout 2 adds move records. A record ↷ sits where its range shows: s
is the item right before the range, e the range's last item and p its
priority (the highest wins). Items typed into the range later belong to it.
"Three" moved to the top of a layout 2 document (lexical-y:2: true): its
characters stay last in the stored order, and the record (dashed) shows them
first in the editor.
A join record (j: 1) shows its range inline, at its own position. Joining
"One" into the moved "Three" (Backspace) deletes One's marker and writes a
join record at the end of "Three", so neither line's characters are copied.
The join record (dashed) shows "One" after "Three", in one line.
Upgrade. A document starts at layout 1 and is upgraded in place, lazily, by the first client that writes a move. Nothing else is rewritten. Documents that never see a move stay at layout 1, and older clients keep editing them.
The record never shrinks. A block lifted out of a paragraph upgrades the document too.
What changes when you turn on collaboration
Because a paragraph, heading or list item is stored as text followed by a
marker, it can only hold inline content: text, line breaks, links and inline
decorators. Stock Lexical does not stop a block from ending up inside one, so
YCollabExtension adds
NodeStructureExtension, which
rewrites such shapes into ones the binding can store. The client whose edit
makes such a shape rewrites it in that edit (or, for an update that ran
without transforms, right after it), and the rewrite only moves content:
nothing is deleted. In the diagrams below, a box holds the boxes under it.
A block inside a paragraph is split around, so the block keeps its type. The same holds for a heading, code block, nested quote or table inside a quote or list item.
A heading inside a link becomes a heading holding the link.
Paragraphs inside a quote become lines of one quote, joined by line
breaks, as HTML's <li><p>a</p><p>b</p></li> already imports. Paragraphs
inside a list item become lines of the item the same way.
A block decorator inside a list item splits the list, as inserting a horizontal rule into a list item does. In a numbered list, the numbering continues: the second list starts where the first one stopped (an item that held only the rule goes, and the next item takes its number).
Adjacent equal links merge (same URL, target, rel and title), and so do adjacent lists of the same type. Inline content directly in the root or in a table cell (text, a link, a mark) is wrapped in a paragraph.
What this means for your app:
- Where these shapes come from: pasted or imported HTML, documents saved by an editor without the extension, app code that inserts a block into a paragraph, and concurrent edits. The client whose edit makes such a shape rewrites it in that edit (or, for an update without transforms, right after it). Shapes left by concurrent edits are shown as stored until a local edit touches them (see Limits).
- Only editors with the extension are affected. Editors without
@lexical/y(orNodeStructureExtension) keep these shapes. Shadow roots,OverflowNodeand classes that declare nothing are never rewritten. - Some content looks different afterwards. A quote or list item that held paragraphs shows them as lines of one quote or item, a heading or code block inside a quote is moved out of it, and a list around a horizontal rule becomes two lists, the second numbered on from the first.
- To keep blocks inside a container, make it hold blocks. Declare
children: 'block'on a custom container (a callout that holds paragraphs; stray text in it is then wrapped in a paragraph), or use a shadow-root quote,$createQuoteNode({shadowRoot: true}), which holds paragraphs and is left alone.
Edits made by code (agents, tools)
Code that edits a document on someone's behalf (an agent, an import, a formatter) merges with collaborators best when its edits look like a person's:
- Edit text in place (insert and delete characters in a text node) rather than replacing blocks or whole documents. A replaced block is a delete and an insert, so what collaborators type into it at the same time is lost (see Limits). When a line is mostly rewritten (an agent's rewrite, a paste over several words), the binding replaces whole words: what a collaborator types inside the replaced words at the same time lands in one piece at the start of the new text, never inside a word. Typing, deleting and one-word replacements are still written character by character.
- Apply an edit to the state it was computed from, then merge. An edit
planned from an older read (a model's answer arrives seconds later) can
land in the wrong place if it is applied to the current state. Load that
read's update into a new
Y.Doc, bind a headless editor to it withYBinding, apply the edit there, and apply the update it produced (Y.encodeStateAsUpdate(copy, readStateVector)) to the live document: Yjs merges it with what changed since. The copy's writes go into the live document, so give itsYBindingthe sameclientIDRangeas the other clients (see Servers).
On a server, editYState from @lexical/y/headless does the second step:
run it on the state the edit was computed from and merge the update it
returns into the live document (see
Edits by agents and tools).
Servers
Any Yjs 14 server or relay can host the documents. Clients of
@lexical/yjs write to other roots (root, root-v2), never to
DEFAULT_ROOT_NAME ('lexical-y'), so they cannot change a @lexical/y
document's content and the server needs no check to keep them out.
To seed, edit or read documents on the server, see
Server-side editing.
Servers built on yrs before 0.28 (y-crdt) read client ids as 32-bit
numbers, while Yjs 14 draws 53-bit ones: an author can receive its own
content back as another client's on reconnect (duplicating it), or lose
offline edits. For such a server, pass clientIDRange: 'uint32' on every
client of the document and in the server's @lexical/y/headless config. Give the document a 32-bit client id
before you create the awareness and the provider, because an awareness takes
the document's client id when it is created:
doc.clientID = crypto.getRandomValues(new Uint32Array(1))[0] || 1;
Use yrs 0.26 or later. yrs 0.23.4 through 0.25.0 can drop part of a reconnecting client's delete set when a deleted range starts on a block the server has already garbage collected: the server keeps content that client deleted while its changes did not reach the server (offline, a dropped connection, a reload from local storage), and that client then differs from everyone else for good, with no warning. 32-bit client ids do not prevent it; yrs 0.26.0 fixed it. Before 0.28, the 32-bit client ids above are still needed.
Limits
Every client converges to the same document, but some concurrent edits do not merge as a user might expect:
- Moves. Moving blocks within one container (dragging a paragraph,
moving a list item, reordering table rows) keeps their content: what a
collaborator types in them at the same time stays with them, and two
collaborators moving the same block show it once. Moving a block into
another container (into a table cell or a collapsible) is a delete and a
re-insert: text typed into it at the same time lands at its old position,
or is lost when that position is gone (a collaborator removed or moved the
container it was in), and two collaborators moving the same block show it
twice when either moves it into another container. Lexical operations that
put a block inside a list item (turning a paragraph into a list inside a
container, indenting list items that hold blocks) behave the same way. The
first move in a document (or the first block lifted out of a
paragraph) records layout version 2 in it, which clients of an older
@lexical/yopen read only. - Joins. Joining a moved line with the line it now follows keeps both lines' content, but a join combined with other edits in the same update is a copy, so a collaborator's concurrent edits there can show twice.
- Delete wins. Text typed into a container that a collaborator deletes at the same time is deleted with it, and so is a block moved into it.
- Last writer wins for the fields of one link (URL and target change together) and for a field of one paragraph or list item.
- Mark nodes.
MarkNodeis an element with its own content, so wrapping a range moves the text into it, and concurrent typing in that range stays outside. Store comments as NodeState instead, withMarkStateExtension. - Set-valued NodeState (
arraySetValue, whichMarkStateExtensionuses) merges per member on text, line breaks and nodes stored as their own Yjs node (such as decorators), so two collaborators commenting on the same words both keep their comment. On a line such as a paragraph or heading, a list item, a list or a link the set is one value, and concurrent changes to it keep one writer's set. The state needs no registration: a client that has not used it yet holds the members as one unknown value, which its first$getStatereads, and writes them back one per member. Do not name another state with a set's key followed by U+001F ('tags\u001fx'next to a set'tags'): that is the name the binding stores the set's memberxunder, so it refuses such a state, even one without a value, whenever it writes it or the set. - Named slots. A slot holds one node: two collaborators setting the same slot at once keep one writer's node, and text typed in a slot that a collaborator replaces or removes at the same time is lost (as with delete wins). Moving a block rewrites its slots with it (see Moves). Slots on a node stored as a line, a format or a group, or on the root, are not stored (see Warnings).
- Not synchronized: nested editor instances (their JSON snapshots are),
and properties outside a class's
$configschema and NodeState. - Shapes concurrent edits leave are shown as stored. No client repairs
them; the next local edit that touches one changes it, as that client's
own edit.
- A table whose rows end up with different lengths (a row insert ‖ a column insert: the new row lacks the new column) stays so until the next table command, which pads it. Two clients running a table command on it at once both pad it, and the table gets an extra empty column.
- A list item that holds its nested list next to other content (text, a
second list) stays so until the next local edit there. Lexical's
commands, its paste and
NodeStructureExtension, which every@lexical/yeditor runs, give a nested list an item of its own; only writers without that normalization store this shape.
- Content written without Lexical's normalization (an update with
skipTransforms, orsetEditorStatewith a state the editor did not build) is normalized by its author right after, as part of the same edit; other clients show it as written until that arrives, and an author that goes offline in between leaves it so until someone edits there. A Lexical command used on such a shape before the normalization arrives can fail (Shift+Enter in a list item that holds only a block decorator throws). - A line without a marker. Text typed into the last block of a container while a collaborator removes that block is kept, as a line without its marker (shown as a paragraph). Other edits in that container leave it so; two clients that type into it at once each give it a marker, which splits it in two (one part can be empty).
- List type change ‖ new item. Changing a list's type while a collaborator adds an item to it (Enter in the list) splits the list: the new item keeps the old type, in a list of its own between the two halves.
- Blocks that arrive without an id. With
BlockIdExtension, a block that reaches clients without an id (written by a client without the extension) is named by each client from the document it has. Clients that hold different concurrent edits give it different ids, which converge on one. - Initial content with random values. Clients that initialize a new
document at once write it once only when their content is identical. An
extension that gives new blocks random ids makes it differ, so the content
shows twice; so does initializing a root that held content before. Seed
new documents on the server with
seedYState, or give the initial blocks fixed ids. - Undo keeps a container whole once another client has put content in it. Undoing a removal restores the text as new content: a block a collaborator moved out of the removed range into another container at the same time shows twice (the original next to the moved copy), and when two collaborators remove the same text and both undo, it shows twice.
- Large lists and moves. A structural edit in a list costs time proportional to the list on every client, and a format change in a container that holds moved blocks is read in full by the receiving clients.
- Records over time. Each move leaves a small tombstone (about 18 bytes
once Yjs collects garbage), as any Yjs delete does; a delete and a
re-insert leaves about the same. Live move records stay at most one per
moved range, apart from rare cases tracked in
#9455: a block moved
back to where it was, a record that lost a loop between two concurrent
moves, and a record whose range a collaborator deleted, until the next
local edit of that container. Deleted items an undo manager can restore
are not collected until its stacks are cleared. For long-lived rooms, have the
server reload the document from time to time, as Yjs recommends:
Y.applyUpdate(new Y.Doc(), Y.encodeStateAsUpdate(doc)).Y.mergeUpdatesdoes not collect garbage. - NodeState key order. Other clients (and any later reader) get a node's NodeState with its keys in sorted order, which every client builds the same way, not in the order the author's editor exported them (a Yjs map does not keep one). Compare node JSON without relying on key order.
- Other races. A split racing a change of the line's type gives the
first half the splitter's type. Bold ‖ bold on adjacent ranges of one line
can leave part unformatted. A node whose
isInline()changes is written again in its new form, so text typed inside it at the same time lands next to it.
Changing the layout and migrating
The wire format
in the package README is the contract for what a room stores: the markers,
attributes and records, and their names. Every room records the layout
versions it needs (lexical-y:<n>: true, a record that only grows;
LAYOUT_VERSION is currently 2), and a client reads the highest.
- Changes that keep the layout: additions older clients can ignore, such as a new optional attribute. Rooms keep working in old and new clients.
- Changes that bump
LAYOUT_VERSION: anything older clients would misread. A newer@lexical/yreads every older layout and adds the new version to a room's record only when it first writes something that needs it, in the same transaction; from then on, older clients open that room read only. Moves are such a change: the first move in a room records layout 2. Upgrade every client of a room together. - Changing your own node types: fields are stored by name, so adding a field with a default, or dropping one, works as in Lexical JSON: a field a room does not have reads as its default, and one your class no longer has is ignored. A change to a class's declared node structure does not apply to rooms that already hold that type (they keep the recorded kind); reseed them to adopt it.
Reseeding a room
No converter ships today. To move a room's content into a new layout, or out
of @lexical/yjs, write it into a new room with seedYState:
-
Get the content as Lexical JSON. If your database holds it, use that. If you store only Yjs, read it with the binding that wrote it:
readYStatefor an@lexical/yroom, or an editor with@lexical/yjsfor a@lexical/yjsroom, theneditor.getEditorState().toJSON(). -
Seed the new room with the same extensions as the clients:
import {readYState, seedYState} from '@lexical/y/headless';import {$getEditor, $getRoot, $parseSerializedNode} from 'lexical';const config = {extensions: [AppNodesExtension]};// 1. The content as Lexical JSON (here read from an @lexical/y room).const json = readYState(oldState, config, () =>$getEditor().getEditorState().toJSON(),);// 2. A new room holding it.const seed = seedYState(config, () => {for (const child of json.root.children) {$getRoot().append($parseSerializedNode(child));}}); -
Switch clients to the new room. Store
seedunder a new room name, point upgraded clients at it, and retire the old room. A client that still holds the old room (an open tab, an offline cache) must drop it: merging the old room into the new one would mix the two.
Moving from @lexical/yjs
@lexical/y writes a different root, and initialize() refuses a document
whose @lexical/yjs roots hold content, so an old document is never shown
as empty or overwritten. Keep existing documents on @lexical/yjs and start
new ones on @lexical/y, or reseed them as above. Because the seed holds
only the @lexical/y root, a @lexical/yjs document can also keep its name:
merge the seed into the stored document next to the old roots (see
Converting a @lexical/yjs document).
Either way, upgrade every client of the document at once: edits old clients
make stay in the old root.