Repository navigation
[lexical][lexical-compiler][lexical-fast-check][lexical-mark][lexical-website][lexical-yjs] Feature: Experimental MarkStateExtension and set-valued NodeState with arraySetValue - #9380
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
I think this is something that yjs14 can represent cleanly, and a better approach here would be to have set valued state and have a way to wire that through with custom collab v2 serialization rather than to contort the model to fit v2 constraints |
| } else if ($isElementNode(node)) { | ||
| for (const child of node.getChildren()) { |
There was a problem hiding this comment.
Actually, besides children, you should also check the slots in both ElementNode and DecoratorNode, as they may also contain markable nodes
There was a problem hiding this comment.
Done. Collecting and marking now look through the slots of ElementNode and DecoratorNode hosts: a range across a host, a NodeSelection of a host, $removeMarkID without a selection, rebuilding markIDNodeKeys, the HTML import rule and $migrateMarkNodesToMarkState. Tests are under slots in MarkStateExtension.test.ts.
| const klasses: Klass<TextNode>[] = []; | ||
| // @internal access with precedent (NormalizeInlineElementsExtension) | ||
| for (const {klass} of editor._nodes.values()) { | ||
| if (klass === TextNode || klass.prototype instanceof TextNode) { |
There was a problem hiding this comment.
Perhaps we should include DecoratorTextNode here, or provide a way to parameterize the set of "markable" classes?
There was a problem hiding this comment.
DecoratorTextNode is inline, so it was already marked through the inline-DecoratorNode rule; there's a test for it now. The set is also configurable: markableNodes takes node classes and guard functions, with DEFAULT_MARKABLE_NODES = [TextNode, LineBreakNode, $isInlineDecoratorNode] as the default (extend it with [...DEFAULT_MARKABLE_NODES, MyNode]). The transforms registered here only split typed text off the edge of a marked TextNode, so they stay per TextNode class; a DecoratorTextNode never receives typed text.
…Feature: Experimental MarkStateExtension with set-valued NodeState for collaboration friendly marks
## Description
Current behavior: comment and annotation marks can only be stored as
`MarkNode` wrappers. Overlapping marks become sibling `MarkNode`s whose `ids`
the app has to keep consistent (with `registerNestedElementResolver`, without
it they nest), and every add or remove is a structural change. With the Yjs
v2 binding, concurrent edits around a mark move or duplicate text: typing
inside a range while a peer comments on it moves the typed text out of the
range, two peers commenting on the same text duplicate it, and removing or
undoing a comment while a peer types inside it loses the typed text.
NodeState has no way to hold a set that peers change concurrently: a
binding stores each key as one value, so two peers adding different
members to the same set keep only one peer's set.
New behavior (all opt-in and `@experimental`, `MarkNode` and its APIs are
unchanged):
- `lexical`: `createState` takes `collab: 'value' | 'set'` (default
`'value'`, exposed as `StateConfig.collab`). A `'set'` state serializes to
an array of strings (one array in JSON); collaboration bindings store each
member as its own entry, `<key>` + `NODE_STATE_SET_MEMBER_SEPARATOR`
(U+001F) + `<member>`, so concurrent additions and removals of different
members merge. NodeState joins a member entry back into the set wherever
it reads one (JSON import, `updateFromJSON` and `updateFromUnknown` from a
binding, and a later first read or writable copy), but only when a
`'set'` StateConfig with that key is known for the node type (declared in
`$config` or used on a node of that type) and no StateConfig uses the
entry key itself; otherwise the entry stays an ordinary key and is written
back as it is. So JSON saved by an editor whose Lexical version kept the
members as separate keys loads with its marks, and an unrelated key that
contains U+001F is never misread. `createState` rejects a `'set'` key that
contains U+001F. Helpers for bindings: `splitCollabStateEntries` and
`$getCollabSetStateKeys`. Flow types included.
- `@lexical/yjs`:
- v2 writes a set-valued state as one text attribute (TextNode) or element
attribute (other nodes) per member, `s_<key>\u001f<member>`.
- v1 writes one entry per member in the node's `__state` Y.Map, adding
and deleting entries as members change.
- The read paths are unchanged: they pass the stored entries to NodeState,
which joins them. A peer that does not know the state keeps each member
as its own unknown key and writes it back as it is, so it does not
collapse the members.
- `'value'` states are stored exactly as before.
- `@lexical/mark` adds `MarkStateExtension` (`@lexical/mark/MarkState`). The
ids of a leaf are one set-valued NodeState, `markIds` (`MARK_STATE_KEY`),
`{"$": {"markIds": ["c1", "c2"]}}` in JSON, so marks overlap freely and
concurrent adds and removes of different ids merge in v2 and in v1 (where
no TextNode split or merge is involved).
- `$addMarkID(id, selection)`, `$removeMarkID(id, selection?)`,
`$getMarkIDsAtSelection(selection?, 'any' | 'all')`, `$getNodeMarkIDs(node)`
(`ID` casing as in `$getMarkIDs` and `MarkNode.getIDs`). Ids must be
non-empty and free of whitespace; `$addMarkID` throws otherwise.
- Config: `disabled`, `exportIDsToHTML` (default `false`) and
`markableNodes`: node classes (matched with `instanceof`) and guard
functions that decide which nodes carry ids. The default,
`DEFAULT_MARKABLE_NODES`, is TextNode, LineBreakNode and
`$isInlineDecoratorNode` (every inline DecoratorNode, which includes
`DecoratorTextNode`).
- Marking a range also marks the content of the slots of the ElementNodes
and DecoratorNodes in it (and of a slot host in a NodeSelection);
removing an id from the whole document, rebuilding the output, the HTML
import rule and `$migrateMarkNodesToMarkState()` look inside slots too.
- When the editor is built, the extension registers the `markIds`
StateConfig on every node type, so ids read from JSON or from a peer are
parsed (and written back per id) before the editor has marked anything.
- Output: `disabled`, `exportIDsToHTML` and `markIDNodeKeys`, a signal with
a Map from each id to the keys of the leaves that carry it, maintained
from update listeners (so it also works headless, after collaboration
updates and after undo). `$removeMarkID(id)` uses it instead of walking
the document.
- Rendering through `DOMRenderExtension`: the `mark` / `markOverlap` theme
classes and a `data-lexical-mark-ids` attribute. HTML export writes the
attribute only with `exportIDsToHTML` (like `MarkNode`, ids are not
exported by default), and a `DOMImportExtension` rule reads it back.
- Text typed at the edge of a marked run does not join it (as with
`MarkNode`), implemented with a TextNode transform that compares with the
caret position before the update; composition is handled from
`COMPOSITION_START_COMMAND` because transforms skip the composing node.
Text inserted inside a run keeps the ids, including when the core puts it
in a new TextNode (replacing a selection, a format change at the caret, a
single-node paste), and next to inline elements such as links, whose
leaves count as the neighbors. Collaboration and history updates are left
alone.
- `$migrateMarkNodesToMarkState()` converts a `MarkNode` document.
- Docs: a new "Comments and Annotations" page under Collaboration, and a
"Collaboration: set-valued state" section on the NodeState page. They
describe the limits:
- v1 syncs a TextNode split or merge as a delete and a re-insert, so the
races that split or merge TextNodes (including removing the last id of
a run) still move or duplicate text on v1;
- with three peers, and with two peers when one adds and removes ids in
one update while the other types in the overlap, v2 can extend a mark
(the peers converge), because it re-applies the text attributes of a
whole paragraph from a possibly stale view. The v2 stale-attribute fix
(#9381) makes these pass; `test.fails` cases pin them until it lands;
- a mark racing a paragraph merge stays order dependent;
- leaves that are re-created (code highlighting, node replacement) lose
their ids.
Interaction with other open PRs:
- #9379 (unknown node types) touches `Utils.ts` and `SyncV2.ts` too. An
earlier revision of this change conflicted with it there; this revision
applies cleanly on top of it in either order, and the yjs, mark and
Collab tests pass on the combination. If a conflict comes back after a
rebase, keep both sides: this change only adds the `collab: 'set'` branch
of the known-state loop in `syncNodeStateFromLexical` with its two
helpers (`Utils.ts`) and the `splitCollabStateEntries` call in
`stateToAttributes` (`SyncV2.ts`), plus their imports.
- #9381 (v2 stale attributes): whichever of #9380 and #9381 lands second
flips the 4 v2 `test.fails` in `MarkStateCollab.test.tsx` (three peers,
2 orders; add and remove in one update, 2 orders) to `test`. With #9381
cherry-picked on top of this commit (no conflict), vitest reports
"Expect test to fail" for exactly those four.
The format of this extension was never released, so the JSON
(`markIds` array) and Yjs layout (`s_markIds\u001f<id>`) are new; earlier
drafts of this change used one `mark:<id>` key per id, which is not read.
Bytes per operation are within a few percent of one key per id (the key
name is 4 characters longer); storing the set whole is larger as well as
last-writer-wins:
```
"Revenue grew 4% in Q3.": add c1 (8-15), add c2 (12-19), add c3 (8-12), remove c1, remove c2
v1 set (this change) 299 364 30 41 36 doc 1019
v1 mark:<id> keys 296 355 27 59 45 doc 1031
v1 whole set 306 361 35 69 46 doc 1060
v2 set (this change) 139 243 177 196 86 doc 870
v2 mark:<id> keys 133 231 165 184 83 doc 825
v2 whole set 145 262 182 197 117 doc 934
```
## Test plan
### Before
The two-peer scenarios of `MarkStateCollab.test.tsx` written with the
`MarkNode` API (`$wrapSelectionInMarkNode`, the nested element resolver,
`deleteID` / `$unwrapMarkNode`) in a scratch copy not part of this commit,
on the v2 plugin. Both peers converge on the wrong document:
```
W1: typing inside a range ‖ a peer marks it
paragraph("Revenue by " mark[c1]("grew 4%") " in Q3.")
W3: two peers mark the same range
paragraph("Revenue " mark[c1]("grew 4%") " in Q3." mark[c2]("grew 4%") " in Q3.")
two peers mark overlapping ranges
paragraph("Revenue " mark[c1]("grew 4%") " in Q3." mark[c2](" 4% in ") "Q3.")
W4 (both variants), R1, removing a mark ‖ a peer marks the same range
paragraph("Revenue grew 4% in Q3.")
```
The new tests against the previous draft of this change (one `mark:<id>`
key per id, no `collab` option, no slots or `markableNodes`):
```
$ npx vitest --project unit --no-watch packages/lexical-react/src/__tests__/unit/CollaborationSetState.test.ts packages/lexical-mark/src/__tests__/unit/MarkStateCollab.test.tsx packages/lexical-mark/src/__tests__/unit/MarkStateExtension.test.ts
× v1/v2 on element/text > concurrent additions of different members merge
AssertionError: expected [ 'b', 'shared' ] to deeply equal [ 'a', 'b', 'shared' ]
× v1/v2 on element/text > a removal and a concurrent addition both apply
× slots > marking a range marks the content of the slots in it
Expected: ... test-figure{paragraph("A caption"[c1])} ...
Received: ... test-figure{paragraph("A caption")} ...
× slots > a NodeSelection of a slot host marks the content of its slots
× slots > the output is rebuilt from the slots of a loaded state
× slots > a MarkNode inside a slot migrates
× markable nodes > a class list / a guard function / extending the default with a block decorator
× each id is its own text attribute / entry in the state map
Test Files 3 failed (3)
Tests 20 failed | 78 passed | 8 expected fail (106)
```
The decoding tests against the revision before that (config-free joining
in the bindings only, no joining in NodeState):
```
× JSON with one key per id, as an older collaboration client saves it, shows the marks
Expected: "paragraph("Revenue grew 4% in Q3."[c1,c2])"
Received: "paragraph("Revenue grew 4% in Q3.")"
× member entries in JSON are joined into a known set-valued state
AssertionError: expected [ 'z' ] to deeply equal [ 'a', 'b:c', 'z' ]
× member entries read before the state is known are joined on first use
× a member entry adds or removes one member
× a collab: 'set' key can not contain the separator
× v1/v2 on element/text > a value state whose key contains U+001F is synced as is
AssertionError: expected '' to be 'x'
Tests 9 failed | 229 passed (238)
```
### After
```
$ npx vitest --project unit --no-watch packages/lexical-mark packages/lexical-yjs packages/lexical-react/src/__tests__/unit/Collab packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts
Test Files 29 passed (29)
Tests 1139 passed | 8 expected fail (1147)
```
- `CollaborationSetState.test.ts`: a generic `collab: 'set'` state on a
paragraph and on a TextNode, v1 and v2, two offline peers: concurrent
additions of different members merge (`['a', 'b', 'shared']`), a removal
and a concurrent addition both apply, a value state whose key contains
U+001F syncs as is, and the same state with `collab: 'value'` keeps one
peer's whole set.
- `MarkStateCollab.test.tsx`, both client id orders, asserting the tree, the
`markIDNodeKeys` output and the Y.Doc on every peer:
- v2: W1, W3, overlapping ranges, typing in an overlap ‖ second mark,
W4 (both), R1, resolving one of two marks ‖ typing in the overlap,
removing ‖ marking the same range, a line break, edge typing; the
stored attributes (`s_markIds\u001fc1`, ...); a peer without the
extension typing in a marked run keeps the attributes per id.
- v1: one `__state` entry per id; two peers marking the same TextNode
(`"grew 4%"[c0,c1,c2,c9]`), removing ‖ marking it, resolving ‖ typing
inside (`"grew by 4%"[c9]`), undo after a peer typed inside.
- 8 expected failures: three peers (2 orders) and add-and-remove in one
update ‖ typing in the overlap (2 orders) on v2, which pass with #9381
cherry-picked on top (vitest reports "Expect test to fail" for all
four); the paragraph merge race (2 orders); and v1 resolving the only
mark of a TextNode ‖ typing inside it (2 orders), where v1 moves the
typed text to the end of the paragraph.
- `MarkStateExtension.test.ts`: overlap, queries, split and merge, edge
typing, composition, links, ids, HTML, undo, rendering, migration, the
JSON format, and new: slots (a range across a slot host, a NodeSelection,
removal with and without the extension, rebuilding the output from a
loaded state, migrating a MarkNode in a slot), `markableNodes` (the
default with `DecoratorTextNode`, a class list, a guard, extending the
default with a block decorator), and JSON with one key per id as an older
collaboration client saves it.
- `LexicalNodeState.test.ts`: the collab default, split, joining member
entries from JSON (with a whole value, removed members), before the state
is known (on first read and on a writable copy), one member at a time, a
key with U+001F that is not a member of a known set (kept as is), the
`createState` check, and `$getCollabSetStateKeys`.
Also run: `pnpm run test-unit` (395 files, 9685 passed, 8 expected fail,
1 skipped), the source tree-shaking test (341 pass), `pnpm run tsc`,
`pnpm run flow`, eslint and prettier on the touched files, and
`pnpm run build-docs` (the website build, which fails on broken links and
anchors; it passes, and the `lexical_mark#marknode`, `#markstateextension`
and `node-state#collaboration-set-valued-state` anchors exist).
Not exercised: real browsers (native `beforeinput` typing, IME composition,
paste at a mark edge) and real Yjs providers.
f4054e8 to
18d290e
Compare
|
Agreed, reworked along those lines. The ids are now one set-valued NodeState, |
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: |
…Feature: Experimental MarkStateExtension with set-valued NodeState for collaboration friendly marks
Current behavior: comment and annotation marks can only be stored as
`MarkNode` wrappers. Overlapping marks become sibling `MarkNode`s whose `ids`
the app has to keep consistent (with `registerNestedElementResolver`, without
it they nest), and every add or remove is a structural change. With the Yjs
v2 binding, concurrent edits around a mark move or duplicate text: typing
inside a range while a peer comments on it moves the typed text out of the
range, two peers commenting on the same text duplicate it, and removing or
undoing a comment while a peer types inside it loses the typed text.
NodeState has no way to hold a set that peers change concurrently: a
binding stores each key as one value, so two peers adding different
members to the same set keep only one peer's set.
New behavior (all opt-in and `@experimental`, `MarkNode` and its APIs are
unchanged):
- `lexical`: `createState` takes `collab: 'value' | 'set'` (default
`'value'`, exposed as `StateConfig.collab`). A `'set'` state serializes to
an array of strings (one array in JSON); collaboration bindings store each
member as its own entry, `<key>` + `NODE_STATE_SET_MEMBER_SEPARATOR`
(U+001F) + `<member>`, so concurrent additions and removals of different
members merge. NodeState joins a member entry back into the set wherever
it reads one (JSON import, `updateFromJSON` and `updateFromUnknown` from a
binding, and a later first read or writable copy), but only when a
`'set'` StateConfig with that key is known for the node type (declared in
`$config` or used on a node of that type) and no StateConfig uses the
entry key itself; otherwise the entry stays an ordinary key and is written
back as it is. So JSON saved by an editor whose Lexical version kept the
members as separate keys loads with its marks, and an unrelated key that
contains U+001F is never misread. `createState` rejects a `'set'` key that
contains U+001F. Helpers for bindings: `splitCollabStateEntries` and
`$getCollabSetStateKeys`. Flow types included.
- `@lexical/yjs`:
- v2 writes a set-valued state as one text attribute (TextNode) or element
attribute (other nodes) per member, `s_<key>\u001f<member>`.
- v1 writes one entry per member in the node's `__state` Y.Map, adding
and deleting entries as members change.
- The read paths are unchanged: they pass the stored entries to NodeState,
which joins them. A peer that does not know the state keeps each member
as its own unknown key and writes it back as it is, so it does not
collapse the members.
- `'value'` states are stored exactly as before.
- `@lexical/mark` adds `MarkStateExtension` (`@lexical/mark/MarkState`). The
ids of a leaf are one set-valued NodeState, `markIds` (`MARK_STATE_KEY`),
`{"$": {"markIds": ["c1", "c2"]}}` in JSON, so marks overlap freely and
concurrent adds and removes of different ids merge in v2 and in v1 (where
no TextNode split or merge is involved).
- `$addMarkID(id, selection)`, `$removeMarkID(id, selection?)`,
`$getMarkIDsAtSelection(selection?, 'any' | 'all')`, `$getNodeMarkIDs(node)`
(`ID` casing as in `$getMarkIDs` and `MarkNode.getIDs`). Ids must be
non-empty and free of whitespace; `$addMarkID` throws otherwise.
- Config: `disabled`, `exportIDsToHTML` (default `false`) and
`markableNodes`: node classes (matched with `instanceof`) and guard
functions that decide which nodes carry ids. The default,
`DEFAULT_MARKABLE_NODES`, is TextNode, LineBreakNode and
`$isInlineDecoratorNode` (every inline DecoratorNode, which includes
`DecoratorTextNode`).
- Marking a range also marks the content of the slots of the ElementNodes
and DecoratorNodes in it (and of a slot host in a NodeSelection);
removing an id from the whole document, rebuilding the output, the HTML
import rule and `$migrateMarkNodesToMarkState()` look inside slots too.
- When the editor is built, the extension registers the `markIds`
StateConfig on every node type, so ids read from JSON or from a peer are
parsed (and written back per id) before the editor has marked anything.
- Output: `disabled`, `exportIDsToHTML` and `markIDNodeKeys`, a signal with
a Map from each id to the keys of the leaves that carry it, maintained
from update listeners (so it also works headless, after collaboration
updates and after undo). `$removeMarkID(id)` uses it instead of walking
the document.
- Rendering through `DOMRenderExtension`: the `mark` / `markOverlap` theme
classes and a `data-lexical-mark-ids` attribute. HTML export writes the
attribute only with `exportIDsToHTML` (like `MarkNode`, ids are not
exported by default), and a `DOMImportExtension` rule reads it back.
- Text typed at the edge of a marked run does not join it (as with
`MarkNode`), implemented with a TextNode transform that compares with the
caret position before the update; composition is handled from
`COMPOSITION_START_COMMAND` because transforms skip the composing node.
Text inserted inside a run keeps the ids, including when the core puts it
in a new TextNode (replacing a selection, a format change at the caret, a
single-node paste), and next to inline elements such as links, whose
leaves count as the neighbors. Collaboration and history updates are left
alone.
- `$migrateMarkNodesToMarkState()` converts a `MarkNode` document.
- Docs: a new "Comments and Annotations" page under Collaboration, and a
"Collaboration: set-valued state" section on the NodeState page. They
describe the limits:
- v1 syncs a TextNode split or merge as a delete and a re-insert, so the
races that split or merge TextNodes (including removing the last id of
a run) still move or duplicate text on v1;
- with three peers, and with two peers when one adds and removes ids in
one update while the other types in the overlap, v2 can extend a mark
(the peers converge), because it re-applies the text attributes of a
whole paragraph from a possibly stale view. The v2 stale-attribute fix
(#9381) makes these pass; `test.fails` cases pin them until it lands;
- a mark racing a paragraph merge stays order dependent;
- leaves that are re-created (code highlighting, node replacement) lose
their ids.
Interaction with other open PRs:
- #9379 (unknown node types) touches `Utils.ts` and `SyncV2.ts` too. An
earlier revision of this change conflicted with it there; this revision
applies cleanly on top of it in either order, and the yjs, mark and
Collab tests pass on the combination. If a conflict comes back after a
rebase, keep both sides: this change only adds the `collab: 'set'` branch
of the known-state loop in `syncNodeStateFromLexical` with its two
helpers (`Utils.ts`) and the `splitCollabStateEntries` call in
`stateToAttributes` (`SyncV2.ts`), plus their imports.
- #9381 (v2 stale attributes): whichever of #9380 and #9381 lands second
flips the 4 v2 `test.fails` in `MarkStateCollab.test.tsx` (three peers,
2 orders; add and remove in one update, 2 orders) to `test`. With #9381
cherry-picked on top of this commit (no conflict), vitest reports
"Expect test to fail" for exactly those four.
The format of this extension was never released, so the JSON
(`markIds` array) and Yjs layout (`s_markIds\u001f<id>`) are new; earlier
drafts of this change used one `mark:<id>` key per id, which is not read.
Bytes per operation are within a few percent of one key per id (the key
name is 4 characters longer); storing the set whole is larger as well as
last-writer-wins:
```
"Revenue grew 4% in Q3.": add c1 (8-15), add c2 (12-19), add c3 (8-12), remove c1, remove c2
v1 set (this change) 299 364 30 41 36 doc 1019
v1 mark:<id> keys 296 355 27 59 45 doc 1031
v1 whole set 306 361 35 69 46 doc 1060
v2 set (this change) 139 243 177 196 86 doc 870
v2 mark:<id> keys 133 231 165 184 83 doc 825
v2 whole set 145 262 182 197 117 doc 934
```
The two-peer scenarios of `MarkStateCollab.test.tsx` written with the
`MarkNode` API (`$wrapSelectionInMarkNode`, the nested element resolver,
`deleteID` / `$unwrapMarkNode`) in a scratch copy not part of this commit,
on the v2 plugin. Both peers converge on the wrong document:
```
W1: typing inside a range ‖ a peer marks it
paragraph("Revenue by " mark[c1]("grew 4%") " in Q3.")
W3: two peers mark the same range
paragraph("Revenue " mark[c1]("grew 4%") " in Q3." mark[c2]("grew 4%") " in Q3.")
two peers mark overlapping ranges
paragraph("Revenue " mark[c1]("grew 4%") " in Q3." mark[c2](" 4% in ") "Q3.")
W4 (both variants), R1, removing a mark ‖ a peer marks the same range
paragraph("Revenue grew 4% in Q3.")
```
The new tests against the previous draft of this change (one `mark:<id>`
key per id, no `collab` option, no slots or `markableNodes`):
```
$ npx vitest --project unit --no-watch packages/lexical-react/src/__tests__/unit/CollaborationSetState.test.ts packages/lexical-mark/src/__tests__/unit/MarkStateCollab.test.tsx packages/lexical-mark/src/__tests__/unit/MarkStateExtension.test.ts
× v1/v2 on element/text > concurrent additions of different members merge
AssertionError: expected [ 'b', 'shared' ] to deeply equal [ 'a', 'b', 'shared' ]
× v1/v2 on element/text > a removal and a concurrent addition both apply
× slots > marking a range marks the content of the slots in it
Expected: ... test-figure{paragraph("A caption"[c1])} ...
Received: ... test-figure{paragraph("A caption")} ...
× slots > a NodeSelection of a slot host marks the content of its slots
× slots > the output is rebuilt from the slots of a loaded state
× slots > a MarkNode inside a slot migrates
× markable nodes > a class list / a guard function / extending the default with a block decorator
× each id is its own text attribute / entry in the state map
Test Files 3 failed (3)
Tests 20 failed | 78 passed | 8 expected fail (106)
```
The decoding tests against the revision before that (config-free joining
in the bindings only, no joining in NodeState):
```
× JSON with one key per id, as an older collaboration client saves it, shows the marks
Expected: "paragraph("Revenue grew 4% in Q3."[c1,c2])"
Received: "paragraph("Revenue grew 4% in Q3.")"
× member entries in JSON are joined into a known set-valued state
AssertionError: expected [ 'z' ] to deeply equal [ 'a', 'b:c', 'z' ]
× member entries read before the state is known are joined on first use
× a member entry adds or removes one member
× a collab: 'set' key can not contain the separator
× v1/v2 on element/text > a value state whose key contains U+001F is synced as is
AssertionError: expected '' to be 'x'
Tests 9 failed | 229 passed (238)
```
```
$ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-mark packages/lexical-yjs packages/lexical-react/src/__tests__/unit/Collab packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts
Test Files 29 passed (29)
Tests 1139 passed | 8 expected fail (1147)
```
- `CollaborationSetState.test.ts`: a generic `collab: 'set'` state on a
paragraph and on a TextNode, v1 and v2, two offline peers: concurrent
additions of different members merge (`['a', 'b', 'shared']`), a removal
and a concurrent addition both apply, a value state whose key contains
U+001F syncs as is, and the same state with `collab: 'value'` keeps one
peer's whole set.
- `MarkStateCollab.test.tsx`, both client id orders, asserting the tree, the
`markIDNodeKeys` output and the Y.Doc on every peer:
- v2: W1, W3, overlapping ranges, typing in an overlap ‖ second mark,
W4 (both), R1, resolving one of two marks ‖ typing in the overlap,
removing ‖ marking the same range, a line break, edge typing; the
stored attributes (`s_markIds\u001fc1`, ...); a peer without the
extension typing in a marked run keeps the attributes per id.
- v1: one `__state` entry per id; two peers marking the same TextNode
(`"grew 4%"[c0,c1,c2,c9]`), removing ‖ marking it, resolving ‖ typing
inside (`"grew by 4%"[c9]`), undo after a peer typed inside.
- 8 expected failures: three peers (2 orders) and add-and-remove in one
update ‖ typing in the overlap (2 orders) on v2, which pass with #9381
cherry-picked on top (vitest reports "Expect test to fail" for all
four); the paragraph merge race (2 orders); and v1 resolving the only
mark of a TextNode ‖ typing inside it (2 orders), where v1 moves the
typed text to the end of the paragraph.
- `MarkStateExtension.test.ts`: overlap, queries, split and merge, edge
typing, composition, links, ids, HTML, undo, rendering, migration, the
JSON format, and new: slots (a range across a slot host, a NodeSelection,
removal with and without the extension, rebuilding the output from a
loaded state, migrating a MarkNode in a slot), `markableNodes` (the
default with `DecoratorTextNode`, a class list, a guard, extending the
default with a block decorator), and JSON with one key per id as an older
collaboration client saves it.
- `LexicalNodeState.test.ts`: the collab default, split, joining member
entries from JSON (with a whole value, removed members), before the state
is known (on first read and on a writable copy), one member at a time, a
key with U+001F that is not a member of a known set (kept as is), the
`createState` check, and `$getCollabSetStateKeys`.
Also run on this commit: `pnpm run tsc` and `pnpm run flow` (0 errors).
With the `@lexical/y` follow-up on top (no further changes to these files):
`pnpm run build`, the tree-shaking tests (source 360 pass, build output 284
pass), eslint and prettier on the touched files, and `pnpm run build-docs`
(the website build, which fails on broken links and anchors; it passes, and
the `lexical_mark#marknode`, `#markstateextension` and
`node-state#collaboration-set-valued-state` anchors exist).
Not exercised: real browsers (native `beforeinput` typing, IME composition,
paste at a mark edge) and real Yjs providers.
## Description Stacked on #9438 (the `@lexical/y` stack: #9400, #9449, #9437, #9438). Depends on #9380 (`MarkStateExtension` and `collab: 'set'` NodeState). This branch carries that commit as a temporary dependency commit, to be dropped once #9380 merges. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own Y.Node, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` format per member (`splitCollabStateEntries`). Concurrent additions and removals of different members merge. Reading is unchanged: NodeState joins the member entries back into the set (#9380). Block markers, wrappers and list groups still store the set whole. - A peer that does not know the state keeps each member as its own NodeState key and writes it back unchanged, so it never collapses the members. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, so it reads the members the same way (otherwise every write of a set would be reported to the binding's `onWarn` as a `'self-check'` warning). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one set-valued state, like `MarkStateExtension`; `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit in the `@lexical/y` README and on the Yjs 14 collaboration page now says where the set is stored per member and where it is still one value (line markers, groups, inline wrappers). Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 83 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 12 / 142 / 10 113 / 144 / 113 ``` ## Test plan New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. ### Before `Schema.ts` and `SelfCheck.ts` reverted to the dependency commit: ``` $ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 Tests 17 failed | 40 passed (57) ``` ### After ``` $ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y packages/lexical-yjs packages/lexical-mark packages/lexical-react/src/__tests__/unit/Collab packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts Test Files 75 passed (75) Tests 3209 passed | 8 expected fail | 2 skipped (3219) ``` The 8 expected failures are `MarkStateCollab.test.tsx`'s pinned v2 and v1 limits from #9380 (#9381 is not in this stack). The 2 skipped tests are in `ListsInLines.test.ts` and are skipped on #9400 as well. Fuzz with comments as one set-valued state, 500 seeds plus 100 gc seeds: ``` $ FUZZ_SEEDS=500 npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/Fuzz.test.ts ✓ seeds 1..51 ... ✓ seeds 451..501, ✓ gc seeds 1..51, ✓ gc seeds 51..101 Tests 12 passed (12) ``` On the whole stack (this commit on top), the same fuzz at 2,000 + 500 gc seeds, with and without block moves, passes (116 of 116 chunks), and so does `pnpm run test-unit` (443 files). Also run: `pnpm run tsc`, `pnpm run flow` (0 errors), eslint and prettier on the touched files, `pnpm run build`, the tree-shaking tests (source 364 pass, build output 286 pass) and `pnpm run build-docs`. Not exercised: real Yjs 14 providers and browsers.
…Feature: Experimental MarkStateExtension with set-valued NodeState for collaboration friendly marks
## Description
Current behavior: comment and annotation marks can only be stored as
`MarkNode` wrappers. Overlapping marks become sibling `MarkNode`s whose `ids`
the app has to keep consistent (with `registerNestedElementResolver`, without
it they nest), and every add or remove is a structural change. With the Yjs
v2 binding, concurrent edits around a mark move or duplicate text: typing
inside a range while a peer comments on it moves the typed text out of the
range, two peers commenting on the same text duplicate it, and removing or
undoing a comment while a peer types inside it loses the typed text.
NodeState has no way to hold a set that peers change concurrently: a
binding stores each key as one value, so two peers adding different
members to the same set keep only one peer's set.
New behavior (all opt-in and `@experimental`, `MarkNode` and its APIs are
unchanged):
- `lexical`: `createState` takes `collab: 'value' | 'set'` (default
`'value'`, exposed as `StateConfig.collab`). A `'set'` state serializes to
an array of strings (one array in JSON); collaboration bindings store each
member as its own entry, `<key>` + `NODE_STATE_SET_MEMBER_SEPARATOR`
(U+001F) + `<member>`, so concurrent additions and removals of different
members merge. NodeState joins a member entry back into the set wherever
it reads one (JSON import, `updateFromJSON` and `updateFromUnknown` from a
binding, and a later first read or writable copy), but only when a
`'set'` StateConfig with that key is known for the node type (declared in
`$config` or used on a node of that type) and no StateConfig uses the
entry key itself; otherwise the entry stays an ordinary key and is written
back as it is. So JSON saved by an editor whose Lexical version kept the
members as separate keys loads with its marks, and an unrelated key that
contains U+001F is never misread. `createState` rejects a `'set'` key that
contains U+001F. Helpers for bindings: `splitCollabStateEntries` and
`$getCollabSetStateKeys`. Flow types included.
- `@lexical/yjs`:
- v2 writes a set-valued state as one text attribute (TextNode) or element
attribute (other nodes) per member, `s_<key>\u001f<member>`.
- v1 writes one entry per member in the node's `__state` Y.Map, adding
and deleting entries as members change.
- The read paths are unchanged: they pass the stored entries to NodeState,
which joins them. A peer that does not know the state keeps each member
as its own unknown key and writes it back as it is, so it does not
collapse the members.
- `'value'` states are stored exactly as before.
- `@lexical/mark` adds `MarkStateExtension` (`@lexical/mark/MarkState`). The
ids of a leaf are one set-valued NodeState, `markIds` (`MARK_STATE_KEY`),
`{"$": {"markIds": ["c1", "c2"]}}` in JSON, so marks overlap freely and
concurrent adds and removes of different ids merge in v2 and in v1 (where
no TextNode split or merge is involved).
- `$addMarkID(id, selection)`, `$removeMarkID(id, selection?)`,
`$getMarkIDsAtSelection(selection?, 'any' | 'all')`, `$getNodeMarkIDs(node)`
(`ID` casing as in `$getMarkIDs` and `MarkNode.getIDs`). Ids must be
non-empty and free of whitespace; `$addMarkID` throws otherwise.
- Config: `disabled`, `exportIDsToHTML` (default `false`) and
`markableNodes`: node classes (matched with `instanceof`) and guard
functions that decide which nodes carry ids. The default,
`DEFAULT_MARKABLE_NODES`, is TextNode, LineBreakNode and
`$isInlineDecoratorNode` (every inline DecoratorNode, which includes
`DecoratorTextNode`).
- Marking a range also marks the content of the slots of the ElementNodes
and DecoratorNodes in it (and of a slot host in a NodeSelection);
removing an id from the whole document, rebuilding the output, the HTML
import rule and `$migrateMarkNodesToMarkState()` look inside slots too.
- When the editor is built, the extension registers the `markIds`
StateConfig on every node type, so ids read from JSON or from a peer are
parsed (and written back per id) before the editor has marked anything.
- Output: `disabled`, `exportIDsToHTML` and `markIDNodeKeys`, a signal with
a Map from each id to the keys of the leaves that carry it, maintained
from update listeners (so it also works headless, after collaboration
updates and after undo). `$removeMarkID(id)` uses it instead of walking
the document.
- Rendering through `DOMRenderExtension`: the `mark` / `markOverlap` theme
classes and a `data-lexical-mark-ids` attribute. HTML export writes the
attribute only with `exportIDsToHTML` (like `MarkNode`, ids are not
exported by default), and a `DOMImportExtension` rule reads it back.
- Text typed at the edge of a marked run does not join it (as with
`MarkNode`), implemented with a TextNode transform that compares with the
caret position before the update; composition is handled from
`COMPOSITION_START_COMMAND` because transforms skip the composing node.
Text inserted inside a run keeps the ids, including when the core puts it
in a new TextNode (replacing a selection, a format change at the caret, a
single-node paste), and next to inline elements such as links, whose
leaves count as the neighbors. Collaboration and history updates are left
alone.
- `$migrateMarkNodesToMarkState()` converts a `MarkNode` document.
- Docs: a new "Comments and Annotations" page under Collaboration (when to
use `MarkStateExtension` rather than `MarkNode`, usage, limitations), a
short "Collaboration: set-valued state" section on the NodeState page, and
an entry on the included extensions page. The limits, with the test
evidence behind them:
- v1 syncs a TextNode split or merge as a delete and a re-insert, so the
races that split or merge TextNodes (including removing the last id of
a run) still move or duplicate text on v1;
- with three peers, and with two peers when one adds and removes ids in
one update while the other types in the overlap, v2 can extend a mark
(the peers converge), because it re-applies the text attributes of a
whole paragraph from a possibly stale view. The v2 stale-attribute fix
(#9381) makes these pass; `test.fails` cases pin them until it lands;
- a mark racing a paragraph merge stays order dependent;
- leaves that are re-created (code highlighting, node replacement) lose
their ids.
Interaction with other open PRs:
- #9379 (unknown node types) touches `Utils.ts` and `SyncV2.ts` too. An
earlier revision of this change conflicted with it there; this revision
applies cleanly on top of it in either order, and the yjs, mark and
Collab tests pass on the combination. If a conflict comes back after a
rebase, keep both sides: this change only adds the `collab: 'set'` branch
of the known-state loop in `syncNodeStateFromLexical` with its two
helpers (`Utils.ts`) and the `splitCollabStateEntries` call in
`stateToAttributes` (`SyncV2.ts`), plus their imports.
- #9381 (v2 stale attributes): whichever of #9380 and #9381 lands second
flips the 4 v2 `test.fails` in `MarkStateCollab.test.tsx` (three peers,
2 orders; add and remove in one update, 2 orders) to `test`. With #9381
cherry-picked on top of this commit (no conflict), vitest reports
"Expect test to fail" for exactly those four.
The format of this extension was never released, so the JSON
(`markIds` array) and Yjs layout (`s_markIds\u001f<id>`) are new; earlier
drafts of this change used one `mark:<id>` key per id, which is not read.
Bytes per operation are within a few percent of one key per id (the key
name is 4 characters longer); storing the set whole is larger as well as
last-writer-wins:
```
"Revenue grew 4% in Q3.": add c1 (8-15), add c2 (12-19), add c3 (8-12), remove c1, remove c2
v1 set (this change) 299 364 30 41 36 doc 1019
v1 mark:<id> keys 296 355 27 59 45 doc 1031
v1 whole set 306 361 35 69 46 doc 1060
v2 set (this change) 139 243 177 196 86 doc 870
v2 mark:<id> keys 133 231 165 184 83 doc 825
v2 whole set 145 262 182 197 117 doc 934
```
## Test plan
### Before
The two-peer scenarios of `MarkStateCollab.test.tsx` written with the
`MarkNode` API (`$wrapSelectionInMarkNode`, the nested element resolver,
`deleteID` / `$unwrapMarkNode`) in a scratch copy not part of this commit,
on the v2 plugin. Both peers converge on the wrong document:
```
W1: typing inside a range ‖ a peer marks it
paragraph("Revenue by " mark[c1]("grew 4%") " in Q3.")
W3: two peers mark the same range
paragraph("Revenue " mark[c1]("grew 4%") " in Q3." mark[c2]("grew 4%") " in Q3.")
two peers mark overlapping ranges
paragraph("Revenue " mark[c1]("grew 4%") " in Q3." mark[c2](" 4% in ") "Q3.")
W4 (both variants), R1, removing a mark ‖ a peer marks the same range
paragraph("Revenue grew 4% in Q3.")
```
The new tests against the previous draft of this change (one `mark:<id>`
key per id, no `collab` option, no slots or `markableNodes`):
```
$ npx vitest --project unit --no-watch packages/lexical-react/src/__tests__/unit/CollaborationSetState.test.ts packages/lexical-mark/src/__tests__/unit/MarkStateCollab.test.tsx packages/lexical-mark/src/__tests__/unit/MarkStateExtension.test.ts
× v1/v2 on element/text > concurrent additions of different members merge
AssertionError: expected [ 'b', 'shared' ] to deeply equal [ 'a', 'b', 'shared' ]
× v1/v2 on element/text > a removal and a concurrent addition both apply
× slots > marking a range marks the content of the slots in it
Expected: ... test-figure{paragraph("A caption"[c1])} ...
Received: ... test-figure{paragraph("A caption")} ...
× slots > a NodeSelection of a slot host marks the content of its slots
× slots > the output is rebuilt from the slots of a loaded state
× slots > a MarkNode inside a slot migrates
× markable nodes > a class list / a guard function / extending the default with a block decorator
× each id is its own text attribute / entry in the state map
Test Files 3 failed (3)
Tests 20 failed | 78 passed | 8 expected fail (106)
```
The decoding tests against the revision before that (config-free joining
in the bindings only, no joining in NodeState):
```
× JSON with one key per id, as an older collaboration client saves it, shows the marks
Expected: "paragraph("Revenue grew 4% in Q3."[c1,c2])"
Received: "paragraph("Revenue grew 4% in Q3.")"
× member entries in JSON are joined into a known set-valued state
AssertionError: expected [ 'z' ] to deeply equal [ 'a', 'b:c', 'z' ]
× member entries read before the state is known are joined on first use
× a member entry adds or removes one member
× a collab: 'set' key can not contain the separator
× v1/v2 on element/text > a value state whose key contains U+001F is synced as is
AssertionError: expected '' to be 'x'
Tests 9 failed | 229 passed (238)
```
### After
```
$ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-mark packages/lexical-yjs packages/lexical-react/src/__tests__/unit/Collab packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts
Test Files 29 passed (29)
Tests 1139 passed | 8 expected fail (1147)
```
- `CollaborationSetState.test.ts`: a generic `collab: 'set'` state on a
paragraph and on a TextNode, v1 and v2, two offline peers: concurrent
additions of different members merge (`['a', 'b', 'shared']`), a removal
and a concurrent addition both apply, a value state whose key contains
U+001F syncs as is, and the same state with `collab: 'value'` keeps one
peer's whole set.
- `MarkStateCollab.test.tsx`, both client id orders, asserting the tree, the
`markIDNodeKeys` output and the Y.Doc on every peer:
- v2: W1, W3, overlapping ranges, typing in an overlap ‖ second mark,
W4 (both), R1, resolving one of two marks ‖ typing in the overlap,
removing ‖ marking the same range, a line break, edge typing; the
stored attributes (`s_markIds\u001fc1`, ...); a peer without the
extension typing in a marked run keeps the attributes per id.
- v1: one `__state` entry per id; two peers marking the same TextNode
(`"grew 4%"[c0,c1,c2,c9]`), removing ‖ marking it, resolving ‖ typing
inside (`"grew by 4%"[c9]`), undo after a peer typed inside.
- 8 expected failures: three peers (2 orders) and add-and-remove in one
update ‖ typing in the overlap (2 orders) on v2, which pass with #9381
cherry-picked on top (vitest reports "Expect test to fail" for all
four); the paragraph merge race (2 orders); and v1 resolving the only
mark of a TextNode ‖ typing inside it (2 orders), where v1 moves the
typed text to the end of the paragraph.
- `MarkStateExtension.test.ts`: overlap, queries, split and merge, edge
typing, composition, links, ids, HTML, undo, rendering, migration, the
JSON format, and new: slots (a range across a slot host, a NodeSelection,
removal with and without the extension, rebuilding the output from a
loaded state, migrating a MarkNode in a slot), `markableNodes` (the
default with `DecoratorTextNode`, a class list, a guard, extending the
default with a block decorator), and JSON with one key per id as an older
collaboration client saves it.
- `LexicalNodeState.test.ts`: the collab default, split, joining member
entries from JSON (with a whole value, removed members), before the state
is known (on first read and on a writable copy), one member at a time, a
key with U+001F that is not a member of a known set (kept as is), the
`createState` check, and `$getCollabSetStateKeys`.
Also run on this commit: `pnpm run tsc` and `pnpm run flow` (0 errors).
With the `@lexical/y` follow-up on top (no further changes to these files):
`pnpm run build`, the tree-shaking tests (source 360 pass, build output 284
pass), eslint and prettier on the touched files, and `pnpm run build-docs`
(the website build, which fails on broken links and anchors; it passes, and
the `lexical_mark#marknode`, `#markstateextension` and
`node-state#collaboration-set-valued-state` anchors exist).
Not exercised: real browsers (native `beforeinput` typing, IME composition,
paste at a mark edge) and real Yjs providers.
## Description Stacked on #9438 (the `@lexical/y` stack: #9400, #9449, #9437, #9438). Depends on #9380 (`MarkStateExtension` and `collab: 'set'` NodeState). This branch carries that commit as a temporary dependency commit, to be dropped once #9380 merges. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own Y.Node, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` format per member (`splitCollabStateEntries`). Concurrent additions and removals of different members merge. Reading is unchanged: NodeState joins the member entries back into the set (#9380). Block markers, wrappers and list groups still store the set whole. - A peer that does not know the state keeps each member as its own NodeState key and writes it back unchanged, so it never collapses the members. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, so it reads the members the same way (otherwise every write of a set would be reported to the binding's `onWarn` as a `'self-check'` warning). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one set-valued state, like `MarkStateExtension`; `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (paragraphs and list items, lists, links); the README's wire format adds the member entries (`s:<key>\u001f<member>` = `true`); the Comments and NodeState pages name `@lexical/y` among the bindings that store members separately. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 83 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 12 / 142 / 10 113 / 144 / 113 ``` ## Test plan New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. ### Before `Schema.ts` and `SelfCheck.ts` reverted to the dependency commit: ``` $ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 Tests 17 failed | 40 passed (57) ``` ### After ``` $ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y packages/lexical-yjs packages/lexical-mark packages/lexical-react/src/__tests__/unit/Collab packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts Test Files 76 passed (76) Tests 3256 passed | 8 expected fail | 2 skipped (3266) ``` The 8 expected failures are `MarkStateCollab.test.tsx`'s pinned v2 and v1 limits from #9380 (#9381 is not in this stack). The 2 skipped tests are in `ListsInLines.test.ts` and are skipped on #9400 as well. Fuzz with comments as one set-valued state, on the whole stack (this commit on top), 2,000 seeds plus 500 gc seeds, without and with block moves (25 seeds per test): ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts ✓ @lexical/y fuzz (100) ✓ @lexical/y fuzz with block moves (103) Tests 203 passed (203) ``` `pnpm run test-unit` on the whole stack: 444 files, 11,999 passed, 3 skipped. Also run: `pnpm run tsc`, `pnpm run flow` (0 errors), eslint and prettier on the touched files, `pnpm run build`, the tree-shaking tests (source 364 pass, build output 286 pass) and `pnpm run build-docs`. Not exercised: real Yjs 14 providers and browsers.
2dd9c9c to
81fdca4
Compare
…-website][lexical-yjs] Feature: Experimental MarkStateExtension and set-valued NodeState with arraySetValue
## Description
Current behavior: NodeState has no value type for a set. A state holding one
needs a hand-written `parse`, `unparse` and `isEqual`, nothing keeps a value
written with `$setState` in one canonical order, and nothing tells code that
reads the state that its members are independent. Comment and annotation
marks can only be stored as `MarkNode` wrappers: overlapping marks become
sibling `MarkNode`s whose `ids` the app has to keep consistent (with
`registerNestedElementResolver`; without it they nest), and every add or
remove restructures the tree.
New behavior (all opt-in and `@experimental`; existing states, schemas,
`MarkNode` and the rest of `@lexical/mark` are unchanged, and `@lexical/yjs`
gets no source change):
**`lexical`: `arraySetValue(item)`**, a value schema in the `stringValue` /
`arrayValue` family:
`createState('tags', {parse: arraySetValue(stringValue())})` is a
`StateConfig<'tags', readonly string[]>`.
- The value is a frozen array of strings used as a set: sorted by UTF-16 code
unit, no duplicates. Parsing keeps the entries `item` accepts (others are
dropped, not coerced), dedupes, sorts and freezes; a non-array is the
frozen empty array, which is the default. An already canonical frozen value
is returned as is.
- `$setState` puts a value written to such a state, directly or from an
updater, into the same form, so `$setState(node, tagsState, ['b', 'a', 'a'])`
stores `['a', 'b']`. For every other state `$setState` stores the value as
given, as before.
- Equality is element by element (so "same members", since both sides are
canonical): an updater returning the same members in another order does
not dirty the node, and the empty set is left out of the JSON. The JSON is
the sorted array, so equal sets serialize identically.
- Members are strings (`T extends string`, so `enumValue([...])` works as the
item), which gives a well-defined order. An item schema that declines some
strings in its `accepts` makes parsing drop them, so a set can admit only
well-formed members. A development build refuses an item that does not
produce strings (only reachable from untyped code).
- The schema meta says the value is a set: `stateConfig.schema?.meta.kind ===
'set'`, with `meta.item`, marks it as a set whose members are independent,
so code that stores or merges values can treat each member separately.
This adds one variant to `SerializationSchemaMeta` and nothing to
`StateConfig`. `@lexical/fast-check` generates inputs for it.
- It must be the whole value of a `createState`. A development build refuses
it inside another combinator, in an `objectValue` field and as a node
property (`nodeSchema`, `withField`). The check is added to the
development-only checks those combinators already run; it is the only
change to them.
- Flow types, and `arraySetValue` in the compiler's pure-factory list.
**`@lexical/mark`: `MarkStateExtension`** (exported from `@lexical/mark`).
Mark ids are a set-valued NodeState, `markIds` (`MARK_STATE_KEY`), on the
leaves they cover: `TextNode`, `LineBreakNode` and inline `DecoratorNode`s by
default. There is no wrapper node. The ids live on the leaves, so they travel
with the text: typing inside a marked run adds to the TextNode that carries
the ids, marking part of a run splits the TextNode and neighbors with the
same ids merge back, and copying, cutting or deleting text carries or
deletes its ids. Marks overlap freely, and adding or removing a comment
changes NodeState only. In JSON a leaf covered by `c1` and `c2` has
`{"$": {"markIds": ["c1", "c2"]}}`.
- Helpers: `$addMarkID(id, selection)`, `$removeMarkID(id, selection?)` (no
selection: everywhere), `$getMarkIDsAtSelection(selection?, 'any' | 'all')`,
`$getNodeMarkIDs(node)`, `$migrateMarkNodesToMarkState(node?)`,
`$isInlineDecoratorNode` (a type guard), `MARK_STATE_KEY`,
`MARK_STATE_IDS_ATTRIBUTE`, `DEFAULT_MARKABLE_NODES`. The getters return new
sorted arrays the caller may change.
- Ids are non-empty strings without whitespace. `$addMarkID` and the
migration throw on anything else; an invalid id read from JSON or HTML,
written with `$setState`, or applied with `updateFromUnknown` is dropped,
through the item schema of the state.
- Config: `disabled`, `exportIDsToHTML` (default `false`, like `MarkNode`) and
`markableNodes` (node classes and guard functions).
- Output: `markIDNodeKeys`, a signal mapping each id to the keys of the leaves
that carry it, maintained from update listeners (so it works headless and
after undo). Each update costs what it changed: the dirty leaves, and the
leaves under the nodes it removed. A `setEditorState` (undo and redo
included), whose dirty sets do not describe the change, is compared with
the previous state node by node, reading only the nodes that are not the
same object in both. `$removeMarkID(id)` uses the output instead of
walking the document.
- Text inserted by a local edit gets the ids shared by the text right before
and right after where it was inserted (within its block), plus, when it
replaces a selection, the ids all the replaced text had, plus, for pasted
content, its own ids. So text inserted at the edge of a marked run does
not join it (as with `MarkNode`), text inserted inside a run does,
retyping a commented word keeps the comment (also when it replaces all of
the marked text, where `MarkNode` loses the comment), and pasted content
keeps the ids it was copied with and also joins the run it is pasted
inside, and so do dropped content and nodes that code inserts. Text
inserted into existing text has no ids of its own, also when a transform
then splits it off into a copy of that text: text typed or pasted as
plain text after a commented hashtag is not commented, as with
`MarkNode`. Text that is not deleted keeps its ids, also when the core
or a transform moves it into a new TextNode (a hashtag or a mention created from commented text, a
segmented node that typing turns into text). An id removed with
`$removeMarkID` in the same update is not given back, to that text or
to inserted text. That holds for the whole update (and the updates
batched with it): also where the removal did not reach, and after the
update adds the id again. The docs list this as a limitation.
- A TextNode whose text gets different ids is split when its pieces stay of
its own class: `TextNode`, or the class that replaces it through a node
replacement (with or without `withKlass`). Other TextNodes are not split
and get every id their text had: token and segmented nodes, and
subclasses whose boundaries their own transforms set, such as a hashtag
or a code highlighting token (their pieces would be plain text, which
those transforms merge back). In such a node, text typed at the edge of a
mark joins it. Text inserted at the end of such a node that its transform
then splits off is told apart by identity: `splitText` gives the piece the
node's NodeState, so the piece holds the very array of the node's ids,
while pasted, dropped, imported or inserted content, and ids added with
`$addMarkID`, are an array of their own even when they are the same ids.
So a new `TextNode` of the class `splitText` creates, whose nearest
earlier sibling from before the update is a `TextNode` of another class
holding the same array (`===`), is a piece split off it, and those ids
are not its own. This does not depend on how the text was inserted or on
what a DataTransfer holds, so a drop, a paste whose HTML equals its plain
text (as iOS sends with autocorrect), and nodes that code inserts and
marks in the same update all come out like `MarkNode`. The array is
shared only by copying NodeState as it is: `splitText`, `$copyNode`,
`$setState` with a value read from another node, and JSON from
`exportJSON()` imported without a round trip through a string.
Code that gives a plain `TextNode` the array of such a node that way and
inserts it right after that node gets it unmarked at the end of the mark;
the docs list this as a limitation.
- How the inserted text is found: a root transform compares the changed
children around the caret with the previous editor state. A child that
is the same object in both states is unchanged, and one on each side
bounds the comparison. Within that, the text both states share at the
start and at the end is compared as a few units, so a keystroke costs a
scan of the changed TextNodes plus units for the changed text only, also
in one long TextNode (see the table below). Text is compared by code
point, so no surrogate pair is split. The change ends at the caret. When
it replaces a selection, the selection is the one recorded when
`CONTROLLED_TEXT_INSERTION_COMMAND` or `PASTE_COMMAND` was last
dispatched, inside an update or not (typing, autocorrection and the DOM
`paste` event all record it), or the one the composition started with.
The record is forgotten when the editor commits and at the next
microtask, and it is used only when the text in its place is in new
TextNodes, as the core inserts it, so a handler that wraps the selection
instead is not taken for a replacement. Updates batched into one commit
are compared with the document from before the commit, as one edit: the
last command dispatched before the commit decides the replaced selection
for all of them. Typed text in such a batch does not affect nodes that
code inserts: they keep their own ids.
Without a recorded selection (code calling `selection.insertText()`
directly) the longest common subsequence of the old and new text tells
the kept letters, which keep their ids, from the inserted ones; then a
replacement across the edge of a mark that starts or ends with the
letter it replaces can join that mark. So the rule holds whichever
TextNode the core puts the text in (native input, `insertText`, a new
node for a toggled format or for the text replacing a selection, an input
method, a multi-node paste, a caret placed in the same update). History
replays and updates tagged `COLLABORATION_TAG` are left alone, and so is
a composition whose paragraph such an update edited while it was in
progress.
- Marking a range also marks the content of slots inside it; removal, the
output, HTML import and migration look inside slots too.
- Rendering: the `mark` / `markOverlap` theme classes and a
`data-lexical-mark-ids` attribute on each marked leaf. With
`exportIDsToHTML` HTML export writes the attribute, and a
`DOMImportExtension` rule reads it back.
- When the editor is built, the extension registers the `markIds` state on
every node type, so ids read from JSON are parsed at once.
- New dependencies of `@lexical/mark`: `@lexical/extension`, `@lexical/html`
and `@lexical/internal` (`@lexical/internal` is inlined by the build).
- It works with `NodeStructureExtension` on: the ids stay on the leaves that
its repairs move (a block lifted out of a heading, a heading split around
a quote), and the output follows them. The
extension's tests and both property tests give the same results with it
on.
**Docs:** a "Comments and Annotations" page under Collaboration (how ids
follow the text, a `MarkNode` to `MarkStateExtension` table, the inserted
text rule and its limits, and how `@lexical/yjs` syncs the ids), a
"Set-valued state" section on the NodeState page, and an entry on the
included extensions page.
**Changes since the version reviewed earlier** (levensta's review comments
and Bob's request for set-valued state):
- `arraySetValue` replaces the `collab: 'set'` option on `createState`. The
state is declared as a value schema like any other, and the core has no
collaboration vocabulary: `StateCollabEncoding`, the `collab` field and the
split-entry helpers are gone.
- The `@lexical/yjs` changes are dropped: per-member storage of set-valued
state is no longer part of this PR, and the `@lexical/yjs` sources are
identical to `main`. The only file this PR adds under
`packages/lexical-yjs` is the two-peer test of `MarkStateExtension`, which
lives there because it imports `@lexical/yjs`, `yjs` and the collaboration
plugin.
## Test plan
### Before
The new tests on the previous version of this PR:
```
$ npx vitest --project unit --no-watch packages/lexical-mark/src/__tests__/unit/MarkStateExtension.test.ts packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts packages/lexical-fast-check/src/__tests__/unit/LexicalFastCheck.test.ts
× typing at the edges of a mark > pasted Lexical data keeps its ids after a marked hashtag
Expected: ["code", "paragraph(\"see \" \"#foo\"[c1] \" bar\"[c1] \" bar\")"]
Received: ["code", "paragraph(\"see \" \"#foo\"[c1] \" bar bar\")"]
× typing at the edges of a mark > a plain TextNode given the ids array of a marked hashtag is taken for a piece split off it
Expected: ["$addMarkID", "paragraph(\"see \" \"#foo\"[c1] \" more\"[c1] \" bar\")"]
Received: ["$addMarkID", "paragraph(\"see \" \"#foo\"[c1] \" more bar\")"]
× typing at the edges of a mark > text dropped from another editor after a marked hashtag keeps its ids, like MarkNode
Expected: "paragraph("see " "#foo"[c1] " more"[c1] " bar")"
Received: "paragraph("see " "#foo"[c1] " more bar")"
× typing at the edges of a mark > text that code inserts after a hashtag and marks in the same update keeps its ids
Expected: "paragraph("see " "#foo"[c1] " Q"[c1] " bar")"
Received: "paragraph("see " "#foo"[c1] " Q bar")"
× typing at the edges of a mark > pasted text whose HTML is the same text is not marked after a marked hashtag, like MarkNode
Expected: ["paste", "paragraph(\"see \" \"#foo\"[c1] \", x bar\")"]
Received: ["paste", "paragraph(\"see \" \"#foo\"[c1] \", x\"[c1] \" bar\")"]
Test Files 1 failed | 2 passed (3)
Tests 5 failed | 116 passed (121)
```
The previous version compared the ids by equality and exempted pastes
whose DataTransfer had Lexical or HTML data. A test stops at its first
failing case: the drop, the run of nodes inserted by code and the
`beforeinput` with such a DataTransfer failed the same way.
The new NodeState tests on `main`:
```
$ npx vitest --project unit --no-watch packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts
FAIL |unit| packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts
TypeError: arraySetValue is not a function
Test Files 1 failed (1)
Tests no tests
```
### After
```
$ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-mark/ packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts packages/lexical/src/__tests__/unit/LexicalSchema.test.ts packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx packages/lexical-fast-check/
✓ |unit| packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts (1 test)
✓ |unit| packages/lexical-fast-check/src/__tests__/unit/CloneCarriesSchemaFields.test.ts (13 tests)
✓ |unit| packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx (30 tests)
✓ |unit| packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts (177 tests)
✓ |unit| packages/lexical-mark/src/__tests__/unit/MarkStateExtension.test.ts (101 tests)
✓ |unit| packages/lexical/src/__tests__/unit/LexicalSchema.test.ts (207 tests)
✓ |unit| packages/lexical-fast-check/src/__tests__/unit/LexicalFastCheck.test.ts (19 tests)
✓ |unit| packages/lexical-mark/__tests__/unit/LexicalMarkNode.test.ts (10 tests)
✓ |unit| packages/lexical-fast-check/src/__tests__/unit/GeneratedParser.test.ts (1 test)
✓ |unit| packages/lexical-mark/src/__tests__/unit/MarkGeneratedJSON.test.ts (3 tests)
Test Files 10 passed (10)
Tests 558 passed | 4 expected fail (562)
```
- `LexicalNodeState.test.ts`, `set-valued state (arraySetValue)`: the type,
the frozen empty default and the `'set'` meta; parsing (dedupe, dropped
entries, UTF-16 order, freeze, non-arrays, canonical values kept, frozen
values that are not canonical, an `enumValue` item, an item that declines
some strings); in-place mutation throws; `$setState` and updaters store
the canonical form; equality; JSON (sorted, empty omitted, stable round
trip of a state declared in `$config`, an undeclared state read after
loading JSON); an explicit `unparse` still wins; the development refusal
in all ten places and of an item that does not produce strings. A
separate test checks that `$setState` keeps the exact value it is given
for `arrayValue`, `objectValue`, a hand-written parse and an updater.
- `LexicalFastCheck.test.ts`: `nodeArbitrary` of a node with a flat
`arraySetValue` state generates arrays of the item's values, unsorted and
with duplicates among them, and importing each sample stores the sorted
set.
- `MarkStateExtension.test.ts`: overlap, queries, getters returning new
arrays, split and merge, edge typing, composition, links, ids, HTML, undo,
rendering, `disabled` (also from the start), migration, slots,
`markableNodes` (also two editors with different sets), the JSON format,
and the inserted text rule: typing next to a gap in a mark, a caret placed
programmatically at the start of a run, text inserted in the same update
that moves the caret, replacing a whole run, composition in a new TextNode
for a toggled format, multi-node paste inside a run, pasted ids kept at an
edge and inside a run, nodes inserted with `insertNodes`; replacing a
selection with text that shares its first or last letter with it, or with
an autocorrection, inside a run, over a whole run and across its start,
with the selection committed first or set in the same update, each
compared with `MarkNode` on the same edit; a replacement by code that
dispatches no command; a handler that wraps the selection instead of
replacing it; a hashtag (`HashtagExtension`), a token node created by a
transform and a segmented node turned into text, compared with
`MarkNode`; the replaced selection when the command is dispatched outside
an update, through `PASTE_COMMAND` and through a DOM `paste` event; the
selection of a command that changed nothing not reaching a later update;
an id removed in the same update (from a hashtag, by range, and before or
after a replacement); a 20,000-character TextNode edited at, inside and
across the edges of a mark; emoji typed inside a run and replaced without
a command; the class that replaces TextNode (with and without
`withKlass`) typed at both edges of a mark, and text typed, pasted
(`PASTE_COMMAND` and a DOM `paste` event) and inserted by code after a
marked hashtag, each compared with `MarkNode`; pasted Lexical data with
the ids of a hashtag after it, also inserted by code without a paste
command; text dropped from another editor there, compared with
`MarkNode`; text that code inserts after a hashtag and marks in the same
update, compared with `MarkNode`, and a run of nodes that code inserts
there, each marked; a paste and a `beforeinput` whose HTML equals their
plain text, compared with `MarkNode`; a plain TextNode given the hashtag's
ids array (the documented limitation) and the same text marked with
`$addMarkID`; an update tagged
`COLLABORATION_TAG` editing the paragraph of a composition, and another
paragraph; the output after undo, after a `setEditorState` that a
transform also dirties, after loading JSON and after removing a
paragraph; invalid ids from JSON, from `updateFromUnknown` and from HTML.
- `MarkStateProperty.test.ts`: a seeded property test. Random sequences of
typing (also in the same update as the caret move, and with a toggled
format), replacing a selection, composition, Backspace and Delete, range
deletion, Enter, formatting, block type changes, adding and removing ids,
copy and cut and paste, undo and redo, on three paragraphs with up to five
overlapping ids. Typed letters are lowercase half of the time, so they can
equal the letters around them, and sometimes an emoji (some of which
share their first code unit). It also removes an id in the same update as
typing or a replacement, before or after it, and sends paste events,
which dispatch `PASTE_COMMAND` outside an update, over a selection (often
with text that starts with its first letter) or at the caret. Every third
seed replaces TextNode with a subclass through a node replacement. A
replacement is a new letter, the first
or the last letter of the selection, the selection with two letters
swapped, its start followed by a new letter, or a new letter followed by
its end; it is typed or sent as an autocorrection, with the selection
committed first or set in the same update, sometimes across two
paragraphs. After every step it checks every character's text and ids
against a model of the rule above, `markIDNodeKeys` against a full
recomputation, `$getMarkIDsAtSelection` (`'any'` and `'all'`, collapsed and
ranged, forward and backward) against the characters, the DOM attribute
and classes, and that no equal siblings are left unmerged. 40 seeds of 30
steps in CI (about 2 s); run locally at 2,000 seeds of 40 steps
(`MARK_STATE_PROPERTY_SEEDS=2000 MARK_STATE_PROPERTY_STEPS=40`, 74 s): all
pass, also with `NodeStructureExtension` added to the editor.
- `MarkStateCollab.test.tsx` (in `packages/lexical-yjs`), both client id
orders, asserting the tree, the `markIDNodeKeys` output and the Y.Doc on
every peer:
- v2: typing inside a range ‖ a peer marks it, two peers mark the same
range (text stays in place, both peers converge on one peer's ids),
typing in an overlap ‖ a second mark, removing or undoing a comment ‖ a
peer types inside it, resolving one of two marks ‖ typing in the
overlap, edge typing.
- v1: two peers marking the same TextNode (one set wins), resolving ‖
typing inside, undo after a peer typed inside.
- Removing an id ‖ a peer adds another to the same text, on v1 and v2: the
documented last-writer-wins outcome, where the removed id comes back in
one client id order and the added one is dropped in the other.
- 4 expected failures pinned as known limitations: the paragraph merge race
and v1 resolving the only mark of a TextNode ‖ typing inside it, in both
client id orders.
Also run:
- `pnpm run test-unit`: 9,798 passed, 4 expected fail (the ones above), 1
skipped. Compared test by test with `main` (9,652 passed, 1 skipped):
none missing, none changed, 150 added.
- Without the extension, JSON, compact JSON, HTML export and a JSON round
trip of 8 HTML fixtures, a Markdown fixture, a document with NodeState of
five kinds and overlapping `MarkNode`s (40 outputs) are byte-identical to
`main`, with and without `NodeStructureExtension`.
- Keystroke cost: the median of 300 keystrokes at random positions, in ms,
on `main` and on this PR with the extension disabled and enabled
(headless unless marked DOM). In one long TextNode, the text that both
states share at its start and end is compared as a few units (an
earlier version of this PR compared every character, 5.79 ms on the
first row).
| Document | `main` | Disabled | Enabled |
| --- | --- | --- | --- |
| One 50,000-character paragraph in a single TextNode, no comments | 0.11 | 0.10 | 0.35 |
| Same, DOM | 0.32 | 0.28 | 0.76 |
| Same, 1 comment | 0.05 | 0.04 | 0.24 |
| One 50,000-character paragraph, 1,000 comments | 0.72 | 0.74 | 0.81 |
| Same, DOM | 0.60 | 0.58 | 0.67 |
| One paragraph of 2,000 lines joined by line breaks, 1,000 comments | 1.87 | 1.96 | 2.05 |
| Same, DOM | 1.18 | 1.10 | 1.26 |
| 10,000 paragraphs, no comments | 11.70 | 11.78 | 11.01 |
| 10,000 paragraphs, 1,000 comments | 13.45 | 12.98 | 12.31 |
| 10,000 paragraphs, 10,000 comments | 20.24 | 20.07 | 21.84 |
Undo on 10,000 paragraphs with 10,000 comments: 42.6 ms on `main`, 42.2
ms disabled, 56.0 ms enabled. An undo
compares the restored state with the current one node by node, and only
reads the nodes that differ.
- `pnpm run tsc`, `pnpm run tsc-test`, `pnpm run flow` (with Flow smoke
tests of `arraySetValue` and the `MarkStateExtension` API),
`pnpm run build-types`, eslint and prettier on the touched files, the
source tree-shaking test, `pnpm run build-prod` and the integration
tree-shaking test, and the website build with its link check.
`git diff main -- packages/lexical-yjs/src` lists only the added test.
Not exercised: real browsers (native `beforeinput` typing and
autocorrection, IME composition, the clipboard; the DOM `paste` event is
simulated in jsdom) and real Yjs providers.
81fdca4 to
63b89be
Compare
…format per member ## Description Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array, which the state's own parse turns into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives), only when the reader knows a set-valued state with that key for the node type and no StateConfig uses the entry key itself. A peer that does not know the state keeps each member as its own NodeState key and writes it back unchanged, so it never collapses the members. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a state when it writes it while the set is known for the node: an invariant (`devInvariant`) in development, a warning in production (the value is then stored under its own key, as a reader that knows a state of that name reads it). A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`; `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), and not to name another state with a set's key and U+001F; the README's wire format adds the member entries (`s:<key>\u001f<member>` = `true`), the empty key, and the reserved names; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. Limit: a peer that does not know the state exports the members it keeps as separate keys in its JSON (`"markIds\u001fc1": true`), and Lexical does not join those keys when the JSON is loaded later. Register the state on every peer, as the docs say. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 83 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 12 / 142 / 10 113 / 144 / 113 ``` ## Test plan New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written; a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader. ### Before `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error Test Files 3 failed (3) Tests 22 failed | 45 passed (67) ``` The three tests of this revision's fixes, with this revision's tests and the previous revision of `Schema.ts` and `SelfCheck.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error # both values written under one attribute × a value state stored by a client that has no set of that name is read as itself AssertionError: expected [ Array(1) ] to deeply equal [] # the self-check reported a mismatch × its members are joined on read AssertionError: expected { root: … } to deeply equal { root: … } # the empty key's members were not joined Tests 3 failed | 7 passed (10) ``` ### After ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 49 passed (49) Tests 2313 passed | 2 skipped (2315) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests are in `ListsInLines.test.ts` and are skipped on #9400 as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 missing, 0 changed, 46 added), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (367 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: real Yjs 14 providers and browsers; the collab Y e2e suite ran on #9438, not on this commit.
…format per member Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array under the set's key, unless a StateConfig uses the entry key itself or the set's key is a StateConfig that does not hold a set. For a set-valued state the reader knows, the state's own parse turns the array into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives). For one it does not know yet, the sorted array is kept as an unknown NodeState value, which the writer stores one entry per member again, so such a peer never collapses the members; and since Lexical parses an unknown value when a state is first used, a client that starts using the state after it read the document (the usual way: `createState`, then `$getState`/`$setState`, with nothing registered) reads the set, and its writes keep the members. The state needs no registration. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a StateConfig, whether or not it holds a value, whenever it writes that state or the set on a node for which both are known (used on it or registered for its type): an invariant (`devInvariant`) in development, a warning in production, and the set is then stored whole, as one value, so no reader drops a member. Only StateConfigs are refused: an entry no StateConfig knows is a set's member or another client's data, and is written back as it is. A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`, and registers it for text the way `MarkStateExtension` does (in the node type's shared state config, with no editor update, so that the peers' identical seed is still a load for `BlockIdExtension` and gets the same ids on every peer); `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), that the state needs no registration, and not to name another state with a set's key and U+001F, and the old "NodeState sets" limit (one value per text run) is removed; the README's wire format adds the member entries (`s:<key>\u001f<member>` = `true`), the empty key, and the reserved names; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. A peer that does not know the state exports the joined set in its JSON (`"markIds": ["c1"]`), which a later JSON load parses as the set. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 83 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 12 / 142 / 10 113 / 144 / 113 ``` New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written, also when it is only registered and never set (the set's write is refused); a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader. A set used without registration, both client id orders: a client that starts using the set after it read the document reads the members, types in the tagged text, adds a member and removes one, and every peer, the stored keys and a fresh reader agree, with no error or warning; concurrent changes merge when one client learned the set late; a client that never uses the set edits the text and keeps its members, and its JSON equals the others'; the headless API seeds such a state, reads it, adds a member and edits the text without touching it. `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error × a state named like a member entry is refused even without a value × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) × concurrent changes merge when one client learned the set late (2 of 2 orders) × a client that never uses the set keeps its members (2 of 2 orders) Test Files 3 failed (3) Tests 29 failed | 46 passed (75) ``` The tests of this revision's fixes (a set used without registration, and a state named like a member entry that is only registered), with this revision's tests and the previous revision of `Schema.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts × a state named like a member entry is refused even without a value AssertionError: expected [Function] to throw an error # readers that know it dropped member x × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) AssertionError: expected [] to deeply equal [ 'a' ] × concurrent changes merge when one client learned the set late (2 of 2 orders) Error: @lexical/y: the NodeState key "tags\u001fa" has the name of a member entry of the set-valued state "tags" (its key, U+001F, a member); rename the state. × a client that never uses the set keeps its members (2 of 2 orders) AssertionError: expected { root: … } to deeply equal { root: … } # its JSON held the member entries × the headless API seeds, reads and edits a set used without registration AssertionError: expected [] to deeply equal [ 'a' ] Tests 8 failed | 10 passed (18) ``` ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 51 passed (51) Tests 2355 passed | 2 skipped (2357) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests are in `ListsInLines.test.ts` and are skipped on #9400 as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` Property test with comments (a reviewer's scratch harness, not committed: 2–3 human peers with `MarkStateExtension` and the self-check on, typing, structure, bold, comments added and resolved, undo, through a delaying and reordering relay, while agents edit stale stored states with `editYState`, 60 steps per session), 2,000 sessions each: comments, comments with block ids, and storing the returned `state` when the agent edited the latest state. 0 sessions in which the binding diverged; the last mode had 5 sessions whose stored state read differently before which one client's `Doc` keeps pending structs it could apply (a `@y/y` 14.0.0-rc.29 issue reproduced with Yjs alone). Collab Y e2e on this commit (development build, `collab-y-server.mjs` relay, 2 workers, no retries): Chromium 29 passed; Firefox 26 passed, 3 skipped (the IME specs are Chromium only). On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 missing, 0 changed, 54 added: `MarkState.test.ts` 33, `SetState.test.ts` 18, `Size.test.ts` 3), and with the stack's base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,482 added; the website's generated `stackblitz.test.ts` audits are left out of both comparisons), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (371 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: WebKit, and real Yjs 14 providers other than the playground relay.
…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 ... ```
…format per member Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array under the set's key, unless a StateConfig uses the entry key itself or the set's key is a StateConfig that does not hold a set. For a set-valued state the reader knows, the state's own parse turns the array into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives). For one it does not know yet, the sorted array is kept as an unknown NodeState value, which the writer stores one entry per member again, as it does any string array under that key on a node of that type (the reader notes the key per node type, so a JSON copy of the node's state is stored the same way): an unchanged set writes nothing, and a changed one writes only the members it adds or removes, never the whole set. So such a peer never collapses the members; and since Lexical parses an unknown value when a state is first used, a client that starts using the state after it read the document (the usual way: `createState`, then `$getState`/`$setState`, with nothing registered) reads the set, and its writes keep the members. The state needs no registration. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a StateConfig, whether or not it holds a value, whenever it writes that state or the set on a node for which both are known (used on it or registered for its type): an invariant (`devInvariant`) in development, a warning in production, and the set is then stored whole, as one value, so no reader drops a member. Only StateConfigs are refused: an entry no StateConfig knows is a set's member or another client's data, and is written back as it is. A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - **Every member round-trips.** Yjs stores format and attribute names as UTF-8, which turns a lone surrogate into U+FFFD, so two members that differ only there would be read back as one. A member that holds a lone surrogate, or that starts with U+001F, is stored escaped: `s:<key>\u001f\u001f` followed by the member's JSON, with every surrogate code unit written as a `\uXXXX` escape (ASCII). Every other member is stored as itself. - **Layout 2.** Member entries are a stored shape older clients misread (they see `s:markIds\u001fc1` as some other NodeState, and no comment), so they are layout 2, as the package README's layout rules require: `LAYOUT_VERSION` is 2; a new document still records `lexical-y:1`, and the transaction that writes a document's first member entry also records `lexical-y:2` (undo keeps it). From then on, clients that only read layout 1 (#9400 to #9438 builds) open the document read only, with the `@lexical/y/unsupported-layout` warning, instead of editing it without its comments; documents that never hold a member entry stay at layout 1 and older clients keep editing them. The planned move records (#9449) become layout 3. A client that is active and reads the version a peer just recorded does not read the whole document again when the record arrives (it changes nothing it reads or writes). - A reader that compares a node with what is stored does not refuse a state named like a member entry (refusals are for writes), so a document holding one, stored by a client that knows only that state, still reads in full on clients that know both. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`, and registers it for text the way `MarkStateExtension` does (in the node type's shared state config, with no editor update, so that the peers' identical seed is still a load for `BlockIdExtension` and gets the same ids on every peer); `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), that the state needs no registration, and not to name another state with a set's key and U+001F, and the old "NodeState sets" limit (one value per text run) is removed, and the limit says that storing members is layout 2 and what older clients then do; the layout section says `LAYOUT_VERSION` is 2 and when a room records it; the README's wire format gets a layout 2 section (the member entries `s:<key>\u001f<member>` = `true`, their escaping, the empty key, the reserved names, and the lazy upgrade), and its layout record rule says "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. A peer that does not know the state exports the joined set in its JSON (`"markIds": ["c1"]`), which a later JSON load parses as the set. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 109 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 12 / 142 / 10 113 / 144 / 113 ``` The first comment in a document also records layout 2 (26 bytes, once per document); without that record it is 83 / 10 / 77. New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. Mark ids on the wire: ten ids on one text run, among them lone high and low surrogates (`'\ud800'`, `'\ud801'`, `'\udc00'`, `'x\udbff'`), a valid pair and ids starting with U+001F: every peer and a fresh reader read them back exactly, every stored name is well-formed, and a peer that removes `'\ud800'` removes only that one. A JSON copy of a commented text node (`node.updateFromJSON(JSON.parse( JSON.stringify(node.exportJSON())))` through the headless API, with `MarkStateExtension` or a nodes-only config): an unchanged copy writes nothing; a copy made while a human resolves A and adds B keeps B only (with and without a text edit, both merge orders); a copy that adds C to a JSON still holding A, while a human resolves A, gives C. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written, also when it is only registered and never set (the set's write is refused); a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader; members holding lone surrogates, a valid pair and one starting with U+001F on a text run, a line break, an inline and a block decorator read back exactly on every peer and a fresh reader. The layout record: a set stored whole on a paragraph leaves the document at layout 1; the update that writes the first member entry also records `lexical-y:2`, which every peer then has and undo keeps; through the headless API a seed and a text edit without members stay at layout 1, the edit that adds a member records layout 2 in its update, and a seed with a member records both. A set used without registration, both client id orders: a client that starts using the set after it read the document reads the members, types in the tagged text, adds a member and removes one, and every peer, the stored keys and a fresh reader agree, with no error or warning; concurrent changes merge when one client learned the set late; a client that never uses the set edits the text and keeps its members, and its JSON equals the others'; the headless API seeds such a state, reads it, adds a member and edits the text without touching it. `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error × a state named like a member entry is refused even without a value × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) × concurrent changes merge when one client learned the set late (2 of 2 orders) × a client that never uses the set keeps its members (2 of 2 orders) Test Files 3 failed (3) Tests 29 failed | 46 passed (75) ``` This revision's fixes (members that are not well-formed UTF-16, a JSON copy of an unknown set, and layout 2), with this revision's tests and the previous revision of `Binding.ts`, `Read.ts`, `Schema.ts` and `constants.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } } # peers read '\ufffd' × an unchanged copy writes nothing (nodes only) AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null × an unchanged copy writes nothing (nodes only, seeded nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere) AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ] × a changed copy writes only the members it adds or removes AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ] × are read back exactly on text, a line break and stored nodes × the first member entry records layout 2 in its own update, and undo keeps it AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] × the headless API records layout 2 with the first member entry only Tests 9 failed | 137 passed (146) ``` The same, on this revision: `Tests 146 passed (146)`. A layout 2 document opened by the previous commit (#9438, layout 1 only), written here with one comment and read there with `MarkStateExtension`: `status: "readonly"`, warning `@lexical/y: the document uses layout 2, not one this version supports (1 to 1); it is read only.` (before this revision: `active`, no warning, and no comment shown). ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 130 passed | 2 skipped (132) Tests 4416 passed | 6 expected fail | 2 skipped (4424) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests (`IncidentReplay.test.ts` and `TabLeakReplay.test.ts`) and the 6 expected failures (pinned limits in `regressions/`) are #9400's as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` Property test with comments (a reviewer's scratch harness, not committed: 2–3 human peers with `MarkStateExtension` and the self-check on, typing, structure, bold, comments added and resolved, undo, through a delaying and reordering relay, while agents edit stale stored states with `editYState`, 60 steps per session), 2,000 sessions each: comments, comments with block ids, and storing the returned `state` when the agent edited the latest state. 0 sessions in which the binding diverged; the last mode had 5 sessions whose stored state read differently before which one client's `Doc` keeps pending structs it could apply (a `@y/y` 14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its comments mode with the self-check off (2,000 sessions) and on (500 sessions) gives the same result in every session as #9438. A first version of the layout 2 record made every peer read the whole document again when the record arrived, which changed the result of 3 of those 2,000 sessions (text shown twice); the binding now skips that read when it already reads the recorded version, and the 3 sessions are as on #9438. Collab Y e2e on this commit (the development build as CI makes it, with the binding's self-check on, `collab-y-server.mjs` relay, 2 workers, no retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs are Chromium only). On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 changed, 66 added: `MarkState.test.ts` 41, `SetState.test.ts` 21, `Size.test.ts` 3, and `Lifecycle.test.ts`'s version gate test renamed from "(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,616 added; the website's generated `stackblitz.test.ts` audits are left out of both comparisons), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (371 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: WebKit, and real Yjs 14 providers other than the playground relay.
…format per member Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array under the set's key, unless a StateConfig uses the entry key itself or the set's key is a StateConfig that does not hold a set. For a set-valued state the reader knows, the state's own parse turns the array into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives). For one it does not know yet, the sorted array is kept as an unknown NodeState value, which the writer stores one entry per member again, as it does any string array under that key on a node of that type (the reader notes the key per node type, so a JSON copy of the node's state is stored the same way): an unchanged set writes nothing, and a changed one writes only the members it adds or removes, never the whole set. So such a peer never collapses the members; and since Lexical parses an unknown value when a state is first used, a client that starts using the state after it read the document (the usual way: `createState`, then `$getState`/`$setState`, with nothing registered) reads the set, and its writes keep the members. The state needs no registration. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a StateConfig, whether or not it holds a value, whenever it writes that state or the set on a node for which both are known (used on it or registered for its type): an invariant (`devInvariant`) in development, a warning in production, and the set is then stored whole, as one value, so no reader drops a member. Only StateConfigs are refused: an entry no StateConfig knows is a set's member or another client's data, and is written back as it is. A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - **Every member round-trips.** Yjs stores format and attribute names as UTF-8, which turns a lone surrogate into U+FFFD, so two members that differ only there would be read back as one. A member that holds a lone surrogate, or that starts with U+001F, is stored escaped: `s:<key>\u001f\u001f` followed by the member's JSON, with every surrogate code unit written as a `\uXXXX` escape (ASCII). Every other member is stored as itself. - **Layout 2.** Member entries are a stored shape older clients misread (they see `s:markIds\u001fc1` as some other NodeState, and no comment), so they are layout 2, as the package README's layout rules require: `LAYOUT_VERSION` is 2; a new document still records `lexical-y:1`, and the transaction that writes a document's first member entry also records `lexical-y:2` (undo keeps it). From then on, clients that only read layout 1 (#9400 to #9438 builds) open the document read only, with the `@lexical/y/unsupported-layout` warning, instead of editing it without its comments; documents that never hold a member entry stay at layout 1 and older clients keep editing them. The planned move records (#9449) become layout 3. A client that is active and reads the version a peer just recorded does not read the whole document again when the record arrives (it changes nothing it reads or writes). The version is recorded in a `finally` inside each transaction that writes content (an edit's, the initial write's and the rewrite that recovers from a failed write), so a write that throws part way, which Yjs still commits and sends, carries it too; once a document records it, a transaction's inserts are not scanned for member entries. - **One format family per set.** The write cursor bounds the format items a delete leaves, and keeps a format's items at the boundaries a concurrent writer relies on, per format family (#9400's `formatFamily`). Here a set's member entries (`s:<key>\u001f<member>`, escaped members included) and a whole array an earlier build stored under `s:<key>` are one family, the set's key, so they follow the rules the whole set follows: the run a delete leaves keeps a bounded number of member items per set, not per member (a comment added to each of 60 words typed and deleted again at one place leaves at most 4 live items, not 2 per comment); and removing a member from a range that holds another member's boundary writes the removed member's value again there, so text a peer types before that boundary does not bring the member back. Removing a comment whose range holds another comment's start costs 51 bytes (redo 48) instead of 10. - A reader that compares a node with what is stored does not refuse a state named like a member entry (refusals are for writes), so a document holding one, stored by a client that knows only that state, still reads in full on clients that know both. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`, and registers it for text the way `MarkStateExtension` does (in the node type's shared state config, with no editor update, so that the peers' identical seed is still a load for `BlockIdExtension` and gets the same ids on every peer); `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), that the state needs no registration, and not to name another state with a set's key and U+001F, and the old "NodeState sets" limit (one value per text run) is removed, and the limit says that storing members is layout 2 and what older clients then do; the layout section says `LAYOUT_VERSION` is 2 and when a room records it; the README's wire format gets a layout 2 section (the member entries `s:<key>\u001f<member>` = `true`, their escaping, the empty key, the reserved names, and the lazy upgrade), and its layout record rule says "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. A peer that does not know the state exports the joined set in its JSON (`"markIds": ["c1"]`), which a later JSON load parses as the set. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 109 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 51 / 116 / 48 113 / 144 / 113 ``` The first comment in a document also records layout 2 (26 bytes, once per document); without that record it is 83 / 10 / 77. New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. Mark ids on the wire: ten ids on one text run, among them lone high and low surrogates (`'\ud800'`, `'\ud801'`, `'\udc00'`, `'x\udbff'`), a valid pair and ids starting with U+001F: every peer and a fresh reader read them back exactly, every stored name is well-formed, and a peer that removes `'\ud800'` removes only that one. A JSON copy of a commented text node (`node.updateFromJSON(JSON.parse( JSON.stringify(node.exportJSON())))` through the headless API, with `MarkStateExtension` or a nodes-only config): an unchanged copy writes nothing; a copy made while a human resolves A and adds B keeps B only (with and without a text edit, both merge orders); a copy that adds C to a JSON still holding A, while a human resolves A, gives C. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written, also when it is only registered and never set (the set's write is refused); a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader; members holding lone surrogates, a valid pair and one starting with U+001F on a text run, a line break, an inline and a block decorator read back exactly on every peer and a fresh reader. The layout record: a set stored whole on a paragraph leaves the document at layout 1; the update that writes the first member entry also records `lexical-y:2`, which every peer then has and undo keeps; through the headless API a seed and a text edit without members stay at layout 1, the edit that adds a member records layout 2 in its update, and a seed with a member records both; a write that throws part way (the edit and the rewrite that recovers from it each write everything, then throw), with `NODE_ENV` development and production, and an initial write into a root inside another shared type that throws part way, both send `lexical-y:2` in the first update, with the member entry. A set used without registration, both client id orders: a client that starts using the set after it read the document reads the members, types in the tagged text, adds a member and removes one, and every peer, the stored keys and a fresh reader agree, with no error or warning; concurrent changes merge when one client learned the set late; a client that never uses the set edits the text and keeps its members, and its JSON equals the others'; the headless API seeds such a state, reads it, adds a member and edits the text without touching it. `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error × a state named like a member entry is refused even without a value × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) × concurrent changes merge when one client learned the set late (2 of 2 orders) × a client that never uses the set keeps its members (2 of 2 orders) Test Files 3 failed (3) Tests 29 failed | 46 passed (75) ``` This revision's fixes (members that are not well-formed UTF-16, a JSON copy of an unknown set, and layout 2), with this revision's tests and the previous revision of `Binding.ts`, `Read.ts`, `Schema.ts` and `constants.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } } # peers read '\ufffd' × an unchanged copy writes nothing (nodes only) AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null × an unchanged copy writes nothing (nodes only, seeded nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere) AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ] × a changed copy writes only the members it adds or removes AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ] × are read back exactly on text, a line break and stored nodes × the first member entry records layout 2 in its own update, and undo keeps it AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] × the headless API records layout 2 with the first member entry only Tests 9 failed | 137 passed (146) ``` The same, on this revision (two more tests, below): `Tests 148 passed (148)`. #9400's `regressions/Formats.test.ts` with the previous revision of `Schema.ts` (every key a family of its own) and of `Size.test.ts`'s budget: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > F24A-1: words typed and deleted again at one place > leave a bounded number of format items (comments) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 3,2,1) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 3,2,1) Tests 5 failed | 94 passed | 4 expected fail (103) ``` The same, on this revision: `Tests 99 passed | 4 expected fail (103)`. A write that throws part way, with the previous revision of `Binding.ts` (which recorded the version after the write, so not when it threw): ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts -t 'throws part way' × a write that throws part way still sends layout 2 with the member entries it wrote, in development and production × an initial write that throws part way still sends layout 2 with the member entries it wrote AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] Tests 2 failed | 21 skipped (23) ``` A layout 2 document opened by the previous commit (#9438, layout 1 only), written here with one comment and read there with `MarkStateExtension`: `status: "readonly"`, warning `@lexical/y: the document uses layout 2, not one this version supports (1 to 1); it is read only.` (before this revision: `active`, no warning, and no comment shown). ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 134 passed | 2 skipped (136) Tests 4600 passed | 12 expected fail | 2 skipped (4614) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests (`IncidentReplay.test.ts` and `TabLeakReplay.test.ts`) and the 12 expected failures (pinned limits in `regressions/`) are #9400's as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` Property test with comments (a reviewer's scratch harness, not committed: 2–3 human peers with `MarkStateExtension` and the self-check on, typing, structure, bold, comments added and resolved, undo, through a delaying and reordering relay, while agents edit stale stored states with `editYState`, 60 steps per session), 2,000 sessions each: comments, comments with block ids, and storing the returned `state` when the agent edited the latest state. 0 sessions in which the binding diverged; the last mode had 5 sessions whose stored state read differently before which one client's `Doc` keeps pending structs it could apply (a `@y/y` 14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its comments mode with the self-check off (2,000 sessions) and on (500 sessions) gives the same result in every session as #9438. A first version of the layout 2 record made every peer read the whole document again when the record arrived, which changed the result of 3 of those 2,000 sessions (text shown twice); the binding now skips that read when it already reads the recorded version, and the 3 sessions are as on #9438. Collab Y e2e on this commit (the development build as CI makes it, with the binding's self-check on, `collab-y-server.mjs` relay, 2 workers, no retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs are Chromium only). On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 changed, 68 added: `MarkState.test.ts` 41, `SetState.test.ts` 23, `Size.test.ts` 3, and `Lifecycle.test.ts`'s version gate test renamed from "(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,807 added; the website's generated `stackblitz.test.ts` audits are left out of both comparisons), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (371 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: WebKit, and real Yjs 14 providers other than the playground relay.
…format per member Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array under the set's key, unless a StateConfig uses the entry key itself or the set's key is a StateConfig that does not hold a set. For a set-valued state the reader knows, the state's own parse turns the array into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives). For one it does not know yet, the sorted array is kept as an unknown NodeState value, which the writer stores one entry per member again, as it does any string array under that key on a node of that type (the reader notes the key per node type, so a JSON copy of the node's state is stored the same way): an unchanged set writes nothing, and a changed one writes only the members it adds or removes, never the whole set. So such a peer never collapses the members; and since Lexical parses an unknown value when a state is first used, a client that starts using the state after it read the document (the usual way: `createState`, then `$getState`/`$setState`, with nothing registered) reads the set, and its writes keep the members. The state needs no registration. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a StateConfig, whether or not it holds a value, whenever it writes that state or the set on a node for which both are known (used on it or registered for its type): an invariant (`devInvariant`) in development, a warning in production, and the set is then stored whole, as one value, so no reader drops a member. Only StateConfigs are refused: an entry no StateConfig knows is a set's member or another client's data, and is written back as it is. A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - **Every member round-trips.** Yjs stores format and attribute names as UTF-8, which turns a lone surrogate into U+FFFD, so two members that differ only there would be read back as one. A member that holds a lone surrogate, or that starts with U+001F, is stored escaped: `s:<key>\u001f\u001f` followed by the member's JSON, with every surrogate code unit written as a `\uXXXX` escape (ASCII). Every other member is stored as itself. - **Layout 2.** Member entries are a stored shape older clients misread (they see `s:markIds\u001fc1` as some other NodeState, and no comment), so they are layout 2, as the package README's layout rules require: `LAYOUT_VERSION` is 2; a new document still records `lexical-y:1`, and the transaction that writes a document's first member entry also records `lexical-y:2` (undo keeps it). From then on, clients that only read layout 1 (#9400 to #9438 builds) open the document read only, with the `@lexical/y/unsupported-layout` warning, instead of editing it without its comments; documents that never hold a member entry stay at layout 1 and older clients keep editing them. The planned move records (#9449) become layout 3. A client that is active and reads the version a peer just recorded does not read the whole document again when the record arrives (it changes nothing it reads or writes). The version is recorded in a `finally` inside each transaction that writes content (an edit's, the initial write's and the rewrite that recovers from a failed write), so a write that throws part way, which Yjs still commits and sends, carries it too; once a document records it, a transaction's inserts are not scanned for member entries. - **One format family per set.** The write cursor bounds the format items a delete leaves, and keeps a format's items at the boundaries a concurrent writer relies on, per format family (#9400's `formatFamily`). Here a set's member entries (`s:<key>\u001f<member>`, escaped members included) and a whole array an earlier build stored under `s:<key>` are one family, the set's key, so they follow the rules the whole set follows: the run a delete leaves keeps a bounded number of member items per set, not per member (a comment added to each of 60 words typed and deleted again at one place leaves at most 4 live items, not 2 per comment); and removing a member from a range that holds another member's boundary writes the removed member's value again there, so text a peer types before that boundary does not bring the member back. Removing a comment whose range holds another comment's start costs 51 bytes (redo 48) instead of 10. - A reader that compares a node with what is stored does not refuse a state named like a member entry (refusals are for writes), so a document holding one, stored by a client that knows only that state, still reads in full on clients that know both. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`, and registers it for text the way `MarkStateExtension` does (in the node type's shared state config, with no editor update, so that the peers' identical seed is still a load for `BlockIdExtension` and gets the same ids on every peer); `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), that the state needs no registration, and not to name another state with a set's key and U+001F, and the old "NodeState sets" limit (one value per text run) is removed, and the limit says that storing members is layout 2 and what older clients then do; the layout section says `LAYOUT_VERSION` is 2 and when a room records it; the README's wire format gets a layout 2 section (the member entries `s:<key>\u001f<member>` = `true`, their escaping, the empty key, the reserved names, and the lazy upgrade), and its layout record rule says "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. A peer that does not know the state exports the joined set in its JSON (`"markIds": ["c1"]`), which a later JSON load parses as the set. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 109 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 51 / 116 / 48 113 / 144 / 113 ``` The first comment in a document also records layout 2 (26 bytes, once per document); without that record it is 83 / 10 / 77. New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. Mark ids on the wire: ten ids on one text run, among them lone high and low surrogates (`'\ud800'`, `'\ud801'`, `'\udc00'`, `'x\udbff'`), a valid pair and ids starting with U+001F: every peer and a fresh reader read them back exactly, every stored name is well-formed, and a peer that removes `'\ud800'` removes only that one. A JSON copy of a commented text node (`node.updateFromJSON(JSON.parse( JSON.stringify(node.exportJSON())))` through the headless API, with `MarkStateExtension` or a nodes-only config): an unchanged copy writes nothing; a copy made while a human resolves A and adds B keeps B only (with and without a text edit, both merge orders); a copy that adds C to a JSON still holding A, while a human resolves A, gives C. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written, also when it is only registered and never set (the set's write is refused); a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader; members holding lone surrogates, a valid pair and one starting with U+001F on a text run, a line break, an inline and a block decorator read back exactly on every peer and a fresh reader. The layout record: a set stored whole on a paragraph leaves the document at layout 1; the update that writes the first member entry also records `lexical-y:2`, which every peer then has and undo keeps; through the headless API a seed and a text edit without members stay at layout 1, the edit that adds a member records layout 2 in its update, and a seed with a member records both; a write that throws part way (the edit and the rewrite that recovers from it each write everything, then throw), with `NODE_ENV` development and production, and an initial write into a root inside another shared type that throws part way, both send `lexical-y:2` in the first update, with the member entry. A set used without registration, both client id orders: a client that starts using the set after it read the document reads the members, types in the tagged text, adds a member and removes one, and every peer, the stored keys and a fresh reader agree, with no error or warning; concurrent changes merge when one client learned the set late; a client that never uses the set edits the text and keeps its members, and its JSON equals the others'; the headless API seeds such a state, reads it, adds a member and edits the text without touching it. `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error × a state named like a member entry is refused even without a value × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) × concurrent changes merge when one client learned the set late (2 of 2 orders) × a client that never uses the set keeps its members (2 of 2 orders) Test Files 3 failed (3) Tests 29 failed | 46 passed (75) ``` This revision's fixes (members that are not well-formed UTF-16, a JSON copy of an unknown set, and layout 2), with this revision's tests and the previous revision of `Binding.ts`, `Read.ts`, `Schema.ts` and `constants.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } } # peers read '\ufffd' × an unchanged copy writes nothing (nodes only) AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null × an unchanged copy writes nothing (nodes only, seeded nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere) AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ] × a changed copy writes only the members it adds or removes AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ] × are read back exactly on text, a line break and stored nodes × the first member entry records layout 2 in its own update, and undo keeps it AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] × the headless API records layout 2 with the first member entry only Tests 9 failed | 137 passed (146) ``` The same, on this revision (two more tests, below): `Tests 148 passed (148)`. #9400's `regressions/Formats.test.ts` with the previous revision of `Schema.ts` (every key a family of its own) and of `Size.test.ts`'s budget: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > F24A-1: words typed and deleted again at one place > leave a bounded number of format items (comments) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 3,2,1) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 3,2,1) Tests 5 failed | 94 passed | 4 expected fail (103) ``` The same, on this revision: `Tests 99 passed | 4 expected fail (103)`. A write that throws part way, with the previous revision of `Binding.ts` (which recorded the version after the write, so not when it threw): ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts -t 'throws part way' × a write that throws part way still sends layout 2 with the member entries it wrote, in development and production × an initial write that throws part way still sends layout 2 with the member entries it wrote AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] Tests 2 failed | 21 skipped (23) ``` A layout 2 document opened by the previous commit (#9438, layout 1 only), written here with one comment and read there with `MarkStateExtension`: `status: "readonly"`, warning `@lexical/y: the document uses layout 2, not one this version supports (1 to 1); it is read only.` (before this revision: `active`, no warning, and no comment shown). ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 134 passed | 2 skipped (136) Tests 4604 passed | 12 expected fail | 2 skipped (4618) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests (`IncidentReplay.test.ts` and `TabLeakReplay.test.ts`) and the 12 expected failures (pinned limits in `regressions/`) are #9400's as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` Property test with comments (a reviewer's scratch harness, not committed: 2–3 human peers with `MarkStateExtension` and the self-check on, typing, structure, bold, comments added and resolved, undo, through a delaying and reordering relay, while agents edit stale stored states with `editYState`, 60 steps per session), 2,000 sessions each: comments, comments with block ids, and storing the returned `state` when the agent edited the latest state. 0 sessions in which the binding diverged; the last mode had 5 sessions whose stored state read differently before which one client's `Doc` keeps pending structs it could apply (a `@y/y` 14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its comments mode with the self-check off (2,000 sessions) and on (500 sessions) gives the same result in every session as #9438. A first version of the layout 2 record made every peer read the whole document again when the record arrived, which changed the result of 3 of those 2,000 sessions (text shown twice); the binding now skips that read when it already reads the recorded version, and the 3 sessions are as on #9438. Collab Y e2e on this commit (the development build as CI makes it, with the binding's self-check on, `collab-y-server.mjs` relay, 2 workers, no retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs are Chromium only). On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 changed, 68 added: `MarkState.test.ts` 41, `SetState.test.ts` 23, `Size.test.ts` 3, and `Lifecycle.test.ts`'s version gate test renamed from "(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,811 added; the website's generated `stackblitz.test.ts` audits are left out of both comparisons), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (371 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: WebKit, and real Yjs 14 providers other than the playground relay.
…format per member Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array under the set's key, unless a StateConfig uses the entry key itself or the set's key is a StateConfig that does not hold a set. For a set-valued state the reader knows, the state's own parse turns the array into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives). For one it does not know yet, the sorted array is kept as an unknown NodeState value, which the writer stores one entry per member again, as it does any string array under that key on a node of that type (the reader notes the key per node type, so a JSON copy of the node's state is stored the same way): an unchanged set writes nothing, and a changed one writes only the members it adds or removes, never the whole set. So such a peer never collapses the members; and since Lexical parses an unknown value when a state is first used, a client that starts using the state after it read the document (the usual way: `createState`, then `$getState`/`$setState`, with nothing registered) reads the set, and its writes keep the members. The state needs no registration. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a StateConfig, whether or not it holds a value, whenever it writes that state or the set on a node for which both are known (used on it or registered for its type): an invariant (`devInvariant`) in development, a warning in production, and the set is then stored whole, as one value, so no reader drops a member. Only StateConfigs are refused: an entry no StateConfig knows is a set's member or another client's data, and is written back as it is. A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - **Every member round-trips.** Yjs stores format and attribute names as UTF-8, which turns a lone surrogate into U+FFFD, so two members that differ only there would be read back as one. A member that holds a lone surrogate, or that starts with U+001F, is stored escaped: `s:<key>\u001f\u001f` followed by the member's JSON, with every surrogate code unit written as a `\uXXXX` escape (ASCII). Every other member is stored as itself. - **Layout 2.** Member entries are a stored shape older clients misread (they see `s:markIds\u001fc1` as some other NodeState, and no comment), so they are layout 2, as the package README's layout rules require: `LAYOUT_VERSION` is 2; a new document still records `lexical-y:1`, and the transaction that writes a document's first member entry also records `lexical-y:2` (undo keeps it). From then on, clients that only read layout 1 (#9400 to #9438 builds) open the document read only, with the `@lexical/y/unsupported-layout` warning, instead of editing it without its comments; documents that never hold a member entry stay at layout 1 and older clients keep editing them. The planned move records (#9449) become layout 3. A client that is active and reads the version a peer just recorded does not read the whole document again when the record arrives (it changes nothing it reads or writes). The version is recorded in a `finally` inside each transaction that writes content (an edit's, the initial write's and the rewrite that recovers from a failed write), so a write that throws part way, which Yjs still commits and sends, carries it too; once a document records it, a transaction's inserts are not scanned for member entries. - **One format family per set.** The write cursor bounds the format items a delete leaves, and keeps a format's items at the boundaries a concurrent writer relies on, per format family (#9400's `formatFamily`). Here a set's member entries (`s:<key>\u001f<member>`, escaped members included) and a whole array an earlier build stored under `s:<key>` are one family, the set's key, so they follow the rules the whole set follows: the run a delete leaves keeps a bounded number of member items per set, not per member (a comment added to each of 60 words typed and deleted again at one place leaves at most 4 live items, not 2 per comment); and removing a member from a range that holds another member's boundary writes the removed member's value again there, so text a peer types before that boundary does not bring the member back. Removing a comment whose range holds another comment's start costs 51 bytes (redo 48) instead of 10. - A reader that compares a node with what is stored does not refuse a state named like a member entry (refusals are for writes), so a document holding one, stored by a client that knows only that state, still reads in full on clients that know both. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`, and registers it for text the way `MarkStateExtension` does (in the node type's shared state config, with no editor update, so that the peers' identical seed is still a load for `BlockIdExtension` and gets the same ids on every peer); `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), that the state needs no registration, and not to name another state with a set's key and U+001F, and the old "NodeState sets" limit (one value per text run) is removed, and the limit says that storing members is layout 2 and what older clients then do; the layout section says `LAYOUT_VERSION` is 2 and when a room records it; the README's wire format gets a layout 2 section (the member entries `s:<key>\u001f<member>` = `true`, their escaping, the empty key, the reserved names, and the lazy upgrade), and its layout record rule says "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. A peer that does not know the state exports the joined set in its JSON (`"markIds": ["c1"]`), which a later JSON load parses as the set. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 109 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 51 / 116 / 48 113 / 144 / 113 ``` The first comment in a document also records layout 2 (26 bytes, once per document); without that record it is 83 / 10 / 77. New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. Mark ids on the wire: ten ids on one text run, among them lone high and low surrogates (`'\ud800'`, `'\ud801'`, `'\udc00'`, `'x\udbff'`), a valid pair and ids starting with U+001F: every peer and a fresh reader read them back exactly, every stored name is well-formed, and a peer that removes `'\ud800'` removes only that one. A JSON copy of a commented text node (`node.updateFromJSON(JSON.parse( JSON.stringify(node.exportJSON())))` through the headless API, with `MarkStateExtension` or a nodes-only config): an unchanged copy writes nothing; a copy made while a human resolves A and adds B keeps B only (with and without a text edit, both merge orders); a copy that adds C to a JSON still holding A, while a human resolves A, gives C. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written, also when it is only registered and never set (the set's write is refused); a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader; members holding lone surrogates, a valid pair and one starting with U+001F on a text run, a line break, an inline and a block decorator read back exactly on every peer and a fresh reader. The layout record: a set stored whole on a paragraph leaves the document at layout 1; the update that writes the first member entry also records `lexical-y:2`, which every peer then has and undo keeps; through the headless API a seed and a text edit without members stay at layout 1, the edit that adds a member records layout 2 in its update, and a seed with a member records both; a write that throws part way (the edit and the rewrite that recovers from it each write everything, then throw), with `NODE_ENV` development and production, and an initial write into a root inside another shared type that throws part way, both send `lexical-y:2` in the first update, with the member entry. A set used without registration, both client id orders: a client that starts using the set after it read the document reads the members, types in the tagged text, adds a member and removes one, and every peer, the stored keys and a fresh reader agree, with no error or warning; concurrent changes merge when one client learned the set late; a client that never uses the set edits the text and keeps its members, and its JSON equals the others'; the headless API seeds such a state, reads it, adds a member and edits the text without touching it. `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error × a state named like a member entry is refused even without a value × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) × concurrent changes merge when one client learned the set late (2 of 2 orders) × a client that never uses the set keeps its members (2 of 2 orders) Test Files 3 failed (3) Tests 29 failed | 46 passed (75) ``` This revision's fixes (members that are not well-formed UTF-16, a JSON copy of an unknown set, and layout 2), with this revision's tests and the previous revision of `Binding.ts`, `Read.ts`, `Schema.ts` and `constants.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } } # peers read '\ufffd' × an unchanged copy writes nothing (nodes only) AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null × an unchanged copy writes nothing (nodes only, seeded nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere) AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ] × a changed copy writes only the members it adds or removes AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ] × are read back exactly on text, a line break and stored nodes × the first member entry records layout 2 in its own update, and undo keeps it AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] × the headless API records layout 2 with the first member entry only Tests 9 failed | 137 passed (146) ``` The same, on this revision (two more tests, below): `Tests 148 passed (148)`. #9400's `regressions/Formats.test.ts` with the previous revision of `Schema.ts` (every key a family of its own) and of `Size.test.ts`'s budget: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > F24A-1: words typed and deleted again at one place > leave a bounded number of format items (comments) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 3,2,1) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 3,2,1) Tests 5 failed | 94 passed | 4 expected fail (103) ``` The same, on this revision: `Tests 99 passed | 4 expected fail (103)`. A write that throws part way, with the previous revision of `Binding.ts` (which recorded the version after the write, so not when it threw): ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts -t 'throws part way' × a write that throws part way still sends layout 2 with the member entries it wrote, in development and production × an initial write that throws part way still sends layout 2 with the member entries it wrote AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] Tests 2 failed | 21 skipped (23) ``` A layout 2 document opened by the previous commit (#9438, layout 1 only), written here with one comment and read there with `MarkStateExtension`: `status: "readonly"`, warning `@lexical/y: the document uses layout 2, not one this version supports (1 to 1); it is read only.` (before this revision: `active`, no warning, and no comment shown). ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 134 passed | 2 skipped (136) Tests 4615 passed | 12 expected fail | 2 skipped (4629) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests (`IncidentReplay.test.ts` and `TabLeakReplay.test.ts`) and the 12 expected failures (pinned limits in `regressions/`) are #9400's as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` Property test with comments (a reviewer's scratch harness, not committed: 2–3 human peers with `MarkStateExtension` and the self-check on, typing, structure, bold, comments added and resolved, undo, through a delaying and reordering relay, while agents edit stale stored states with `editYState`, 60 steps per session), 2,000 sessions each: comments, comments with block ids, and storing the returned `state` when the agent edited the latest state. 0 sessions in which the binding diverged; the last mode had 5 sessions whose stored state read differently before which one client's `Doc` keeps pending structs it could apply (a `@y/y` 14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its comments mode with the self-check off (2,000 sessions) and on (500 sessions) gives the same result in every session as #9438. A first version of the layout 2 record made every peer read the whole document again when the record arrived, which changed the result of 3 of those 2,000 sessions (text shown twice); the binding now skips that read when it already reads the recorded version, and the 3 sessions are as on #9438. Collab Y e2e on this commit (the development build as CI makes it, with the binding's self-check on, `collab-y-server.mjs` relay, 2 workers, no retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs are Chromium only). On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 changed, 68 added: `MarkState.test.ts` 41, `SetState.test.ts` 23, `Size.test.ts` 3, and `Lifecycle.test.ts`'s version gate test renamed from "(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,822 added; the website's generated `stackblitz.test.ts` audits are left out of both comparisons), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (371 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: WebKit, and real Yjs 14 providers other than the playground relay.
…format per member Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array under the set's key, unless a StateConfig uses the entry key itself or the set's key is a StateConfig that does not hold a set. For a set-valued state the reader knows, the state's own parse turns the array into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives). For one it does not know yet, the sorted array is kept as an unknown NodeState value, which the writer stores one entry per member again, as it does any string array under that key on a node of that type (the reader notes the key per node type, so a JSON copy of the node's state is stored the same way): an unchanged set writes nothing, and a changed one writes only the members it adds or removes, never the whole set. So such a peer never collapses the members; and since Lexical parses an unknown value when a state is first used, a client that starts using the state after it read the document (the usual way: `createState`, then `$getState`/`$setState`, with nothing registered) reads the set, and its writes keep the members. The state needs no registration. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a StateConfig, whether or not it holds a value, whenever it writes that state or the set on a node for which both are known (used on it or registered for its type): an invariant (`devInvariant`) in development, a warning in production, and the set is then stored whole, as one value, so no reader drops a member. Only StateConfigs are refused: an entry no StateConfig knows is a set's member or another client's data, and is written back as it is. A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - **Every member round-trips.** Yjs stores format and attribute names as UTF-8, which turns a lone surrogate into U+FFFD, so two members that differ only there would be read back as one. A member that holds a lone surrogate, or that starts with U+001F, is stored escaped: `s:<key>\u001f\u001f` followed by the member's JSON, with every surrogate code unit written as a `\uXXXX` escape (ASCII). Every other member is stored as itself. - **Layout 2.** Member entries are a stored shape older clients misread (they see `s:markIds\u001fc1` as some other NodeState, and no comment), so they are layout 2, as the package README's layout rules require: `LAYOUT_VERSION` is 2; a new document still records `lexical-y:1`, and the transaction that writes a document's first member entry also records `lexical-y:2` (undo keeps it). From then on, clients that only read layout 1 (#9400 to #9438 builds) open the document read only, with the `@lexical/y/unsupported-layout` warning, instead of editing it without its comments; documents that never hold a member entry stay at layout 1 and older clients keep editing them. The planned move records (#9449) become layout 3. A client that is active and reads the version a peer just recorded does not read the whole document again when the record arrives (it changes nothing it reads or writes). The version is recorded in a `finally` inside each transaction that writes content (an edit's, the initial write's and the rewrite that recovers from a failed write), so a write that throws part way, which Yjs still commits and sends, carries it too; once a document records it, a transaction's inserts are not scanned for member entries. - **One format family per set.** The write cursor bounds the format items a delete leaves, and keeps a format's items at the boundaries a concurrent writer relies on, per format family (#9400's `formatFamily`). Here a set's member entries (`s:<key>\u001f<member>`, escaped members included) and a whole array an earlier build stored under `s:<key>` are one family, the set's key, so they follow the rules the whole set follows: the run a delete leaves keeps a bounded number of member items per set, not per member (a comment added to each of 60 words typed and deleted again at one place leaves at most 4 live items, not 2 per comment); and removing a member from a range that holds another member's boundary writes the removed member's value again there, so text a peer types before that boundary does not bring the member back. Removing a comment whose range holds another comment's start costs 51 bytes (redo 48) instead of 10. - A reader that compares a node with what is stored does not refuse a state named like a member entry (refusals are for writes), so a document holding one, stored by a client that knows only that state, still reads in full on clients that know both. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`, and registers it for text the way `MarkStateExtension` does (in the node type's shared state config, with no editor update, so that the peers' identical seed is still a load for `BlockIdExtension` and gets the same ids on every peer); `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), that the state needs no registration, and not to name another state with a set's key and U+001F, and the old "NodeState sets" limit (one value per text run) is removed, and the limit says that storing members is layout 2 and what older clients then do; the layout section says `LAYOUT_VERSION` is 2 and when a room records it; the README's wire format gets a layout 2 section (the member entries `s:<key>\u001f<member>` = `true`, their escaping, the empty key, the reserved names, and the lazy upgrade), and its layout record rule says "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. A peer that does not know the state exports the joined set in its JSON (`"markIds": ["c1"]`), which a later JSON load parses as the set. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 109 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 51 / 116 / 48 113 / 144 / 113 ``` The first comment in a document also records layout 2 (26 bytes, once per document); without that record it is 83 / 10 / 77. New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. Mark ids on the wire: ten ids on one text run, among them lone high and low surrogates (`'\ud800'`, `'\ud801'`, `'\udc00'`, `'x\udbff'`), a valid pair and ids starting with U+001F: every peer and a fresh reader read them back exactly, every stored name is well-formed, and a peer that removes `'\ud800'` removes only that one. A JSON copy of a commented text node (`node.updateFromJSON(JSON.parse( JSON.stringify(node.exportJSON())))` through the headless API, with `MarkStateExtension` or a nodes-only config): an unchanged copy writes nothing; a copy made while a human resolves A and adds B keeps B only (with and without a text edit, both merge orders); a copy that adds C to a JSON still holding A, while a human resolves A, gives C. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written, also when it is only registered and never set (the set's write is refused); a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader; members holding lone surrogates, a valid pair and one starting with U+001F on a text run, a line break, an inline and a block decorator read back exactly on every peer and a fresh reader. The layout record: a set stored whole on a paragraph leaves the document at layout 1; the update that writes the first member entry also records `lexical-y:2`, which every peer then has and undo keeps; through the headless API a seed and a text edit without members stay at layout 1, the edit that adds a member records layout 2 in its update, and a seed with a member records both; a write that throws part way (the edit and the rewrite that recovers from it each write everything, then throw), with `NODE_ENV` development and production, and an initial write into a root inside another shared type that throws part way, both send `lexical-y:2` in the first update, with the member entry. A set used without registration, both client id orders: a client that starts using the set after it read the document reads the members, types in the tagged text, adds a member and removes one, and every peer, the stored keys and a fresh reader agree, with no error or warning; concurrent changes merge when one client learned the set late; a client that never uses the set edits the text and keeps its members, and its JSON equals the others'; the headless API seeds such a state, reads it, adds a member and edits the text without touching it. `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error × a state named like a member entry is refused even without a value × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) × concurrent changes merge when one client learned the set late (2 of 2 orders) × a client that never uses the set keeps its members (2 of 2 orders) Test Files 3 failed (3) Tests 29 failed | 46 passed (75) ``` This revision's fixes (members that are not well-formed UTF-16, a JSON copy of an unknown set, and layout 2), with this revision's tests and the previous revision of `Binding.ts`, `Read.ts`, `Schema.ts` and `constants.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } } # peers read '\ufffd' × an unchanged copy writes nothing (nodes only) AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null × an unchanged copy writes nothing (nodes only, seeded nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere) AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ] × a changed copy writes only the members it adds or removes AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ] × are read back exactly on text, a line break and stored nodes × the first member entry records layout 2 in its own update, and undo keeps it AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] × the headless API records layout 2 with the first member entry only Tests 9 failed | 137 passed (146) ``` The same, on this revision (two more tests, below): `Tests 148 passed (148)`. #9400's `regressions/Formats.test.ts` with the previous revision of `Schema.ts` (every key a family of its own) and of `Size.test.ts`'s budget: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > F24A-1: words typed and deleted again at one place > leave a bounded number of format items (comments) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 3,2,1) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 3,2,1) Tests 5 failed | 94 passed | 4 expected fail (103) ``` The same, on this revision: `Tests 99 passed | 4 expected fail (103)`. A write that throws part way, with the previous revision of `Binding.ts` (which recorded the version after the write, so not when it threw): ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts -t 'throws part way' × a write that throws part way still sends layout 2 with the member entries it wrote, in development and production × an initial write that throws part way still sends layout 2 with the member entries it wrote AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] Tests 2 failed | 21 skipped (23) ``` A layout 2 document opened by the previous commit (#9438, layout 1 only), written here with one comment and read there with `MarkStateExtension`: `status: "readonly"`, warning `@lexical/y: the document uses layout 2, not one this version supports (1 to 1); it is read only.` (before this revision: `active`, no warning, and no comment shown). ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 134 passed | 2 skipped (136) Tests 4621 passed | 12 expected fail | 2 skipped (4635) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests (`IncidentReplay.test.ts` and `TabLeakReplay.test.ts`) and the 12 expected failures (pinned limits in `regressions/`) are #9400's as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` Property test with comments (a reviewer's scratch harness, not committed: 2–3 human peers with `MarkStateExtension` and the self-check on, typing, structure, bold, comments added and resolved, undo, through a delaying and reordering relay, while agents edit stale stored states with `editYState`, 60 steps per session), 2,000 sessions each: comments, comments with block ids, and storing the returned `state` when the agent edited the latest state. 0 sessions in which the binding diverged; the last mode had 5 sessions whose stored state read differently before which one client's `Doc` keeps pending structs it could apply (a `@y/y` 14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its comments mode with the self-check off (2,000 sessions) and on (500 sessions) gives the same result in every session as #9438. A first version of the layout 2 record made every peer read the whole document again when the record arrived, which changed the result of 3 of those 2,000 sessions (text shown twice); the binding now skips that read when it already reads the recorded version, and the 3 sessions are as on #9438. Collab Y e2e on this commit (the development build as CI makes it, with the binding's self-check on, `collab-y-server.mjs` relay, 2 workers, no retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs are Chromium only). On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 changed, 68 added: `MarkState.test.ts` 41, `SetState.test.ts` 23, `Size.test.ts` 3, and `Lifecycle.test.ts`'s version gate test renamed from "(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,828 added; the website's generated `stackblitz.test.ts` audits are left out of both comparisons), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (371 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: WebKit, and real Yjs 14 providers other than the playground relay.
…format per member Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array under the set's key, unless a StateConfig uses the entry key itself or the set's key is a StateConfig that does not hold a set. For a set-valued state the reader knows, the state's own parse turns the array into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives). For one it does not know yet, the sorted array is kept as an unknown NodeState value, which the writer stores one entry per member again, as it does any string array under that key on a node of that type (the reader notes the key per node type, so a JSON copy of the node's state is stored the same way): an unchanged set writes nothing, and a changed one writes only the members it adds or removes, never the whole set. So such a peer never collapses the members; and since Lexical parses an unknown value when a state is first used, a client that starts using the state after it read the document (the usual way: `createState`, then `$getState`/`$setState`, with nothing registered) reads the set, and its writes keep the members. The state needs no registration. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a StateConfig, whether or not it holds a value, whenever it writes that state or the set on a node for which both are known (used on it or registered for its type): an invariant (`devInvariant`) in development, a warning in production, and the set is then stored whole, as one value, so no reader drops a member. Only StateConfigs are refused: an entry no StateConfig knows is a set's member or another client's data, and is written back as it is. A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - **Every member round-trips.** Yjs stores format and attribute names as UTF-8, which turns a lone surrogate into U+FFFD, so two members that differ only there would be read back as one. A member that holds a lone surrogate, or that starts with U+001F, is stored escaped: `s:<key>\u001f\u001f` followed by the member's JSON, with every surrogate code unit written as a `\uXXXX` escape (ASCII). Every other member is stored as itself. - **Layout 2.** Member entries are a stored shape older clients misread (they see `s:markIds\u001fc1` as some other NodeState, and no comment), so they are layout 2, as the package README's layout rules require: `LAYOUT_VERSION` is 2; a new document still records `lexical-y:1`, and the transaction that writes a document's first member entry also records `lexical-y:2` (undo keeps it). From then on, clients that only read layout 1 (#9400 to #9438 builds) open the document read only, with the `@lexical/y/unsupported-layout` warning, instead of editing it without its comments; documents that never hold a member entry stay at layout 1 and older clients keep editing them. The planned move records (#9449) become layout 3. A client that is active and reads the version a peer just recorded does not read the whole document again when the record arrives (it changes nothing it reads or writes). The version is recorded in a `finally` inside each transaction that writes content (an edit's, the initial write's and the rewrite that recovers from a failed write), so a write that throws part way, which Yjs still commits and sends, carries it too; once a document records it, a transaction's inserts are not scanned for member entries. - **One format family per set.** The write cursor bounds the format items a delete leaves, and keeps a format's items at the boundaries a concurrent writer relies on, per format family (#9400's `formatFamily`). Here a set's member entries (`s:<key>\u001f<member>`, escaped members included) and a whole array an earlier build stored under `s:<key>` are one family, the set's key, so they follow the rules the whole set follows: the run a delete leaves keeps a bounded number of member items per set, not per member (a comment added to each of 60 words typed and deleted again at one place leaves at most 4 live items, not 2 per comment); and removing a member from a range that holds another member's boundary writes the removed member's value again there, so text a peer types before that boundary does not bring the member back. Removing a comment whose range holds another comment's start costs 51 bytes (redo 48) instead of 10. - A reader that compares a node with what is stored does not refuse a state named like a member entry (refusals are for writes), so a document holding one, stored by a client that knows only that state, still reads in full on clients that know both. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`, and registers it for text the way `MarkStateExtension` does (in the node type's shared state config, with no editor update, so that the peers' identical seed is still a load for `BlockIdExtension` and gets the same ids on every peer); `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), that the state needs no registration, and not to name another state with a set's key and U+001F, and the old "NodeState sets" limit (one value per text run) is removed, and the limit says that storing members is layout 2 and what older clients then do; the layout section says `LAYOUT_VERSION` is 2 and when a room records it; the README's wire format gets a layout 2 section (the member entries `s:<key>\u001f<member>` = `true`, their escaping, the empty key, the reserved names, and the lazy upgrade), and its layout record rule says "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. A peer that does not know the state exports the joined set in its JSON (`"markIds": ["c1"]`), which a later JSON load parses as the set. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 109 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 51 / 116 / 48 113 / 144 / 113 ``` The first comment in a document also records layout 2 (26 bytes, once per document); without that record it is 83 / 10 / 77. New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. Mark ids on the wire: ten ids on one text run, among them lone high and low surrogates (`'\ud800'`, `'\ud801'`, `'\udc00'`, `'x\udbff'`), a valid pair and ids starting with U+001F: every peer and a fresh reader read them back exactly, every stored name is well-formed, and a peer that removes `'\ud800'` removes only that one. A JSON copy of a commented text node (`node.updateFromJSON(JSON.parse( JSON.stringify(node.exportJSON())))` through the headless API, with `MarkStateExtension` or a nodes-only config): an unchanged copy writes nothing; a copy made while a human resolves A and adds B keeps B only (with and without a text edit, both merge orders); a copy that adds C to a JSON still holding A, while a human resolves A, gives C. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written, also when it is only registered and never set (the set's write is refused); a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader; members holding lone surrogates, a valid pair and one starting with U+001F on a text run, a line break, an inline and a block decorator read back exactly on every peer and a fresh reader. The layout record: a set stored whole on a paragraph leaves the document at layout 1; the update that writes the first member entry also records `lexical-y:2`, which every peer then has and undo keeps; through the headless API a seed and a text edit without members stay at layout 1, the edit that adds a member records layout 2 in its update, and a seed with a member records both; a write that throws part way (the edit and the rewrite that recovers from it each write everything, then throw), with `NODE_ENV` development and production, and an initial write into a root inside another shared type that throws part way, both send `lexical-y:2` in the first update, with the member entry. A set used without registration, both client id orders: a client that starts using the set after it read the document reads the members, types in the tagged text, adds a member and removes one, and every peer, the stored keys and a fresh reader agree, with no error or warning; concurrent changes merge when one client learned the set late; a client that never uses the set edits the text and keeps its members, and its JSON equals the others'; the headless API seeds such a state, reads it, adds a member and edits the text without touching it. `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error × a state named like a member entry is refused even without a value × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) × concurrent changes merge when one client learned the set late (2 of 2 orders) × a client that never uses the set keeps its members (2 of 2 orders) Test Files 3 failed (3) Tests 29 failed | 46 passed (75) ``` This revision's fixes (members that are not well-formed UTF-16, a JSON copy of an unknown set, and layout 2), with this revision's tests and the previous revision of `Binding.ts`, `Read.ts`, `Schema.ts` and `constants.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } } # peers read '\ufffd' × an unchanged copy writes nothing (nodes only) AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null × an unchanged copy writes nothing (nodes only, seeded nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere) AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ] × a changed copy writes only the members it adds or removes AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ] × are read back exactly on text, a line break and stored nodes × the first member entry records layout 2 in its own update, and undo keeps it AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] × the headless API records layout 2 with the first member entry only Tests 9 failed | 137 passed (146) ``` The same, on this revision (two more tests, below): `Tests 148 passed (148)`. #9400's `regressions/Formats.test.ts` with the previous revision of `Schema.ts` (every key a family of its own) and of `Size.test.ts`'s budget: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > F24A-1: words typed and deleted again at one place > leave a bounded number of format items (comments) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 3,2,1) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 3,2,1) Tests 5 failed | 94 passed | 4 expected fail (103) ``` The same, on this revision: `Tests 99 passed | 4 expected fail (103)`. A write that throws part way, with the previous revision of `Binding.ts` (which recorded the version after the write, so not when it threw): ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts -t 'throws part way' × a write that throws part way still sends layout 2 with the member entries it wrote, in development and production × an initial write that throws part way still sends layout 2 with the member entries it wrote AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] Tests 2 failed | 21 skipped (23) ``` A layout 2 document opened by the previous commit (#9438, layout 1 only), written here with one comment and read there with `MarkStateExtension`: `status: "readonly"`, warning `@lexical/y: the document uses layout 2, not one this version supports (1 to 1); it is read only.` (before this revision: `active`, no warning, and no comment shown). ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 134 passed | 2 skipped (136) Tests 4629 passed | 12 expected fail | 2 skipped (4643) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests (`IncidentReplay.test.ts` and `TabLeakReplay.test.ts`) and the 12 expected failures (pinned limits in `regressions/`) are #9400's as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` Property test with comments (a reviewer's scratch harness, not committed: 2–3 human peers with `MarkStateExtension` and the self-check on, typing, structure, bold, comments added and resolved, undo, through a delaying and reordering relay, while agents edit stale stored states with `editYState`, 60 steps per session), 2,000 sessions each: comments, comments with block ids, and storing the returned `state` when the agent edited the latest state. 0 sessions in which the binding diverged; the last mode had 5 sessions whose stored state read differently before which one client's `Doc` keeps pending structs it could apply (a `@y/y` 14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its comments mode with the self-check off (2,000 sessions) and on (500 sessions) gives the same result in every session as #9438. A first version of the layout 2 record made every peer read the whole document again when the record arrived, which changed the result of 3 of those 2,000 sessions (text shown twice); the binding now skips that read when it already reads the recorded version, and the 3 sessions are as on #9438. Collab Y e2e on this commit (the development build as CI makes it, with the binding's self-check on, `collab-y-server.mjs` relay, 2 workers, no retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs are Chromium only). On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 changed, 68 added: `MarkState.test.ts` 41, `SetState.test.ts` 23, `Size.test.ts` 3, and `Lifecycle.test.ts`'s version gate test renamed from "(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,836 added; the website's generated `stackblitz.test.ts` audits are left out of both comparisons), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (371 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: WebKit, and real Yjs 14 providers other than the playground relay.
…format per member Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array under the set's key, unless a StateConfig uses the entry key itself or the set's key is a StateConfig that does not hold a set. For a set-valued state the reader knows, the state's own parse turns the array into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives). For one it does not know yet, the sorted array is kept as an unknown NodeState value, which the writer stores one entry per member again, as it does any string array under that key on a node of that type (the reader notes the key per node type, so a JSON copy of the node's state is stored the same way): an unchanged set writes nothing, and a changed one writes only the members it adds or removes, never the whole set. So such a peer never collapses the members; and since Lexical parses an unknown value when a state is first used, a client that starts using the state after it read the document (the usual way: `createState`, then `$getState`/`$setState`, with nothing registered) reads the set, and its writes keep the members. The state needs no registration. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a StateConfig, whether or not it holds a value, whenever it writes that state or the set on a node for which both are known (used on it or registered for its type): an invariant (`devInvariant`) in development, a warning in production, and the set is then stored whole, as one value, so no reader drops a member. Only StateConfigs are refused: an entry no StateConfig knows is a set's member or another client's data, and is written back as it is. A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - **Every member round-trips.** Yjs stores format and attribute names as UTF-8, which turns a lone surrogate into U+FFFD, so two members that differ only there would be read back as one. A member that holds a lone surrogate, or that starts with U+001F, is stored escaped: `s:<key>\u001f\u001f` followed by the member's JSON, with every surrogate code unit written as a `\uXXXX` escape (ASCII). Every other member is stored as itself. - **Layout 2.** Member entries are a stored shape older clients misread (they see `s:markIds\u001fc1` as some other NodeState, and no comment), so they are layout 2, as the package README's layout rules require: `LAYOUT_VERSION` is 2; a new document still records `lexical-y:1`, and the transaction that writes a document's first member entry also records `lexical-y:2` (undo keeps it). From then on, clients that only read layout 1 (#9400 to #9438 builds) open the document read only, with the `@lexical/y/unsupported-layout` warning, instead of editing it without its comments; documents that never hold a member entry stay at layout 1 and older clients keep editing them. The planned move records (#9449) become layout 3. A client that is active and reads the version a peer just recorded does not read the whole document again when the record arrives (it changes nothing it reads or writes). The version is recorded in a `finally` inside each transaction that writes content (an edit's, the initial write's and the rewrite that recovers from a failed write), so a write that throws part way, which Yjs still commits and sends, carries it too; once a document records it, a transaction's inserts are not scanned for member entries. - **One format family per set.** The write cursor bounds the format items a delete leaves, and keeps a format's items at the boundaries a concurrent writer relies on, per format family (#9400's `formatFamily`). Here a set's member entries (`s:<key>\u001f<member>`, escaped members included) and a whole array an earlier build stored under `s:<key>` are one family, the set's key, so they follow the rules the whole set follows: the run a delete leaves keeps a bounded number of member items per set, not per member (a comment added to each of 60 words typed and deleted again at one place leaves at most 4 live items, not 2 per comment); and removing a member from a range that holds another member's boundary writes the removed member's value again there, so text a peer types before that boundary does not bring the member back. Removing a comment whose range holds another comment's start costs 51 bytes (redo 48) instead of 10. - A reader that compares a node with what is stored does not refuse a state named like a member entry (refusals are for writes), so a document holding one, stored by a client that knows only that state, still reads in full on clients that know both. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`, and registers it for text the way `MarkStateExtension` does (in the node type's shared state config, with no editor update, so that the peers' identical seed is still a load for `BlockIdExtension` and gets the same ids on every peer); `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), that the state needs no registration, and not to name another state with a set's key and U+001F, and the old "NodeState sets" limit (one value per text run) is removed, and the limit says that storing members is layout 2 and what older clients then do; the layout section says `LAYOUT_VERSION` is 2 and when a room records it; the README's wire format gets a layout 2 section (the member entries `s:<key>\u001f<member>` = `true`, their escaping, the empty key, the reserved names, and the lazy upgrade), and its layout record rule says "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. A peer that does not know the state exports the joined set in its JSON (`"markIds": ["c1"]`), which a later JSON load parses as the set. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 109 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 51 / 116 / 48 113 / 144 / 113 ``` The first comment in a document also records layout 2 (26 bytes, once per document); without that record it is 83 / 10 / 77. New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. Mark ids on the wire: ten ids on one text run, among them lone high and low surrogates (`'\ud800'`, `'\ud801'`, `'\udc00'`, `'x\udbff'`), a valid pair and ids starting with U+001F: every peer and a fresh reader read them back exactly, every stored name is well-formed, and a peer that removes `'\ud800'` removes only that one. A JSON copy of a commented text node (`node.updateFromJSON(JSON.parse( JSON.stringify(node.exportJSON())))` through the headless API, with `MarkStateExtension` or a nodes-only config): an unchanged copy writes nothing; a copy made while a human resolves A and adds B keeps B only (with and without a text edit, both merge orders); a copy that adds C to a JSON still holding A, while a human resolves A, gives C. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written, also when it is only registered and never set (the set's write is refused); a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader; members holding lone surrogates, a valid pair and one starting with U+001F on a text run, a line break, an inline and a block decorator read back exactly on every peer and a fresh reader. The layout record: a set stored whole on a paragraph leaves the document at layout 1; the update that writes the first member entry also records `lexical-y:2`, which every peer then has and undo keeps; through the headless API a seed and a text edit without members stay at layout 1, the edit that adds a member records layout 2 in its update, and a seed with a member records both; a write that throws part way (the edit and the rewrite that recovers from it each write everything, then throw), with `NODE_ENV` development and production, and an initial write into a root inside another shared type that throws part way, both send `lexical-y:2` in the first update, with the member entry. A set used without registration, both client id orders: a client that starts using the set after it read the document reads the members, types in the tagged text, adds a member and removes one, and every peer, the stored keys and a fresh reader agree, with no error or warning; concurrent changes merge when one client learned the set late; a client that never uses the set edits the text and keeps its members, and its JSON equals the others'; the headless API seeds such a state, reads it, adds a member and edits the text without touching it. `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error × a state named like a member entry is refused even without a value × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) × concurrent changes merge when one client learned the set late (2 of 2 orders) × a client that never uses the set keeps its members (2 of 2 orders) Test Files 3 failed (3) Tests 29 failed | 46 passed (75) ``` This revision's fixes (members that are not well-formed UTF-16, a JSON copy of an unknown set, and layout 2), with this revision's tests and the previous revision of `Binding.ts`, `Read.ts`, `Schema.ts` and `constants.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } } # peers read '\ufffd' × an unchanged copy writes nothing (nodes only) AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null × an unchanged copy writes nothing (nodes only, seeded nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere) AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ] × a changed copy writes only the members it adds or removes AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ] × are read back exactly on text, a line break and stored nodes × the first member entry records layout 2 in its own update, and undo keeps it AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] × the headless API records layout 2 with the first member entry only Tests 9 failed | 137 passed (146) ``` The same, on this revision (two more tests, below): `Tests 148 passed (148)`. #9400's `regressions/Formats.test.ts` with the previous revision of `Schema.ts` (every key a family of its own) and of `Size.test.ts`'s budget: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > F24A-1: words typed and deleted again at one place > leave a bounded number of format items (comments) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 3,2,1) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 3,2,1) Tests 5 failed | 94 passed | 4 expected fail (103) ``` The same, on this revision: `Tests 99 passed | 4 expected fail (103)`. A write that throws part way, with the previous revision of `Binding.ts` (which recorded the version after the write, so not when it threw): ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts -t 'throws part way' × a write that throws part way still sends layout 2 with the member entries it wrote, in development and production × an initial write that throws part way still sends layout 2 with the member entries it wrote AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] Tests 2 failed | 21 skipped (23) ``` A layout 2 document opened by the previous commit (#9438, layout 1 only), written here with one comment and read there with `MarkStateExtension`: `status: "readonly"`, warning `@lexical/y: the document uses layout 2, not one this version supports (1 to 1); it is read only.` (before this revision: `active`, no warning, and no comment shown). ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 134 passed | 2 skipped (136) Tests 4645 passed | 12 expected fail | 2 skipped (4659) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests (`IncidentReplay.test.ts` and `TabLeakReplay.test.ts`) and the 12 expected failures (pinned limits in `regressions/`) are #9400's as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` Property test with comments (a reviewer's scratch harness, not committed: 2–3 human peers with `MarkStateExtension` and the self-check on, typing, structure, bold, comments added and resolved, undo, through a delaying and reordering relay, while agents edit stale stored states with `editYState`, 60 steps per session), 2,000 sessions each: comments, comments with block ids, and storing the returned `state` when the agent edited the latest state. 0 sessions in which the binding diverged; the last mode had 5 sessions whose stored state read differently before which one client's `Doc` keeps pending structs it could apply (a `@y/y` 14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its comments mode with the self-check off (2,000 sessions) and on (500 sessions) gives the same result in every session as #9438. A first version of the layout 2 record made every peer read the whole document again when the record arrived, which changed the result of 3 of those 2,000 sessions (text shown twice); the binding now skips that read when it already reads the recorded version, and the 3 sessions are as on #9438. Collab Y e2e on this commit (the development build as CI makes it, with the binding's self-check on, `collab-y-server.mjs` relay, 2 workers, no retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs are Chromium only). On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 changed, 68 added: `MarkState.test.ts` 41, `SetState.test.ts` 23, `Size.test.ts` 3, and `Lifecycle.test.ts`'s version gate test renamed from "(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,852 added; the website's generated `stackblitz.test.ts` audits are left out of both comparisons), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (371 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: WebKit, and real Yjs 14 providers other than the playground relay.
…format per member Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array under the set's key, unless a StateConfig uses the entry key itself or the set's key is a StateConfig that does not hold a set. For a set-valued state the reader knows, the state's own parse turns the array into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives). For one it does not know yet, the sorted array is kept as an unknown NodeState value, which the writer stores one entry per member again, as it does any string array under that key on a node of that type (the reader notes the key per node type, so a JSON copy of the node's state is stored the same way): an unchanged set writes nothing, and a changed one writes only the members it adds or removes, never the whole set. So such a peer never collapses the members; and since Lexical parses an unknown value when a state is first used, a client that starts using the state after it read the document (the usual way: `createState`, then `$getState`/`$setState`, with nothing registered) reads the set, and its writes keep the members. The state needs no registration. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a StateConfig, whether or not it holds a value, whenever it writes that state or the set on a node for which both are known (used on it or registered for its type): an invariant (`devInvariant`) in development, a warning in production, and the set is then stored whole, as one value, so no reader drops a member. Only StateConfigs are refused: an entry no StateConfig knows is a set's member or another client's data, and is written back as it is. A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - **Every member round-trips.** Yjs stores format and attribute names as UTF-8, which turns a lone surrogate into U+FFFD, so two members that differ only there would be read back as one. A member that holds a lone surrogate, or that starts with U+001F, is stored escaped: `s:<key>\u001f\u001f` followed by the member's JSON, with every surrogate code unit written as a `\uXXXX` escape (ASCII). Every other member is stored as itself. - **Layout 2.** Member entries are a stored shape older clients misread (they see `s:markIds\u001fc1` as some other NodeState, and no comment), so they are layout 2, as the package README's layout rules require: `LAYOUT_VERSION` is 2; a new document still records `lexical-y:1`, and the transaction that writes a document's first member entry also records `lexical-y:2` (undo keeps it). From then on, clients that only read layout 1 (#9400 to #9438 builds) open the document read only, with the `@lexical/y/unsupported-layout` warning, instead of editing it without its comments; documents that never hold a member entry stay at layout 1 and older clients keep editing them. The planned move records (#9449) become layout 3. A client that is active and reads the version a peer just recorded does not read the whole document again when the record arrives (it changes nothing it reads or writes). The version is recorded in a `finally` inside each transaction that writes content (an edit's, the initial write's and the rewrite that recovers from a failed write), so a write that throws part way, which Yjs still commits and sends, carries it too; once a document records it, a transaction's inserts are not scanned for member entries. - **One format family per set.** The write cursor bounds the format items a delete leaves, and keeps a format's items at the boundaries a concurrent writer relies on, per format family (#9400's `formatFamily`). Here a set's member entries (`s:<key>\u001f<member>`, escaped members included) and a whole array an earlier build stored under `s:<key>` are one family, the set's key, so they follow the rules the whole set follows: the run a delete leaves keeps a bounded number of member items per set, not per member (a comment added to each of 60 words typed and deleted again at one place leaves at most 4 live items, not 2 per comment); and removing a member from a range that holds another member's boundary writes the removed member's value again there, so text a peer types before that boundary does not bring the member back. Removing a comment whose range holds another comment's start costs 51 bytes (redo 48) instead of 10. - **Known limit: a removed member leaves an item.** Removing a member from text that stores its set per member (resolving a comment with `$removeMarkID`) leaves one small live format item after that text (about 30 bytes with a short comment id), which the binding cannot safely clean up: a collaborator writing inside that text at the same time may still rely on it (#9400's write cursor keeps the item after a format change's range for that writer, for any key; a set stored whole reuses it for the next comment there, a member's key is not written again). So the document grows with every member removed, not only with its content. Removing the same member again at the same place adds nothing, and adding a member and undoing it leaves nothing. The docs now recommend resolving a comment without removing its id: keep the id in the text, mark the thread resolved in the app's own store, and leave resolved ids out when rendering (see the `MarkStateExtension` option for that). Unresolving is then free and the document does not change. Removing the id stays documented as the alternative, with this cost ([Resolving comments](https://lexical.dev/docs/collaboration/comments#resolving-comments)). - A reader that compares a node with what is stored does not refuse a state named like a member entry (refusals are for writes), so a document holding one, stored by a client that knows only that state, still reads in full on clients that know both. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`, and registers it for text the way `MarkStateExtension` does (in the node type's shared state config, with no editor update, so that the peers' identical seed is still a load for `BlockIdExtension` and gets the same ids on every peer); `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), that the state needs no registration, and not to name another state with a set's key and U+001F, and the old "NodeState sets" limit (one value per text run) is removed, and the limit says that storing members is layout 2 and what older clients then do; the layout section says `LAYOUT_VERSION` is 2 and when a room records it; the README's wire format gets a layout 2 section (the member entries `s:<key>\u001f<member>` = `true`, their escaping, the empty key, the reserved names, and the lazy upgrade), and its layout record rule says "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The Comments and Annotations page gets a "Resolving comments" section: keep a resolved comment's id in the text and its thread's state in the app's store (unresolving is then free, and the document does not change), or remove the id with `$removeMarkID` and add it again to unresolve, which under `@lexical/y` leaves one live item per removal; the Yjs 14 page's limits get a "Removed set members" item that says the same and links that section. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. A peer that does not know the state exports the joined set in its JSON (`"markIds": ["c1"]`), which a later JSON load parses as the set. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 109 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 51 / 116 / 48 113 / 144 / 113 ``` The first comment in a document also records layout 2 (26 bytes, once per document); without that record it is 83 / 10 / 77. What each way of resolving a comment leaves, 200 comments on the same words, through `MarkStateExtension` and `YCollabExtension` as an app builds them, two clients with pinned client ids (a scratch probe, not committed; live format items, and bytes a GC'd copy of the document grows by per comment): ``` $removeMarkID (resolved by the author or the other client) 200 items, 49 B per comment (81 B with UUID ids) the id kept in the text, resolved in the app's store 400 items (2 per comment, its range), 65 B one comment resolved and reopened 200 times 1 item a comment added, then undone 0 items ``` New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. Mark ids on the wire: ten ids on one text run, among them lone high and low surrogates (`'\ud800'`, `'\ud801'`, `'\udc00'`, `'x\udbff'`), a valid pair and ids starting with U+001F: every peer and a fresh reader read them back exactly, every stored name is well-formed, and a peer that removes `'\ud800'` removes only that one. A JSON copy of a commented text node (`node.updateFromJSON(JSON.parse( JSON.stringify(node.exportJSON())))` through the headless API, with `MarkStateExtension` or a nodes-only config): an unchanged copy writes nothing; a copy made while a human resolves A and adds B keeps B only (with and without a text edit, both merge orders); a copy that adds C to a JSON still holding A, while a human resolves A, gives C. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written, also when it is only registered and never set (the set's write is refused); a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader; members holding lone surrogates, a valid pair and one starting with U+001F on a text run, a line break, an inline and a block decorator read back exactly on every peer and a fresh reader. The layout record: a set stored whole on a paragraph leaves the document at layout 1; the update that writes the first member entry also records `lexical-y:2`, which every peer then has and undo keeps; through the headless API a seed and a text edit without members stay at layout 1, the edit that adds a member records layout 2 in its update, and a seed with a member records both; a write that throws part way (the edit and the rewrite that recovers from it each write everything, then throw), with `NODE_ENV` development and production, and an initial write into a root inside another shared type that throws part way, both send `lexical-y:2` in the first update, with the member entry. A set used without registration, both client id orders: a client that starts using the set after it read the document reads the members, types in the tagged text, adds a member and removes one, and every peer, the stored keys and a fresh reader agree, with no error or warning; concurrent changes merge when one client learned the set late; a client that never uses the set edits the text and keeps its members, and its JSON equals the others'; the headless API seeds such a state, reads it, adds a member and edits the text without touching it. `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error × a state named like a member entry is refused even without a value × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) × concurrent changes merge when one client learned the set late (2 of 2 orders) × a client that never uses the set keeps its members (2 of 2 orders) Test Files 3 failed (3) Tests 29 failed | 46 passed (75) ``` This revision's fixes (members that are not well-formed UTF-16, a JSON copy of an unknown set, and layout 2), with this revision's tests and the previous revision of `Binding.ts`, `Read.ts`, `Schema.ts` and `constants.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } } # peers read '\ufffd' × an unchanged copy writes nothing (nodes only) AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null × an unchanged copy writes nothing (nodes only, seeded nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere) AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ] × a changed copy writes only the members it adds or removes AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ] × are read back exactly on text, a line break and stored nodes × the first member entry records layout 2 in its own update, and undo keeps it AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] × the headless API records layout 2 with the first member entry only Tests 9 failed | 137 passed (146) ``` The same, on this revision (two more tests, below): `Tests 148 passed (148)`. #9400's `regressions/Formats.test.ts` with the previous revision of `Schema.ts` (every key a family of its own) and of `Size.test.ts`'s budget: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > F24A-1: words typed and deleted again at one place > leave a bounded number of format items (comments) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 3,2,1) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 3,2,1) Tests 5 failed | 94 passed | 4 expected fail (103) ``` The same, on this revision: `Tests 99 passed | 4 expected fail (103)`. A write that throws part way, with the previous revision of `Binding.ts` (which recorded the version after the write, so not when it threw): ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts -t 'throws part way' × a write that throws part way still sends layout 2 with the member entries it wrote, in development and production × an initial write that throws part way still sends layout 2 with the member entries it wrote AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] Tests 2 failed | 21 skipped (23) ``` A layout 2 document opened by the previous commit (#9438, layout 1 only), written here with one comment and read there with `MarkStateExtension`: `status: "readonly"`, warning `@lexical/y: the document uses layout 2, not one this version supports (1 to 1); it is read only.` (before this revision: `active`, no warning, and no comment shown). ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 135 passed | 2 skipped (137) Tests 4667 passed | 12 expected fail | 2 skipped (4681) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests (`IncidentReplay.test.ts` and `TabLeakReplay.test.ts`) and the 12 expected failures (pinned limits in `regressions/`) are #9400's as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` Property test with comments (a reviewer's scratch harness, not committed: 2–3 human peers with `MarkStateExtension` and the self-check on, typing, structure, bold, comments added and resolved, undo, through a delaying and reordering relay, while agents edit stale stored states with `editYState`, 60 steps per session), 2,000 sessions each: comments, comments with block ids, and storing the returned `state` when the agent edited the latest state. 0 sessions in which the binding diverged; the last mode had 5 sessions whose stored state read differently before which one client's `Doc` keeps pending structs it could apply (a `@y/y` 14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its comments mode with the self-check off (2,000 sessions) and on (500 sessions) gives the same result in every session as #9438. A first version of the layout 2 record made every peer read the whole document again when the record arrived, which changed the result of 3 of those 2,000 sessions (text shown twice); the binding now skips that read when it already reads the recorded version, and the 3 sessions are as on #9438. Collab Y e2e on this commit (the development build as CI makes it, with the binding's self-check on, `collab-y-server.mjs` relay, 2 workers, no retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs are Chromium only). On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 changed, 68 added: `MarkState.test.ts` 41, `SetState.test.ts` 23, `Size.test.ts` 3, and `Lifecycle.test.ts`'s version gate test renamed from "(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,875 added: 4,856 on the previous revision, plus the 19 tests #9437 now adds for its writer; the website's generated `stackblitz.test.ts` audits are left out of both comparisons), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (372 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: WebKit, and real Yjs 14 providers other than the playground relay.
…format per member Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array under the set's key, unless a StateConfig uses the entry key itself or the set's key is a StateConfig that does not hold a set. For a set-valued state the reader knows, the state's own parse turns the array into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives). For one it does not know yet, the sorted array is kept as an unknown NodeState value, which the writer stores one entry per member again, as it does any string array under that key on a node of that type (the reader notes the key per node type, so a JSON copy of the node's state is stored the same way): an unchanged set writes nothing, and a changed one writes only the members it adds or removes, never the whole set. So such a peer never collapses the members; and since Lexical parses an unknown value when a state is first used, a client that starts using the state after it read the document (the usual way: `createState`, then `$getState`/`$setState`, with nothing registered) reads the set, and its writes keep the members. The state needs no registration. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a StateConfig, whether or not it holds a value, whenever it writes that state or the set on a node for which both are known (used on it or registered for its type): an invariant (`devInvariant`) in development, a warning in production, and the set is then stored whole, as one value, so no reader drops a member. Only StateConfigs are refused: an entry no StateConfig knows is a set's member or another client's data, and is written back as it is. A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - **Every member round-trips.** Yjs stores format and attribute names as UTF-8, which turns a lone surrogate into U+FFFD, so two members that differ only there would be read back as one. A member that holds a lone surrogate, or that starts with U+001F, is stored escaped: `s:<key>\u001f\u001f` followed by the member's JSON, with every surrogate code unit written as a `\uXXXX` escape (ASCII). Every other member is stored as itself. - **Layout 2.** Member entries are a stored shape older clients misread (they see `s:markIds\u001fc1` as some other NodeState, and no comment), so they are layout 2, as the package README's layout rules require: `LAYOUT_VERSION` is 2; a new document still records `lexical-y:1`, and the transaction that writes a document's first member entry also records `lexical-y:2` (undo keeps it). From then on, clients that only read layout 1 (#9400 to #9438 builds) open the document read only, with the `@lexical/y/unsupported-layout` warning, instead of editing it without its comments; documents that never hold a member entry stay at layout 1 and older clients keep editing them. The planned move records (#9449) become layout 3. A client that is active and reads the version a peer just recorded does not read the whole document again when the record arrives (it changes nothing it reads or writes). The version is recorded in a `finally` inside each transaction that writes content (an edit's, the initial write's and the rewrite that recovers from a failed write), so a write that throws part way, which Yjs still commits and sends, carries it too; once a document records it, a transaction's inserts are not scanned for member entries. - **One format family per set.** The write cursor bounds the format items a delete leaves, and keeps a format's items at the boundaries a concurrent writer relies on, per format family (#9400's `formatFamily`). Here a set's member entries (`s:<key>\u001f<member>`, escaped members included) and a whole array an earlier build stored under `s:<key>` are one family, the set's key, so they follow the rules the whole set follows: the run a delete leaves keeps a bounded number of member items per set, not per member (a comment added to each of 60 words typed and deleted again at one place leaves at most 4 live items, not 2 per comment); and removing a member from a range that holds another member's boundary writes the removed member's value again there, so text a peer types before that boundary does not bring the member back. Removing a comment whose range holds another comment's start costs 51 bytes (redo 48) instead of 10. - **Known limit: a removed member leaves an item.** Removing a member from text that stores its set per member (resolving a comment with `$removeMarkID`) leaves one small live format item after that text (about 30 bytes with a short comment id), which the binding cannot safely clean up: a collaborator writing inside that text at the same time may still rely on it (#9400's write cursor keeps the item after a format change's range for that writer, for any key; a set stored whole reuses it for the next comment there, a member's key is not written again). So the document grows with every member removed, not only with its content. Removing the same member again at the same place adds nothing, and adding a member and undoing it leaves nothing. The docs now recommend resolving a comment without removing its id: keep the id in the text, mark the thread resolved in the app's own store, and leave resolved ids out when rendering (see the `MarkStateExtension` option for that). Unresolving is then free and the document does not change. Removing the id stays documented as the alternative, with this cost ([Resolving comments](https://lexical.dev/docs/collaboration/comments#resolving-comments)). - A reader that compares a node with what is stored does not refuse a state named like a member entry (refusals are for writes), so a document holding one, stored by a client that knows only that state, still reads in full on clients that know both. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`, and registers it for text the way `MarkStateExtension` does (in the node type's shared state config, with no editor update, so that the peers' identical seed is still a load for `BlockIdExtension` and gets the same ids on every peer); `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), that the state needs no registration, and not to name another state with a set's key and U+001F, and the old "NodeState sets" limit (one value per text run) is removed, and the limit says that storing members is layout 2 and what older clients then do; the layout section says `LAYOUT_VERSION` is 2 and when a room records it; the README's wire format gets a layout 2 section (the member entries `s:<key>\u001f<member>` = `true`, their escaping, the empty key, the reserved names, and the lazy upgrade), and its layout record rule says "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The Comments and Annotations page gets a "Resolving comments" section: keep a resolved comment's id in the text and its thread's state in the app's store (unresolving is then free, and the document does not change), or remove the id with `$removeMarkID` and add it again to unresolve, which under `@lexical/y` leaves one live item per removal; the Yjs 14 page's limits get a "Removed set members" item that says the same and links that section. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. A peer that does not know the state exports the joined set in its JSON (`"markIds": ["c1"]`), which a later JSON load parses as the set. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 109 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 51 / 116 / 48 113 / 144 / 113 ``` The first comment in a document also records layout 2 (26 bytes, once per document); without that record it is 83 / 10 / 77. What each way of resolving a comment leaves, 200 comments on the same words, through `MarkStateExtension` and `YCollabExtension` as an app builds them, two clients with pinned client ids (a scratch probe, not committed; live format items, and bytes a GC'd copy of the document grows by per comment): ``` $removeMarkID (resolved by the author or the other client) 200 items, 49 B per comment (81 B with UUID ids) the id kept in the text, resolved in the app's store 400 items (2 per comment, its range), 65 B one comment resolved and reopened 200 times 1 item a comment added, then undone 0 items ``` New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. Mark ids on the wire: ten ids on one text run, among them lone high and low surrogates (`'\ud800'`, `'\ud801'`, `'\udc00'`, `'x\udbff'`), a valid pair and ids starting with U+001F: every peer and a fresh reader read them back exactly, every stored name is well-formed, and a peer that removes `'\ud800'` removes only that one. A JSON copy of a commented text node (`node.updateFromJSON(JSON.parse( JSON.stringify(node.exportJSON())))` through the headless API, with `MarkStateExtension` or a nodes-only config): an unchanged copy writes nothing; a copy made while a human resolves A and adds B keeps B only (with and without a text edit, both merge orders); a copy that adds C to a JSON still holding A, while a human resolves A, gives C. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written, also when it is only registered and never set (the set's write is refused); a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader; members holding lone surrogates, a valid pair and one starting with U+001F on a text run, a line break, an inline and a block decorator read back exactly on every peer and a fresh reader. The layout record: a set stored whole on a paragraph leaves the document at layout 1; the update that writes the first member entry also records `lexical-y:2`, which every peer then has and undo keeps; through the headless API a seed and a text edit without members stay at layout 1, the edit that adds a member records layout 2 in its update, and a seed with a member records both; a write that throws part way (the edit and the rewrite that recovers from it each write everything, then throw), with `NODE_ENV` development and production, and an initial write into a root inside another shared type that throws part way, both send `lexical-y:2` in the first update, with the member entry. A set used without registration, both client id orders: a client that starts using the set after it read the document reads the members, types in the tagged text, adds a member and removes one, and every peer, the stored keys and a fresh reader agree, with no error or warning; concurrent changes merge when one client learned the set late; a client that never uses the set edits the text and keeps its members, and its JSON equals the others'; the headless API seeds such a state, reads it, adds a member and edits the text without touching it. `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error × a state named like a member entry is refused even without a value × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) × concurrent changes merge when one client learned the set late (2 of 2 orders) × a client that never uses the set keeps its members (2 of 2 orders) Test Files 3 failed (3) Tests 29 failed | 46 passed (75) ``` This revision's fixes (members that are not well-formed UTF-16, a JSON copy of an unknown set, and layout 2), with this revision's tests and the previous revision of `Binding.ts`, `Read.ts`, `Schema.ts` and `constants.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } } # peers read '\ufffd' × an unchanged copy writes nothing (nodes only) AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null × an unchanged copy writes nothing (nodes only, seeded nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere) AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ] × a changed copy writes only the members it adds or removes AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ] × are read back exactly on text, a line break and stored nodes × the first member entry records layout 2 in its own update, and undo keeps it AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] × the headless API records layout 2 with the first member entry only Tests 9 failed | 137 passed (146) ``` The same, on this revision (two more tests, below): `Tests 148 passed (148)`. #9400's `regressions/Formats.test.ts` with the previous revision of `Schema.ts` (every key a family of its own) and of `Size.test.ts`'s budget: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > F24A-1: words typed and deleted again at one place > leave a bounded number of format items (comments) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 3,2,1) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 3,2,1) Tests 5 failed | 94 passed | 4 expected fail (103) ``` The same, on this revision: `Tests 99 passed | 4 expected fail (103)`. A write that throws part way, with the previous revision of `Binding.ts` (which recorded the version after the write, so not when it threw): ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts -t 'throws part way' × a write that throws part way still sends layout 2 with the member entries it wrote, in development and production × an initial write that throws part way still sends layout 2 with the member entries it wrote AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] Tests 2 failed | 21 skipped (23) ``` A layout 2 document opened by the previous commit (#9438, layout 1 only), written here with one comment and read there with `MarkStateExtension`: `status: "readonly"`, warning `'@lexical/y/unsupported-layout'` (`data`: `{reason: 'newer', found: 2, supported: 1}`; message `layout 2 is newer than 1` since #9400's typed warnings) (before this revision: `active`, no warning, and no comment shown). ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 136 passed | 2 skipped (138) Tests 4674 passed | 12 expected fail | 2 skipped (4688) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests (`IncidentReplay.test.ts` and `TabLeakReplay.test.ts`) and the 12 expected failures (pinned limits in `regressions/`) are #9400's as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` Property test with comments (a reviewer's scratch harness, not committed: 2–3 human peers with `MarkStateExtension` and the self-check on, typing, structure, bold, comments added and resolved, undo, through a delaying and reordering relay, while agents edit stale stored states with `editYState`, 60 steps per session), 2,000 sessions each: comments, comments with block ids, and storing the returned `state` when the agent edited the latest state. 0 sessions in which the binding diverged; the last mode had 5 sessions whose stored state read differently before which one client's `Doc` keeps pending structs it could apply (a `@y/y` 14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its comments mode with the self-check off (2,000 sessions) and on (500 sessions) gives the same result in every session as #9438. A first version of the layout 2 record made every peer read the whole document again when the record arrived, which changed the result of 3 of those 2,000 sessions (text shown twice); the binding now skips that read when it already reads the recorded version, and the 3 sessions are as on #9438. Collab Y e2e on this commit (the development build as CI makes it, with the binding's self-check on, `collab-y-server.mjs` relay, 2 workers, no retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs are Chromium only). On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 changed, 68 added: `MarkState.test.ts` 41, `SetState.test.ts` 23, `Size.test.ts` 3, and `Lifecycle.test.ts`'s version gate test renamed from "(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,882 added: 4,875 on the previous revision, plus #9400's 3 new `WarningTypes.test.ts` tests and #9437's 4 new tests (`createYDoc`, and that `YBinding` hides `flushPending`); the website's generated `stackblitz.test.ts` audits are left out of both comparisons), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (372 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: WebKit, and real Yjs 14 providers other than the playground relay.
…format per member Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438). Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued NodeState), which is on main. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: arraySetValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `arraySetValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array under the set's key, unless a StateConfig uses the entry key itself or the set's key is a StateConfig that does not hold a set. For a set-valued state the reader knows, the state's own parse turns the array into its canonical value (a frozen array, sorted and without duplicates, the same value a local `$setState` or a JSON load gives). For one it does not know yet, the sorted array is kept as an unknown NodeState value, which the writer stores one entry per member again, as it does any string array under that key on a node of that type (the reader notes the key per node type, so a JSON copy of the node's state is stored the same way): an unchanged set writes nothing, and a changed one writes only the members it adds or removes, never the whole set. So such a peer never collapses the members; and since Lexical parses an unknown value when a state is first used, a client that starts using the state after it read the document (the usual way: `createState`, then `$getState`/`$setState`, with nothing registered) reads the set, and its writes keep the members. The state needs no registration. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A set-valued state whose own key contains U+001F is stored whole. A set whose key is the empty string is stored and read like any other (`s:\u001f<member>`). - **Reserved names.** A member entry's name is the set's key, U+001F and the member, so another state named that way (`'tags\u001fx'` next to a set `'tags'`) would be stored under the same attribute as member `x` of `tags`. The binding refuses such a StateConfig, whether or not it holds a value, whenever it writes that state or the set on a node for which both are known (used on it or registered for its type): an invariant (`devInvariant`) in development, a warning in production, and the set is then stored whole, as one value, so no reader drops a member. Only StateConfigs are refused: an entry no StateConfig knows is a set's member or another client's data, and is written back as it is. A reader keeps an entry as an ordinary key whenever it knows a state of the entry's own name, so a document written by a client that does not know the set (and so does not refuse) still reads correctly. - **Every member round-trips.** Yjs stores format and attribute names as UTF-8, which turns a lone surrogate into U+FFFD, so two members that differ only there would be read back as one. A member that holds a lone surrogate, or that starts with U+001F, is stored escaped: `s:<key>\u001f\u001f` followed by the member's JSON, with every surrogate code unit written as a `\uXXXX` escape (ASCII). Every other member is stored as itself. - **Layout 2.** Member entries are a stored shape older clients misread (they see `s:markIds\u001fc1` as some other NodeState, and no comment), so they are layout 2, as the package README's layout rules require: `LAYOUT_VERSION` is 2; a new document still records `lexical-y:1`, and the transaction that writes a document's first member entry also records `lexical-y:2` (undo keeps it). From then on, clients that only read layout 1 (#9400 to #9438 builds) open the document read only, with the `@lexical/y/unsupported-layout` warning, instead of editing it without its comments; documents that never hold a member entry stay at layout 1 and older clients keep editing them. The planned move records (#9449) become layout 3. A client that is active and reads the version a peer just recorded does not read the whole document again when the record arrives (it changes nothing it reads or writes). The version is recorded in a `finally` inside each transaction that writes content (an edit's, the initial write's and the rewrite that recovers from a failed write), so a write that throws part way, which Yjs still commits and sends, carries it too; once a document records it, a transaction's inserts are not scanned for member entries. - **One format family per set.** The write cursor bounds the format items a delete leaves, and keeps a format's items at the boundaries a concurrent writer relies on, per format family (#9400's `formatFamily`). Here a set's member entries (`s:<key>\u001f<member>`, escaped members included) and a whole array an earlier build stored under `s:<key>` are one family, the set's key, so they follow the rules the whole set follows: the run a delete leaves keeps a bounded number of member items per set, not per member (a comment added to each of 60 words typed and deleted again at one place leaves at most 4 live items, not 2 per comment); and removing a member from a range that holds another member's boundary writes the removed member's value again there, so text a peer types before that boundary does not bring the member back. Removing a comment whose range holds another comment's start costs 51 bytes (redo 48) instead of 10. - **Known limit: a removed member leaves an item.** Removing a member from text that stores its set per member (resolving a comment with `$removeMarkID`) leaves one small live format item after that text (about 30 bytes with a short comment id), which the binding cannot safely clean up: a collaborator writing inside that text at the same time may still rely on it (#9400's write cursor keeps the item after a format change's range for that writer, for any key; a set stored whole reuses it for the next comment there, a member's key is not written again). So the document grows with every member removed, not only with its content. Removing the same member again at the same place adds nothing, and adding a member and undoing it leaves nothing. The docs now recommend resolving a comment without removing its id: keep the id in the text, mark the thread resolved in the app's own store, and leave resolved ids out when rendering (see the `MarkStateExtension` option for that). Unresolving is then free and the document does not change. Removing the id stays documented as the alternative, with this cost ([Resolving comments](https://lexical.dev/docs/collaboration/comments#resolving-comments)). - A reader that compares a node with what is stored does not refuse a state named like a member entry (refusals are for writes), so a document holding one, stored by a client that knows only that state, still reads in full on clients that know both. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, and every StateConfig whose key contains U+001F, so it reads the members and those ordinary keys the same way (otherwise every write of a set would be reported to the editor's `onWarn` as a `'@lexical/y/self-check'` warning, and so would an ordinary state whose name looks like a member entry). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `arraySetValue` state, like `MarkStateExtension`, and registers it for text the way `MarkStateExtension` does (in the node type's shared state config, with no editor update, so that the peers' identical seed is still a load for `BlockIdExtension` and gets the same ids on every peer); `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links), that the state needs no registration, and not to name another state with a set's key and U+001F, and the old "NodeState sets" limit (one value per text run) is removed, and the limit says that storing members is layout 2 and what older clients then do; the layout section says `LAYOUT_VERSION` is 2 and when a room records it; the README's wire format gets a layout 2 section (the member entries `s:<key>\u001f<member>` = `true`, their escaping, the empty key, the reserved names, and the lazy upgrade), and its layout record rule says "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page says that `@lexical/y` stores the ids separately, and where. The Comments and Annotations page gets a "Resolving comments" section: keep a resolved comment's id in the text and its thread's state in the app's store (unresolving is then free, and the document does not change), or remove the id with `$removeMarkID` and add it again to unresolve, which under `@lexical/y` leaves one live item per removal; the Yjs 14 page's limits get a "Removed set members" item that says the same and links that section. The core NodeState page is not changed: it only says that `meta.kind === 'set'` marks a set whose members are independent. A peer that does not know the state exports the joined set in its JSON (`"markIds": ["c1"]`), which a later JSON load parses as the set. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 109 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 51 / 116 / 48 113 / 144 / 113 ``` The first comment in a document also records layout 2 (26 bytes, once per document); without that record it is 83 / 10 / 77. What each way of resolving a comment leaves, 200 comments on the same words, through `MarkStateExtension` and `YCollabExtension` as an app builds them, two clients with pinned client ids (a scratch probe, not committed; live format items, and bytes a GC'd copy of the document grows by per comment): ``` $removeMarkID (resolved by the author or the other client) 200 items, 49 B per comment (81 B with UUID ids) the id kept in the text, resolved in the app's store 400 items (2 per comment, its range), 65 B one comment resolved and reopened 200 times 1 item a comment added, then undone 0 items ``` New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. Mark ids on the wire: ten ids on one text run, among them lone high and low surrogates (`'\ud800'`, `'\ud801'`, `'\udc00'`, `'x\udbff'`), a valid pair and ids starting with U+001F: every peer and a fresh reader read them back exactly, every stored name is well-formed, and a peer that removes `'\ud800'` removes only that one. A JSON copy of a commented text node (`node.updateFromJSON(JSON.parse( JSON.stringify(node.exportJSON())))` through the headless API, with `MarkStateExtension` or a nodes-only config): an unchanged copy writes nothing; a copy made while a human resolves A and adds B keeps B only (with and without a text edit, both merge orders); a copy that adds C to a JSON still holding A, while a human resolves A, gives C. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `arraySetValue(stringValue())` state, both client id orders: concurrent additions (each peer adds the member the other sorts after) merge on a text run, an inline decorator and a block decorator, stored one key per member on each, and every peer reads back the canonical frozen array (`['a', 'b']`); a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a state named like a member entry of a known set (`'tags\u001fx'`) is refused and nothing is written, also when it is only registered and never set (the set's write is refused); a boolean state of that name stored by a client that does not know the set is read as itself by clients that know both, and the whole-container self-check after a structural edit reports nothing; a set-valued state whose key contains U+001F is stored whole (written as `['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run, a line break, an inline and a block decorator, reads back as `['', 'a\u001fb', 'x']` on every peer and on a fresh reader; members holding lone surrogates, a valid pair and one starting with U+001F on a text run, a line break, an inline and a block decorator read back exactly on every peer and a fresh reader. The layout record: a set stored whole on a paragraph leaves the document at layout 1; the update that writes the first member entry also records `lexical-y:2`, which every peer then has and undo keeps; through the headless API a seed and a text edit without members stay at layout 1, the edit that adds a member records layout 2 in its update, and a seed with a member records both; a write that throws part way (the edit and the rewrite that recovers from it each write everything, then throw), with `NODE_ENV` development and production, and an initial write into a root inside another shared type that throws part way, both send `lexical-y:2` in the first update, with the member entry. A set used without registration, both client id orders: a client that starts using the set after it read the document reads the members, types in the tagged text, adds a member and removes one, and every peer, the stored keys and a fresh reader agree, with no error or warning; concurrent changes merge when one client learned the set late; a client that never uses the set edits the text and keeps its members, and its JSON equals the others'; the headless API seeds such a state, reads it, adds a member and edits the text without touching it. `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[b] test_equation[b] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 × a state named like a member entry of a set is refused AssertionError: expected [Function] to throw an error × a state named like a member entry is refused even without a value × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders) × concurrent changes merge when one client learned the set late (2 of 2 orders) × a client that never uses the set keeps its members (2 of 2 orders) Test Files 3 failed (3) Tests 29 failed | 46 passed (75) ``` This revision's fixes (members that are not well-formed UTF-16, a JSON copy of an unknown set, and layout 2), with this revision's tests and the previous revision of `Binding.ts`, `Read.ts`, `Schema.ts` and `constants.ts`: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } } # peers read '\ufffd' × an unchanged copy writes nothing (nodes only) AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null × an unchanged copy writes nothing (nodes only, seeded nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only) × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere) AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ] × a changed copy writes only the members it adds or removes AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ] × are read back exactly on text, a line break and stored nodes × the first member entry records layout 2 in its own update, and undo keeps it AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] × the headless API records layout 2 with the first member entry only Tests 9 failed | 137 passed (146) ``` The same, on this revision (two more tests, below): `Tests 148 passed (148)`. #9400's `regressions/Formats.test.ts` with the previous revision of `Schema.ts` (every key a family of its own) and of `Size.test.ts`'s budget: ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > F24A-1: words typed and deleted again at one place > leave a bounded number of format items (comments) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 3,2,1) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 1,2,3) FAIL |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 3,2,1) Tests 5 failed | 94 passed | 4 expected fail (103) ``` The same, on this revision: `Tests 99 passed | 4 expected fail (103)`. A write that throws part way, with the previous revision of `Binding.ts` (which recorded the version after the write, so not when it threw): ``` $ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts -t 'throws part way' × a write that throws part way still sends layout 2 with the member entries it wrote, in development and production × an initial write that throws part way still sends layout 2 with the member entries it wrote AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ] Tests 2 failed | 21 skipped (23) ``` A layout 2 document opened by the previous commit (#9438, layout 1 only), written here with one comment and read there with `MarkStateExtension`: `status: "readonly"`, warning `'@lexical/y/unsupported-layout'` (`data`: `{reason: 'newer', found: 2, supported: 1}`; message `layout 2 is newer than 1` since #9400's typed warnings) (before this revision: `active`, no warning, and no comment shown). ``` $ npx vitest --project unit --no-watch packages/lexical-y/ Test Files 136 passed | 2 skipped (138) Tests 4674 passed | 12 expected fail | 2 skipped (4688) $ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx Test Files 5 passed (5) Tests 141 passed | 4 expected fail (145) ``` The 2 skipped tests (`IncidentReplay.test.ts` and `TabLeakReplay.test.ts`) and the 12 expected failures (pinned limits in `regressions/`) are #9400's as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 100 passed (100) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 16 passed (16) ``` Property test with comments (a reviewer's scratch harness, not committed: 2–3 human peers with `MarkStateExtension` and the self-check on, typing, structure, bold, comments added and resolved, undo, through a delaying and reordering relay, while agents edit stale stored states with `editYState`, 60 steps per session), 2,000 sessions each: comments, comments with block ids, and storing the returned `state` when the agent edited the latest state. 0 sessions in which the binding diverged; the last mode had 5 sessions whose stored state read differently before which one client's `Doc` keeps pending structs it could apply (a `@y/y` 14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its comments mode with the self-check off (2,000 sessions) and on (500 sessions) gives the same result in every session as #9438. A first version of the layout 2 record made every peer read the whole document again when the record arrived, which changed the result of 3 of those 2,000 sessions (text shown twice); the binding now skips that read when it already reads the recorded version, and the 3 sessions are as on #9438. Collab Y e2e on this commit (the development build as CI makes it, with the binding's self-check on, `collab-y-server.mjs` relay, 2 workers, no retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs are Chromium only). On this commit: `pnpm run test-unit` compared test by test with #9438 (0 failed, 0 changed, 68 added: `MarkState.test.ts` 41, `SetState.test.ts` 23, `Size.test.ts` 3, and `Lifecycle.test.ts`'s version gate test renamed from "(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,882 added: 4,875 on the previous revision, plus #9400's 3 new `WarningTypes.test.ts` tests and #9437's 4 new tests (`createYDoc`, and that `YBinding` hides `flushPending`); the website's generated `stackblitz.test.ts` audits are left out of both comparisons), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (372 passed), `pnpm run build-prod` and the built tree-shaking test (286 passed), and the website build with TypeDoc and the broken link check (`pnpm run build-docs`) all pass. Not exercised: WebKit, and real Yjs 14 providers other than the playground relay.
Description
Current behavior: NodeState has no value type for a set. A state holding one
needs a hand-written
parse,unparseandisEqual, nothing keeps a valuewritten with
$setStatein one canonical order, and nothing tells code thatreads the state that its members are independent. Comment and annotation
marks can only be stored as
MarkNodewrappers: overlapping marks becomesibling
MarkNodes whoseidsthe app has to keep consistent (withregisterNestedElementResolver; without it they nest), and every add orremove restructures the tree.
New behavior (all opt-in and
@experimental; existing states, schemas,MarkNodeand the rest of@lexical/markare unchanged, and@lexical/yjsgets no source change):
lexical:arraySetValue(item), a value schema in thestringValue/arrayValuefamily:createState('tags', {parse: arraySetValue(stringValue())})is aStateConfig<'tags', readonly string[]>.unit, no duplicates. Parsing keeps the entries
itemaccepts (others aredropped, not coerced), dedupes, sorts and freezes; a non-array is the
frozen empty array, which is the default. An already canonical frozen value
is returned as is.
$setStateputs a value written to such a state, directly or from anupdater, into the same form, so
$setState(node, tagsState, ['b', 'a', 'a'])stores
['a', 'b']. For every other state$setStatestores the value asgiven, as before.
canonical): an updater returning the same members in another order does
not dirty the node, and the empty set is left out of the JSON. The JSON is
the sorted array, so equal sets serialize identically.
T extends string, soenumValue([...])works as theitem), which gives a well-defined order. An item schema that declines some
strings in its
acceptsmakes parsing drop them, so a set can admit onlywell-formed members. A development build refuses an item that does not
produce strings (only reachable from untyped code).
stateConfig.schema?.meta.kind === 'set', withmeta.item, marks it as a set whose members are independent,so code that stores or merges values can treat each member separately.
This adds one variant to
SerializationSchemaMetaand nothing toStateConfig.@lexical/fast-checkgenerates inputs for it.createState. A development build refusesit inside another combinator, in an
objectValuefield and as a nodeproperty (
nodeSchema,withField). The check is added to thedevelopment-only checks those combinators already run; it is the only
change to them.
arraySetValuein the compiler's pure-factory list.@lexical/mark:MarkStateExtension(exported from@lexical/mark).Mark ids are a set-valued NodeState,
markIds(MARK_STATE_KEY), on theleaves they cover:
TextNode,LineBreakNodeand inlineDecoratorNodes bydefault. There is no wrapper node. The ids live on the leaves, so they travel
with the text: typing inside a marked run adds to the TextNode that carries
the ids, marking part of a run splits the TextNode and neighbors with the
same ids merge back, and copying, cutting or deleting text carries or
deletes its ids. Marks overlap freely, and adding or removing a comment
changes NodeState only. In JSON a leaf covered by
c1andc2has{"$": {"markIds": ["c1", "c2"]}}.$addMarkID(id, selection),$removeMarkID(id, selection?)(noselection: everywhere),
$getMarkIDsAtSelection(selection?, 'any' | 'all'),$getNodeMarkIDs(node),$migrateMarkNodesToMarkState(node?),$isInlineDecoratorNode(a type guard),MARK_STATE_KEY,MARK_STATE_IDS_ATTRIBUTE,DEFAULT_MARKABLE_NODES. The getters return newsorted arrays the caller may change.
$addMarkIDand themigration throw on anything else; an invalid id read from JSON or HTML,
written with
$setState, or applied withupdateFromUnknownis dropped,through the item schema of the state.
disabled,exportIDsToHTML(defaultfalse, likeMarkNode) andmarkableNodes(node classes and guard functions).markIDNodeKeys, a signal mapping each id to the keys of the leavesthat carry it, maintained from update listeners (so it works headless and
after undo). Each update costs what it changed: the dirty leaves, and the
leaves under the nodes it removed. A
setEditorState(undo and redoincluded), whose dirty sets do not describe the change, is compared with
the previous state node by node, reading only the nodes that are not the
same object in both.
$removeMarkID(id)uses the output instead ofwalking the document.
and right after where it was inserted (within its block), plus, when it
replaces a selection, the ids all the replaced text had, plus, for pasted
content, its own ids. So text inserted at the edge of a marked run does
not join it (as with
MarkNode), text inserted inside a run does,retyping a commented word keeps the comment (also when it replaces all of
the marked text, where
MarkNodeloses the comment), and pasted contentkeeps the ids it was copied with and also joins the run it is pasted
inside, and so do dropped content and nodes that code inserts. Text
inserted into existing text has no ids of its own, also when a transform
then splits it off into a copy of that text: text typed or pasted as
plain text after a commented hashtag is not commented, as with
MarkNode. Text that is not deleted keeps its ids, also when the coreor a transform moves it into a new TextNode (a hashtag or a mention created from commented text, a
segmented node that typing turns into text). An id removed with
$removeMarkIDin the same update is not given back, to that text orto inserted text. That holds for the whole update (and the updates
batched with it): also where the removal did not reach, and after the
update adds the id again. The docs list this as a limitation.
its own class:
TextNode, or the class that replaces it through a nodereplacement (with or without
withKlass). Other TextNodes are not splitand get every id their text had: token and segmented nodes, and
subclasses whose boundaries their own transforms set, such as a hashtag
or a code highlighting token (their pieces would be plain text, which
those transforms merge back). In such a node, text typed at the edge of a
mark joins it. Text inserted at the end of such a node that its transform
then splits off is told apart by identity:
splitTextgives the piece thenode's NodeState, so the piece holds the very array of the node's ids,
while pasted, dropped, imported or inserted content, and ids added with
$addMarkID, are an array of their own even when they are the same ids.So a new
TextNodeof the classsplitTextcreates, whose nearestearlier sibling from before the update is a
TextNodeof another classholding the same array (
===), is a piece split off it, and those idsare not its own. This does not depend on how the text was inserted or on
what a DataTransfer holds, so a drop, a paste whose HTML equals its plain
text (as iOS sends with autocorrect), and nodes that code inserts and
marks in the same update all come out like
MarkNode. The array isshared only by copying NodeState as it is:
splitText,$copyNode,$setStatewith a value read from another node, and JSON fromexportJSON()imported without a round trip through a string.Code that gives a plain
TextNodethe array of such a node that way andinserts it right after that node gets it unmarked at the end of the mark;
the docs list this as a limitation.
children around the caret with the previous editor state. A child that
is the same object in both states is unchanged, and one on each side
bounds the comparison. Within that, the text both states share at the
start and at the end is compared as a few units, so a keystroke costs a
scan of the changed TextNodes plus units for the changed text only, also
in one long TextNode (see the table below). Text is compared by code
point, so no surrogate pair is split. The change ends at the caret. When
it replaces a selection, the selection is the one recorded when
CONTROLLED_TEXT_INSERTION_COMMANDorPASTE_COMMANDwas lastdispatched, inside an update or not (typing, autocorrection and the DOM
pasteevent all record it), or the one the composition started with.The record is forgotten when the editor commits and at the next
microtask, and it is used only when the text in its place is in new
TextNodes, as the core inserts it, so a handler that wraps the selection
instead is not taken for a replacement. Updates batched into one commit
are compared with the document from before the commit, as one edit: the
last command dispatched before the commit decides the replaced selection
for all of them. Typed text in such a batch does not affect nodes that
code inserts: they keep their own ids.
Without a recorded selection (code calling
selection.insertText()directly) the longest common subsequence of the old and new text tells
the kept letters, which keep their ids, from the inserted ones; then a
replacement across the edge of a mark that starts or ends with the
letter it replaces can join that mark. So the rule holds whichever
TextNode the core puts the text in (native input,
insertText, a newnode for a toggled format or for the text replacing a selection, an input
method, a multi-node paste, a caret placed in the same update). History
replays and updates tagged
COLLABORATION_TAGare left alone, and so isa composition whose paragraph such an update edited while it was in
progress.
output, HTML import and migration look inside slots too.
mark/markOverlaptheme classes and adata-lexical-mark-idsattribute on each marked leaf. WithexportIDsToHTMLHTML export writes the attribute, and aDOMImportExtensionrule reads it back.markIdsstate onevery node type, so ids read from JSON are parsed at once.
@lexical/mark:@lexical/extension,@lexical/htmland
@lexical/internal(@lexical/internalis inlined by the build).NodeStructureExtensionon: the ids stay on the leaves thatits repairs move (a block lifted out of a heading, a heading split around
a quote), and the output follows them. The
extension's tests and both property tests give the same results with it
on.
Docs: a "Comments and Annotations" page under Collaboration (how ids
follow the text, a
MarkNodetoMarkStateExtensiontable, the insertedtext rule and its limits, and how
@lexical/yjssyncs the ids), a"Set-valued state" section on the NodeState page, and an entry on the
included extensions page.
Changes since the version reviewed earlier (levensta's review comments
and Bob's request for set-valued state):
arraySetValuereplaces thecollab: 'set'option oncreateState. Thestate is declared as a value schema like any other, and the core has no
collaboration vocabulary:
StateCollabEncoding, thecollabfield and thesplit-entry helpers are gone.
@lexical/yjschanges are dropped: per-member storage of set-valuedstate is no longer part of this PR, and the
@lexical/yjssources areidentical to
main. The only file this PR adds underpackages/lexical-yjsis the two-peer test ofMarkStateExtension, whichlives there because it imports
@lexical/yjs,yjsand the collaborationplugin.
Test plan
Before
The new tests on the previous version of this PR:
The previous version compared the ids by equality and exempted pastes
whose DataTransfer had Lexical or HTML data. A test stops at its first
failing case: the drop, the run of nodes inserted by code and the
beforeinputwith such a DataTransfer failed the same way.The new NodeState tests on
main:After
LexicalNodeState.test.ts,set-valued state (arraySetValue): the type,the frozen empty default and the
'set'meta; parsing (dedupe, droppedentries, UTF-16 order, freeze, non-arrays, canonical values kept, frozen
values that are not canonical, an
enumValueitem, an item that declinessome strings); in-place mutation throws;
$setStateand updaters storethe canonical form; equality; JSON (sorted, empty omitted, stable round
trip of a state declared in
$config, an undeclared state read afterloading JSON); an explicit
unparsestill wins; the development refusalin all ten places and of an item that does not produce strings. A
separate test checks that
$setStatekeeps the exact value it is givenfor
arrayValue,objectValue, a hand-written parse and an updater.LexicalFastCheck.test.ts:nodeArbitraryof a node with a flatarraySetValuestate generates arrays of the item's values, unsorted andwith duplicates among them, and importing each sample stores the sorted
set.
MarkStateExtension.test.ts: overlap, queries, getters returning newarrays, split and merge, edge typing, composition, links, ids, HTML, undo,
rendering,
disabled(also from the start), migration, slots,markableNodes(also two editors with different sets), the JSON format,and the inserted text rule: typing next to a gap in a mark, a caret placed
programmatically at the start of a run, text inserted in the same update
that moves the caret, replacing a whole run, composition in a new TextNode
for a toggled format, multi-node paste inside a run, pasted ids kept at an
edge and inside a run, nodes inserted with
insertNodes; replacing aselection with text that shares its first or last letter with it, or with
an autocorrection, inside a run, over a whole run and across its start,
with the selection committed first or set in the same update, each
compared with
MarkNodeon the same edit; a replacement by code thatdispatches no command; a handler that wraps the selection instead of
replacing it; a hashtag (
HashtagExtension), a token node created by atransform and a segmented node turned into text, compared with
MarkNode; the replaced selection when the command is dispatched outsidean update, through
PASTE_COMMANDand through a DOMpasteevent; theselection of a command that changed nothing not reaching a later update;
an id removed in the same update (from a hashtag, by range, and before or
after a replacement); a 20,000-character TextNode edited at, inside and
across the edges of a mark; emoji typed inside a run and replaced without
a command; the class that replaces TextNode (with and without
withKlass) typed at both edges of a mark, and text typed, pasted(
PASTE_COMMANDand a DOMpasteevent) and inserted by code after amarked hashtag, each compared with
MarkNode; pasted Lexical data withthe ids of a hashtag after it, also inserted by code without a paste
command; text dropped from another editor there, compared with
MarkNode; text that code inserts after a hashtag and marks in the sameupdate, compared with
MarkNode, and a run of nodes that code insertsthere, each marked; a paste and a
beforeinputwhose HTML equals theirplain text, compared with
MarkNode; a plain TextNode given the hashtag'sids array (the documented limitation) and the same text marked with
$addMarkID; an update taggedCOLLABORATION_TAGediting the paragraph of a composition, and anotherparagraph; the output after undo, after a
setEditorStatethat atransform also dirties, after loading JSON and after removing a
paragraph; invalid ids from JSON, from
updateFromUnknownand from HTML.MarkStateProperty.test.ts: a seeded property test. Random sequences oftyping (also in the same update as the caret move, and with a toggled
format), replacing a selection, composition, Backspace and Delete, range
deletion, Enter, formatting, block type changes, adding and removing ids,
copy and cut and paste, undo and redo, on three paragraphs with up to five
overlapping ids. Typed letters are lowercase half of the time, so they can
equal the letters around them, and sometimes an emoji (some of which
share their first code unit). It also removes an id in the same update as
typing or a replacement, before or after it, and sends paste events,
which dispatch
PASTE_COMMANDoutside an update, over a selection (oftenwith text that starts with its first letter) or at the caret. Every third
seed replaces TextNode with a subclass through a node replacement. A
replacement is a new letter, the first
or the last letter of the selection, the selection with two letters
swapped, its start followed by a new letter, or a new letter followed by
its end; it is typed or sent as an autocorrection, with the selection
committed first or set in the same update, sometimes across two
paragraphs. After every step it checks every character's text and ids
against a model of the rule above,
markIDNodeKeysagainst a fullrecomputation,
$getMarkIDsAtSelection('any'and'all', collapsed andranged, forward and backward) against the characters, the DOM attribute
and classes, and that no equal siblings are left unmerged. 40 seeds of 30
steps in CI (about 2 s); run locally at 2,000 seeds of 40 steps
(
MARK_STATE_PROPERTY_SEEDS=2000 MARK_STATE_PROPERTY_STEPS=40, 74 s): allpass, also with
NodeStructureExtensionadded to the editor.MarkStateCollab.test.tsx(inpackages/lexical-yjs), both client idorders, asserting the tree, the
markIDNodeKeysoutput and the Y.Doc onevery peer:
range (text stays in place, both peers converge on one peer's ids),
typing in an overlap ‖ a second mark, removing or undoing a comment ‖ a
peer types inside it, resolving one of two marks ‖ typing in the
overlap, edge typing.
typing inside, undo after a peer typed inside.
documented last-writer-wins outcome, where the removed id comes back in
one client id order and the added one is dropped in the other.
and v1 resolving the only mark of a TextNode ‖ typing inside it, in both
client id orders.
Also run:
pnpm run test-unit: 9,798 passed, 4 expected fail (the ones above), 1skipped. Compared test by test with
main(9,652 passed, 1 skipped):none missing, none changed, 150 added.
Without the extension, JSON, compact JSON, HTML export and a JSON round
trip of 8 HTML fixtures, a Markdown fixture, a document with NodeState of
five kinds and overlapping
MarkNodes (40 outputs) are byte-identical tomain, with and withoutNodeStructureExtension.Keystroke cost: the median of 300 keystrokes at random positions, in ms,
on
mainand on this PR with the extension disabled and enabled(headless unless marked DOM). In one long TextNode, the text that both
states share at its start and end is compared as a few units (an
earlier version of this PR compared every character, 5.79 ms on the
first row).
mainUndo on 10,000 paragraphs with 10,000 comments: 42.6 ms on
main, 42.2ms disabled, 56.0 ms enabled. An undo
compares the restored state with the current one node by node, and only
reads the nodes that differ.
pnpm run tsc,pnpm run tsc-test,pnpm run flow(with Flow smoketests of
arraySetValueand theMarkStateExtensionAPI),pnpm run build-types, eslint and prettier on the touched files, thesource tree-shaking test,
pnpm run build-prodand the integrationtree-shaking test, and the website build with its link check.
git diff main -- packages/lexical-yjs/srclists only the added test.Not exercised: real browsers (native
beforeinputtyping andautocorrection, IME composition, the clipboard; the DOM
pasteevent issimulated in jsdom) and real Yjs providers.