Repository navigation
[lexical-extension][lexical-html][lexical-yjs][lexical-website][lexical-devtools] Feature: Stable block ids (BlockIdExtension) - #9421
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
lexical
@lexical/a11y
@lexical/clipboard
@lexical/code
@lexical/code-core
@lexical/code-prism
@lexical/code-shiki
@lexical/compiler
@lexical/devtools-core
@lexical/dragon
@lexical/eslint-plugin
@lexical/extension
@lexical/fast-check
@lexical/file
@lexical/hashtag
@lexical/headless
@lexical/history
@lexical/html
@lexical/internal
@lexical/link
@lexical/list
@lexical/mark
@lexical/markdown
@lexical/mdast
@lexical/offset
@lexical/overflow
@lexical/plain-text
@lexical/react
@lexical/rich-text
@lexical/selection
@lexical/table
@lexical/tailwind
@lexical/text
@lexical/utils
@lexical/yjs
commit: |
|
I haven't looked at it recently but there is another open PR that addresses this type of feature (scoped to an example) #9174 |
| let runtimes: undefined | WeakMap<LexicalEditor, BlockIdRuntime>; | ||
|
|
||
| /** Per-editor state, created lazily so that the module has no side effects. */ | ||
| function getRuntimes(): WeakMap<LexicalEditor, BlockIdRuntime> { | ||
| if (runtimes === undefined) { | ||
| runtimes = new WeakMap(); | ||
| } | ||
| return runtimes; | ||
| } | ||
|
|
There was a problem hiding this comment.
I don't think we should make a habit out of this, we already have the extension registered and can store any data with it. If we are adamant about making it hard to acquire a reference to it from the output type there are plenty of ways to do that (e.g. a symbol).
There was a problem hiding this comment.
Agreed, removed. The per-editor state (config and index) is now the extension's init result: build and register get it from state.getInitResult(), the same way HistoryExtension keeps its signals. The output still only exposes disabled, $getBlockById and $isIdentifiedBlock, and the module has no state of its own.
| /** | ||
| * Makes a new id. It must return a non-empty string of at most 128 | ||
| * characters. Collisions with ids in use are retried, so it does not need | ||
| * to be globally unique; tests can inject a deterministic counter. | ||
| * Default: {@link generateBlockId}. | ||
| */ | ||
| generateId: () => string; |
There was a problem hiding this comment.
In the context of collab, shortened ids without some kind of prefix identifying the peer seems risky
There was a problem hiding this comment.
Agreed, 48 bits was too short. I went with longer random ids: generateBlockId now makes 21 URL-safe characters: 126 random bits, more than a v4 UUID's 122.
I also considered a per-editor random prefix plus a counter, and decided against it as the default:
- Outside a collab session there's no peer identity to use (a server editing stored JSON has none), so the prefix itself has to be random. To stay unique across every session that ever edits a document, it needs roughly 72 bits. That makes ids 13–15 characters instead of 21, so it saves about 6 characters per block.
- It makes ids sequential. If an agent mistypes
…-17as…-18, it silently edits a different block. A mistyped random id matches no block, so the edit fails visibly. Since we show these ids to models (data-block-id), I think that matters more than 6 characters. - With 126 bits, a document with a million blocks has less than a 10⁻²⁶ chance of containing two equal ids. Local collisions are still retried.
generateId stays configurable. The docs ("Id format") say that a replacement must stay unique across peers, for example with a per-peer prefix. The format test checks the length and that all 64 symbols get used.
There was a problem hiding this comment.
I never suggested a counter, just a peer identifier prefix if the IDs themselves are going to be short
There was a problem hiding this comment.
You're right, sorry, I misread that as a counter. With the ids now 21 random characters (126 bits) rather than short, a peer prefix shouldn't be needed for collision safety, so I left it out to keep ids opaque for agents. Happy to add a peer prefix if you'd still prefer one.
| function $isLiveIdentified( | ||
| runtime: BlockIdRuntime, | ||
| node: null | LexicalNode, | ||
| ): node is LexicalNode { |
There was a problem hiding this comment.
This needs to use a brand otherwise typescript will imply !$isLiveIdentified(runtime, node) ⇒ !(node is LexicalNode)
There was a problem hiding this comment.
Fixed. It now narrows to a branded LiveIdentifiedBlock (LexicalNode & {readonly [LiveIdentifiedBlockBrand]: never}, where LiveIdentifiedBlockBrand is a declare const … unique symbol, so nothing is emitted). A false result now leaves null | LexicalNode as it is.
| while (stack.length > 0 && position.size < wanted.size) { | ||
| const node = stack.pop()!; | ||
| if (wanted.has(node.getKey())) { | ||
| position.set(node.getKey(), position.size); | ||
| } | ||
| if ($isElementNode(node)) { | ||
| const children = node.getChildren(); | ||
| for (let i = children.length - 1; i >= 0; i--) { | ||
| stack.push(children[i]); | ||
| } | ||
| } |
There was a problem hiding this comment.
This traversal ignores slots
There was a problem hiding this comment.
Fixed, and it went further than that walk. Every traversal now visits slot values as well as children:
- the index rebuild after
setEditorStateor undo; - removals: removing a host takes the blocks in its slots out of the index;
- the lookup while disabled;
- the document-order tie-break.
isBefore and getParent stop at a slot boundary, so the old pairwise comparison also mis-ordered nodes in different slot frames. Document order is now a slot-aware common-ancestor comparison: a host's slots come first, in their canonical order, then its children, which is the order $dfsWithSlots uses. Replacing a slot value with $setSlot in one update also keeps the id, the same as replace.
Blocks inside slots get ids wherever $isIdentifiedBlock opts in, and the docs have a recipe. The new BlockIdExtension.slots.test.ts has 10 tests: assignment, duplicates, committed duplicates between a slot and its host's children and between two slots (created in either order), $setSlot, $setBlocksType inside a slot, the index after undo and after setEditorState, host removal, and the lookup while disabled. On the previous revision, 5 of them fail: both committed-duplicate tests, the $setSlot replacement, the index after undo, and the disabled lookup.
| return result; | ||
| } | ||
|
|
||
| /** Sort nodes of the active state into document order. */ |
There was a problem hiding this comment.
It might be better to use Number(node.__key) order (which happens to be a strictly increasing counter), it's an implementation detail but I think it will probably work better and be a lot cheaper to compute correctly.
There was a problem hiding this comment.
Thanks, this was worth taking apart. I now use key order wherever it's safe, and document order only where it has to be peer-independent:
-
All holders got the id in this local update (several copies pasted or imported together): the lowest key keeps it. Only this editor makes that decision, and the others receive the result, so a runtime-local order is fine. Fresh ids are also assigned in key order now. They used to be sorted by document order, and that turned out to be the expensive part.
-
Several holders already had the id committed: this is a duplicate from merging concurrent edits, and every peer that sees it repairs it in a follow-up update. Here the order has to be the same on every peer, and keys aren't. Each peer creates the nodes it receives in its own order, so each peer has the smaller key on its own copy. With key order, each peer keeps its own copy and re-ids the other one, and once those writes merge, neither block has the original id.
I checked this by substituting key order in that branch.
BlockIdCollab.test.ts › concurrent moves of one block (a duplicate after merge) are repaired oncefails on v1 withexpected [] to have a length of 1(no block carriesa1any more). A new unit test that commits the same duplicate with its nodes created in either order also fails.
On cost: document order as previously implemented was expensive only on the >32-node walk path, which was used by the fresh-id sort. Median µs on a 10,000-block root:
scenario old sort new doc-order min key sort
2 holders at 1/3 and 2/3 509.4 444.4 0.8
2 holders at 10 and 9990 3.3 2.0 0.7
2 adjacent holders at 5000 2.0 1.1 0.7
20 adjacent at 5000 25.5 16.2 5.9
33 adjacent at 5000 (walk path) 2211.9 26.4 9.6
50 adjacent at 9900 (walk path) 3239.3 35.2 14.3
50 adjacent at 100 (walk path) 902.6 40.1 14.3
The new document-order comparison is essentially a slot-aware isBefore: it finds the common ancestor, then walks siblings from both branches. It costs O(depth) plus the distance between the two branches, and it runs only to repair a committed duplicate. End to end on 10k blocks, comparing with and without the extension (interleaved), pasting 50 blocks went from +8–9 ms to +2–4 ms. The remote-duplicate repair is about +30 ms, but that's the second commit itself; ordering the two holders is 0.44 ms of it.
8a6a8fd to
acb5a36
Compare
|
Thanks for the pointer. I read #9174 in full. It implements one application-owned policy on released APIs: a RootNode transform that walks the whole document with
I didn't take its policy choices (cut and paste moves the id here, and ids stay off text nodes through the predicate rather than by clearing them on paste). This PR doesn't touch |
acb5a36 to
a39d277
Compare
a39d277 to
bf4986e
Compare
bf4986e to
2196f0f
Compare
6df861e to
3b0e97a
Compare
2196f0f to
1caab03
Compare
…al-devtools] Feature: Stable block ids (BlockIdExtension) ## Description Lexical has no stable way to address a block from outside the editor. Node keys exist only at runtime and change on every load, and a block's position changes with every edit. Code that edits a document block by block needs an id that survives serialization, reloads and changes applied from other replicas. Examples: an AI agent that reads blocks and answers `replace <id>`, `insert after <id>` or `delete <id>`, or a server pipeline that patches stored JSON. This PR adds an `@experimental`, opt-in `BlockIdExtension` to `@lexical/extension`, and an opt-in `BlockIdHTMLExtension` to `@lexical/html`. It builds on #9452, which has merged, so its base is main. The default predicate reads the `children` a class declares, through `getDeclaredNodeStructure`. The extension also declares an optional peer dependency on `NodeStructureExtension` so that, when both are present, it registers after it (see below). Editors that do not register the extension see no change in state, JSON, transforms, exports or behavior. - **Storage.** The id is NodeState (`blockIdState`, key `blockId`), serialized as `"$": {"blockId": "…"}`. - It survives clones, undo/redo and the Lexical clipboard. - Anything that copies NodeState carries it. - It is declared `resetOnCopyNode`, so `$copyNode` does not copy it. - A valid id is 1 to 64 characters of the base64url alphabet (`A`–`Z`, `a`–`z`, `0`–`9`, `-`, `_`): safe in URLs, HTML attributes and JSON, and wide enough for UUIDs, nanoids and shorter app ids, so an app that already stores such ids under `$.blockId` can adopt `blockIdState` without migrating documents. Any other value, from JSON, HTML, another replica, `generateId` or a direct `$setState`, reads as no id, and the block gets a new one through the normal rules (positional in a load, derived in a repair). - **API.** - Lookup: `$getBlockId(node)` and `$getBlockById(id)`. While enabled, the lookup uses an index that is updated from each commit's dirty nodes (including elements created or rewritten in the commit), and every hit is checked against the active state. - Config: `$isIdentifiedBlock` (default `$defaultIsIdentifiedBlock`), `generateId` (default `generateBlockId`) and `disabled` (also an output signal). - The index lives in the extension's init result, typed `unknown` in TypeScript and Flow alike, not in its output. - **Which blocks get ids.** `$defaultIsIdentifiedBlock` identifies: - every element and decorator child of the root (a top-level list or table included); - every nested block that holds text: a non-inline element whose class declares `children: 'inline'`, or a list that includes `'inline'`, as `ListItemNode` does; - every nested block decorator. Nested wrappers get no id: nested lists, table rows and cells, shadow roots, and nested elements whose class declares no `children`. Slot values and blocks in slots follow the nested rules. One preset is exported: `$isRootChildBlock`, the root's children only. Other sets compose from the default, as the docs show. - **New ids.** `generateBlockId` makes 21 base64url characters: 126 random bits from `crypto.getRandomValues`, more than a v4 UUID's 122. There is no `Math.random` fallback. Without `crypto.getRandomValues` it throws, and the app must configure `generateId`. A `generateId` value that is invalid (not a string included) or already used is discarded and `generateId` is called again; 32 in a row throw. - **Assignment.** Every identified block without an id gets one in the update that creates it, including blocks from `importJSON`, HTML import and markdown import. `setEditorState(parseEditorState(json))` assigns every missing id in that one commit, so a headless server can load, assign and save in one synchronous write. Updates applied with `skipTransforms` or tagged `COLLABORATION_TAG` or `HISTORIC_TAG` are repaired by a discrete follow-up update. - **Documents stored without ids** get **positional ids** on load: SHA-256 of the document key and the block's place, as 21 base64url characters. The key is the SHA-256 of `editorState.toJSON(true).root` without ids, written as canonical JSON. Every editor that loads the same document with the same nodes, predicate and transforms derives the same ids without writing first, and the first write stores them. Blocks created later by edits get random ids. A load is named once its transforms have settled, so the key is taken from the document the load ends with. A stored document that loading changes (equal adjacent lists that `ListNode` merges, or anything `NodeStructureExtension` repairs) therefore gets the positional ids of the loaded document, which cannot be computed from its stored JSON alone; see Known limits. - **Uniqueness.** When several identified blocks share an id: - The block that was identified with it before the update keeps it; copies made in this update yield (paste, duplicate, `$copyNode`, JSON or HTML import, an explicit `$setState`). An id left on a block that is not identified is not reserved. - If several had it before (a duplicate produced when concurrent changes from different replicas merge), the earliest in document order keeps it. The k-th later holder gets `base64url(SHA-256("dup" U+0000 id U+0000 k))[0..21]`, so every replica repairs it alike, in time independent of document size. - If none had it (several copies made in one local update), a copy that took the content of the removed original keeps it (a list merged into an adjacent copy), else the first one created. - A copy that yields its id counts as a block without one, so a copy of a list pasted right above an equal list continues that list when the two merge. - **Edits.** Ids stay with the content the user sees. Enter, Backspace join, `$setBlocksType`, paragraph to list, `replace`, `$setSlot` and moves keep the id. Cut and paste keeps the id; a copy gets a new one. Undo and redo restore ids exactly. - **Ids follow the structure an update ends with.** Ids are assigned in a root transform, and other transforms can still restructure the document in later passes of the same update: `ListNode` can merge a run of equal adjacent lists over several passes, and `NodeStructureExtension` splits, joins, lifts and merges blocks in a root transform of its own. A generated id that an earlier pass gave a new block is therefore provisional within the update. A later pass can still replace it with the id of a block that the new one continues, and a copy that yielded its id takes it back once the original has been merged into it. With `NodeStructureExtension`: - a block split around a block lifted out of it keeps its id on the first piece, and the later pieces get fresh ids; - a block lifted out of a block that it leaves empty takes that block's place, and its id if it has none, as `replace` does; - paragraphs joined into a block as lines leave that block its id; - equal adjacent lists merge into the first, which keeps its id; a new list without an id continues the list merged into it. The result does not depend on the order in which the two extensions are listed, and edits give the same ids when `NodeStructureExtension` is enabled after the editor is built; loads then differ (see Known limits). - **HTML.** `BlockIdHTMLExtension` writes `data-block-id` on exported identified blocks and reads it back through `DOMImportExtension`, subject to the validity and uniqueness rules. An id imported onto a block that is not identified once inserted (a table cell, a nested list) is dropped. Its `export` and `import` flags turn off either direction. It lives in `@lexical/html` because `@lexical/html` already depends on `@lexical/extension`. - **Docs.** A new page, Extensions > Block IDs, covers: - setup and the agent recipe (one update per operation, keeping a person's selection when the agent replaces a block it touches); - which blocks get ids, and nested editors; - how ids follow edits, ids left on blocks that stop being identified, and uniqueness; - documents stored without ids, and what a load that changes the document does to their ids; - how ids follow the structure that `NodeStructureExtension` repairs; - HTML and configuration, including enabling the extension on every editor that writes; - the id format: exactly what is hashed, canonical JSON (ECMA-262 `JSON.stringify` semantics: integer-like keys first, escaping, number formatting), canonical slot order, what the freeze covers, and a literal end-to-end test vector for implementations in other languages. The PR also adds entries in the included-extensions list, and Flow types for both extensions. ### Collaboration Block ids are plain NodeState, so they sync wherever replicas sync NodeState, and the duplicate repair gives the same result on every replica. Enable the extension on every client that writes; the positional-id limit when one does not is documented. A short new page, Collaboration > Block IDs ([`packages/lexical-website/docs/collaboration/block-ids.md`](https://lexical.dev/docs/collaboration/block-ids), added to the collaboration sidebar), covers this. ### Design notes - **Why NodeState.** It is the one storage that JSON, clones, undo and the clipboard already carry, and that any replica copying NodeState carries too. An identity owned by one sync mechanism would tie ids to it and would not exist without it. - **Why 126 random bits rather than a writer prefix.** A server editing stored JSON has no writer identity, so a prefix would itself have to be random. Random ids are opaque: a mistyped id names no block, instead of silently naming a neighbouring one. `generateId` stays configurable for apps that want prefixed ids. - **Why a strict id alphabet.** The format is frozen: loosening the accepted set later is compatible, tightening it would re-id stored documents. Ids outside base64url did not survive an HTML round trip (`\r\n` became `\n`, NUL became U+FFFD). `^[A-Za-z0-9_-]{1,64}$` is the alphabet the extension writes, with room for the ids other systems already use. - **Why document order for committed duplicates.** Each editor numbers the nodes it receives in its own order. With key order, each replica would keep its own copy, and the merged document would lose the id. The concurrent-moves test fails exactly that way when key order is substituted. - **Why positional ids.** Random ids assigned on load would differ on every read. Deriving them from the document's content and place makes readers and replicas agree. The document key keeps the same place in two versions of a document from sharing an id. - **Why positional ids stay keyed by the whole document.** With an editor that does not run the extension writing between two replicas' repairs, the replicas see different documents and can write different ids for the same block; the merged document keeps one, so an id one replica already wrote changes once (the replicas converge, ids stay unique, nothing changes afterwards). A per-block scheme (hash of the block's own JSON plus its rank among identical blocks) narrows but does not remove this: the blocks that editor edits still change, a block inserted with the same content as an earlier one shifts the ranks after it, and without a document-level salt identical blocks get the same id in every document; a salt every replica agrees on would have to come from the document itself, which that editor can change too. It would also give unchanged blocks the same id across versions, dropping the property above. So the scheme stays as it is, and the docs state the limit plainly: enable the extension on every editor that writes. The tests below show the behavior. Related: #9174 is an example app with an application-owned id policy (128-bit random ids, a fresh id on every paste). This PR is the reusable version, convergent across replicas, and does not touch the files #9174 edits. ## Test plan New tests: - `BlockIdExtension.test.ts` (headless, 85 tests): - assignment and documents stored without ids, including a load during which an app transform creates a node it never inserts (still one commit, with every id); - id validity: invalid stored ids (numbers, empty, 65 characters, spaces, markup, control characters, lone surrogates, non-ASCII, `doc:12`) read as absent and get positional ids; 64-character, 11-character and UUID ids are kept; an invalid id from another replica is repaired; an invalid id set with `$setState` reads as absent; invalid `generateId` values, a value that is not a string included, are retried, and 32 in a row throw; - uniqueness: copies above and below the original, several copies in one update, committed duplicates, `$copyNode`, the clipboard, cut and paste, undo, copies of a list that merge with the original (also on both sides of it, merged over several transform passes), and a copy of a list pasted right above an equal list; - split and merge in paragraphs, headings, quotes and list items; - type changes and moves; - the index: `$getBlockById` finds every identified block after a document with ids on the root children only is loaded (by `setEditorState` and as the initial state), after the documented `$setState` recipe on a list or table, after a copy of such a list, and after `setEditorState` of a list whose items repeat an id; O(dirty) predicate calls; - ids left on blocks that stop being identified; - the default predicate across tables, lists, an undeclared container, a shadow root, a link and nested inline and block decorators; a custom predicate (headings at any depth); copy and cut of nested list items through the clipboard; - `disabled`, and repair after updates without transforms. - `BlockIdExtension.structure.test.ts` (38 tests): the same 11 cases with `NodeStructureExtension` listed after this extension, listed before it, and enabled after the editor is built: a paragraph and a heading split around a lifted block, a block lifted out of the paragraph it empties, a list lifted out of a link (the items keep their ids and the link), paragraphs joined as lines, equal adjacent lists, nested lists joined at a seam, a new list, with and without an id, merged with the list after it, a copy of a list merged with the equal list after it, and copies of a list on both sides of it and apart from it. Each checks the exact ids and that the index finds every block. Five load tests, with the extensions in either order: a stored document with equal adjacent lists gets the positional ids of the merged document, the same as an editor without `NodeStructureExtension`; a stored paragraph that holds a quote gets the positional ids of the split document. - `BlockIdExtension.property.test.ts` (20 seeds in CI): random sequences of 40 local edits (typing, Enter, joins, range deletes, type changes, moves, duplicates, multi-copy pastes, indent and outdent, list conversion, moves into table cells, replace, undo/redo, reloads with an injected duplicate). After every step, every identified block has exactly one id, ids are unique, `$getBlockById` finds every block, pre-existing blocks keep their ids, and undo and redo return to a state seen before. `BLOCK_ID_PROPERTY_SEEDS` runs more. - `BlockIdExtension.format.test.ts` (10 tests): the frozen format. It checks SHA-256 and UTF-8 against Node, the canonical JSON, and positional and duplicate ids against an independent implementation, pinned to literal values, plus the end-to-end vector printed in the docs. - `BlockIdExtension.slots.test.ts` (10 tests): slot values and slot containers, duplicates across slots and children, `$setSlot`, the index after undo and `setEditorState`, host removal, and the lookup while disabled. - `BlockIdExtension.dom.test.ts` (5 tests, jsdom): typing, Enter, Backspace, clipboard paste, legacy HTML paste, undo. - `BlockIdHTMLExtension.test.ts` (10 tests): off by default, export, round trip, imported ids through the uniqueness rule, invalid imported ids ignored, an imported id dropped from a block that is not identified, export into another realm's document, the `export` and `import` flags, and readers of an id-less document agreeing. - `BlockIdDocs.test.ts` (5 tests): the code examples of the Block IDs page, as written there, with a person's caret inside the block the agent replaces, and with a selection from the block before into the replaced block, from it into the block after, backwards, and inside it. - `BlockIdCollab.test.ts` (16 tests per binding, `@lexical/yjs` v1 and v2): assignment, late joiners, concurrent Enter, duplicates and moves, a document stored without ids opened concurrently, type changes, undo/redo, nested lists, and clients without the extension writing mid-session (a block added while the peers are apart; a block added while a peer has unsynced typing; peers that open an id-less document at different versions). Every test checks convergence, unique ids and quiescence. - `BlockIdCollabFuzz.test.ts`: deterministic randomized runs with 2–3 replicas, flat and nested, 8 seeds per binding and variant in CI. `BLOCK_ID_FUZZ_SEEDS` runs more. - `BlockIdExtension.perf.test.ts`: skipped unless `BLOCK_ID_PERF=1`. ### Before On main (with #9452) with the new test files copied in, every block id test fails, because the extension does not exist: ``` $ npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension packages/lexical-html/src/__tests__/unit/BlockId packages/lexical-yjs/src/__tests__/unit/BlockIdCollab Error: Cannot find module '../../internal/positionalBlockId' imported from …/BlockIdExtension.test.ts TypeError: Cannot read properties of undefined (reading 'name') TypeError: (0 , $getBlockId) is not a function Test Files 11 failed (11) Tests 142 failed (142) ``` ### After ``` $ npx vitest --project unit --no-watch <the same files> ↓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts (1 test | 1 skipped) ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.structure.test.ts (38 tests) ✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts (32 tests) ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.property.test.ts (20 tests) ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.format.test.ts (10 tests) ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.slots.test.ts (10 tests) ✓ |unit| packages/lexical-html/src/__tests__/unit/BlockIdDocs.test.ts (5 tests) ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts (85 tests) ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts (5 tests) ✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts (32 tests) ✓ |unit| packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts (10 tests) Test Files 10 passed | 1 skipped (11) Tests 247 passed | 1 skipped (248) $ pnpm run test-unit Test Files 408 passed | 1 skipped (409) Tests 10105 passed | 2 skipped (10107) ``` Every test on main passes unchanged (9768 of 9768 test ids, same status). `pnpm run tsc`, `tsc-test`, `pnpm run flow`, ESLint and Prettier are clean, the tree-shaking tests pass on the sources and on the production build, `build-prod` succeeds, and the website builds with no broken links. Property test at 1,000 seeds: 1000 passed (`BLOCK_ID_PROPERTY_SEEDS=1000`). Ids compared with a reference build that names blocks only once the transforms of an update have settled (otherwise the code of this PR). This used a local harness that is not committed: the property test's edits plus moves into list items and quotes, and an agent that reads ids and later replaces blocks by id, over 1,000 seeds × 40 steps, traces compared up to the naming of new ids. The ids are identical in every sequence in all five configurations: without `NodeStructureExtension`; with it listed after this extension; listed before it; enabled after the editor is built through its `disabled` output; and through `registerNodeStructure()`. Against the same reference, the first rebased version of this PR differed in 55 sequences without `NodeStructureExtension` and 127 with it listed second, and the previous version in 36, 41, 41, 57 and 57 sequences in those five configurations. Every difference of the previous version is in a list that pasted copies of a list merge into: the reference keeps on it the id of the list they merged with, where the previous version gave it a fresh id and dropped that id or left it on a copy. The cases are a copy pasted right above an equal list and, with `NodeStructureExtension` enabled after the build, several copies of a list merged with the original. Known limits: - **Loading a stored document that the load changes.** Positional ids are derived from the document the load ends with, not from the stored JSON. Where `ListNode` merges equal adjacent lists, editors with and without `NodeStructureExtension` derive the same ids. Where `NodeStructureExtension` repairs more (a paragraph split around a quote stored inside it, for example), the document key changes, so every block of such a document (not only the blocks the repair creates) gets ids that differ from those of an editor without `NodeStructureExtension`, and a reader working from the stored JSON must apply the same repairs first. Editors that load it with the same nodes and extensions agree. Documents that loading does not change, including the docs' test vector, are not affected. Making untouched blocks keep the ids of an editor without `NodeStructureExtension` would mean naming a load before `NodeStructureExtension`'s repairs, which run in a root transform registered before this extension's, and Lexical has no hook before the transforms of `setEditorState`. - **`NodeStructureExtension` enabled after the editor is built.** Its repairs then run after this extension's naming in each pass. Edits give the same ids as above, but a load is named before the repairs: blocks the repairs keep get the positional ids of the document as it was before them, a list merged into another loses its id, and blocks the repairs create get ids from the document the load ends with. Fuzz at 2,000 seeds per variant (`BLOCK_ID_FUZZ_SEEDS=2000`): v1 passes every seed, flat and nested. On v2, 55 seeds fail (7 flat, 48 nested). All 55 trace to the experimental `@lexical/yjs` v2 binding, not to this extension: - 37 nested: when indent creates a nested list, the list's `blockId` is at its default (`$copyNode` resets it), and the v2 binding's create path writes that default into Yjs as an `undefined` attribute (its update path drops it). Receiving peers end with `"$": {"blockId": undefined}` on one peer (27) or throw on a stale list node inside the binding (10). The smallest repro is two steps on one peer: make a list, indent. A one-character change in the binding (`!== null` to `!= null` when it filters state attributes) removes all 37. - 9 (6 flat, 3 nested): the v2 binding writes each Lexical child into whichever Y element of the same type sits at its position, so after concurrent moves an edit lands in another block's element. The binding then overwrites a block's `blockId` (last writer wins), writes one id onto two elements (the documented duplicate rule then renames one holder), or Yjs undo recreates an element without its attributes. The same minimized scripts pass on v1, and converge on v2 without the extension. - 9 fail with the extension removed too (8 diverge or throw; 1 leaves an empty list element in Yjs that keeps the network from settling). The v2 binding is not changed here. Performance, on a headless 10,000-block document, with and without the extension, interleaved round by round (`BLOCK_ID_PERF=1 npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts`, shared machine under load): ``` 10000 blocks, median, interleaved without with delta keystroke (300) 14.755 ms 15.279 ms 0.524 ms Enter (300) 15.488 ms 17.675 ms 2.187 ms paste 20 blocks (50) 17.742 ms 20.244 ms 2.502 ms paste 50 blocks (50) 20.080 ms 24.029 ms 3.950 ms remote duplicate (50) 24.987 ms 55.247 ms 30.260 ms first load, no ids (12) 113.748 ms 296.409 ms 182.660 ms of which document key: 58.927 ms load, ids stored (12) 135.323 ms 177.253 ms 41.930 ms ``` Across three runs the deltas moved by a few milliseconds (keystroke 0.4 to 0.9 ms, Enter 2.0 to 2.5 ms, paste of 50 blocks 3.5 to 4.0 ms, first load 174 to 183 ms, stored ids 37 to 42 ms, remote duplicate 29 to 30 ms). Three runs of the previous version of this PR, interleaved with these, fell in the same range (keystroke 0.6 to 0.8 ms, Enter 2.2 to 2.5 ms, paste of 50 blocks 3.5 to 3.9 ms, first load 180 to 185 ms, stored ids 34 to 39 ms, remote duplicate 29 to 32 ms); a load of these documents takes the same transform passes in both. A block without an id applied from another replica (written only by editors without the extension) gets a positional id, so that repair hashes the document once. Not exercised: real browsers.
1caab03 to
a3ab5be
Compare
…al-y][lexical-yjs] Feature: @lexical/y, an experimental Yjs 14 collaboration binding
## Description
A new experimental package, `@lexical/y`: a collaboration binding for
Lexical on Yjs 14 (`@y/y`). `@lexical/yjs` (Yjs 13) is unchanged: Yjs 14 is a
different npm package with a different API, so a Yjs 14 binding cannot
replace it in place, and an application uses one or the other.
Try it: [jot.rovira.sh](https://jot.rovira.sh), a full-page note anyone
with the link can edit at the same time, built on `@lexical/y` (source:
[zurfyx/jot](https://github.com/zurfyx/jot)).
Current behavior: the only binding, `@lexical/yjs`, stores one shared
element per Lexical node. Splitting, joining, retyping or re-indenting a
paragraph, and linking or unlinking text, are written as a delete and a
re-insert, so a collaborator's concurrent typing there can be lost or
misplaced (see Before), and every Enter or heading change rewrites
elements (see the bytes table).
New behavior: `@lexical/y` stores a paragraph, heading, quote or list item
as its characters followed by a marker, a list as the items it groups and a
link as a format over its characters. The storage is derived from general
facts the 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 line classes 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.
These edits then keep the characters and merge with concurrent typing.
Built on the `$config` keys, their declarations on Lexical's nodes and the
opt-in `NodeStructureExtension` (#9452, on main); the binding registers that
normalization, so each client writes its own edits in the normalized form
the declarations describe, and shows a remote change as it is stored (a
remote change never makes a reader write). There are no collab-specific keys
in core and no binding-level storage overrides.
Also new here: `describeStorage(editor, binding?)` (the kind per type), and a
per-document pin: the first write of a type records its kind and identity
fields on the root (`k:<type>`, outside the undo history); a later client
whose class derives another kind uses the recorded kind when it can store
the class that way, and opens read only otherwise. List identity is the
declared `mergeAdjacent.by` fields only (`listType`), so NodeState such as a
block id never splits a list.
Entries (all `@experimental`):
- `@lexical/y`: `YBinding` (its `editor`, `doc`, `root`, `status`, `pins`
and `undoManager` are read-only getters), `YCollabExtension` (binding,
collaborative undo, `status` signal; conflicts with the history
extensions), `describeStorage`, `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and
the types `YBindingOptions`, `YBindingStatus`, `YCursor`, `YCollabConfig`,
`ClientIDRange`, `StorageKind`, and the warning code constants below with
their union type `YWarningCode`. No React, no DOM requirement.
- `lexical`: `LexicalWarning` (`extends Error`, `readonly code: string`,
`readonly data?`), a generic class with no codes of its own, and the
update tag `DEFER_COMPOSITION_MERGE_TAG` (see Core).
- `@lexical/extension`: one new `BlockIdExtension` option,
`repairTransforms` (default `true`, behaviour unchanged; see Block ids).
- The www entry stub `packages/lexical-y/LexicalY.js`, as every other
single-entry package has.
- No server entry: old clients write other roots (see "Old clients"), so a
server needs no API of its own; the two constants a server may want
(`DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`) come from the main entry.
- Seeding a document on a server is `seedYState` in `@lexical/y/headless`
(#9437, stacked on this); the internal one-off writer is not exported.
Warnings: `lexical` exports `LexicalWarning` (`extends Error`, `readonly
code`, `readonly data?`), which packages pass to the editor's existing
`onWarn` (its `(error: Error) => void` signature is unchanged) for warn-level
conditions with a stable, package-namespaced code (`code` is a `string`;
core knows no codes). Documented under "Errors and warnings" in Defining
Extensions, with neutral example codes. `@lexical/y` has no `onWarn` option
of its own: every
warning goes to the editor's `onWarn` as a `LexicalWarning`, with an exported
constant per code: `UNSUPPORTED_LAYOUT_WARNING`
(`'@lexical/y/unsupported-layout'`), `UNKNOWN_NODE_TYPES_WARNING` and
`STORAGE_MISMATCH_WARNING` (each makes the binding read only),
`SELF_CHECK_WARNING`, `RECOVERED_READ_WARNING`, `RECOVERED_WRITE_WARNING`,
`NESTED_FALLBACK_WARNING` (a class stored nested, for example a link subclass
that overrides `shouldMergeAdjacentLink`) and `UNSYNCED_VALUE_WARNING`, each
with documented `data`, and their union, the `YWarningCode` type. Codes are
public API: never renamed or reused, only added, so a `switch` over them
needs a `default`. A warning is delivered once a change has been applied
in full, never from inside a Yjs observer or transaction, and a handler that
throws does not affect syncing (its error is rethrown in a microtask). The
class and value warnings (`NESTED_FALLBACK_WARNING`,
`UNSYNCED_VALUE_WARNING`) are found once per process and reported once per
binding (a class's only to editors that register it), so a second editor
gets them too. `YBindingOptions.onStatus` is called the same way: once the
binding's work is done and Yjs is idle, never inside a Yjs observer.
Without an `onWarn`, Lexical's default applies (it throws in development,
outside Yjs, and `console.warn`s in production).
Docs: a new page, Collaboration > Yjs 14 (`@lexical/y`): when to use it
rather than `@lexical/yjs`, install, setup with `YCollabExtension` and a
provider, the options, warnings (the codes, their `data`, delivery and the
default handler), how content is stored (diagrams of a paragraph and a
heading, a nested list, a link and a table next to the sequence that stores
them), the wire format (a diagram of layout 1: a container's sequence of
characters, `¶` markers with their attributes, format ranges and nested
nodes, and the root's layout record and storage pins, with the stored names
checked against a dumped document and a link to the README's
specification), what changes when collaboration is on (why, a before/after diagram per
rule: a block split around, a heading in a link, paragraphs in a quote
becoming one quote with line breaks, a horizontal rule splitting a numbered
list with its numbering continued, adjacent equal links; and what it means for an
app), edits made by code (agents and tools: edit text in place, apply an
edit to the state it was computed from and merge), servers (old clients,
yrs before 0.28), limits, and upgrading from
`@lexical/yjs` (no in-place migration yet). `LexicalWarning` is documented
under "Errors and warnings" in Defining Extensions. The package README is
short (install, a minimal example, links to the pages and the API reference,
how to run the long fuzz and replay a seed) and holds the frozen wire
format. `DEFER_COMPOSITION_MERGE_TAG` is listed under
Updates > Common Update Tags. A session of 10,000 edits
takes about 217 KB, against 2.8 MB with the default `@lexical/yjs` layout
(see Performance).
`@y/y` is a peer and dev dependency pinned exactly to 14.0.0-rc.29 (npm's
`latest` tag points at an older release candidate). rc.29 is past the
repository's 7-day minimum release age; the lockfile resolves `@y/y@14.0.0-rc.29`
(integrity `sha512-A4W9Bnrf…`) and nothing else. The cursor equivalence test
passes on it.
Core (`lexical`): two generic pieces, and nothing about collaboration
(no collaboration vocabulary, API or behaviour; `@lexical/y` keeps its own
codes and checks):
- `LexicalWarning` (above).
- A new update tag, `DEFER_COMPOSITION_MERGE_TAG` (`'defer-composition-merge'`,
exported from `lexical` next to the other tags, documented in Updates >
Common Update Tags). While an IME composition is active, an update carrying
it does not merge text into or out of the composed text node: a merge
rewrites the composed DOM text node, and the browser's composition range
would take in the merged text. Once such a merge was held back, later steps
of the same composition hold it back too (a private `_compositionMergeHeld`
key, cleared whenever the composition key changes); the nodes merge when
the composition ends. It is for any update that changes text next to a
composition without user input (changes applied from another source);
`@lexical/y` adds it to the updates that apply a remote change. Without it
normalization ignores the composition, so every other update, including
one tagged `COLLABORATION_TAG` or `SKIP_COLLAB_TAG`, merges exactly as
before: `LexicalNormalizationComposition.test.ts` runs 112 scenarios (7
operations next to the composed node × 8 tags, including
`COLLABORATION_TAG`, × with and without `skipTransforms`) composing and not
composing and requires identical JSON and node identities, and
`SyncCompositionUnchanged.test.ts` (`@lexical/yjs`) drives v1 and v2
bindings (8 scenarios × 2 client id orders each) with a composition in
progress and compares every step with traces recorded on main. A hold
keyed on `COLLABORATION_TAG`, as an earlier revision of this PR had, fails
2 of them (v1). Checked that `@lexical/y` still needs it: without the tag,
6 of the 21 tests in its main composition block fail (a peer joins the
lines while composing).
Block ids: `@lexical/y` works with `BlockIdExtension` (#9421, on main),
which gives every new block an id stored as NodeState:
- The update that names the blocks a remote change brings (positional ids,
the same on every client that has the same document) is made by every
client that reads the change: a follow-up of the commit, which may set
attributes or delete, never insert (see Write path). `BlockIdExtension`
gains an option, `repairTransforms` (default `true`, unchanged): with
`false`, the follow-up sets the ids without running transforms and changes
nothing else. `YCollabExtension` sets it through a peer dependency
(`declarePeerDependency('@lexical/extension/BlockId',
{repairTransforms: false})`), so an app that adds both extensions gets it.
With `true` (an editor that uses `YBinding` directly without setting it,
or an app that sets it, which overrides `YCollabExtension`), the naming
update also runs the editor's transforms over what the remote change
brought: the binding writes only the attributes and deletions they make
and reads the rest again (tagging that read as the naming update, so that
the extension does not make it again), and attributes the transforms
derive can disagree between clients. The docs say to set it to `false`:
forced to `true` in `YExtension.ts`, 1 of the 15 `BlockIds.test.ts` tests
fails (the test of the setting itself), and with `BlockIdExtension`
editors `NormalizationConvergence.test.ts` fails 51 of its 1,131 cases,
with or without the self-check: the 48 runs of adjacent equal lists
written inside a list item without the normalization, and 3 of its 100
randomized sessions, which end with clients showing different content.
The BlockId Fuzz (2,000 + 500 seeds) and Races pass.
No other `BlockIdExtension` behaviour changes, and its existing tests are
unchanged.
- A line that concurrent edits leave without its marker (text typed into a
paragraph a peer removed, read as a paragraph) has no stored id. Its
positional id would cover the whole document, so clients holding
different concurrent edits derived different ids, and with follow-ups
limited to attributes they could not converge. The reader derives it
instead, from Yjs identity: `y`, the client of the line's first character's
item, `_` and that item's clock (base 36), set as the block's NodeState
when `BlockIdExtension` is registered and the line is a block it names.
Every client and a fresh reader derive the same id from the same
document, whatever order they saw changes in; the edit that next changes
the line stores it with the marker it writes, so the id does not change.
No storage, no follow-up write; part of layout 1 (unreleased). A read
that recovers by rebuilding the editor keeps it.
- Initial content: two clients that initialize a new document with the same
content write the same bytes with `BlockIdExtension` too (both id orders,
with and without text, with a different `generateId` per client): the
extension names a document's first content positionally, so the ids are
the same before the content is hashed (see Data model).
Changes in this revision (each with a regression test):
- Only a client's own edits are written, and what made a commit decides
it, not its tags alone. Lexical commits the updates queued during one
listener phase together, with their tags merged, so an app's update
queued from a listener (the character limit's wrapping, an app's own
edit) could share a commit with the binding's list refresh and was not
written: its author showed it, the document never got it, and later
writes failed. The binding's own updates (the refresh, showing what a
composition held back, reading containers again, the author's
normalization) no longer run from its listener: they wait until the
editor is idle, so each commits alone (what a composition held back shows
then, or when the next remote change is read, also once another
composition has started), and the normalization, queued from the listener
so that it runs before a remote change can be read, does nothing when
another update is committed with it. An update queued in the same phase
as `BlockIdExtension`'s naming update is still committed with it (see
Known limits).
- While the binding writes, an update that changes content commits at once,
as with `discrete: true`. One queued from a listener waited for a
microtask, and a remote change the provider applied in that task was
integrated first, so the update was written at positions computed without
it (a failed write, or text in another place).
- A change the binding does not write is read again. Follow-ups may set
attributes or delete (deletes were refused too); what else they change is
not written, nothing of that container is, and it is read again, so the
editor shows the document (it kept the change, and differed from every
other client). A remote change that arrives first is read after those
containers are read in full, and the author's normalization waits for
that read. With `repairTransforms: true`, `BlockIdExtension`'s naming
update no longer stalls the binding (see Block ids).
- A transform registered while a document is open (a plugin that mounts
once the editor is editable, such as the playground's table cell
resizer) makes Lexical run it over the whole document in an update of its
own: that update is a follow-up, so a client that loads a ragged table
shows it as stored instead of padding it on its own screen.
- A line without a marker that an update did not change is left without
one: two clients making structural edits in its container at once each
gave it a marker (an extra empty paragraph everywhere).
- A new editor bound to a document an editor of the same client wrote, and
a read that recovers, no longer reuse segment keys (a token typed later
merged into an earlier one on every other client).
- A saved EditorState set again is written whole: descendants that changed
under ancestors that kept their objects were not written.
- `BlockIdExtension`'s naming update stays out of the undo history.
- An unknown line type inside a list stored as a node makes the binding read
only, as everywhere else (it read as a list item and a local edit could
overwrite it); read recovery keeps the derived ids of lines without a
marker; a layout record removed from an active empty root makes the
binding read only.
- `internal/UpdateRoots.ts`, used only by tests, moves to the test
utilities; nine unused exports are removed.
Data model:
- Shared root `doc.get('lexical-y')`, a new root name, with a layout record:
one root attribute per layout version the document needs (`lexical-y:1:
true`). A reader gates on the highest version present; the record only
grows (no client deletes one), and a writer records a version in the same
transaction as, and before, the first content that needs it, so two
clients upgrading at once (3 ‖ 2) leave every reader at 3 (a single
last-writer-wins number could come out as 2). Any change to how a stored
shape is read is a new version. The editor stays read only until the record
has been read. A newer version, a malformed record, content without one,
or a record removed from a document the binding was writing keeps it read
only; going read only clears the undo history.
- `initialize()` (after the provider's first sync) marks only an empty root.
An `editor.update()` still pending when it runs is committed first and is
part of the initial content (it was written afterwards as an ordinary,
undoable edit, so two clients seeding the same content that way showed it
twice).
It refuses (read only, `'unsupported-layout'`) when an older layout's root
(`root`, `root-v2`) has content; a binding with `convert: true` writes the
layout root next to it. Into a pristine root (one that never held an item
or an attribute, deleted ones included), the initial content is written
with a client id hashed from the layout version, the target shared type
(its top-level name or item id) and the exact items written (encoded from
a scratch document), so two clients initializing the same content into
the same new root at once write it once, while different roots or content
never share an id; outside the undo history. It is the binding's first
write, so its segment keys (token-mode text) are that id and a counter
from 0 on every client. A root that held anything is initialized under
the client's own id: around retained items two clients' copies could
differ under one derived id (the scratch document does not hold them),
and Yjs never reconciles two items with one id. Content-derived ids
are 53-bit hashes (cyrb53) under `clientIDRange: 'uint53'` and 32-bit under
`'uint32'`, so they live in the same range as the clients' own ids; every
client of a document must use the same range. The real client id is back
before the transaction's observers and update handlers run, so a provider
that relays synchronously from an update handler never sees (or makes the
binding write follow-ups under) a derived id.
- The wire format is frozen as layout 1 in the README (root and attributes,
markers, run terminators, `b:`/`i:` prefixes, `c`, `t`, `p:`, `s:`, `g`,
`g:`, `l`, `o`, `@`, `f:`, `k`, `w:`, `#`, `k:<type>` pins, value
encoding, the layout record, the derived id of a line without a marker). Layout 2 (#9449, stacked on this) adds move records.
- Every container (the root and every node stored as its own Y.Node) holds
one sequence of text, child nodes and line markers (Yjs 14 Y.Node children
are unified, so no XmlText per container is needed).
- A line (a block class declaring `children: 'inline'`, schema-complete) is
its inline content followed
by a marker: a child `Y.Node` named `¶` whose map attributes hold the
line's type (left out for a paragraph), schema fields (minus derived),
NodeState, and for a group item the group type, key fields and level. Not
a character with formats (such as U+2029) and not an embed:
* map attributes merge per key (last writer wins), so a concurrent heading
change and indent both apply, without format start/end items in the
sequence;
* the marker's identity (its item) never changes when its attributes do,
where an immutable embed would have to be replaced (and could be
duplicated by concurrent replacements);
* block attributes never mix with inline formats, and text may contain
any character.
- Groups (lists) are rebuilt from consecutive items; local groups are kept
in the same canonical shape by a transform (adjacent equal groups and
wrapper items merged, empty groups removed); derived fields (list
numbering) are recomputed by a refresh update on every client. Only the
declared `mergeAdjacent.by` fields identify a group (`listType` for a list);
its other synced fields and NodeState do not split it. A nested item's marker
also records its outer groups and their wrapper items' fields (`o`), so an
indented first item keeps its outer list's type and the wrappers' fields
sync.
- Storage follows the class, never the instance: a line class stays a line
even with a block child (the child is stored as a node inside its
content, for example in a shadow-root quote, unless the normalization
lifts it out; see Normalization). `isInline()` still decides
where a node sits: a format applies to inline instances, a line to block
ones. A node whose
`isInline()` changes (a class computing it from a field) is written again
in its new form: a format becomes an `i:` node inside the line, and back.
Undeclared or invalid blocks are `b:<type>` child nodes with the
class's own (compact) JSON as attributes; inline elements that are not
formats and inline decorators are `i:<type>` children.
- A container records what it holds (`c`: blocks or inline content) when it
is created, from its declared `children` or its children, and never
changes it:
leftover inline content of a block container reads as a paragraph on every
reader; inline content directly in a block container is always ended by a
`¦` terminator.
- Inline elements stored as formats (declared inline, with `mergeAdjacent`)
are one format key each
(`w:link`, whose value holds the wrapper's fields); text formats are one
key per format (`f:bold`), plus type, JSON fields, NodeState and, for text
nodes Lexical would not merge, a segment key (`k`). Formats apply to any
child, so a link can span a line break or an inline decorator; a line
break's NodeState is a format of its `\n`. Two adjacent equal links keep an
instance key (`#`) so they stay two links on every peer.
- NodeState equal to its default is not stored (setting it back deletes
the key). Element `textFormat`/`textStyle` are always stored.
- Schema completeness (own `$config()`, no hand-written `exportJSON`,
`updateFromJSON` or `afterCloneFrom` below the declaring class) is
required for lines, groups and inline formats; anything else is a node.
- Editor instances (nested caption editors) are not synchronized; JSON
snapshots of them are (members that JSON would drop are dropped).
- A class with a hand-written serialization is a node; an edit to one of its
own fields alone is written (the whole node's JSON is compared) and read
through `updateFromJSON`, then `importJSON` for fields it does not know.
- Unknown types fail closed: a client that meets a node, line, text or
group type it does not register (a line inside a list stored as a node
included) goes read only with a warning, so it never hides and later
deletes content it cannot show.
Write path:
- Anchored edits: Y.Node#insert/delete/format walk the type from its start
on every call in rc.29, so the binding edits the sequence from the item it
knows (the previous line's marker) with a port of Yjs' text position
algorithm. A test runs random operations through it and through
Y.Node#applyDelta and requires identical documents (byte for byte).
- A keystroke (one text node of a line changed, same formats, every other
child unchanged including inside links) diffs only that node's old and
new text, anchored at the caret, and writes at its offset: cost in the line's
items, not its length (0.4 ms in a 200,000-character paragraph).
- Identity-anchored structure: units matched by node key (a weighted
longest increasing subsequence: as many blocks as possible stay in place,
a list counting as one block; between equal counts a block node, whose
rewrite copies its subtree, outweighs lines). A line whose content did not
change (node identity against the previous state, inline elements
included) is never diffed; removed or moved units are deleted exactly;
only split, join and type-change segments are diffed, as one sequence of
the segment's items with the caret as the diff anchor: text that moved to
another line keeps its items (no re-insert of a moved tail, so text a peer
deleted is not resurrected). Each character keeps its old item only if it
comes from the same Lexical text node as before (text nodes merged by a
join or an unlink are attributed using the caret at the join, else by
common prefix and suffix, among the nodes removed from the content being
rewritten; text merged from elsewhere is new), so text that moved between
nodes or lines is written as new text, never built from equal old
characters. Diffs never split a surrogate pair. A Lexical node replaced in
place by a new one keeps its shared node and content: a different type is
recorded in the node's `t` attribute (a paragraph held by a list item
turned into a heading keeps a peer's concurrent typing). Enter inserts a
marker, Backspace deletes one, a type, indent or list type change only
sets marker attributes.
- Structure is read from node links (the root is always marked dirty);
attributes are written only for changed keys; inserted content carries its
formats (no reformat after insert); format passes walk runs, not
characters.
- Follow-ups: updates every client makes after a commit (the refresh of a
group's derived fields, `BlockIdExtension`'s naming update, the update
Lexical makes to run a transform registered while the document is open
over all of it) are written through one check: they may set attributes
or delete, never insert a marker, materialize a line without one, or
insert content. What else they change is not written, and the binding
reads those containers again, so the editor keeps showing the document (a
development warning names the change). The re-read of a naming update's
change is tagged as that update, so that `BlockIdExtension` does not make
it again on what was read; content a follow-up changes every time it runs
(a list's own transforms in each refresh) is read again three times in a
row, then once more without the refresh. What made
a commit decides whether it is one: the binding's own updates commit
alone (they run when the editor is idle), and the transform's update
commits alone and dirties every node of a type that just gained a
transform. An update another listener queues in the same listener phase
as the naming update is committed with it and counts as part of it.
- While the binding writes, every local update that changes content commits
at once (as `discrete: true` does) instead of in a microtask, so a remote
change the provider applies in the same task never finds one waiting.
- An update of the client's own that ran no transforms is normalized by the
client right after it (see Normalization), in the same undo step.
- Self-check (off by default; `selfCheck` and `selfCheckSample`, also options
of `YCollabExtension`; skipped while such a normalization is pending):
every line a write touched is read back from Yjs (text, formats, line
break NodeState, marker), and every container a structural write touched,
or where a group item's marker changed, is read whole into a fresh editor
and compared with the editor's JSON (node types, list structure, wrapper
fields, NodeState); mismatches go to the editor's `onWarn` as a
`'@lexical/y/self-check'` warning. The whole
container read runs every time for containers of up to 256 units and is
sampled in proportion above that (Enter in a 2,000-block document went
from about 50 to about 12 ms in development). Lexical's tests turn it on
through their helpers and fail on a warning.
Read path: a local update still pending (one without transforms, which
does not commit at once) is committed before a remote transaction is read,
and a container that still shows a follow-up's change the binding did not
write is read in full first; changed items are bucketed by container once
per transaction; an inserted or deleted format item re-derives the start formats
of the following units (past block nodes too) until they agree again; each
changed item is located by walking to the next end item; text edits update
lines in place; structural changes re-parse only the touched units (groups
next to them are regrouped without re-reading untouched lines); formats that
span a marker propagate only while the value at the next unit's start
changes (re-reading the next unit as a region when it cannot be updated in
place); an inline element that cannot be empty is not shown when peers
deleted all its content; NodeState keys are read in sorted order. The local
selection is captured as relative positions before each remote transaction
(a caret anchored to the character on its left, a range to its edge
characters) and restored in the same update (an end item a peer deleted is
skipped when a position is resolved). While the local editor is composing
(IME), remote inserts into the composing line are applied to Yjs but not to
that line's nodes (the browser composes into their DOM); readers and writers
of that line skip those ids, and the line is read again when the composition
ends (a read that only moves the composed line, regrouping its list, keeps
what is hidden hidden; if the composing client removes the line, what was
hidden in it is read where it is stored). Deletions, formats and structure in
the composing line are read at
once, keeping the composed text node (its key and text): text a peer joins
into the line goes into nodes of its own, and a composing line joined into
the next keeps its node for the merged line. Remote reads skip Lexical's
transforms, so every list whose children a read changed, or whose items
gained or lost a nested list, is refreshed afterwards by running the list
class's own transforms with its siblings hidden (list numbering is computed
the same way on every peer, and a transform never merges two lists on one
peer only; in an editor that is not focused that refresh does not set the
DOM selection (SKIP_DOM_SELECTION_TAG), which would move the focus into it,
while a focused editor sets it as usual, so a refresh that reshapes the DOM
under the caret keeps the caret). After a remote change that refresh writes
a group's stored fields (`g:<field>`, `o`) to its items' markers only for
groups whose fields the change or the refresh changed (a list's text
format), and otherwise only fills in a marker that lacks them: a marker can
hold the fields as another client wrote them while a reader takes the
group's from its first item, and two clients that did not hold the same
items yet (so each took another first item) rewrote each other's marker
without end. A list whose own fields a remote change changes (its start)
is refreshed too (its items kept the old numbering on the reader); groups are told apart by their first declared key field
only (a list by its type, as Lexical merges lists), and a region read back
empty regroups its neighbours. Groups and wrapper items carry their
textFormat and textStyle (Lexical serializes them only while an element has
no text), and each wrapper reads the fields its own group recorded. A list
stored as a node inside a line (Lexical keeps blocks pasted into a list item
inside it) reads text left without a marker as one of its items; an element
that cannot be empty is shown only while its content is not, on every
reader, and a line of another type in it (a quote) reads as one of its items,
as `ListNode.splice` converts a block put into a list; two such lists of one
type that end up next to each other (added by two peers at once) stay two
lists until a local edit merges them. When the local tree joins
two wrapper items, the nested lists they hold are joined too, as a reader
builds them. A link's own textFormat is stored with its value. The character
diff of a line places a change at the caret only while the text after the
caret is unchanged (after a join the caret is before the new text). A marker
attribute a peer removed resets the field even when exportJSON hides it
(`checked` outside a check list). A NodeState value read before its key's
config was known is replaced by the known value when the node is written (a
reset comment is removed on every peer).
Recovery: a stored node a write deletes without giving it a new shared node
loses its mapping (no later write goes into a deleted node, where Yjs drops
what is inserted; this was the "cursor advanced past the end" exception on
paste). A write that throws part way is followed by a rewrite of every
container in a fresh transaction; a remote read that throws is followed by a
rebuild of the editor from the shared content (what every fresh reader
shows) in a fresh update; both are reported through `onWarn`. When the
self-check finds the editor different from the shared content after a
remote change (the shared content is right, the editor is not), those
containers are read again. (After a local write the editor is the intent,
so a mismatch there is only reported.)
A text diff with a run of equal characters places the change at the caret
(a space typed next to a space), and never splits a surrogate pair.
Normalization: the binding registers `NodeStructureExtension`'s
normalization, and `YCollabExtension` depends on the extension, so editors
without `@lexical/y` are unaffected. A local edit is normalized by Lexical
as it is made, so what a client writes is normalized. Content the
normalization would change can still reach a peer:
- written without it (an update with `skipTransforms`, `setEditorState`
with a state the editor did not build, an older client): its author
normalizes it right after, as part of the same edit (above); the update
that normalizes marks what the first one changed dirty, with the elements
holding it, and calls `INTERNAL_$normalizeNodeStructure` on them. Readers
show the update as written until the normalization arrives;
- produced by concurrent edits (text typed into a paragraph a peer
removed from a table cell, a row insert ‖ a column insert, two lists
added to one list item): every client shows it as stored, and the next
local edit that touches it normalizes it, as that client's edit.
No client normalizes another client's content on its own, so no two
clients write the same repair. 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: the holder's inline content split around it,
each part a line with the holder's marker, and the held line with its own
marker, so readers never see the nested shape and the author's
normalization only changes markers. The shape changes collaboration brings
are listed on the docs page ("What changes when you turn on collaboration",
with before/after diagrams): paragraphs in a quote or list item become lines
of one quote or item, other blocks inside inline content are lifted (split
around, link re-wrapped), a horizontal rule in a numbered list splits the
list and continues the numbering, inline content in a block holder is
wrapped in a paragraph, adjacent equal links and lists merge (also without
`LinkExtension`), and shadow roots, `OverflowNode` (stored nested inside its
line, never split around) and undeclared classes are left alone. A class
whose merge is decided by an overridable method keeps that method as the
authority: a `LinkNode` subclass that overrides `shouldMergeAdjacentLink`
is stored as a nested node, not as a format.
Storage reads only `getDeclaredNodeStructure` from `lexical` (its `derived`
set tells which fields are not stored), plus which nodes it treats as
inline content.
Lists: `@lexical/list`'s paths (JSON and HTML paste, `insertNodes`,
markdown import and shortcuts, indent and outdent, list commands and
deletions; 26 checked) never put a list directly in a list item's line
(`listitem[text, list]`): they nest lists in wrapper items, which are stored
as levels. Only direct API calls and writers outside the binding make that
shape; two such lists stay two lists until a local edit merges them (as
y-prosemirror and TipTap do), so the shared list merge is gone rather than
replaced by lifting.
Containers opt out of Yjs' remote formatting cleanup, which rescans every
type with formats after a remote format change (O(document) here): the
binding marks its containers as having no formats before Yjs decides. The
document's `cleanupFormatting` flag and the app's other types are untouched.
Servers on yrs before 0.28 read client ids as 32-bit numbers, while Yjs 14
draws 53-bit ones. With Yjs 14's default ids:
- a ywasm 0.23.5 relay 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;
- a real yrs 0.23 server rejects the reconnect ("the awareness update is
malformed"), and edits made offline are lost.
yrs/ywasm 0.28.0 is fine. Opt-in compatibility: `clientIDRange: 'uint32'`
(binding and extension) keeps the document's client id, and the ids the
binding derives from content, in 32 bits, including when Yjs draws a new
one. The default, `'uint53'`, leaves Yjs 14's ids unchanged. The binding
does not own the awareness, which takes the document's client id when it is
created; the docs tell apps to give the document a 32-bit id before
creating the awareness and provider. With 32-bit ids, a yrs 0.23 server
converges, including offline edits, reconnects and late joiners.
Old clients: the new root name and the layout version gate stay (a newer
layout opens read only). Clients of the Yjs 13 bindings never read or write
this root, so they cannot change a `@lexical/y` document's content and
servers need no check of their own.
Undo: Yjs 14 UndoManager on the root, tracking only this binding's writes;
`undo()` and `redo()` do nothing while the binding is not active (they
wrote into a document the client had gone read only on), and going read
only clears the history, so the `UndoManager` itself writes nothing. A
container the undone change inserted that holds another client's content is
kept whole (its fields and own content too), unless the undo also restores
a container of the same type (the change was a move: keeping the copy
would duplicate it).
Cursors: `getCursor()` / `$resolveCursor()` (relative positions on items;
no provider wiring or rendering).
`@y/y` internals used (all in rc.29; a bump must re-run the cursor
equivalence test): `new Item(...)`, `item.integrate`, `getItemCleanStart`,
`createID`, `Item.left/right/origin/rightOrigin/parent/content/deleted/
countable/length`, `YNode._start`, `_item`, `_map`,
`_searchMarker`, `_hasFormatting`, the `beforeObserverCalls` event,
`doc.store.getItem/getClock/clients`, `findIndexSS`, `iterateStructsByIdSet`,
`Transaction.insertSet/deleteSet` (and, in the tests only, `decodeUpdate`
and `findRootTypeKey`).
Supported: split, join, partial joins, heading/quote/paragraph, list type,
indent/outdent, Enter in list items, checked state, alignment and NodeState
of lines, links and other inline formats (incl. property changes and spans
across line breaks), text formats, comments as NodeState, tables and any
nested containers (collapsible-like container > title + content, cell >
collapsible, box > box), block and inline decorators, inline elements
(MarkNode) with nested content, undo/redo, cursors, local selection across
remote edits.
Known limits:
- A move is a delete and a reinsert: text a peer types into a moved line
lands in its old neighbour. The cheaper side is rewritten: a long move
rewrites the moved block, not every block it passed; in a swap the smaller
block is re-created (a collapsible dragged past a box keeps a peer's
typing inside it); between equal blocks the moved one (Lexical's record of
explicit moves, `_recordNodeMoves`). A block a peer moves into a container
that another peer removes at the same time is removed with it (delete
wins). When a peer removes a range and undoes the removal while another
moves a block out of that range, the undo restores the block next to the
moved copy, so it shows twice (Yjs undo restores deleted items as new
ones).
- Lexical restructures written as moves lose a peer's concurrent typing in
the moved paragraph, and two peers making the same restructure at once
both write it, so its content shows twice: a list created from a paragraph
inside a container that is not a shadow root (a box), indenting, unlisting
or pasting list items that hold blocks, a normalization (a merge, a lift)
two clients make from different states. Two peers pulling the same text
across a container edge (range deletes from a list item into a
collapsible title) both copy it.
- Shapes concurrent edits leave are shown as stored until a local edit
touches them: a table whose rows end up with different lengths (row insert
‖ column insert) 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. Two lists in one list item's line (only direct API
calls and outside writers make the shape) stay two lists until an edit in
the second merges them, written as a move.
- Content written without Lexical's normalization is shown as written on
other clients until its author's normalization arrives (right after the
write); an author that goes offline in between leaves it unnormalized until
someone edits there. A Lexical command used on such a shape meanwhile can
fail: Shift+Enter in a list item that holds only a block decorator throws
in core's `insertNodes`.
- A list type change racing a new item in that list (Enter in it) splits the
list: the new item keeps the old type, in a list of its own between the two
halves (`@lexical/yjs` keeps one list).
- A list held by a paragraph (written 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).
- An update applied with `skipTransforms` waits for its commit like any
other Lexical update: a remote change the provider applies in the same
task before it commits is integrated first, and the update is written
after it.
- Properties a class keeps outside its `$config()` schema and NodeState are
not synced; such classes are stored as nodes with a warning naming the
properties (Lexical itself drops them when it clones the node).
- 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 (a state declared with `arraySetValue(...)`, which
MarkStateExtension uses for its mark ids) is stored as one value per text
run in this PR, not one entry per member: two peers changing the set of
the same text at once (two comments on the same words) keep one writer's
set (converged, no error). Per-member storage is #9439, stacked on this PR,
to land 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.
- Text typed into the last block of a container while a peer removes that
block is kept as a line without a marker (shown as a paragraph). Other
edits in the container leave it so; two clients typing into it at once
each give it a marker, which splits it in two (one part can be empty).
- Slots are not synchronized; a link's fields merge as a whole (last
writer wins).
- Yjs format semantics: bold ‖ bold on adjacent ranges of one line can leave
part unformatted (the same on Yjs 13).
- A join ‖ removal of the joined line also joins the next line (nothing
deleted comes back); unwrapping a container is a removal and a
reinsertion of its lines, so text a peer types inside it at the same time
is lost, as is text typed inside a container a peer removed (delete
wins).
- Two clients initializing with different content at once both keep their
content (converged). Content with random values counts as different, and
so does initializing a root that held content before (written under each
client's own id): seed new documents in one place (on the server), or
give the initial blocks fixed ids.
- Undo never deletes a container another client has put content in (it is
kept whole).
- 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 (positional ids); clients holding different
concurrent edits give it different ids, which converge on one. An update
another listener queues in the same listener phase as that 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 node whose `isInline()` changes 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).
- Several edits to one line in a single update are written as one replace
(a peer's caret inside it moves to the edge).
- Structural edits in a large list cost time proportional to the list on
both sides (regrouping and renumbering).
- Relies on the @y/y internals listed above.
- Version gate: the highest `lexical-y:<n>` the root records must be at most
`LAYOUT_VERSION`, and every `lexical-y:` attribute an integer from 1 set to
`true`; 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; use the opt-in
32-bit range for them, and create the awareness from that document.
Known open issues (from randomized runs; see Test plan):
- An update made between a follow-up whose change was not written and the
read that undoes it in the editor (an app's update queued from a listener
in the same task) is written against the editor that still shows that
change. With `skipTransforms` writes, block ids and such an app listener,
106 of 500 randomized sessions rewrote the document after "cursor
advanced past the end", and 1 ended with a client different from a fresh
reader. Without `skipTransforms` writes, none.
- Block moves: with moves in the randomized scripts, @lexical/y loses or
duplicates more than v2 on 6 of 1,000 seeds (the same 6 as on the previous revision; 0 of 200 with gc), all in the move limits
above.
- Self-check: with the self-check on, a remote change can leave the editor
briefly different from the shared content (two adjacent equal lists the
incremental reader has not regrouped yet); the binding then reads those
containers again and reports a `'@lexical/y/self-check'` warning
(none of the 2,000 randomized normalization sessions in Test plan, with
or without block ids; 4 of 2,000 property sessions with block ids, see Test plan). With it off (the default), sessions end
with every client equal to a fresh reader.
- NodeState keys of a node keep the order of the author's local history in
its own editor (values equal; other clients read them sorted).
- Not a binding issue: `$toggleLink(null)` on a range that ends at the edge
of a link's text throws in `$splitLinkAtSelection` (empty
`extractedChildren`), in any editor on main; the fuzz no longer generates
it.
## Test plan
### Before
The tests this revision adds or changes, run on the previous revision
(the new files copied in). Each file's failing tests:
```
$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/<file>
ListenerUpdates.test.ts Tests 10 failed | 1 passed (11)
× an update an app's listener queues after a list change is written
(block ids: false) / (block ids: true)
× an update an app's listener queues when a composition ends is written,
with the remote text held back until then
× an overflow wrapping queued from a listener after a list change is written
× an update an app's listener queues is written when a remote change to its
line is applied in the same task
× with repairTransforms: true, a block written inside a paragraph without the
normalization is shown once (block ids on the author / on the receiver only)
× with repairTransforms: true, a link written directly in the root without the
normalization is wrapped once
× a remote change read while the editor still shows a change the binding did
not write is read on the document
× a transform registered while the document is open does not insert: the
editor reads the document again
BindingState.test.ts Tests 7 failed | 1 passed (8)
× a new editor bound to a document an editor of the same client wrote keeps
its text nodes apart
× a saved EditorState restored with setEditorState is written whole (from
another editor) / (from the same editor)
× a read that recovers keeps the ids lines without a marker derive
× a read that recovers keeps the text nodes it writes next apart from those it read
× a line of a type the editor does not register makes the binding read only
(inside a list stored as a node)
× removing the layout record while the root is empty makes the binding read only
ShownAsStored.test.ts Tests 1 failed | 5 passed (6)
× a transform registered after the document was read does not change what
was read, and an edit made right after it is written
BlockIds.test.ts Tests 1 failed | 14 passed (15)
× the update that names the blocks a remote change brings stays out of the
client's undo history
ConcurrentShapes.test.ts Tests 2 failed | 11 passed (13)
× list type ‖ list type / Enter ‖ Enter in its container leaves it a line
without a marker
Composition.test.ts Tests 61 passed (61)
```
The one test of `ListenerUpdates.test.ts` that passes there (a transform
registered while the document is open removes a paragraph, and the removal
is written) pins the rule that a follow-up may delete: the previous revision
wrote that update as an edit. The new `Composition.test.ts` case (a
composition that starts before the last one showed what it held back) pins
a case of this revision's own waiting: the previous revision showed held-back
text in the same commit chain, so it passes there.
Randomized runs that found the problems this revision fixes (and, in the
playground, a client that loaded a document holding a ragged table padded it
on its own screen, writing nothing):
```
# the app-listener harness below, 500 sessions, no block ids, previous revision
a write failed and the document was rewritten: 409 sessions; diverged: 57
(an app's update committed together with the binding's list refresh was refused)
# the same, during this revision, before local updates committed at once
"cursor advanced past the end" out of the session: 17 of 500;
with skipTransforms and the self-check on, local self-check warnings: 117 of 300
(an update queued from a listener, written after a remote change applied in the same task)
```
### After
```
$ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs packages/lexical-extension
Test Files 82 passed | 1 skipped (83)
Tests 2940 passed | 4 expected fail | 3 skipped (2947)
```
Long runs (the table plugin registered in the fuzz):
```
# STORAGE_PROP_SEEDS=1000 STORAGE_FUZZ_SEEDS=500 SHAPE_FUZZ_SEEDS=600 NORMALIZE_FUZZ_SEEDS=2000
# DerivedStorage, ConcurrentShapesFuzz, NormalizationConvergence, Races
Test Files 4 passed (4)
Tests 4605 passed (4605)
normalization fuzz: {"duplicated":[],"healed":[],"seeds":2000}
# FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500: Fuzz
Tests 100 passed (100)
# LEXICAL_Y_BLOCK_ID=1, the same seeds: Fuzz, Races, NormalizationConvergence
Test Files 3 passed (3)
Tests 3194 passed (3194)
normalization fuzz: {"duplicated":[],"healed":[],"seeds":2000}
```
Differential (`FUZZ_DIFF=1`, the same scripts on this binding and on
`@lexical/yjs`'s v2 layout):
```
# FUZZ_NO_MOVE=1, 2,000 seeds; with FUZZ_GC=1, 500 seeds
absolute failures 0, worse than v2 0 (both)
# with moves, 1,000 seeds; with FUZZ_GC=1, 200 seeds
worse than v2: seeds 272, 295, 394, 410 (dup), 524, 752 (loss); with gc: 0
```
Randomized property run (2-4 `YCollabExtension` editors,
`MarkStateExtension` in half the sessions, gc in 20%, partial delivery,
ordinary edits plus `skipTransforms` writes, `registerTablePlugin`; every
session checks convergence, a fresh reader, Lexical's normalization as an
oracle, block id uniqueness, the tokens typed and a runaway guard), 2,000
sessions per lane, self-check off (the default), this revision against the
previous one:
```
block ids on block ids off no skipTransforms
new prev new prev new prev
diverged 0 0 0 0 0 0
fresh-reader mismatch 0 0 0 0 0 0
duplicate / missing block ids 0 / 0 0 / 0 n/a n/a n/a n/a
runaway growth, errors 0 0 0 0 0 0
an op threw 2 2 2 2 0 0
token shown twice 115 116 92 95 1 1
token lost: a concurrent removal 571 574 568 570 577 576
token lost: unexplained 10 10 9 9 4 4
token lost: the author's outdent 23 23 24 24 2 2
ragged table at the end 251 249 250 250 294 295
table with an all-empty column 543 543 537 536 576 576
left unnormalized (shown as stored) 28 30 30 31 1 1
```
With the self-check on (block ids on): 4 sessions with a self-check
warning, against 11 (a line holding lines inside a table cell, compared
before its author's normalization ran, was reported). "An op threw" is a
line break inserted into a list item holding only a block decorator, which
another client shows until the author's normalization arrives (see Known
limits). "Lost: a concurrent removal" is delete wins; "lost: unexplained"
and "lost: the author's outdent" (a token the author's own outdent removes
from its editor, before any sync) are the same on both revisions. "Ragged"
and "left unnormalized" are the shapes concurrent edits leave, shown as
stored by design. A table with an all-empty column counts inserted empty
columns too.
A second randomized harness drives the editors as an app does, with an
update listener that queues an edit of its own after 30% of the local
commits (as the character limit and other plugins do), and checks the same
properties (a payload check across peers and relays included):
```
no block ids block ids block ids, mixed, skipTransforms,
skipTransforms self-check on
sessions 500 500 500 300
new prev new prev new prev new prev
a write failed, document rewritten 0 409 0 392 106 396 37 271
error reaching onError 0 409 0 391 3 382 0 260
diverged / fresh-reader mismatch 0/0 57/57 0/0 72/72 1/1 100/100 0/0 2/2
exception out of the session 0 32 0 51 0 72 0 12
follow-up change refused (dev) 0 443 0 431 399 420 126 283
self-check warning, local/remote off off off off off off 2/0 282/231
token shown twice 0 2 1 2 27 18 14 16
ragged table at the end 215 195 220 183 237 206 126 117
left unnormalized 1 1 2 3 14 7 5 7
```
The lanes without `skipTransforms` are clean. With `skipTransforms` writes
and block ids, an app update Lexical commits together with
`BlockIdExtension`'s naming update counts as part of that update (see
Known limits): its inserts are not written and the editor reads them back.
The rewrites ("cursor advanced past the end") come from an update made
before that read, which is written against the editor that still shows
the refused change; the binding rewrites the document and every client
converges, except 1 session of 500. This is open.
Every scenario the reviews of the previous revision reported is one of the
tests listed under Before.
On this commit: tsc (the project, the tests and the scripts), flow (0
errors), eslint and prettier pass; `build-prod`, `build-types` and the
website build (with its link check) succeed, and the tree-shaking audit of
the built packages passes (284 of 284); core (`lexical` and
`lexical-extension`, `src` and `flow`) adds no collaboration vocabulary
compared with main (`14aea377a`). `pnpm run test-unit` on a clean checkout: 12,540 tests (12,536
passed, 4 skipped; the website build adds 36 audits of its generated pages,
12,576 with them), against 10,072 (10,070 passed, 2 skipped) on main;
comparing the two reports, no test of main fails, is missing or changed.
Performance was not measured again on this revision: the figures above (a
keystroke in a 200,000-character paragraph, the size of a 10,000-edit
session) are the previous revision's. This revision commits local updates
at once while the binding writes, and makes the binding's own updates wait
for a microtask; both are open for measurement.
Not exercised in this revision: real browsers (the playground end-to-end
run that found the ragged-table load divergence was not re-run here), a real
yrs server process, other Yjs 14 providers than `@y/websocket`, and mobile
browsers.
…ed since #9353 ## Description The changesets in this PR covered main up to #9353. Since then, 27 PRs that change a published package's shipped code have merged without one, so the v0.53.0 release would list them only under "All changes". This adds a changeset for each, with a `PR:` line and the author's handle: - `[breaking]`: #9478 (`@lexical/mdast` table alignment moves out of the `mdastTableAlign` NodeState) and #9329 (`reconcileObservedMutation`, `@internal`), both with `Migration:` and `Detect:`. - `[feature]`: #9452, #9421, #9380 (experimental), #9360, #9365. - `[perf]`: #9349. - `[fix]`: the remaining 19. #9396, #9392, #9270 and #9360 carry `Verify:` because they change observable output. Website, playground, devtools, CI and internal lint changes need none. ## Test plan ### Before ``` $ git log --format=%s fd661f0..origin/main # merged since this PR's base (27 PRs touching published packages' src/flow, none with a changeset) ``` ### After ``` $ pnpm run check-changesets Changeset check passed: 54 pending changeset(s) valid. $ pnpm run changelog ## v0.53.0 (2026-10-27) ### Breaking changes - **lexical, @lexical/clipboard, @lexical/selection, @lexical/table**: Let mouse drags select across inline decorators; ... (#9329) - **@lexical/mdast**: `MdastTableExtension` reads and writes GFM tables, ... (#9478) - **@lexical/code-core, ...**: Remove the extensions deprecated in v0.52.0 and earlier (#9316) ### Behavior changes ... ```
…hangeset at the @lexical/html/BlockIdHTMLExtension entry point ## Description #9474 moved `BlockIdHTMLExtension` out of the `@lexical/html` barrel into its own entry point. Both changes are unreleased, so v0.53.0 users only ever see the new import path: this updates the #9421 changeset to name it rather than adding a breaking entry. ## Test plan ### After ``` $ pnpm run check-changesets Changeset check passed: 55 pending changeset(s) valid. ```
…website][lexical-y][lexical-yjs] Feature: @lexical/y, an experimental Yjs 14 collaboration binding
## Description
A new experimental package, `@lexical/y`: a collaboration binding for
Lexical on Yjs 14 (`@y/y`). `@lexical/yjs` (Yjs 13) is unchanged (its
source; one test file of composition traces is added, see Core): Yjs 14 is a
different npm package with a different API, so a Yjs 14 binding cannot
replace it in place, and an application uses one or the other.
Try it: [jot.rovira.sh](https://jot.rovira.sh), a full-page note anyone
with the link can edit at the same time, built on `@lexical/y` (source:
[zurfyx/jot](https://github.com/zurfyx/jot)).
Current behavior: the only binding, `@lexical/yjs`, stores one shared
element per Lexical node. Splitting, joining, retyping or re-indenting a
paragraph, and linking or unlinking text, are written as a delete and a
re-insert, so a collaborator's concurrent typing there can be lost or
misplaced, and every Enter or heading change rewrites elements.
New behavior: `@lexical/y` stores a paragraph, heading, quote or list item
as its characters followed by a marker, a list as the items it groups and a
link as a format over its characters. The storage is derived from general
facts the 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 line classes 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.
These edits then keep the characters and merge with concurrent typing.
Built on the `$config` keys, their declarations on Lexical's nodes and the
opt-in `NodeStructureExtension` (#9452, on main); the binding registers that
normalization, so each client writes its own edits in the normalized form
the declarations describe, and shows a remote change as it is stored (the
binding writes nothing for a remote change or when a document is opened,
except `BlockIdExtension`'s renaming of blocks inside named slots that
repeat an id, and, rarely, of a quote nested in a quote that holds
paragraphs after a deep copy (see Known open issues); every update the
binding makes itself
(its reads and its refresh) is tagged `COLLABORATION_TAG`, so an app
listener that edits on every change skips those; the update Lexical makes
to run a newly registered transform, which the binding runs on its own,
keeps Lexical's tags).
There are no collab-specific keys
in core and no binding-level storage overrides.
Also new here: `describeStorage(editor, binding?)` (the kind per type), and a
per-document pin: the first write of a type records its kind and identity
fields on the root (`k:<type>`, outside the undo history); a later client
whose class derives another kind uses the recorded kind when it can store
the class that way, and opens read only otherwise. List identity is the
declared `mergeAdjacent.by` fields only (`listType`), so NodeState such as a
block id never splits a list.
Entries (all `@experimental`):
- `@lexical/y`: `YBinding` (its `editor`, `doc`, `root`, `status`, `pins`
and `undoManager` are read-only getters), `YCollabExtension` (binding,
collaborative undo, `status` signal; conflicts with the history
extensions), `describeStorage`, `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and
the types `YBindingOptions`, `YBindingStatus`, `YCursor`, `YCollabConfig`,
`ClientIDRange`, `StorageKind`, the warning code constants below with
their union type `YWarningCode`, the `YWarning` union with a `data` type
per code, and `isYWarning`. No React, no DOM requirement.
- `lexical`: `LexicalWarning` (`extends Error`, `readonly code: string`,
`readonly data?`), a generic class with no codes of its own, and the
update tag `DEFER_COMPOSITION_MERGE_TAG` (see Core). The node structure
normalization gains one internal hook, `INTERNAL_$liftsFromStructure`,
beside its merge and split hooks (see Lists), and the editor state
internal records of text splits and text edits (see Core).
- `@lexical/list`: no new API. Where `NodeStructureExtension` enforces
declared structure (opt-in), a list item that holds a nested list holds
nothing else (lifted only out of an item an update creates or changes);
the outdent of a wrapper item's only or middle item, which deleted what
the wrapper holds beside its nested list, keeps it, in reading order, in
every editor (see Lists).
- `@lexical/extension`: one new `BlockIdExtension` option,
`repairTransforms` (default `true`, behaviour unchanged; see Block ids).
- The www entry stub `packages/lexical-y/LexicalY.js`, as every other
single-entry package has.
- No server entry: old clients write other roots (see "Old clients"), so a
server needs no API of its own; the two constants a server may want
(`DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`) come from the main entry.
- Seeding a document on a server is `seedYState` in `@lexical/y/headless`
(#9437, stacked on this); the internal one-off writer is not exported.
Warnings: `lexical` exports `LexicalWarning` (`extends Error`, `readonly
code`, `readonly data?`), which packages pass to the editor's existing
`onWarn` (its `(error: Error) => void` signature is unchanged) for warn-level
conditions with a stable, package-namespaced code (`code` is a `string`;
core knows no codes). Documented under "Errors and warnings" in Defining
Extensions, with neutral example codes. `@lexical/y` has no `onWarn` option
of its own: every
warning goes to the editor's `onWarn` as a `LexicalWarning`, with an exported
constant per code: `UNSUPPORTED_LAYOUT_WARNING`
(`'@lexical/y/unsupported-layout'`), `UNKNOWN_NODE_TYPES_WARNING` and
`STORAGE_MISMATCH_WARNING` (each makes the binding read only),
`SELF_CHECK_WARNING`, `RECOVERED_READ_WARNING`, `RECOVERED_WRITE_WARNING`,
`NESTED_FALLBACK_WARNING` (a class stored nested, for example a link subclass
that overrides `shouldMergeAdjacentLink`), `UNSYNCED_VALUE_WARNING`,
`UNSUPPORTED_SLOTS_WARNING` (a named slot the document cannot store: the
change is not written and the binding is read only) and
`UNSUPPORTED_CONFIG_WARNING` (`BlockIdExtension` with `repairTransforms:
true`: nothing is written and the binding is read only), and their union,
the `YWarningCode` type. Warnings are typed: `isYWarning(error)` narrows an
`onWarn` argument to `YWarning`, a union in which `code` decides the type of
`data`, and every `data` has a `reason` with the fields of that case (a
layout that is `'newer'` carries the version `found` and the newest
`supported`; `'malformed'` the record's `key` and value; `'legacy-roots'`
the `roots`), so an app renders its own read-only banner from the fields,
and a `switch` whose `default` assigns the warning to `never` fails to
compile when a release adds a code. Messages are short notes for developers
and name no package. Codes are public API: never renamed or reused, only
added. A warning is delivered once a change has been applied in full, never
from inside a Yjs observer or transaction, and a handler that throws does
not affect syncing (its error is rethrown in a microtask). The class and
value warnings (`NESTED_FALLBACK_WARNING`, `UNSYNCED_VALUE_WARNING`) are
found once per process and reported once per binding (a class's only to
editors that register it), so a second editor gets them too.
`YBindingOptions.onStatus` is called the same way: once the binding's work
is done and Yjs is idle, never inside a Yjs observer. Without an `onWarn`,
Lexical's default applies (it throws in development, outside Yjs, and
`console.warn`s in production).
Docs: a new page, Collaboration > Yjs 14 (`@lexical/y`): when to use it
rather than `@lexical/yjs`, install, setup with `YCollabExtension` and a
provider, the options, warnings (the codes, their typed `data` and
reasons, a read-only banner of an app's own, delivery and the default
handler), how content is stored (diagrams of a paragraph and a
heading, a nested list, a link and a table next to the sequence that stores
them), the wire format (a diagram of layout 1: a container's sequence of
characters, `¶` markers with their attributes, format ranges and nested
nodes, and the root's layout record and storage pins, with the stored names
checked against a dumped document and a link to the README's
specification), what changes when collaboration is on (why, a before/after diagram per
rule: a block split around, a heading in a link, paragraphs in a quote
becoming one quote with line breaks, a horizontal rule splitting a numbered
list with its numbering continued, adjacent equal links; and what it means for an
app), edits made by code (agents and tools: edit text in place, apply an
edit to the state it was computed from and merge), servers (old clients,
yrs before 0.28), limits, and upgrading from
`@lexical/yjs` (no in-place migration yet). `LexicalWarning` is documented
under "Errors and warnings" in Defining Extensions. The package README is
short (install, a minimal example, links to the pages and the API reference,
how to run the long fuzz and replay a seed) and holds the frozen wire
format. `DEFER_COMPOSITION_MERGE_TAG` is listed under
Updates > Common Update Tags. A scripted session of 10,000 edits (fixed
peer ids, gc off) grows the document by about 230 KB (230,394 bytes;
217,143 before the word snap of an earlier revision), against 2.8 MB with
the default `@lexical/yjs` layout (a historical comparison, not measured
again).
`@y/y` is a peer and dev dependency pinned exactly to 14.0.0-rc.29 (npm's
`latest` tag points at an older release candidate). rc.29 is past the
repository's 7-day minimum release age; the lockfile resolves `@y/y@14.0.0-rc.29`
(integrity `sha512-A4W9Bnrf…`) and nothing else. The cursor equivalence test
passes on it.
Core (`lexical`): four generic pieces, and nothing about collaboration
(no collaboration vocabulary, API or behaviour; `@lexical/y` keeps its own
codes and checks):
- `LexicalWarning` (above).
- A new update tag, `DEFER_COMPOSITION_MERGE_TAG` (`'defer-composition-merge'`,
exported from `lexical` next to the other tags, documented in Updates >
Common Update Tags). While an IME composition is active, an update carrying
it does not merge text into or out of the composed text node: a merge
rewrites the composed DOM text node, and the browser's composition range
would take in the merged text. Once such a merge was held back, later steps
of the same composition hold it back too (a private `_compositionMergeHeld`
key, cleared whenever the composition key changes); the nodes merge when
the composition ends. It is for any update that changes text next to a
composition without user input (changes applied from another source);
`@lexical/y` adds it to the updates that apply a remote change. Without it
normalization ignores the composition, so every other update, including
one tagged `COLLABORATION_TAG` or `SKIP_COLLAB_TAG`, merges exactly as
before: `LexicalNormalizationComposition.test.ts` runs 112 scenarios (7
operations next to the composed node × 8 tags, including
`COLLABORATION_TAG`, × with and without `skipTransforms`) composing and not
composing and requires identical JSON and node identities, and
`SyncCompositionUnchanged.test.ts` (`@lexical/yjs`) drives v1 and v2
bindings (8 scenarios × 2 client id orders each) with a composition in
progress and compares every step with traces recorded on main. A hold
keyed on `COLLABORATION_TAG`, as an earlier revision of this PR had, fails
2 of them (v1). Checked that `@lexical/y` still needs it: without the tag,
6 of the 21 tests in its main composition block fail (a peer joins the
lines while composing).
- An internal record of text splits, `EditorState#_splitNodes`
(`@internal`, beside `_movedNodes`, and kept like it, by the previous
node map): while an editor records text edits (`_recordTextEdits`, an
`@internal` flag of its own, off by default, which only `@lexical/y` sets
while it is bound), `TextNode#splitText` records, for each new part, the
node it was split from and where in that node's text it starts (a part
of a part counts from the node first cut). Nothing is recorded otherwise,
and nothing reads it but `@lexical/y`, which keeps the characters of a
part split off a node an update deletes (see the range deletes through
`extract()` below). `LexicalTextSplitRecord.test.ts` covers it.
- An internal record of text edits, `EditorState#_textEdits` (`@internal`,
kept like `_splitNodes`): while an editor records text edits, every change of
a text node's text, in order, with the node's text before it:
`TextNode#spliceText` with its offset, what it deleted and what it
inserted (the selection's text insertion goes through it); the
selection's text removal, which still calls `setTextContent` (so a
subclass's override runs) and says which splice it makes; a split, with
where each part starts; a merge; the text Lexical types into a node it
makes for it (typing in another format); a node the selection removes
with what it holds (a range that covers it, typing over a token), as
deleted; any other `setTextContent`, with the node's text before and
after; and every node inserted into or removed from an element's
children, where (its parent and its siblings there, and a text node's
text then), so that a node swapped for another (a transform's `replace`,
`$wrapNodeInElement`, an insert and a remove) is seen where it was: the
three places that link and unlink children (`$insertNodeBetween`,
`$detachNode`, `$detachSiblingRange`) push the entry. Lexical makes the
same calls with and without it, and an editor that does not record moves
pays one flag check per call (`LexicalTextEditRecord.test.ts` compares the states; a typing
and editing bench shows no difference from the base tree). Nothing reads
it but `@lexical/y` (see the exact text edits below).
Block ids: `@lexical/y` works with `BlockIdExtension` (#9421, on main),
which gives every new block an id stored as NodeState:
- The blocks a remote change brings without a unique id are named by the
reader, and nothing is written. Every block shows the first id of its own
list that no block before it (in document order) shows: the id it stores,
then the id derived from its own Yjs identity (`y`, a client, `_`, a
clock, in base 36: a line's marker, a line without a marker's first
character (with `_l` when that is a node stored in the line, which
derives its own id from it), and so the first character of text a read
shows in a paragraph of its own inside a quote that holds paragraphs,
a stored node's item, in a container or
inside a line (a list stored as a node, inside a line: its item, with
`_g`); another list's first item, with `_g` and its level
below the top, `_g1`, `_g2`; a wrapper item's first nested item,
with `_w`, `_w1`, `_w2`, so lists and wrappers nested at the start of a
list differ), then that id followed by `_d`s. So a block that stores no
id, or an id an earlier block also stores or shows (a copy of the JSON of
a block as a reader showed it, whatever id it showed), shows its derived
id; a block that derives an id competes for it with the blocks that store
it whether or not it stores one itself. Each block's id depends only on
blocks before it, so every client with `BlockIdExtension` and every
fresh reader with the same configuration shows the same (a client
settles the ids each change touched: those of the blocks it added,
removed, moved or gave another id); the author's next edit of that block
stores it. `BlockIdExtension` then
has nothing to name after a read (except blocks inside named slots,
below, and the rare nested quote in Known open issues); its
naming update, when one still follows a commit, is a follow-up, which may
set attributes or delete, never insert (see Write path). Clients without
`BlockIdExtension` show only stored ids. Mixed configurations (some
clients that write without `BlockIdExtension`, or with another
`$isIdentifiedBlock`) are supported but discouraged: each client shows
what a fresh reader of its own configuration shows, and the document is
the same for all, but the ids differ between configurations. A client
without the extension shows no id on a block written without one (where
the others show its derived id), keeps the id of a block it copies (two
blocks then store one id: it shows it twice, the others on the first in
document order and a derived id on the second), and shows an id stored on
a list that is not an identified block (a list moved or pasted into a
table cell), where the others show none. Any other block that is not an
identified block where it sits (a box or table pasted into a table cell)
keeps its stored id on every client, so a copy pasted there shows the
original's id on both blocks for every configuration (documented in
Block IDs and y.md). `BlockIdExtension`
gains an option, `repairTransforms` (default `true`, unchanged): with
`false`, the follow-up sets the ids without running transforms and changes
nothing else. `YCollabExtension` sets it through a peer dependency
(`declarePeerDependency('@lexical/extension/BlockId',
{repairTransforms: false})`), so an app that adds both extensions gets it.
With `true` (an editor that uses `YBinding` directly without setting it,
or an app that sets it, which overrides `YCollabExtension`), the naming
update would also run the editor's transforms over what a remote change
brought, and what they derive (the start of a list they split) can differ
between clients: in the previous revision 3 of 100 randomized
normalization sessions ended with clients showing different content. So
the binding fails closed: with `true` it writes nothing (the initial
content neither), is read only, and warns `'@lexical/y/unsupported-config'`
(`UNSUPPORTED_CONFIG_WARNING`, `data: {reason: 'repair-transforms',
options}`).
One other `BlockIdExtension` change, in every editor: a copy of a block
created where it is not an identified block (a list pasted into a nested
list item, where it nests) keeps no id, so the block it was copied from
stays the only holder of its id (before, the nested copy kept it). Its
existing tests are unchanged.
- A line that concurrent edits leave without its marker (text typed into a
paragraph a peer removed, read as a paragraph) has no stored id. Its
positional id would cover the whole document, so clients holding
different concurrent edits derived different ids, and with follow-ups
limited to attributes they could not converge. The reader derives it
instead, from Yjs identity: `y`, the client of the line's first character's
item, `_` and that item's clock (base 36), with `_l` when that item is a
node stored in the line (an inline node, or a block decorator written
without the normalization, which derives its own id from that item), set
as the block's
NodeState when `BlockIdExtension` is registered and the line is a block
it names. Every client and a fresh reader derive the same id from the
same document, whatever order they saw changes in; the edit that next
changes the line stores it with the marker it writes, so the id does not
change. An update that sets another id on the line writes it the same
way, as any change of the line's attributes.
No storage, no follow-up write; part of layout 1 (unreleased). A read
that recovers by rebuilding the editor keeps it.
- Initial content: two clients that initialize a new document with the same
content write the same bytes with `BlockIdExtension` too (both id orders,
with and without text, with a different `generateId` per client): the
extension names a document's first content positionally, so the ids are
the same before the content is hashed (see Data model). The hash covers
the exact bytes the client writes, with its own block id configuration,
which changes them (a nested list's id is stored where nested lists are
not identified blocks): two clients whose configurations differ write
their content twice, never different items under one id.
Changes in this revision (each with a regression test that fails on the
previous revision, unless noted):
- An app's own `blockId` NodeState works without `BlockIdExtension`: where
the editor has no `BlockIdExtension`, the binding never reads or sets
`blockIdState`, so a stored `blockId` key is NodeState like any other, on
lists (whose state their items carry) too. Before, the binding's
transform on lists and its read of a list's id used `@lexical/extension`'s
StateConfig whether or not the extension was registered; Lexical allows
one StateConfig per key on a node class, so an app with its own `blockId`
state (a production app's block id extension) threw `State key collision
"blockId"` on every update that read a list (`AppBlockIdState`: an
author, a peer and a fresh reader show the app's ids, nested lists
included, through edits of those lists; 2 new tests failed). Without the
extension, a nested list whose id equals its parent list's keeps it (the
writer, the reader and the transform no longer drop it): it is the app's
state.
- A shadow root inside a named slot holds its inline children in a
paragraph on the author too: the binding wraps them, as core's shadow
root transform does. The binding enforces node structure, which turns
that transform off, and the normalization starts from the root, so it
never reached a named slot. Before, the `> ` shortcut in a slot (a
production app's details body) left the author with text directly in a
shadow-root quote, where every reader shows a paragraph (the text is
stored as a line without a marker), and apps that read the tree threw
(`Children of root nodes must be elements or decorators`)
(`ShadowRootQuote`: the shortcut with an app transform, and a quote that
takes the paragraph's text while a peer types in it, in both id orders;
4 new tests failed).
- A block decorator in a quote that holds paragraphs (a shadow root)
stays a child of the quote on every reader, as on its author: a read
wraps only inline content there in a paragraph. Before, every
reader showed an image, or a component holding a named slot, inside a
paragraph of its own (`BlockDecoratorContainers`: widgets and a component
put into the root, a cell, a slot's body, a quote and a quote in a cell;
the 4 quote cases failed).
- A read keeps the selection valid while it moves nodes: a point in a text
node it reuses for shorter text goes to the node's end, and where Lexical
throws on a point that the read left invalid (detached in a subtree the
read took apart, gone, or past its node's end) when it removes or moves a
node, that point goes to the other one and the change runs again. The
selection put back afterwards still comes from relative positions;
putting it back never fails the read, and a read that fails clears the
selection, so that the update an undo or redo runs in still commits.
Before, select all over a block decorator, type, undo and redo failed
the redo's read (`$getTextNodeOffset: invalid offset 17 for size 2`), and
Enter over a backward range from a heading, undo and redo, failed it too
(`no common ancestor`, then `selection has been lost`): the editor was
rebuilt, showing text the redo had deleted until the rebuild ran, or the
redo changed nothing (`UndoSelection`: both cases, both undo paths, both
capture timeouts, and a cursor that cannot be put back; 7 new tests
failed).
- A custom text class's flat StateConfig survives the splits Lexical makes:
a line feed's line break gets all of the part's NodeState, flat keys
included, and a plain text node a split made from such a node (it keeps
the class's state configuration, so its JSON has the key flat, where a
plain text node read from JSON ignores it) has the key
stored as NodeState, which every reader keeps; its author reads the line
back, so it shows the same JSON. Before, the line break lost the value
everywhere, and the plain parts lost it on every reader (R11-B F-02;
`FlatTextState`: line feeds in normal, token and segmented nodes, and a
part split off by formatting; 10 new tests failed).
- Two mergeable text nodes that store the same attributes are one run on
the author once a composition between them ends, as on every reader: the
keystroke path leaves an edit whose text node now runs with the node next
to it to the general write, which reads the author back. Before, the edit
that ends the composition went through the keystroke path, which skipped
that check (R11-B F-03; `Composition`: equal object NodeState parsed
apart, both id orders; 2 new tests failed).
- Initialization puts a node selection back by the Yjs identity of its
nodes, never by position: a node's item, a line's marker, a text node's
first character, and for any other node (a list, a list item holding a
nested list, a link) the first of those inside it. The read shows a line
feed as a line break node, which moved the later nodes along, so a node
selection on an inline decorator after a raw line feed (a state set
whole) selected its neighbour, which Delete then removed; a selected node
inside a named slot was dropped (R11-B F-05 and F-01; `Init`: pristine
and used roots, a line feed at the end and in the middle, and a node in
a slot; 6 new tests failed). A selected list, nested list's item, link
or text node, also after a line feed, is kept, and Delete removes what
it removes without the binding (`InitNodeSelectionKinds`, 14 new tests,
which the previous revision passes by position, and which an identity
restore that took only nodes with an item of their own failed 10 of:
R12B-S1).
- After deleting block nodes, the writer diffs what follows from the formats
in effect where the diff starts. Before, deleting a block node and the
line after it took the formats in effect after the block node, so a
format opener that the lines after relied on (a stored run left across a
block node and a marker by concurrent edits: a comment over a callout)
looked redundant and was deleted: every reader lost the comment, or the
bold, on those lines, and the author kept it; where the deleted range
held a closer, a resolved comment came back over the rest of the
document. Replaying the 61 whole-block deletions captured in a soak's 6
sessions, 39 changed blocks the deletion never touched on readers
(comments lost or gained over 1 to 234 blocks, text turning bold or
italic or losing it, once text appearing in a paragraph); now none does,
on the author, a peer or a fresh reader (soak S3-6; `DeletedBlockFormats`:
2 new tests failed).
- Deleting a unit gives the unit after it the deleted unit's start
formats, as it now starts where the deleted one started, so every delete
and diff after deleted units starts from the formats in effect there: one
rule for every unit delete, which the diff above now uses too. Before, a
follow-up's delete (an app's deletion that Lexical merges into
BlockIdExtension's naming commit) of a block node and the line after it,
or its write of a line it emptied after a deleted block node, deleted a
format opener that the content after relied on: every reader lost the
bold there (R12B-C1; `DeletedBlockFormats`: the same deletions in a
follow-up, and a line emptied after the block node in an edit and in a
follow-up, 6 new tests failed; `NamingCommitDeletes`: the deletion merged
into the naming commit, and into an ordinary commit, 4 new tests
failed).
- A remote read maps a caret in a line without a marker that a block node
follows to that line. Before, a caret in text whose line a peer's undo
left without its marker, before a table, went to the end of the line
before, so the next keystrokes landed in another block (soak S3-5;
`RemovedLineCaret`: 1 new test failed, the paragraph control passed).
- The development self-check builds its scratch editor with
`LexicalBuilder` where the bound editor was built so: a node whose
constructor builds a nested editor with `NestedEditorExtension` (the
playground's image caption) threw there, so every self-checked write in a
document holding one warned (soak S3-1; `SelfCheckBuilder`: 1 new test
failed).
- The self-check compares a segment key only where the editor holds the
text in a node that keeps it (a token, segmented or unmergeable node, a
code highlight): a reader keeps a mergeable text node apart only by its
type, mode or detail. Before, a segment key opener that an undo put back
over later lines made 45 of 73 lines of a soak room warn `format k at 0`
on every write; that state now warns on 1 line (see Known open issues)
(`CodeHighlightSelfCheck`: 1 new test failed).
- A change that only touches formats or marks is written as format items,
never as a delete and a re-insert of the text it touches. Lexical's
normalization merges text that no longer differs from its neighbours
into the text node before it; the writer now finds such a merge exactly
(the node's own old text followed by the old texts of the nodes the
normalization merged into it, as the update's own record of them,
`normalizedNodes`, names them, the last one possibly cut where Lexical
split it; a node the update removed without merging it was deleted,
whatever its text), so every character keeps its item. Before, it gave the merged
text to that node whenever the node's own old text happened to end like
it, or when the merged node had been split first: resolving a comment
whose words were followed by a space and a formatted run (`…redanox
[redanux redapax redapex](c1) **redapix…**`), removing bold, italic,
code or a link there, or giving the start of a node the format of the
run before it, deleted the words and inserted them again (64 B against
14 B). Two clients resolving at once showed them twice, a word a peer
deleted meanwhile came back, and text a peer typed right after them
could move in front of them (soak S3-8, from agents' and people's
resolves; `FormatOnlyChanges`: comments, bold, italic, code and links,
added and removed, next to a bold, plain, link or code run, at the
start, middle and end of a line, and in a list item, a table cell, a
collapsible's title and an update that also adds a paragraph, alone and
while a peer makes the same change, deletes one of the words or types
after them; 118 of 576 new tests failed: removals next to a formatted
run in the middle of a line, in every one of those places, and the
first word of a node joining the run before it). A node deleted in the
same update whose text equals the text merged after it (`same ` deleted
and the next `same ` unformatted; `la ` | **`la `** | `la `, the bold one
deleted) is never taken for the merged one, so a peer's concurrent
delete of the merged text, or typing in front of it, stays where it was
made (R13B-C1, R13-A D1; `FormatOnlyChanges`: a run deleted next to an
equal run merged in the same update, by a format, a resolved comment, a
split and three runs, while a peer deletes or types at the start of the
merged run or deletes in the deleted one, both id orders, 10 of 48 new
tests failed; `EqualTextDeletes`: 2 of 6 new tests failed, the
deletions with the caret at the join, which took the first of two
equal removed texts). A range delete across text nodes that Lexical
then merges (`t6z ` | *`t7z `* | `t8z `, `t7z t8` deleted, `t6z ` and
`z ` merged; in a link too) is written as that delete only: the node
keeps a part its old text starts with, the first node merged into it a
part its old text ends with, and the nodes merged after that their
whole texts, where one split of the text fits, or, of several, the one
at the caret the delete leaves at the join. Before, it was written as a
replacement of the merged text, or deleted an equal run of another
node, so a peer's concurrent delete there came back and its typing
moved (soak S4-1: 214 of 600 random range deletes over 3 or 4 text
nodes were written wrong; `LinkMergeDeletes`: in a link and outside
one, equal and other letters, a peer deleting or typing, both id
orders, and those 600 deletes; 5 of 17 new tests failed).
- The same deletes made by app code through `extract()`, the extracted
nodes then removed with no caret left, are written as those deletes too
(`extract()` splits `t8z ` into `t8` and a new `z `, the app removes
`t7z ` and `t8`, and Lexical merges `z ` into `t6z `). With Lexical's
record of its splits (see Core), a part split off a node the update
deleted keeps that node's characters: merged into another node, after
the node's own kept prefix and before the whole texts of nodes merged
after it, or left on its own. Before, the part had no old text of its
own: the write deleted `t7z t8z ` and inserted `z `, or kept an equal
run of another node, and a peer's concurrent delete or typing there was
undone or moved (soak A4 S4-1 through `extract()`: 20 of 32 cases, 225
of 600 random deletes written wrong; `LinkMergeDeletes`: those cases, at
a link's and a line's end, and 600 random deletes through `extract()`;
21 of 33 new tests failed).
- The merge record spans every update a commit batches (two
`editor.update()` calls in one task, or a text transform that edits after
the normalization merged): a node merged in one update and deleted again
in a later one is still in it. The writer takes a split of a merged
node's text only at the caret a range delete leaves at the join, or,
without a caret, where the node's own old text does not explain what is
left, and takes the exact merge only when every node the record merged
into it is in its text. Before, `x ` | **`la `** unbolded and then `la `
deleted kept the deleted node's space and deleted `x `'s, and a delete
that let an equal `la ` merge in kept the deleted node's `la ` and
deleted the survivor (R14-A F1, data loss under a peer's concurrent edit,
from this revision's merge detection by Lexical's record;
`BatchedMergeDeletes`: 2 shapes, the delete by a caret range or node
edits, one commit or two, 4 peer edits, both id orders, and the same by
a text transform; 6 of 72 new tests failed on the previous revision, 24
with that merge detection before this fix).
- The paragraph a read shows around text that lands directly in a quote
that holds paragraphs (typed into a paragraph a collaborator moved into
the quote) gets the block id derived from that text's first character,
as a line without a marker does, settled with the other derived ids, so
`BlockIdExtension` has nothing to name there. Before, the reader gave
that paragraph no id; `BlockIdExtension` named it from each client's
document of the moment, and its naming update, a follow-up that changes
the quote, was not written: clients kept different ids that no one
stored, a fresh reader showed yet another, and the self-check warned on
every read (R12-A B1: 19 to 40 of 300 to 400 sessions per lane in its
lanes with such quotes). A quote in a table cell that comes to hold
paragraphs (no identified block there) now shows no id on a client that
reads that change in place, as on a fresh reader: a line read in place
decides whether it keeps its derived id once its new attributes are
applied (it kept the one it had as a quote that held text). And a
follow-up records no storage kinds: it inserts nothing, so it writes no
type for the first time, and a client that only applied a change wrote
`k:quote` before the record of the change's author arrived
(`ShadowRootQuoteIds`: two and three clients, the paragraph moved into
or replaced by the quote while a peer types, one derived id everywhere,
nothing written on apply, kept by the next local edit there; a stored
copy of that id before and after the quote; the cell's quote read in
place; 27 new tests failed).
- The re-read after a refused follow-up shows a quote that holds text
without a paragraph as a fresh read does. Before, the read took a line of
another container that the refused follow-up had moved into the quote
(the next root paragraph, put first in the quote) for the paragraph it
shows around that text; the line went back to the root, and the text was
gone from its author's editor for good while every peer and fresh reader
showed it (soak A4 S4-4; `QuoteRunReread`: the text before or after the
quote's paragraph, then nothing or an edit elsewhere, each comparing the
re-read with a fresh read; 4 of 4 new tests failed).
- After that race the typist's caret stays in the text it typed: a remote
read resolves a position in a line that holds blocks into the paragraph
that shows it, and a caret a read leaves on such a line goes into the
nearest block. Before, it landed on the quote after its last block, so
the next keystroke started a new paragraph (R12-A S1;
`ShadowRootQuoteIds`: both id orders, moved and replaced, typed into an
empty paragraph or into text, 8 new tests failed).
- A line feed in text set whole shows as a line break node on its author,
as on every reader. A state taken from another editor
(`setEditorState(other.getEditorState())`) marks only its root dirty and
runs only the root's transforms, so the author's normalization now takes
the text nodes Lexical did not mark dirty too; and initial content
written into a used root is read back in every container, a table
cell's included. Before, the author kept `a\nb` in one text node there
(R12-A N3; `AdoptedStateNewlines`: 10 shapes, initialized into a
pristine or used root, with and without a node selection, set from
another editor and parsed while bound; 12 of 60 new tests failed: every
shape set from another editor while bound, and the table cell
initialized into a used root).
- An undefined entry in an array property (a table's `colWidths` after a
column is inserted past the stored widths) is stored with `null` there,
which every reader parses as the class does (`TableNode`: `0`, as its
own JSON round trip gives); the author's normalization now gives its
node that value too, and writes it. Before, the author kept
`[92,92,null,null]` in its JSON against `[92,92,0,0]` on every reader,
for good (soak S3-10; `ColWidthHoles`: holes, and a column inserted past
the widths, alone and while a peer types in a cell; 4 new tests failed).
- Text left without a marker before a block node (a join while a
collaborator puts a widget between the two lines) survives an update
that deletes the block node and the line after it: that text is given a
marker in that write unless nothing followed it before the update
either, and a follow-up's delete of the line after the block node starts
after that text. A follow-up that deletes only the block node is not
written (readers would show that text joined to the next line, which
only a marker, an insert, keeps apart), and its author reads the
document again. Before, the edit was written from the container's start
and deleted the title and that text for every reader while the author
still showed them, and the follow-up deleted that text too (R13-A P1,
data loss; `ImplicitLineDeletes`: by either client, in an edit and in a
follow-up; 6 of 8 new tests failed).
- A line without a marker that a follow-up deletes after a block node it
also deletes is deleted from its own first item, right after the block
node's item: when no line around the block node has a marker (`Title`
[widget] ` XX`, which three clients' concurrent edits leave; or `Head` ¶
`before` [widget] `after`, in the root or a callout), there is no end
item before it to start from. Before, that delete started at the
container's start or after `Head`, and deleted `Title` or `before` too:
every reader and fresh reader showed an empty document, or lost
`before`, while the author kept it (soak A4 S4-3, data loss;
`NoMarkerDeletes`: three clients, each making the follow-up; a table and
a widget with no marker around them; the root and a callout, deleting
the widget with the line after it, before it, both or neither; in an
edit and in a follow-up; 16 of 26 new tests failed).
- A follow-up's change of the content of a line without a marker (left by
concurrent edits anywhere: after a block node at the end of a container,
before a widget, as the last line of a callout or a table cell) is not
written, and its author reads the document again: only a marker, an
insert, could keep the line as the author shows it. Before, emptying the
line, typing in it, deleting from it, or deleting the block node before
it and emptying it was neither written nor refused: the author showed
the change, every peer and fresh reader kept the old text, and no
warning said so (soak A4 S4-2; `ImplicitLineFollowUps`: a quote and a
widget before the line at the end of the root, a widget after it, in an
edit and in a follow-up; 10 of 30 new tests failed).
- A follow-up's change of a field that only a structure write (an insert)
could store is read again: the text format or style of an element that
is not a line (a wrapper list item, a nested list, a callout), which a
follow-up does not write, and the format, indent or direction of a line
without a marker or of the paragraph a read shows around text left
directly in a quote, which keep them nowhere (a read now gives that
paragraph what a fresh read does). Before, those were neither written
nor read again: the author kept them while every reader showed the
stored ones (soak A4 S4-5; `FollowUpTextFields`: set directly, and by
formatting from the end of an item into its nested list, in an edit and
in a follow-up; 11 of 30 new tests failed).
- After a follow-up is written (BlockIdExtension's naming update), the
binding compares each container it touched with what a fresh reader
shows for the document there, and reads that container again where they
differ, as for a change the writer refuses. Only the part holding the
top-level children the follow-up changed and their neighbours is read,
by the reader itself, into an editor of its own; left out are fields
every client derives itself (list numbering, the text format and style a
client's reconciler derives under text), fields no update stores (a
link's own alignment, indent and direction, a list's own indent) and
block ids settled across the document. It is skipped while a composition
holds back remote text and while the author's normalization of an
update without transforms is pending (the editor differs there on
purpose). Before, each shape the follow-up rules missed (a line without
a marker, a field stored nowhere, a paragraph a read made) left its
author showing a change no peer or fresh reader had, with no warning
(soak A4 S4-2, S4-4, S4-5; R15-A 2: a follow-up's NodeState on a line
without a marker or on a quote's run paragraph, `ImplicitStateFollowUps`
2 of 24 new tests failed; a follow-up that indents a list's first item
into the next item's nested list, `ListIndentFollowUps`: the author kept
the nested list's textFormat 18 against 16 on every reader, 1 of 20
failed; `FollowUpFuzz`: random follow-ups over every node kind and
field, in lines without a marker, a quote's raw run, list wrappers,
cells and a callout, the author equal to a fresh read after each and
every peer after the exchange, 19 of 120 sessions failed). With a
follow-up after every keystroke in a 10,000-block document, the check
costs about 1 ms per follow-up (a few blocks read), against 11 to 13 ms
for the follow-up's update itself (`FollowUpCheckCost`).
- An element's text format and style are stored where no text is below
it (an empty line, list item or cell paragraph, one holding only inline
decorators or line breaks), and a follow-up writes them there as every
update does: a follow-up that sets them, or that empties the element
(Lexical sets them from the text removed). Where text is below the
element, Lexical's reconciler derives them on each client that renders
it: a follow-up's change of them is not written and its container is
read again (a paragraph holding only a link included, which Lexical
serializes them for). Before, a follow-up wrote them nowhere and refused
nothing: the author kept them while every reader showed the stored ones
(soak A4 S4-5's residual; `FollowUpEmptyFields`: a root line, a cell, a
callout and a quote paragraph, a paragraph holding only a link or an
inline decorator, text and a link, an empty list item, each field, in an
edit and in a follow-up; 14 of 100 new tests failed).
- A read again gives the paragraph a read shows around text in a quote
what a fresh read gives it, its text format and style and NodeState
included (its block id is derived again). Before, a refused follow-up's
text format or style of such a paragraph holding no text stayed on its
author (R15-B F2; `RunParagraphFollowUps`: a line break or an inline
equation alone in it; 4 of 4 new tests failed).
- A format-only update made of several formatText calls on one line is
written as format items alone. When a line's text is its old text, cut
and joined again by the update's splits and merges alone (each text node
holding it is an old node of the line or a part Lexical split off one,
and starts where its text did; every old node no longer shown was merged
by the normalization), each character keeps the item at its own place.
Before, a node merged after a split was taken for an equal run of
another node, and the words were deleted and inserted again (`<u>ab` |
`<i>la ` | `la la `, italic over [3,9) and underline over [7,8):
`del "abla " ins "abla "`), which undid a peer's concurrent delete there
or moved its typing (soak A4 S4-6; `FormatCallsRewrite`: 4 of 4 new
tests failed; `FormatCallsScan`: of 800 random updates of one to three
calls, 20 rewrote words, 0 now).
- Typing at the start of a commented run after an equal word writes the
typed text alone. MarkStateExtension cuts the typed text off the comment
and it joins the word before; the rest of the run is a part split off
it, which holds its whole old text and now keeps those characters before
any node claims them. Before, the word before claimed the start of the
removed text it begins with: `del "da" ins "da t30z"` for `t30z ` typed
(soak A4 S4-7; `TypeAtMarkStart`: 1 of 5 new tests failed, the equal
word).
- The attribution of a split tail merged into the node before it (the
range deletes through `extract()` below) declines where a node the merge
record holds after it is not in the text (merged and deleted again in a
later update of the same commit, or by a transform), where it would keep
only part of the node's own old text that Lexical did not cut there, and
where the node's own old text explains all that is left and a caret in
it is elsewhere than at the join; the other attributions decide then, as
before that change. Before, it found the tail in an equal neighbour
merged in later, or in the node's own equal characters, and kept the
deleted tail's items and deleted a survivor's (R15-A 1, R15-B F1: data
loss with a peer's concurrent edit; `SplitTailMergeDeletes`: R15-A's
shapes T2 and T3, by node edits or a caret range, in one commit, two
commits or a transform, 24 of 72 new tests failed, all in one commit or a
transform; `SplitTailCaretDeletes`: R15-B's, 4 of 4 failed). R14-B's
merged run that an app transform removes (R14B-C1) holds (12 of 12, as
before this change).
- The writer writes the text edits Lexical records (Core, above) where
they were made, whether or not a caret is left in the text: an insert or
a delete next to equal text keeps every other character, and a
replacement made through them is written as made, not widened to whole
words. The record is replayed over the previous state into each text
node's lineage (which characters are which old characters, and which are
new), used only where it covers every change of the node (its text then
equals what the lineage gives). A node's text set whole
(`setTextContent`, a change the browser makes to the DOM text, as an IME
composition does) is diffed within that node, anchored at the caret and
in whole words, as before (see the next change for what it no longer
touches); a node made with its text (typed in another format, inserted
by app code) is new text (see the next change for a node made again). A
line's write keeps the old characters the record keeps between its
edits (several edits in one update, a split tail left between deleted
runs) rather than writing one hunk around them. Before, the writer
diffed the old and new text,
anchored by the caret, so an edit made without one (an agent's or app
code's edit, typing in an update that then clears or moves the
selection or makes another edit) was written shifted next to equal
text: `t5z ` typed before `t4z ` was written as `5z t` after the `t` of
`t4z`, and with a peer's concurrent delete of `z t4z` every client ended
on `t35z t `, the typed word's `t` gone (soak A4 S4-9; `ExactTextEdits`:
3 of its 4 shapes failed (with the caret kept it passed), and 129 of 300
seeded inserts and deletes next to equal text, one or two in an update,
through the selection or `spliceText`, each checked character by
character against the shared items, were written otherwise than made).
It also writes exactly what the diff guessed at: range deletes with the
selection cleared (soak S4-1's scan: 102 of 600 deleted an equal run of
the right length elsewhere, 0 of 3,000 now; `LinkMergeDeletes` runs its
600 with the selection cleared too), the equal-run cases of
`BatchedMergeDeletes` (now asserted exactly: 12 of 72 failed) and of
R14-A's batched merges, R15-A's split tail left between deleted runs
(T1) and deleted again by node edits in a second commit (T2;
`SplitTailMergeDeletes` now asserts both: 24 of 120 failed), R16-A's
delete-and-retype cases (4 of 8 failed), several edits in one update
(soak S3-4's scan: 113 of 400 written otherwise, 8 now, each a delete
of text typed earlier in the same update, which the scan counts as
deleted), typing in another format twice in one update (171 of 400, 0
now), and typing over a
selection, which Lexical types into a node it makes, cuts into the text
and merges back: "abcdef" with `c` selected and `X` typed, the caret
kept, was written `del "abcdef" ins "abXdef"`, so a peer's concurrent
delete of `a` came back and its typing landed at the start of the text
(soak A5 S5-1; `TypeOverSelection`: 902 of 1,176 type-overs at every
position of four lines (formatted neighbours, comments), selections of
0 to 5 characters, a new letter or text equal to its neighbour, the
caret kept or cleared, were written otherwise than made, and the peer's
delete came back); "the quick brown fox", `x` typed over `ick bro` ‖
bolding `quick` now gives **`qu`**`xwn fox` (it lost the bold).
- A part Lexical split off a node keeps that node's characters by the
record of text edits, not by equal text: the rule of soak S4-7 above (a
part holding a removed node's whole old text keeps its characters) now
applies only to a part the record does not cover. Before (the previous
revision's last change), a part whose text only equalled the node's old
text took them: typing `ab` at the end of a bold `ab` and unbolding the
original half, which merges into the text before it, gave the typed
`ab` the original characters' items, so a peer's concurrent delete of an
original character deleted the typed one instead, and its typing
between them landed inside the typed text (R16A-1, data loss;
`SplitPartReserve`: in one commit, one update or an app transform, a
peer deleting an original character or typing between them, 12 of 32
new tests failed; two commits are a control).
- Several edits in one update, as agents and app code make them, are each
written where they were made, and nodes the update makes are new where
they are put. Before, each of these was written as a rewrite, which
undid a peer's concurrent delete of an untouched character or moved its
typing (every case below fails on the previous revision):
- A text node made next to an edited one, with its format, which Lexical
merges into it: "abcdef" with `X` spliced at 2 and a node `Y` made
after it was written `del "abcdef" ins "abXcdefY"` (soak A5 S5-2; also
with the node made first, and with caret typing). The same with the
caret then put inside the made text, as a snippet insert does (the new
text was written shifted into the equal text before it, S5-5), and a
paste over a selection, plain or rich, whose text Lexical makes as
nodes (R17A-2: written as whole words replaced, as the docs said it
no longer was).
- Edits on either side of a line break or an inline node: `abc` | line
break | `def` with `X` spliced into `abc` and `Y` into `def` was
written `del "abc\ndef" ins "aXbc\ndYef"`, the break included, and an
inline node between them was deleted and made again (S5-3, the S3-4
residual). A line break or an inline node of the line before keeps its
item, and one made in the update is new where it is: a line break
typed or inserted right before another was matched with the old one
and written after it, so a peer's typing after the old break was left
alone on the new line (S5-4, 12 of 24 failed, every one where the
author had the higher client id). Where the record does not say what
some atoms are, the atoms it keeps stay and only the gaps between
them are diffed, each on its own; a whole-word widening never passes
an atom the record keeps.
- A node set whole by `setTextContent` had no lineage, and nor had a
node it merged with, so that node's untouched characters were diffed
with it and written again (`ab` | line break | `a X`, the second set to
`a ` and the break removed, rewrote `ab`). The record now holds the
set's text before and after, and its lineage keeps the prefix and
suffix they share in whole words, the rest replaced: the change stays
in that node. Keeping part of a word is not safe (two replacements of
one word at once would interleave), so a replacement inside one word
is still written as the whole word replaced (documented).
- A node removed by app code and another made in one update (an agent
replacing a word) had the new text take equal characters of the
removed one, as if made again. Now text made where the line's text
changed is new (the next change places text by where it is), and a
node the selection removes with its text is recorded as deleted, not
as a node that left.
`CompoundTextEdits` checks it: seeded updates of 2 to 4 operations
(splice, typing, typing over a range, `setTextContent`, a node made
before or after of the same or another format, a line break or an
inline node made, a node removed, a range formatted, a split, a range
extracted and removed, a range deleted, the caret set or cleared) on one
or two adjacent text nodes, with line breaks and inline nodes between
and beside them, equal ones side by side too, and every character's
provenance modelled: the write must keep every character the update
kept, by its Yjs item, and a peer's concurrent delete of a kept
character must stay deleted. On the previous revision 131 of 525 seeded
updates were written otherwise (1,301 of 5,271 with 6,000 seeds); now 0
(0 of 5,271, and 0 of 17,617 with 20,000 seeds). What it allows is what
the record cannot place exactly: text set whole, and the text or line
break of a made node, may keep characters of text that left the line
otherwise than by a delete (a text set whole, a node removed or
extracted and removed; the next change places it by where it is).
`MadeNodeEdits` (16 tests, 14 failed) holds the shapes above.
- Which characters a line kept follows where they are in the line, not
which node holds them: in storage a node's type, format, link and
segment key are attributes of its characters, so nodes swapped without
changing the line's text change attributes, never text. The record of
node insertions and removals (Core) is replayed with the text edits over
the previous state, each text node's characters as runs of old
characters, typed text (new where it was typed) and text that arrived
otherwise (a node made, a text set whole), and what a node removed from
a line held is kept where it was removed. Each line is then resolved
once: the old characters still in place, in order, are kept (they pin
the line), and in each stretch between them the text that left (a
removed node's, the text a set replaced) and the text that arrived (a
text set, a node made) are aligned by the diff a write makes without the
record, their common start and end in whole words, anchored at the caret
where it is in text that was there before: first all that arrived, of
which set text keeps what it is aligned with; then set text still new,
with what is left between what is kept; then the text of nodes made. A
removed node's text is aligned whole or not at all; typed text and the
characters an exact edit deleted are new and gone where they are, outside
the alignment; the rest is deleted and inserted.
A node made with exactly the text that the nodes
removed right around it held holds those characters from then on, so
what the update does to it next (typing into it, making it again, a
merge) keeps them. Where the record does not explain a line's text (an
unrecorded change, an entry the binding does not know), the line is
diffed as before the record. This replaces the previous revisions'
per-node rules: text a set only inserts taken for text moved out of a
sibling, a node made with exactly the text of one node that left taken
for it made again (`remakes`, `moves`, `made` and `remade` runs), the
made-text checks of the line writer (`placed`, the removed-text check,
the line feeds a line break takes, `partLeft`) and the lineage branch of
the origins: the writer loses 509 lines (614 removed, 105 added), the
replay gains 475 (621 removed, 1,096 added), and `@lexical/y`'s source
as a whole is 26 lines longer (1,235 removed, 1,261 added). Before, a node swap the rules
did not foresee was guessed per node and lost characters next to equal
text, so a peer's concurrent delete there came back or its typing moved:
two equal hashtags or keywords made plain text at once, a hashtag grown
over a keyword the same update made plain text (`TextEntityEdits`: 18 of
2,738 seeded updates with 3,000 seeds, 4 of them new in the previous
revision; now 0), and node swaps around caret edits in one update
(`NodeSwapEdits`, new: a custom text class and a link; a part split off
and made again as the other class, maybe bold, a node made again whole,
two equal neighbours made plain text at once, an entity grown over the
next node or shrunk into it with `setTextContent`, a range wrapped in a
link or unwrapped, each of these where typing, Backspace or Delete land
before and after them in the same update, a peer deleting a kept
character or typing between two at the same time, each character's
provenance checked, and the peers and a fresh reader converging: of 380
seeded updates, 39 written otherwise on the previous revision;
now 0; with 4,000 seeds 390 of 3,850 before, now 17, each
written anew, see Known limits). `TextEntityEdits`, `RemadeText`,
`MadeNodeEdits`, `CompoundTextEdits` and every repro of the previous
revisions' text-entity findings (R17A-1, R18A-1 to R18A-4, R18B-F1) give
what they gave on the previous revision or better. Lexical's record
gains a `delete` entry for a node the selection removes with what it
holds (a text node's removal was a splice of all its text): a line break
or an inline node a selection deletes is a delete, never text that left
(`CompoundTextEdits`: a line break deleted and another made in its
place).
- A stretch's text sets are resolved together, against all the text that
left the stretch. Before, a text set kept the common start and end of
its own node's old text only, and nothing where text arrived in more
than one node:
- a hashtag grown over the bold neighbour after it, once a node made
before its text (a paste, or app code without a caret) had merged into
it, kept its own old `b` for its last character, which came from the
neighbour, so a peer's concurrent edit there landed on the wrong
character on every client (R19A-1);
- a node set whole and a node made after it in one update (an agent's
compose), or text pasted at the end of a stored hashtag (the plugin
moves the pasted letters into it and sets the pasted node to the rest:
two nodes set whole), wrote the set nodes' untouched characters anew,
so a peer's concurrent delete there came back (R19A-2, R19B-F1).
Now the text that arrived in a stretch is aligned with the text that
left it by their common start and end, whatever nodes hold either, and
the text that sets put in place of old characters keeps what it is
aligned with; the text a node made holds, and a set's text in place of
new text only, take their place in the alignment and are new. Text that
left with a removed node is aligned only whole, and next to text a set
replaced that the alignment keeps, so an agent's rewrite of a line keeps
the rewritten node's own last space, not the removed tail's `. `
(`RewriteMerge`). The comparison stays a common prefix and suffix,
linear in the stretch. `MadeNodeEdits` holds these shapes (10 new tests,
9 failed before; the tenth, a node removed before a node set whole,
guards the alignment's ends).
- Text a node made holds takes no old characters from set text, each end
of a stretch's alignment keeps the removed text it covers whatever the
other end does, and a node set whole keeps at least what its own diff
keeps. Before:
- a node made next to a node set whole, with the set node's old text or
its first or last word (an agent's compose, a copy pasted next to the
original), took the alignment, so the set node's own characters were
written anew and a peer's concurrent delete there came back on every
client (R20B-F1, R20A-2);
- a node set whole that took a removed neighbour's text, with a node
made after it, wrote that text anew, as the removed text was aligned
only where the common end covered it, though the common start covered
it and the set node's own text (R20B-F2);
- a text set and a delete of part of the text just set, in one update
(an entity grown and Backspaced, a word set and deleted again), gave
up the stretch, so the set node's untouched characters were written
anew (R20A-1).
Now the old characters the alignment gives made text stay free, and the
set text still new between two kept characters (or a kept one and an
end of the stretch) is aligned with the free old characters between
them, as the stretch is. An end that keeps all the text sets replaced
goes on over the removed node's text right beyond it, where it covers
all of it. Text deleted after it arrived stays in the alignment where it
is, so the old characters its set text is aligned with are deleted, not
given to other text. Last, where one node is set whole in the stretch,
it keeps the old characters of its own that its own diff (its old text
against its text now, as an update that changes only that node is
written) keeps, where the stretch keeps them nowhere else and they fall
in order with what it keeps; a development build checks this floor (an
invariant). Where several nodes are set whole in one stretch (an entity
grown or shrunk into its neighbour), a node's own diff can name
characters that moved into the other node, so the stretch's alignment
alone decides there (with the floor there, `NodeSwapEdits` kept a
character for another in 2 seeds, which no revision since the record
did); where the record lost which old characters a delete took (blind),
nothing is kept, as before (a node's own diff kept a deleted character
in 2 more). The comparisons stay a common prefix and suffix, linear in
the stretch. The new regression suite (`__tests__/unit/regressions/`,
5 files, 78 tests) holds these shapes (R20B-F1, R20B-F2, R20A-1 and
R20A-2: 23 failed before) and the reviews' findings whose repros were
not committed (R14B-C1, R15B-F2, R17A-2, J-1), with the three open
items below as expected failures.
- Each stretch between the old characters the record keeps in place is
resolved by one mechanism, the diff a write makes without the record,
where the record decides nothing; the rules stacked on it before (made
text claims nothing, removed text aligned only at an end and next to
kept set t…
Description
Lexical has no stable way to address a block from outside the editor. Node keys exist only at runtime and change on every load, and a block's position changes with every edit. Code that edits a document block by block needs an id that survives serialization, reloads and changes applied from other replicas. Examples: an AI agent that reads blocks and answers
replace <id>,insert after <id>ordelete <id>, or a server pipeline that patches stored JSON.This PR adds an
@experimental, opt-inBlockIdExtensionto@lexical/extension, and an opt-inBlockIdHTMLExtensionto@lexical/html. It builds on #9452, which has merged, so its base is main. The default predicate reads thechildrena class declares, throughgetDeclaredNodeStructure. The extension also declares an optional peer dependency onNodeStructureExtensionso that, when both are present, it registers after it (see below). Editors that do not register the extension see no change in state, JSON, transforms, exports or behavior.Storage. The id is NodeState (
blockIdState, keyblockId), serialized as"$": {"blockId": "…"}.resetOnCopyNode, so$copyNodedoes not copy it.A–Z,a–z,0–9,-,_): safe in URLs, HTML attributes and JSON, and wide enough for UUIDs, nanoids and shorter app ids, so an app that already stores such ids under$.blockIdcan adoptblockIdStatewithout migrating documents. Any other value, from JSON, HTML, another replica,generateIdor a direct$setState, reads as no id, and the block gets a new one through the normal rules (positional in a load, derived in a repair).API.
$getBlockId(node)and$getBlockById(id). While enabled, the lookup uses an index that is updated from each commit's dirty nodes (including elements created or rewritten in the commit), and every hit is checked against the active state.$isIdentifiedBlock(default$defaultIsIdentifiedBlock),generateId(defaultgenerateBlockId) anddisabled(also an output signal).unknownin TypeScript and Flow alike, not in its output.Which blocks get ids.
$defaultIsIdentifiedBlockidentifies:children: 'inline', or a list that includes'inline', asListItemNodedoes;Nested wrappers get no id: nested lists, table rows and cells, shadow roots, and nested elements whose class declares no
children. Slot values and blocks in slots follow the nested rules. One preset is exported:$isRootChildBlock, the root's children only. Other sets compose from the default, as the docs show.New ids.
generateBlockIdmakes 21 base64url characters: 126 random bits fromcrypto.getRandomValues, more than a v4 UUID's 122. There is noMath.randomfallback. Withoutcrypto.getRandomValuesit throws, and the app must configuregenerateId. AgenerateIdvalue that is invalid (not a string included) or already used is discarded andgenerateIdis called again; 32 in a row throw.Assignment. Every identified block without an id gets one in the update that creates it, including blocks from
importJSON, HTML import and markdown import.setEditorState(parseEditorState(json))assigns every missing id in that one commit, so a headless server can load, assign and save in one synchronous write. Updates applied withskipTransformsor taggedCOLLABORATION_TAGorHISTORIC_TAGare repaired by a discrete follow-up update.Documents stored without ids get positional ids on load: SHA-256 of the document key and the block's place, as 21 base64url characters. The key is the SHA-256 of
editorState.toJSON(true).rootwithout ids, written as canonical JSON. Every editor that loads the same document with the same nodes, predicate and transforms derives the same ids without writing first, and the first write stores them. Blocks created later by edits get random ids. A load is named once its transforms have settled, so the key is taken from the document the load ends with. A stored document that loading changes (equal adjacent lists thatListNodemerges, or anythingNodeStructureExtensionrepairs) therefore gets the positional ids of the loaded document, which cannot be computed from its stored JSON alone; see Known limits.Uniqueness. When several identified blocks share an id:
$copyNode, JSON or HTML import, an explicit$setState). An id left on a block that is not identified is not reserved.base64url(SHA-256("dup" U+0000 id U+0000 k))[0..21], so every replica repairs it alike, in time independent of document size.Edits. Ids stay with the content the user sees. Enter, Backspace join,
$setBlocksType, paragraph to list,replace,$setSlotand moves keep the id. Cut and paste keeps the id; a copy gets a new one. Undo and redo restore ids exactly.Ids follow the structure an update ends with. Ids are assigned in a root transform, and other transforms can still restructure the document in later passes of the same update:
ListNodecan merge a run of equal adjacent lists over several passes, andNodeStructureExtensionsplits, joins, lifts and merges blocks in a root transform of its own. A generated id that an earlier pass gave a new block is therefore provisional within the update. A later pass can still replace it with the id of a block that the new one continues, and a copy that yielded its id takes it back once the original has been merged into it. WithNodeStructureExtension:replacedoes;The result does not depend on the order in which the two extensions are listed, and edits give the same ids when
NodeStructureExtensionis enabled after the editor is built; loads then differ (see Known limits).HTML.
BlockIdHTMLExtensionwritesdata-block-idon exported identified blocks and reads it back throughDOMImportExtension, subject to the validity and uniqueness rules. An id imported onto a block that is not identified once inserted (a table cell, a nested list) is dropped. Itsexportandimportflags turn off either direction. It lives in@lexical/htmlbecause@lexical/htmlalready depends on@lexical/extension.Docs. A new page, Extensions > Block IDs, covers:
NodeStructureExtensionrepairs;JSON.stringifysemantics: integer-like keys first, escaping, number formatting), canonical slot order, what the freeze covers, and a literal end-to-end test vector for implementations in other languages.The PR also adds entries in the included-extensions list, and Flow types for both extensions.
Collaboration
Block ids are plain NodeState, so they sync wherever replicas sync NodeState, and the duplicate repair gives the same result on every replica. Enable the extension on every client that writes; the positional-id limit when one does not is documented. A short new page, Collaboration > Block IDs (
packages/lexical-website/docs/collaboration/block-ids.md, added to the collaboration sidebar), covers this.Design notes
generateIdstays configurable for apps that want prefixed ids.\r\nbecame\n, NUL became U+FFFD).^[A-Za-z0-9_-]{1,64}$is the alphabet the extension writes, with room for the ids other systems already use.Related: #9174 is an example app with an application-owned id policy (128-bit random ids, a fresh id on every paste). This PR is the reusable version, convergent across replicas, and does not touch the files #9174 edits.
Test plan
New tests:
BlockIdExtension.test.ts(headless, 85 tests):doc:12) read as absent and get positional ids; 64-character, 11-character and UUID ids are kept; an invalid id from another replica is repaired; an invalid id set with$setStatereads as absent; invalidgenerateIdvalues, a value that is not a string included, are retried, and 32 in a row throw;$copyNode, the clipboard, cut and paste, undo, copies of a list that merge with the original (also on both sides of it, merged over several transform passes), and a copy of a list pasted right above an equal list;$getBlockByIdfinds every identified block after a document with ids on the root children only is loaded (bysetEditorStateand as the initial state), after the documented$setStaterecipe on a list or table, after a copy of such a list, and aftersetEditorStateof a list whose items repeat an id; O(dirty) predicate calls;disabled, and repair after updates without transforms.BlockIdExtension.structure.test.ts(38 tests): the same 11 cases withNodeStructureExtensionlisted after this extension, listed before it, and enabled after the editor is built: a paragraph and a heading split around a lifted block, a block lifted out of the paragraph it empties, a list lifted out of a link (the items keep their ids and the link), paragraphs joined as lines, equal adjacent lists, nested lists joined at a seam, a new list, with and without an id, merged with the list after it, a copy of a list merged with the equal list after it, and copies of a list on both sides of it and apart from it. Each checks the exact ids and that the index finds every block. Five load tests, with the extensions in either order: a stored document with equal adjacent lists gets the positional ids of the merged document, the same as an editor withoutNodeStructureExtension; a stored paragraph that holds a quote gets the positional ids of the split document.BlockIdExtension.property.test.ts(20 seeds in CI): random sequences of 40 local edits (typing, Enter, joins, range deletes, type changes, moves, duplicates, multi-copy pastes, indent and outdent, list conversion, moves into table cells, replace, undo/redo, reloads with an injected duplicate). After every step, every identified block has exactly one id, ids are unique,$getBlockByIdfinds every block, pre-existing blocks keep their ids, and undo and redo return to a state seen before.BLOCK_ID_PROPERTY_SEEDSruns more.BlockIdExtension.format.test.ts(10 tests): the frozen format. It checks SHA-256 and UTF-8 against Node, the canonical JSON, and positional and duplicate ids against an independent implementation, pinned to literal values, plus the end-to-end vector printed in the docs.BlockIdExtension.slots.test.ts(10 tests): slot values and slot containers, duplicates across slots and children,$setSlot, the index after undo andsetEditorState, host removal, and the lookup while disabled.BlockIdExtension.dom.test.ts(5 tests, jsdom): typing, Enter, Backspace, clipboard paste, legacy HTML paste, undo.BlockIdHTMLExtension.test.ts(10 tests): off by default, export, round trip, imported ids through the uniqueness rule, invalid imported ids ignored, an imported id dropped from a block that is not identified, export into another realm's document, theexportandimportflags, and readers of an id-less document agreeing.BlockIdDocs.test.ts(5 tests): the code examples of the Block IDs page, as written there, with a person's caret inside the block the agent replaces, and with a selection from the block before into the replaced block, from it into the block after, backwards, and inside it.BlockIdCollab.test.ts(16 tests per binding,@lexical/yjsv1 and v2): assignment, late joiners, concurrent Enter, duplicates and moves, a document stored without ids opened concurrently, type changes, undo/redo, nested lists, and clients without the extension writing mid-session (a block added while the peers are apart; a block added while a peer has unsynced typing; peers that open an id-less document at different versions). Every test checks convergence, unique ids and quiescence.BlockIdCollabFuzz.test.ts: deterministic randomized runs with 2–3 replicas, flat and nested, 8 seeds per binding and variant in CI.BLOCK_ID_FUZZ_SEEDSruns more.BlockIdExtension.perf.test.ts: skipped unlessBLOCK_ID_PERF=1.Before
On main (with #9452) with the new test files copied in, every block id test fails, because the extension does not exist:
After
Every test on main passes unchanged (9768 of 9768 test ids, same status).
pnpm run tsc,tsc-test,pnpm run flow, ESLint and Prettier are clean, the tree-shaking tests pass on the sources and on the production build,build-prodsucceeds, and the website builds with no broken links.Property test at 1,000 seeds: 1000 passed (
BLOCK_ID_PROPERTY_SEEDS=1000).Ids compared with a reference build that names blocks only once the transforms of an update have settled (otherwise the code of this PR). This used a local harness that is not committed: the property test's edits plus moves into list items and quotes, and an agent that reads ids and later replaces blocks by id, over 1,000 seeds × 40 steps, traces compared up to the naming of new ids. The ids are identical in every sequence in all five configurations: without
NodeStructureExtension; with it listed after this extension; listed before it; enabled after the editor is built through itsdisabledoutput; and throughregisterNodeStructure(). Against the same reference, the first rebased version of this PR differed in 55 sequences withoutNodeStructureExtensionand 127 with it listed second, and the previous version in 36, 41, 41, 57 and 57 sequences in those five configurations. Every difference of the previous version is in a list that pasted copies of a list merge into: the reference keeps on it the id of the list they merged with, where the previous version gave it a fresh id and dropped that id or left it on a copy. The cases are a copy pasted right above an equal list and, withNodeStructureExtensionenabled after the build, several copies of a list merged with the original.Known limits:
ListNodemerges equal adjacent lists, editors with and withoutNodeStructureExtensionderive the same ids. WhereNodeStructureExtensionrepairs more (a paragraph split around a quote stored inside it, for example), the document key changes, so every block of such a document (not only the blocks the repair creates) gets ids that differ from those of an editor withoutNodeStructureExtension, and a reader working from the stored JSON must apply the same repairs first. Editors that load it with the same nodes and extensions agree. Documents that loading does not change, including the docs' test vector, are not affected. Making untouched blocks keep the ids of an editor withoutNodeStructureExtensionwould mean naming a load beforeNodeStructureExtension's repairs, which run in a root transform registered before this extension's, and Lexical has no hook before the transforms ofsetEditorState.NodeStructureExtensionenabled after the editor is built. Its repairs then run after this extension's naming in each pass. Edits give the same ids as above, but a load is named before the repairs: blocks the repairs keep get the positional ids of the document as it was before them, a list merged into another loses its id, and blocks the repairs create get ids from the document the load ends with.Fuzz at 2,000 seeds per variant (
BLOCK_ID_FUZZ_SEEDS=2000): v1 passes every seed, flat and nested. On v2, 55 seeds fail (7 flat, 48 nested). All 55 trace to the experimental@lexical/yjsv2 binding, not to this extension:blockIdis at its default ($copyNoderesets it), and the v2 binding's create path writes that default into Yjs as anundefinedattribute (its update path drops it). Receiving peers end with"$": {"blockId": undefined}on one peer (27) or throw on a stale list node inside the binding (10). The smallest repro is two steps on one peer: make a list, indent. A one-character change in the binding (!== nullto!= nullwhen it filters state attributes) removes all 37.blockId(last writer wins), writes one id onto two elements (the documented duplicate rule then renames one holder), or Yjs undo recreates an element without its attributes. The same minimized scripts pass on v1, and converge on v2 without the extension.The v2 binding is not changed here.
Performance, on a headless 10,000-block document, with and without the extension, interleaved round by round (
BLOCK_ID_PERF=1 npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts, shared machine under load):Across three runs the deltas moved by a few milliseconds (keystroke 0.4 to 0.9 ms, Enter 2.0 to 2.5 ms, paste of 50 blocks 3.5 to 4.0 ms, first load 174 to 183 ms, stored ids 37 to 42 ms, remote duplicate 29 to 30 ms). Three runs of the previous version of this PR, interleaved with these, fell in the same range (keystroke 0.6 to 0.8 ms, Enter 2.2 to 2.5 ms, paste of 50 blocks 3.5 to 3.9 ms, first load 180 to 185 ms, stored ids 34 to 39 ms, remote duplicate 29 to 32 ms); a load of these documents takes the same transform passes in both. A block without an id applied from another replica (written only by editors without the extension) gets a positional id, so that repair hashes the document once.
Not exercised: real browsers.