Repository navigation
[lexical-code-core][lexical-code-prism][lexical-code-shiki][lexical-y][lexical-website] Bug Fix: The code highlighter keeps the NodeState of text inside a code block when it tokenizes the block again - #9832
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
lexical
@lexical/a11y
@lexical/clipboard
@lexical/code
@lexical/code-core
@lexical/code-prism
@lexical/code-shiki
@lexical/compiler
@lexical/devtools-core
@lexical/dragon
@lexical/eslint-plugin
@lexical/extension
@lexical/fast-check
@lexical/file
@lexical/hashtag
@lexical/headless
@lexical/history
@lexical/html
@lexical/internal
@lexical/link
@lexical/list
@lexical/mark
@lexical/markdown
@lexical/mdast
@lexical/offset
@lexical/overflow
@lexical/plain-text
@lexical/react
@lexical/rich-text
@lexical/selection
@lexical/table
@lexical/tailwind
@lexical/text
@lexical/utils
@lexical/y
@lexical/yjs
commit: |
|
AI review status for this pull request.
|
1c5afe1 to
eaade84
Compare
There was a problem hiding this comment.
Thanks, this looks good. The fix is well scoped: the new path only runs when a code block's text carries NodeState, a block without state is tokenized exactly as before, and the new tests on both highlighters fail on main and pass here. I also checked the collaboration case with two peers on @lexical/yjs (v1 and v2) and @lexical/y: with this change both peers keep the state after one of them highlights the block, and their documents converge.
A few optional, non-blocking suggestions:
- Share
$copyNodeState(packages/lexical-code-core/src/FlatStructureUtils.ts:260). The same function now lives in@lexical/code-core,CodeHighlighterPrism.tsandCodeHighlighterShiki.ts, and this PR adds the same block to all three. Exporting the code-core one as@internal(asregisterCodeGutteralready is) and calling it from both highlighters would keep the copy into a code block and the copy out of one on a single rule. - Use a real set-valued state in the tests (
CodePrismRetokenizeKeepsState.test.ts:45,CodeShikiRetokenizeKeepsState.test.ts:49).membersStateis described as set-valued but has a hand-writtenparse;parse: arraySetValue(stringValue())makes it the kind of state@lexical/ystores one entry per member, which is what the description says the copy preserves. - Consider a two-peer test. The tests stand in for a collaborator's change with
skipTransforms: true. A test in the@lexical/yharness, whichRemoteReadAppEdits.test.tsalready runs with Prism highlighting, would pin the behavior users actually rely on. - Per-update cost with a highlight-node replacement that sets NodeState. When a
CodeHighlightNodereplacement sets a state on every token (likeCreatedHighlightNodein the tests), the early return in$keepCodeNodeStatenever fires, so every pass copies and compares state for every token even though it already matches. In a quick measurement (Prism, a 1,000-line block) that took an update from about 103-109 ms to 138-143 ms; without such a replacement the cost was unchanged, matching your numbers. Skipping the copy where the old node's state already equals the new token's is one way to cut it, if that configuration matters to you.
| * Give `to` the NodeState of `from`, flat states included, keeping the state | ||
| * that `to` has for the keys `from` does not set. | ||
| */ | ||
| function $copyNodeState(from: LexicalNode, to: LexicalNode): void { |
There was a problem hiding this comment.
Optional: this is now the third copy of $copyNodeState (the others are in CodeHighlighterPrism.ts and CodeHighlighterShiki.ts), and this PR adds the same known-state block to each. Exporting this one as @internal (as registerCodeGutter is) and calling it from both highlighters would keep the copy into a code block and the copy out of one on a single rule.
| if (!prevNodes.some(hasNodeState)) { | ||
| return nextNodes; | ||
| } |
There was a problem hiding this comment.
Optional: with a CodeHighlightNode replacement that sets a NodeState on every new token (like CreatedHighlightNode in the tests), this early return never fires, so every pass copies and compares state for every token. In a quick Prism measurement on a 1,000-line block that took an update from about 103-109 ms to 138-143 ms; without such a replacement the cost was unchanged. Skipping the copy where the old node's state already equals the new token's is one way to cut it, if that configuration matters.
| const membersState = createState('members', { | ||
| parse: (value: unknown) => | ||
| Array.isArray(value) ? (value as string[]) : ([] as string[]), | ||
| }); |
There was a problem hiding this comment.
Nit: this is described as a set-valued state, but with a hand-written parse it is not one to @lexical/y (which stores a state one entry per member only when its schema is a set). parse: arraySetValue(stringValue()) here and in the Shiki test would exercise the member-wise case the PR description talks about.
eaade84 to
eb8010d
Compare
|
The head is now eb8010d, rebased onto main bdb33e4 (which includes #9835). The code-package change is unchanged; this commit now also flips #9835's cells for a value set on a held code line (the stock highlighters now carry it), adds cells for a value set on a token the highlighter replaces, and scopes y.md's extension sentence to custom tokenizers that merge characters of several nodes. Please run a full review of the current head. |
There was a problem hiding this comment.
This looks good to me: keeping NodeState through a re-tokenization stops comment and suggestion data from being dropped on code text nobody edited, and the new cells fail on main and pass on this branch. Everything below is optional and non-blocking.
Worth considering
-
Tokens an app tokenizer made, when they are split (
packages/lexical-code-core/src/FlatStructureUtils.ts, lines 391-401). Split parts are built with$createCodeHighlightNode(text, type)plus format and style, and$copyNodeState(from, part)then writes the old child's non-default values over what the token already holds. The stock Prism and Shiki tokenizers are unaffected, but an app tokenizer passed through thetokenizeroption that returns its ownCodeHighlightNodesubclass or sets NodeState on its tokens (as themarkingandnamingtokenizers inComposeHoldRestyledLineTransform.test.tsdo) now:- loses its class and its NodeState on every part when the boundary of a text node with NodeState falls inside its token, on every later pass too;
- keeps a stale value after an edit: a tokenizer that records each token's type in NodeState still says
keywordafterletbecomeslets.
Building each part with
$copyNode(node).setTextContent(...)and copying from the old child only the keys a part does not already hold (the precedence$carryNodeStateuses inpackages/lexical/src/LexicalNodeState.ts) fixes both and keeps every cell in this PR passing. A cell with such a tokenizer would pin whichever behaviour you choose. -
packages/lexical-y/DECISIONS.md, D115 still says that extending a value within a re-tokenized token "is not" written, without the custom-tokenizer scopey.mdnow gives that limit; the 8 new cells show it is written with the stock highlighters. -
The new collaboration cells check the value on the composing client only. They compute
valuesfromt.a, andconverged()compares the peers and the fresh reader throughshow(), which printsmarksbut notnote,anchororflatAnchor. Computingvaluesfor every peer and the fresh reader would assert the "kept on every client and a fresh reader" the description states.
Nits
- The JSDoc of
$keepCodeNodeState(lines 330-331) and the changeset say a token is split "where that state changes", but it is split at the boundaries of every node that has NodeState: two adjacent tokens with the same note stay two tokens. The@lexical/yextension case relies on that per-node split, so rewording fits better than merging. without NodeState, the block is tokenized as beforecompares token text and state but not highlight type; addinggetHighlightType()toshow()would make it catch a type change.@lexical/yjs(collab v1/v2) has no cell with NodeState on code text; a fix verified on@lexical/yis not evidence for that binding.
The earlier inline notes (the third copy of $copyNodeState, the fast path with a highlight-node replacement that sets state on every token, and membersState not being an arraySetValue state) still apply at this head and are still optional.
eb8010d to
57985d3
Compare
|
The head is now 57985d3 (on main bdb33e4). |
There was a problem hiding this comment.
This looks good to me: the highlighters now keep NodeState through a re-tokenization, the new cells fail on main and pass on this branch, and making each split part with $copyNode keeps an app's own highlight class and fields. Thanks for rewording the JSDoc and the changeset to the per-node split. Everything below is optional and non-blocking.
Worth considering
-
A tokenizer's own NodeState still gives way to the old child's (
packages/lexical-code-core/src/FlatStructureUtils.ts, line 436;$copyNodeStateat lines 257-296).$copyNodeState(from, part)writes every non-default value of the old child over what the tokenizer just set on the token. With a tokenizer passed through thetokenizeroption that records each token's highlight type in ascopestate, editinglettoletsleaveslets(now a plain token) withscope=keywordon this branch, on every later pass too;maingives itscope=plain. Copying from the old child only the keys the part does not already hold (the precedence$carryNodeStateuses inpackages/lexical/src/LexicalNodeState.ts) fixes it and keeps every cell in this PR passing. A state declared withresetOnCopyNodeis also reset on each part by$copyNodeand then filled from the old child;$copyNode(node, true)keeps the tokenizer's value, asTextNode.splitTextkeeps state on its parts. Stock Prism and Shiki tokens carry no NodeState, so they are unaffected. A cell with such a tokenizer would pin whichever precedence you choose. -
The limit kept in
packages/lexical-website/docs/collaboration/y.md(lines 1322-1325) no longer matches what happens.$keepCodeNodeStateruns after whatever tokenizer the stock highlighters are given, so a token that merges characters of several nodes is split again at each node with NodeState. Running the 8 new extension cells with a tokenizer that merges the whole line into one token still writes the value on all ofbefore(the same cells fail onmain). Dropping the sentence, or scoping it to a highlighter that does not split at node boundaries, keeps the page accurate;packages/lexical-y/DECISIONS.mdD115 still states that limit with no scope. -
Cost with a highlight-node replacement that sets state on every token. The early return at line 377 never fires in that setup, so every pass splits, copies and compares (
canonicalNodeStateserializes and sorts both nodes). Editing one number in a 1,000-line Prism block took a median of about 107 ms onmainand 164 ms on this branch; with the stock nodes the cost is unchanged (44-50 ms). Skipping the copy where the old child's state already equals the token's would help if that setup matters.
Nits
membersStatein both new test files uses a hand-writtenparse, so@lexical/ystores it whole;parse: arraySetValue(stringValue())would exercise the member-wise case the comments describe.- The new
@lexical/ycells readvaluesfrom the composing client only, andshow()printsmarksbut notnote,anchororflatAnchor; computingvaluesfor every peer and the fresh reader would assert the "kept on every client and a fresh reader" the description states. @lexical/yjs(collab v1/v2) has no cell with NodeState on code text; a fix verified on@lexical/yis not evidence for that binding.
57985d3 to
cc140d3
Compare
|
The head is now cc140d3, rebased onto main b592f98. Since 57985d3: |
There was a problem hiding this comment.
Thanks for the thorough work on this. The new cells fail on main and pass on this branch, and split parts now keep an app's highlight class, its fields and the tokenizer's own NodeState. One regression needs fixing before merge. Everything after it is optional.
Needs a change
-
The NodeState check added to
isEqualreverts state on tokens nobody edited (packages/lexical-code-prism/src/CodeHighlighterPrism.tsline 383,packages/lexical-code-shiki/src/CodeHighlighterShiki.tsline 414).$copyNodeStatekeeps every key a new token already holds (packages/lexical-code-core/src/FlatStructureUtils.ts, lines 268-302). So when a token's class stamps a NodeState key as it makes a token, an untouched token whose value differs from a fresh token's no longer compares equal, and the highlighter replaces it.Take a
CodeHighlightNodereplacement that stamps anauthorstate, the same shape asCreatedHighlightNodein the new tests but with a value that isn't constant:$setState(token, authorState, 'C')on one token reads back the replacement's value at the end of the same update on this branch.mainkeeps'C'. Prism and Shiki behave the same.- When the stamp changes between edits (an author per client, a timestamp, an id), typing one digit in a 1,000-line block recreates all 9,000 text nodes on this branch and none on
main. Every token gets re-stamped, and each edit costs almost twice as much.
AGENTS.md ("Backwards Compatibility") asks that the behavior callers rely on stays intact, and
mainkeeps any token whose text and type didn't change. Removing&& $isSameCodeNodeState(nodeA, nodeB)from bothisEquals (and the now-unused import) restores that rule, and all 20 new highlighter cells and all 532ComposeHoldRestyledLineTransformcells still pass. The split and the copy already give each new token the state of the old node at the same offset, so the comparison isn't needed for that.A cell that sets the stamped key on one token and then inserts a paragraph after the block would pin this. The current
CreatedHighlightNodecells stamp the constant'initialized', which hides it.
Optional
- The three
$copyNodeStatecopies now follow different rules. The one inFlatStructureUtils.tskeeps the keys the target already holds. The ones inCodeHighlighterPrism.tsandCodeHighlighterShiki.ts(text leaving a code block) let the old token's values win. A comment on each, or one shared helper, would make the difference explicit. - The new
@lexical/ycells buildvaluesfrom the composing client only, andshow()printsmarksbut notnote,anchororflatAnchor. Computingvaluesfor every peer and the fresh reader would assert the "kept on every client" that the description states. membersStatein both new test files has a hand-writtenparse, so@lexical/ystores it whole.parse: arraySetValue(stringValue())would exercise the per-member case.@lexical/yjs(collab v1/v2) has no cell with NodeState on code text.- In
ComposeHoldRestyledLineTransform.test.ts, themergingTokenizerblock was inserted between$typeInFirstLineand its doc comment (line 444). That comment now sits abovemergingTokenizer's own.
…][lexical-website] Bug Fix: The code highlighter keeps the NodeState of text inside a code block when it tokenizes the block again
Text inside a code block can carry NodeState of its own: comment ids, a
suggestion's members, which collaboration stores on the text. When text with
NodeState enters a code block (a quote or paragraph merged into it, or a
collaborator's change read with `skipTransforms`), the highlighter keeps it
as it is until its next pass over the block, which any change that makes the
CodeNode dirty runs (an edit inside the block, or a node inserted next to
it). That pass tokenizes the block's text again and splices fresh
CodeHighlightNodes in, so the NodeState of the text was dropped: a comment or
suggestion was lost on text nobody edited. The highlighters already keep
NodeState the other way, when code highlight nodes leave a code block.
The new tokens now keep it (`$keepCodeNodeState` in @lexical/code-core, used
by the Prism and Shiki highlighters): a token is split at the boundaries of
each node with NodeState, and each part, a copy of the token (its class, its
fields and the NodeState the tokenizer gave it), gets the NodeState of the
node its text came from for the keys it does not hold already (as
`$carryNodeState` leaves them), so a value an app's tokenizer derives from
each token is the tokenizer's after an edit, not the old token's. A state
the old node knows by its StateConfig stays known on the copy, here and
where highlight nodes leave a code block: copied as JSON only, a StateConfig
not registered for the new node's class is read back as an unknown value,
which collaboration stores whole (a set-valued state as one value instead of
one entry per member). What the copy has of its own stays as the copy of the
JSON leaves it: a state the old node has at its default value (which its
JSON leaves out) is not copied over the value the copy's class sets when it
is made (a node replacement's own state), and a key the copy's class has a
StateConfig of its own for is read with that one, not given the old node's
StateConfig (which would put that StateConfig in the place of the class's
own for every node of the class, so that a later read with the class's own
throws a State key collision). The highlighters' comparison of old and new
children is unchanged: a token whose text and highlight type (and, with
Shiki, style) did not change is kept as it is, with its class, its fields
and its NodeState, since the split and the copy already give each new token
the NodeState of the old node at the same offset.
Over several edits, a block's old and new tokens can line up differently
than before, since tokens are now split at the boundaries of each node
with NodeState: an old token of an app's own highlight class that was
kept only because the comparison happened to line up there can be
replaced by the highlighter's token, without its fields.
A block with no NodeState (the common case, on every keystroke in code) is
tokenized as before: the helper returns the new tokens untouched after one
pass over the children.
With collaboration (@lexical/y), while a peer composes in a code block that
a collaborator turned into a paragraph or a list item, the binding writes a
scalar NodeState value set in the update that ends the composition on the
line held as code only where the highlighter's tokens carry it. The tokens
now carry it, so such a value is kept on every client: one set on text of
the line, and one set on a code token that the highlighter replaces because
the join changed the line's tokens. A value extended there onto characters
next to others that had it is written too: the characters it was extended
onto come from a node of their own, so the split gives them a token of
their own. The split runs after whatever tokenizer the stock highlighters
are given, so a token that merges characters of several nodes is split
there too: the @lexical/y documentation and D115 now state that limit for
that update only where a code highlighter other than the stock Prism and
Shiki ones merges characters of several nodes into one token.
`.changeset/code-retokenize-keeps-state.md`: a patch for `@lexical/code-core`,
`@lexical/code-prism` and `@lexical/code-shiki`.
`packages/lexical-website/docs/collaboration/y.md` and
`packages/lexical-y/DECISIONS.md` (D115): the extension limit for the update
that ends a held composition is scoped to a code highlighter other than
@lexical/code-prism's and @lexical/code-shiki's that merges characters of
several nodes into one token.
`CodePrismRetokenizeKeepsState.test.ts` and
`CodeShikiRetokenizeKeepsState.test.ts` (one per highlighter):
- a text node with NodeState (a string and a set-valued state) inside a code
block, as a collaborator's change is read (no transforms), keeps both when
a paragraph inserted right after the block makes the highlighter tokenize
it again, in a highlight token of its own, known by its StateConfig;
- a quote merged into a code block keeps the NodeState of its text;
- a block with no NodeState is tokenized exactly as before;
- with a TextNode replacement, and with a code highlight node replacement,
that sets a state when it is made and has a StateConfig of its own for a
key: the text that takes a token's place when it leaves a code block, and
a new token, keep the state their class sets where the old node has that
state at its default value, and read a value the old node has under
another StateConfig for that key with their class's own (no State key
collision). On main, the two cells for text leaving a code block pass
(the copy there is JSON only) and the two for new tokens fail (the state
is dropped).
- with an app's own highlight class, with a field of its own and a NodeState
key it declares flat: an untouched token of that class keeps its class,
its field and its value when the block is tokenized again (it passes on
main too); and where a token an app's tokenizer makes of that class is
split at the boundary of a node with NodeState, each part is of that
class, with its field, and has the NodeState of its own text (on main the
token is not split, so the NodeState is dropped).
- with the code highlight node replacement: an untouched token keeps a value
the app set for the state its class sets when it is made, where a new
token would get another (it passes on main too).
- with an app's tokenizer that sets a NodeState value on each token, derived
from the token (its highlight type and style): after `let` becomes `lets`,
every token, `lets` included, has the value the tokenizer derived from it,
not the old token's (it passes on main too, where nothing is carried).
`ComposeHoldRestyledLineTransform.test.ts` (@lexical/y), with Prism and
Shiki, gc off and on, both client orders, and a NodeState value of three
shapes (a string, a boolean anchor, and that anchor declared flat):
- the 24 cells for a value set on the held line in the update that ends the
composition, with the stock highlighters, which dropped it there, now
expect it carried and written, as with an app's tokenizer that carries it;
- 24 new cells: such a value set on a code token that the highlighter
replaces, the join having changed the line's tokens (`before` and
`let x = 1;` join into `beforelet x = 1;`), is kept on every client and a
fresh reader, with no code highlight node outside code.
- 16 new cells, with the stock highlighters only: a value extended in the
update that ends the composition from `bef` onto `ore` is written on all
of `before`, with the stock tokenizers and with a tokenizer that makes one
token of each run of their tokens (on main, both fail).
- the 4 cells for a composition that ends in the update inserting its text
(written as main writes it) now expect each highlighter token to keep the
comment mark of the word it covers.
```
$ vitest --run --project unit CodePrismRetokenizeKeepsState CodeShikiRetokenizeKeepsState
× a text node with NodeState inside a code block, tokenized again by an insert next to the block (Prism, Shiki)
× a quote merged into a code block keeps the NodeState of its text (Prism, Shiki)
✓ without NodeState, the block is tokenized as before (Prism, Shiki)
✓ text leaving a code block keeps the state its class sets, where the token has that state at its default (Prism, Shiki)
✓ text leaving a code block is read with the StateConfig its class has for a key (Prism, Shiki)
× a new token keeps the state its class sets, where the text it comes from has that state at its default (Prism, Shiki)
× a new token is read with the StateConfig its class has for a key (Prism, Shiki)
AssertionError: expected [] to deeply equal [ true ]
AssertionError: expected 'const a = 1;t50z' to be 'const a = 1;t50z[members=s1]' // Object.is equality
AssertionError: expected [] to deeply equal [ [ true, 'kept', 'initialized' ] ]
AssertionError: expected [] to deeply equal [ [ true, 'kept' ] ]
✓ an untouched token of an app's highlight class, with a field and a NodeState key it declares flat, keeps its class, its field and its value (Prism, Shiki)
× a part of a token an app's tokenizer makes of its own class, split at the boundary of a node with NodeState, is of that class, with its field (Prism, Shiki)
✓ an untouched token keeps the value an app set for a state its class sets when it is made, where a new token gets another (Prism, Shiki)
✓ a NodeState value an app's tokenizer sets on each token, from the token, is the tokenizer's after an edit, not the old token's (Prism, Shiki)
AssertionError: expected [] to deeply equal [ [ 'le', true, 'app', 'a' ], …(1) ]
Tests 10 failed | 12 passed (22)
```
```
$ vitest --run --project unit ComposeHoldRestyledLineTransform
AssertionError: expected '-----------------' to be 'ssssss-----------' // Object.is equality
AssertionError: expected '----------------' to be '------sss-------' // Object.is equality
AssertionError: expected 'sss--------------' to be 'ssssss-----------' // Object.is equality
AssertionError: expected 'paragraph[hl:aa bb cc dd|l|hl:zz|et x…' to be 'paragraph[hl:aa bb|hl: cc/c5|hl: dd/c…' // Object.is equality
Tests 68 failed | 464 passed (532)
```
```
$ vitest --run --project unit CodePrismRetokenizeKeepsState CodeShikiRetokenizeKeepsState
Tests 22 passed (22)
$ vitest --run --project unit ComposeHoldRestyledLineTransform
Tests 532 passed (532)
```
The whole suite, the types and Flow:
```
$ LEXICAL_Y_GC=0 vitest run --project unit --project scripts-unit
Test Files 932 passed | 6 skipped (938)
Tests 38094 passed | 371 expected fail | 161 skipped (38626)
$ LEXICAL_Y_GC=1 vitest run --project unit --project scripts-unit
Test Files 932 passed | 6 skipped (938)
Tests 38094 passed | 371 expected fail | 161 skipped (38626)
$ pnpm run test-integration
Test Files 7 passed (7)
Tests 664 passed (664)
$ pnpm run tsc
$ pnpm run flow
Found 0 errors
```
Files that went over a time or memory bound while the machine was loaded
were run again with four workers, and are counted from that run.
Highlighting cost on every keystroke in a large block (Prism, a JavaScript
block of `const valueN = fetch(N);` lines, an edit of the number in the
middle line, median of five runs of 150 updates each, before -> after):
```
1,000 lines, no NodeState: 49.7 ms -> 50.1 ms
2,000 lines, no NodeState: 111.9 ms -> 110.7 ms
1,000 lines, 20 tokens with state: 49.3 ms -> 52.5 ms
2,000 lines, 40 tokens with state: 110.4 ms -> 118.2 ms
```
The tokens with state are the numbers of every 50th line. Before, they keep
their state too (main's comparison leaves a token whose text and type did
not change in place); after, each pass over a block with NodeState also
splits the new tokens where the state changes and compares the state of old
and new children, which is what the last two pay for.
cc140d3 to
36e34db
Compare
|
The head is now 36e34db (on main b592f98). The NodeState check is out of both highlighters' |
There was a problem hiding this comment.
Thanks, this looks good. With it, the stock Prism and Shiki highlighters keep a comment or suggestion stored as NodeState on code text. I checked that the new cells fail on main and pass here, and that the repro in #9491 ($addMarkID over part of a code token with MarkStateExtension) now marks exactly the selection with both highlighters. The earlier notes on split parts keeping the token's class, tokenizer-set values winning, and isEqual are all addressed. Everything below is optional and non-blocking.
-
Tabs and line breaks with NodeState in the replaced range (
packages/lexical-code-core/src/FlatStructureUtils.ts:347-353,:371-377). Spans skip tabs, and outputs that aren't aCodeHighlightNodeare pushed unchanged. So a TabNode or LineBreakNode with NodeState inside the rangegetDiffRangereplaces gets the tokenizer's fresh node, with no state. Example: a quotefoo⇥bar↵baz, commented end to end withMarkStateExtension, merged into a code block comes out asfoo[c1] ⇥ bar[c1] ↵ baz[c1], so the comment has holes. It isn't a regression, sincemaindrops all of it. Copying the old tab or line break's state onto the new one at the same offset would close it. -
Docs that describe the old behavior.
packages/lexical-website/docs/collaboration/comments.md:436-438still lists #9491 as an open issue. Lines 383-385 say a code token that "grows over the next word gets its ids". With this change the highlighter splits at the comment's edge, so deleting the space inlet xwithletcommented leaves the comment onletonly. Updating both, and addingCloses #9491to the description as AGENTS.md describes, would keep the page accurate. -
A regression test on the real API. The new cells use hand-made
createStateconfigs. #9491's repro throughMarkStateExtension's$addMarkIDwould pin the fix where users meet it. -
Cost with a replacement that stamps state on every token. In that setup, as with the tests'
CreatedHighlightNode, every pass copies state onto every token even when the token already holds every key. I measured a 1,000-line block going from about 109 ms to 144 ms per edit. Returning from$copyNodeStatebefore$getWritableNodeState(FlatStructureUtils.ts:282) whentoalready holds all offrom's keys would avoid most of that. Blocks without NodeState are unaffected. -
Changeset wording. CONTRIBUTING.md and
.changeset/README.mdask for a one-line[fix]summary. Keeping the first sentence there and moving the rest to a second paragraph would read better in the changelog.
The earlier notes on membersState's hand-written parse and on the three copies of $copyNodeState still apply and stay optional.
| if ( | ||
| !$isCodeHighlightNode(node) || | ||
| next === spans.length || | ||
| spans[next].start >= end | ||
| ) { | ||
| out.push(node); | ||
| continue; |
There was a problem hiding this comment.
Optional: a TabNode or LineBreakNode that has NodeState and sits inside the range getDiffRange replaces is pushed here as the tokenizer's fresh node, so its state is dropped. Spans skip tabs (line 350), and line breaks aren't TextNodes. With MarkStateExtension, a quote foo⇥bar↵baz commented end to end and merged into a code block comes out as foo[c1] ⇥ bar[c1] ↵ baz[c1], so the comment gets holes at the tab and the line break. This isn't a regression (main drops all five). Copying the NodeState of the old TabNode or LineBreakNode at the same offset onto the new one would close the gap.
…The code highlighter writes an app tokenizer's token over an old token it adds to ## Description When the code highlighter tokenizes a code block again, it compares the block's children with the new tokens and keeps each old token whose text and highlight type (and, with Shiki, style) did not change. Since #9832, `$keepCodeNodeState` splits a new token at the boundaries of each node with NodeState and gives each part the NodeState of its own text, so the parts now line up with the old nodes. With an app's tokenizer that returns its own CodeHighlightNode subclass (with its own field and NodeState), or sets a NodeState value on its tokens, over code text whose nodes have NodeState (comment ids, say), the comparison then kept the old stock tokens in place of the parts: the tokenizer's class, fields and NodeState were dropped there, which contradicts #9832's description. Before #9832 the unsplit token did not line up, so it replaced them (and dropped the comments instead); where an old token's text already matched a new token's, the old token was kept then too. The highlighter now replaces each old token it keeps, one for one, with the new token at its place, when the new token adds to it and loses nothing of it (`$replaceCodeTokensAddedTo` in @lexical/code-core): the new token is of the old token's class with the same fields, or of an app's own subclass where the old token is a stock CodeHighlightNode; it has the old token's format, style and every NodeState value it has; and it has a class or a NodeState value of its own besides. The comparison itself and the range it replaces are unchanged, so every other old token stays as it is, as before: one that has something the new token does not (a NodeState value the app set, where the new token has another; a field value of the app's class), or that the new token adds nothing to (the common case, with the stock tokenizers and no NodeState), and nothing is written there on each pass. A selection point on a replaced token goes to the new token at the same offset, so the selection stays where it was. Apps that do not run a code highlighter are unaffected: the change is limited to `@lexical/code-core`, `@lexical/code-prism` and `@lexical/code-shiki`. ## Changeset `.changeset/code-tokenizer-class-beside-state.md`: a patch for `@lexical/code-core`, `@lexical/code-prism` and `@lexical/code-shiki`. ## Test plan `CodePrismRetokenizeKeepsState.test.ts` and `CodeShikiRetokenizeKeepsState.test.ts`, with old tokens that have comments of their own, read as a collaborator's change is (no transforms), then tokenized again: - with an app's tokenizer making each token of its own class (with a field and a NodeState value of its own), over old tokens `alpha ` and `beta` that one new token covers: every token is of that class, with its field and the tokenizer's value, and every character keeps its own comment; - with a tokenizer that sets a NodeState value on each token: every token has it, and every character keeps its own comment; - an old token with a NodeState value the app set, where the new token has another value for it, is kept as it is; - over old tokens as the stock tokenizer makes them (matching the new tokens' text, type and style), one of them with a NodeState value the app set: the others are replaced by the app's tokens, one for one, and that one is kept as it is; another pass replaces nothing; - old tokens of the app's class with a field value of their own are kept, where the new tokens of that class have another value, also when they add a NodeState value named as the field. - the selection stays where it was when old tokens are replaced: a caret, a range forward and backward, and a range from the paragraph after the block into it; - with a change inside the line that the highlighter replaces (`1` becomes `1+2`, three tokens), the old tokens the comparison keeps before and after it are replaced too, one for one. On main, the first two fail with Prism (the old stock tokens are kept), and the fourth and the last two fail with both highlighters. ### Before ``` $ vitest --run --project unit CodePrismRetokenizeKeepsState CodeShikiRetokenizeKeepsState × each part of a token an app's tokenizer makes of its own class is of that class, with its field and the tokenizer's NodeState, and has the NodeState of its own text (Prism) × a NodeState value an app's tokenizer sets is on each token, beside the NodeState of its own text (Prism) × among old tokens as the stock tokenizer makes them, each with a comment, the ones a new token adds to are replaced, one for one, and one with a value the app set is kept, on every pass (Prism, Shiki) AssertionError: expected { …(2) } to deeply equal { …(2) } × replacing old tokens a new token adds to keeps the selection where it was: a caret, a range forward and backward, and a range from outside the block (Prism, Shiki) × with a change inside the line that the highlighter replaces, the old tokens a new token adds to before and after it are replaced too, one for one (Prism, Shiki) AssertionError: expected [ [ false, '', '', 'c1' ], …(5) ] to deeply equal [ …(6) ] AssertionError: expected false to be true // Object.is equality Tests 8 failed | 30 passed (38) ``` ### After ``` $ vitest --run --project unit CodePrismRetokenizeKeepsState CodeShikiRetokenizeKeepsState Tests 38 passed (38) ```
…on main ## Description `LaneFuzz.test.ts` lists the finding classes that reproduce on main (`KNOWN_OPEN`), each with its rate per 1,000 histories, and a run of at least 500 histories per lane and gc setting fails when a class grows past its ceiling (1.5 times that rate, or 4 standard deviations above it for a rare class). The rates were measured at 5326e06, before #9835 and #9832, which reduced most of the carry lane's classes: two of them were still listed at 558.7 and 535.7 per 1,000 where main now shows 196.5 and 187.3, so the nightly would pass while those classes almost tripled. The comments still called #9835 open. Every class is measured again on main (8c369d7), over 13,000 histories per lane and gc setting (seeds 100001 to 110000 and 300001 to 303000), taking the higher of the two gc settings, as before: | Class | gc off | gc on | per 1,000 | Was | | --- | --- | --- | --- | --- | | blockconv: ending-phase-other-block | 300 | 344 | 26.5 | 26 | | blockconv: untouched-block-changed | 309 | 342 | 26.3 | 25 | | blockconv: ending-phase-code-highlight-outside-code | 97 | 119 | 9.2 | 58 | | blockconv: ending-phase-text | 112 | 87 | 8.6 | 9.3 | | blockconv: ending-phase-format | 77 | 102 | 7.8 | 10 | | blockconv: ending-phase-boundary | 1 | 0 | 0.1 | (not listed) | | blockconv: ending-phase-state | 0 | 0 | removed | 0.3 | | carry: ending-phase-code-highlight-outside-code | 2555 | 2529 | 196.5 | 558.7 | | carry: ending-phase-field | 2435 | 2385 | 187.3 | 535.7 | | carry: ending-phase-text | 1215 | 1232 | 94.8 | 235 | | carry: decorator-lost | 734 | 748 | 57.5 | 182.3 | | carry: other-block-changed | 155 | 198 | 15.2 | 13.7 | | carry: ending-phase-other-block | 155 | 198 | 15.2 | 13.7 | | carry: ending-phase-state | 93 | 89 | 7.2 | 142 | | carry: target-value | 81 | 93 | 7.2 | 50.3 | The nohold lane shows no finding. `blockconv:ending-phase-state` is removed, as it no longer reproduces. `blockconv:ending-phase-boundary` is added: it reproduces on main once in 26,000 histories (seed 106259 without gc, a release transform that splits the held line, which the collaborator deleted), so a nightly does not fail on it by chance. The comments now name #9835 and #9832 as merged, and the description of `carry:ending-phase-text` says what the class checks (it repeated the one of `carry:decorator-lost`). ## Changeset None: test constants and comments only. ## Test plan ### Before The old rates, on main over seeds 100001 to 102000 (counts / ceilings): ``` $ LANES=carry LANE_GC=0 LANE_SEEDS=2000 LANE_SEED_START=100001 vitest run --project unit packages/lexical-y/src/__tests__/unit/LaneFuzz.test.ts carry gc0: ending-phase-code-highlight-outside-code 414/1676; ending-phase-field 398/1607; ending-phase-text 198/705; decorator-lost 123/546; other-block-changed 24/50; ending-phase-other-block 24/50; ending-phase-state 21/426; target-value 13/150 $ LANES=blockconv LANE_GC=0 LANE_SEEDS=2000 LANE_SEED_START=100001 vitest run --project unit packages/lexical-y/src/__tests__/unit/LaneFuzz.test.ts blockconv gc0: untouched-block-changed 48/80; ending-phase-other-block 47/82; ending-phase-text 22/37; ending-phase-format 17/39; ending-phase-code-highlight-outside-code 12/174; ending-phase-state 0/5 ``` ### After A seed range outside the measurement, at the nightly's 3,000 histories per lane and gc setting (counts / ceilings), and the default smoke slice: ``` $ LANE_SEEDS=3000 LANE_SEED_START=400001 vitest run --project unit packages/lexical-y/src/__tests__/unit/LaneFuzz.test.ts (per lane and gc setting) blockconv gc0: ending-phase-other-block 67/119; untouched-block-changed 67/118; ending-phase-code-highlight-outside-code 21/50; ending-phase-format 21/44; ending-phase-text 16/48; ending-phase-boundary 0/4 blockconv gc1: ending-phase-other-block 75/119; untouched-block-changed 72/118; ending-phase-code-highlight-outside-code 24/50; ending-phase-format 13/44; ending-phase-text 10/48; ending-phase-boundary 0/4 carry gc0: ending-phase-code-highlight-outside-code 586/884; ending-phase-field 551/842; ending-phase-text 296/426; decorator-lost 178/258; other-block-changed 46/74; ending-phase-other-block 46/74; target-value 29/42; ending-phase-state 17/42 carry gc1: ending-phase-code-highlight-outside-code 610/884; ending-phase-field 573/842; ending-phase-text 313/426; decorator-lost 199/258; other-block-changed 44/74; ending-phase-other-block 44/74; ending-phase-state 16/42; target-value 15/42 nohold gc0, gc1: no finding Test Files 1 passed (1) Tests 121 passed (121) (each of the 6 runs) $ vitest run --project unit packages/lexical-y/src/__tests__/unit/LaneFuzz.test.ts Tests 12 passed (12) ```
Text inside a code block can carry NodeState of its own: comment ids, a
suggestion's members, which collaboration stores on the text. When text with
NodeState enters a code block (a quote or paragraph merged into it, or a
collaborator's change read with
skipTransforms), the highlighter keeps itas it is until its next pass over the block, which any change that makes the
CodeNode dirty runs (an edit inside the block, or a node inserted next to
it). That pass tokenizes the block's text again and splices fresh
CodeHighlightNodes in, so the NodeState of the text was dropped: a comment or
suggestion was lost on text nobody edited. The highlighters already keep
NodeState the other way, when code highlight nodes leave a code block.
The new tokens now keep it (
$keepCodeNodeStatein @lexical/code-core, usedby the Prism and Shiki highlighters): a token is split at the boundaries of
each node with NodeState, and each part, a copy of the token (its class, its
fields and the NodeState the tokenizer gave it), gets the NodeState of the
node its text came from for the keys it does not hold already (as
$carryNodeStateleaves them), so a value an app's tokenizer derives fromeach token is the tokenizer's after an edit, not the old token's. A state
the old node knows by its StateConfig stays known on the copy, here and
where highlight nodes leave a code block: copied as JSON only, a StateConfig
not registered for the new node's class is read back as an unknown value,
which collaboration stores whole (a set-valued state as one value instead of
one entry per member). What the copy has of its own stays as the copy of the
JSON leaves it: a state the old node has at its default value (which its
JSON leaves out) is not copied over the value the copy's class sets when it
is made (a node replacement's own state), and a key the copy's class has a
StateConfig of its own for is read with that one, not given the old node's
StateConfig (which would put that StateConfig in the place of the class's
own for every node of the class, so that a later read with the class's own
throws a State key collision). The highlighters' comparison of old and new
children is unchanged: a token whose text and highlight type (and, with
Shiki, style) did not change is kept as it is, with its class, its fields
and its NodeState, since the split and the copy already give each new token
the NodeState of the old node at the same offset.
Over several edits, a block's old and new tokens can line up differently
than before, since tokens are now split at the boundaries of each node
with NodeState: an old token of an app's own highlight class that was
kept only because the comparison happened to line up there can be
replaced by the highlighter's token, without its fields.
A block with no NodeState (the common case, on every keystroke in code) is
tokenized as before: the helper returns the new tokens untouched after one
pass over the children.
With collaboration (@lexical/y), while a peer composes in a code block that
a collaborator turned into a paragraph or a list item, the binding writes a
scalar NodeState value set in the update that ends the composition on the
line held as code only where the highlighter's tokens carry it. The tokens
now carry it, so such a value is kept on every client: one set on text of
the line, and one set on a code token that the highlighter replaces because
the join changed the line's tokens. A value extended there onto characters
next to others that had it is written too: the characters it was extended
onto come from a node of their own, so the split gives them a token of
their own. The split runs after whatever tokenizer the stock highlighters
are given, so a token that merges characters of several nodes is split
there too: the @lexical/y documentation and D115 now state that limit for
that update only where a code highlighter other than the stock Prism and
Shiki ones merges characters of several nodes into one token.
.changeset/code-retokenize-keeps-state.md: a patch for@lexical/code-core,@lexical/code-prismand@lexical/code-shiki.packages/lexical-website/docs/collaboration/y.mdandpackages/lexical-y/DECISIONS.md(D115): the extension limit for the updatethat ends a held composition is scoped to a code highlighter other than
@lexical/code-prism's and @lexical/code-shiki's that merges characters of
several nodes into one token.
CodePrismRetokenizeKeepsState.test.tsandCodeShikiRetokenizeKeepsState.test.ts(one per highlighter):block, as a collaborator's change is read (no transforms), keeps both when
a paragraph inserted right after the block makes the highlighter tokenize
it again, in a highlight token of its own, known by its StateConfig;
that sets a state when it is made and has a StateConfig of its own for a
key: the text that takes a token's place when it leaves a code block, and
a new token, keep the state their class sets where the old node has that
state at its default value, and read a value the old node has under
another StateConfig for that key with their class's own (no State key
collision). On main, the two cells for text leaving a code block pass
(the copy there is JSON only) and the two for new tokens fail (the state
is dropped).
key it declares flat: an untouched token of that class keeps its class,
its field and its value when the block is tokenized again (it passes on
main too); and where a token an app's tokenizer makes of that class is
split at the boundary of a node with NodeState, each part is of that
class, with its field, and has the NodeState of its own text (on main the
token is not split, so the NodeState is dropped).
the app set for the state its class sets when it is made, where a new
token would get another (it passes on main too).
from the token (its highlight type and style): after
letbecomeslets,every token,
letsincluded, has the value the tokenizer derived from it,not the old token's (it passes on main too, where nothing is carried).
ComposeHoldRestyledLineTransform.test.ts(@lexical/y), with Prism andShiki, gc off and on, both client orders, and a NodeState value of three
shapes (a string, a boolean anchor, and that anchor declared flat):
composition, with the stock highlighters, which dropped it there, now
expect it carried and written, as with an app's tokenizer that carries it;
replaces, the join having changed the line's tokens (
beforeandlet x = 1;join intobeforelet x = 1;), is kept on every client and afresh reader, with no code highlight node outside code.
update that ends the composition from
befontooreis written on allof
before, with the stock tokenizers and with a tokenizer that makes onetoken of each run of their tokens (on main, both fail).
(written as main writes it) now expect each highlighter token to keep the
comment mark of the word it covers.
The whole suite, the types and Flow:
Files that went over a time or memory bound while the machine was loaded
were run again with four workers, and are counted from that run.
Highlighting cost on every keystroke in a large block (Prism, a JavaScript
block of
const valueN = fetch(N);lines, an edit of the number in themiddle line, median of five runs of 150 updates each, before -> after):
The tokens with state are the numbers of every 50th line. Before, they keep
their state too (main's comparison leaves a token whose text and type did
not change in place); after, each pass over a block with NodeState also
splits the new tokens where the state changes and compares the state of old
and new children, which is what the last two pay for.