Repository navigation
[lexical-mark][lexical-website] Feature: isMarkIDShown filter for MarkStateExtension - #9489
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: |
|
There is a common user case where a user wants to see the specific place associated with a resolved comment. For example, in Google Docs, when a user hovers the cursor over a comment, the corresponding highlighted text is shaded in gray. I believe it would be beneficial to keep the option to implement this kind of behavior; however, if the mark id attribute is removed entirely, it seems that such highlighting would no longer be possible hover-on-resolved-comment.mov |
…rs, one MarkStateExtension per kind of annotation ## Description Stacked on #9489 (`isMarkIDShown`), which should land first. `MarkStateExtension` maps ids to the text they cover, but nothing says what an id is: comments, suggestions and highlights all share the `markIds` key, the `mark` theme class and one `markIDNodeKeys` output, and every app diffs that output by hand to keep its own thread store in step. This adds mark flavors to `@lexical/mark`: - `defineMarkExtension({name, stateKey, attribute?, className?, overlapClassName?, config?})` makes one extension per kind of annotation. Each flavor works like `MarkStateExtension` on its own set-valued NodeState key, with its own attribute (default `data-lexical-<kebab key>`), classes, config (`isMarkIDShown`, `disabled`, `markableNodes`, `exportIDsToHTML`), output and listeners. Two flavors on the same text never see each other's ids. - `$addMarkID`, `$removeMarkID`, `$getMarkIDsAtSelection`, `$getNodeMarkIDs` and `$migrateMarkNodesToMarkState` take a flavor as an optional first argument: `$addMarkID(CommentMarks, 'c1', selection)`. Without one they act on `MarkStateExtension`, as before. The flavor-first form is the first overload, so the original signature stays the last one and `Parameters<typeof $addMarkID>` and the like do not change (a type test checks this). - `registerMarkIDsListener(editor, flavor, listener)` is called after each commit that changes which ids of a flavor are in the document, with `added`, `removed`, `ids` and the update's `tags`, and once right away when the document already has ids. When all of a comment's text is deleted its id is reported removed (orphan the thread); undo, redo or a paste reports it added again. A disabled flavor reports nothing, and reports the net change when enabled again. - `MarkBaseExtension` is the shared base every flavor depends on (the name `MarkExtension` is taken by the MarkNode extension). It keeps the editor's flavors by key (`flavors` output; `$getMarkIDsByFlavor(node)` reads all of them), throws at build when two flavors share a key or an attribute, and lets the inserted-text rules of the flavors tell a TextNode piece that another flavor's rule split off in this update from inserted content. Without that, text typed at the edge of a mark of one flavor joined a mark of the other (see the Before output). - Two flavors that share a class, or a flavor that uses a theme class of `MarkStateExtension`, do not remove it from each other. - `MarkStateExtension` is now the default flavor, on `markIds`, with the same name, config, output, attribute, theme classes and JSON. Its type gains `stateKey` and `attribute`. `MarkStateExtension.test.ts` is unchanged and passes. The rules are types where they can be: `CommentMarks.stateKey` has the type `'commentIds'`, and a `stateKey` that is not a literal, is empty, contains whitespace, or is `'markIds'` or `'__proto__'` is a type error whose message says how to fix it (the runtime checks the same). Duplicate keys or attributes in one editor can only be caught at build; that error names both flavors and the fix. `defineMarkExtension` is declared `@__NO_SIDE_EFFECTS__` and added to `PURE_FACTORY_FUNCTIONS`, so module-scope flavor definitions tree-shake. Changesets cover `@lexical/mark` and `@lexical/compiler`. Flow declarations and the Flow smoke test cover the new API. The Comments and Annotations docs get a "Mark flavors" section with a `Y.Map` thread store kept in sync through the listener. Collaboration needs no binding change: a flavor is one more NodeState key with the same set schema as `markIds`. `@lexical/yjs` syncs it as any NodeState. In `@lexical/y` (#9400) each flavor is its own `s:<stateKey>` format key, and with #9439 its own family stored one key per id, since #9439 recognizes a set by its schema, not its name. That check is not in this PR because `@lexical/y` is not on this branch; see the test plan. ## Test plan ### Before The new tests against #9489's branch: ``` $ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkFlavors.test.ts packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts FAIL |unit| packages/lexical-mark/src/__tests__/unit/MarkFlavors.test.ts TypeError: defineMarkExtension is not a function FAIL |unit| packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts TypeError: defineMarkExtension is not a function Test Files 2 failed (2) ``` The two-flavor property run with the shared split records turned off (each flavor's rule on its own), showing the cross-flavor interference they fix: ``` $ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts ✓ MarkStateExtension property test (1) × 40 random edit sequences of 30 steps keep the ids of every character + seed 1: document + got: ("axqb") / ("d" "cmro😃q"[c2,c5] "A"[c2]) / ("alau"[c2]) / ("f"[c2] "ubq") + want: ("axqb") / ("d" "cmro😃q"[c2,c5] "A") / ("alau"[c2]) / ("f"[c2] "ubq") ``` ### After ``` $ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkFlavors.test.ts --reporter=verbose ✓ two flavors on the same text > each flavor sees only its own ids ✓ two flavors on the same text > each flavor renders its own classes and attribute ✓ two flavors on the same text > flavors that share a class do not remove it from each other ✓ two flavors on the same text > typing at the end of both marks gives the text the ids of both flavors by the same rule ✓ two flavors on the same text > typing inside both marks gives the text the ids of both flavors by the same rule ✓ two flavors on the same text > typing at the start of both marks gives the text the ids of both flavors by the same rule ✓ two flavors on the same text > text typed at the edge of one flavor joins the other where it is inside ✓ two flavors on the same text > text replacing a selection gets the ids all of it had, per flavor ✓ two flavors on the same text > pasted text keeps the ids of every flavor ✓ registerMarkIDsListener > reports added, removed (orphaned) and restored ids across undo and paste ✓ registerMarkIDsListener > a collaborator update is tagged ✓ registerMarkIDsListener > the first call lists the ids already in the document, and unregistering stops it ✓ registerMarkIDsListener > disabling reports nothing, enabling reports the net change ✓ registerMarkIDsListener > a listener registered while disabled gets every id when enabled ✓ registerMarkIDsListener > a listener that throws on its first call is not registered ✓ registerMarkIDsListener > a flavor disabled by another flavor listener in the same commit reports nothing ✓ registerMarkIDsListener > an editor without the flavor throws, naming the fix ✓ isMarkIDShown per flavor > a flavor filter hides only that flavor ✓ the default flavor > MarkStateExtension is the flavor on markIds ✓ the default flavor > the functions without a flavor act on MarkStateExtension, beside other flavors ✓ the default flavor > $migrateMarkNodesToMarkState can target a flavor ✓ serialization > JSON round trips the ids of every flavor ✓ serialization > ids of a flavor the editor lacks are kept as unknown state ✓ serialization > HTML round trips each flavor through its own attribute ✓ errors > two flavors with the same stateKey fail when the editor is built ✓ errors > two flavors with the same attribute fail when the editor is built ✓ errors > attributes that differ only in case clash ✓ errors > stateKey "" is rejected with the fix in the message ✓ errors > stateKey "a b" is rejected with the fix in the message ✓ errors > stateKey "markIds" is rejected with the fix in the message ✓ errors > stateKey "__proto__" is rejected with the fix in the message ✓ types > the definition types the flavor ✓ types > the original signatures stay the last overloads ✓ types > the type rules reject what the runtime rejects $ MARK_STATE_PROPERTY_SEEDS=3000 MARK_STATE_PROPERTY_STEPS=40 npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts ✓ MarkStateExtension property test (1) ✓ 3000 random edit sequences of 40 steps keep the ids of every character 54224ms ✓ MarkStateExtension property test with two mark flavors (1) ✓ 3000 random edit sequences of 40 steps keep the ids of every character 86535ms Tests 2 passed (2) $ npx vitest run --project unit packages/lexical-mark Test Files 13 passed (13) Tests 852 passed (852) $ npx vitest run scripts/__tests__/unit/treeShakingSource.test.ts packages/lexical-compiler Test Files 7 passed (7) Tests 570 passed (570) $ pnpm run test-unit Test Files 413 passed | 1 skipped (414) Tests 10208 passed | 4 expected fail | 2 skipped (10214) $ pnpm run build && pnpm run build-types (both exit 0) $ pnpm run ci-check Found 0 errors ``` `@lexical/y` check, not part of this PR: on a copy of the #9400 tree with this `MarkStateExtension.ts`, a two-peer test that adds a comment on one peer and a suggestion plus a default-flavor id on the other, on the same words, converges with all three, and removing the comment on one peer leaves the suggestion on both. The Yjs text holds `s:markIds`, `s:commentIds` and `s:suggestionIds` as separate format keys. The `@lexical/y` Slots, EmptyMarks, TypeAtMarkStart, Races, TypeOverSelection and FormatOnlyChanges suites pass there too (751 tests). Browser-mode tests and E2E were not run; the DOM checks run in jsdom.
d3b22e8 to
7644510
Compare
| } | ||
| // @internal access: whether an update is in progress or waiting to | ||
| // commit, which the full reconcile would otherwise join | ||
| if (editor._pendingEditorState !== null) { |
There was a problem hiding this comment.
Codex identified an edge case with this:
[P2] Defer filter rerenders while commit listeners are running.
MarkStateExtension.ts:2247–2253 checks _pendingEditorState, but that field is null during update listeners while _updating remains true. If a listener assigns isMarkIDShown and queues an edit, the full reconcile joins that edit. The mark transform then treats the edit as a state replacement, and SKIP_DOM_SELECTION_TAG suppresses its caret update.
There was a problem hiding this comment.
Fixed in 52c6c99, with your patch plus a deferral when _updating is set without a pending state: the patch alone still let the reconcile join a listener's edit. Regression tests cover a listener that assigns the filter before and after queueing its edit.
etrepum
left a comment
There was a problem hiding this comment.
Claude suggests this patch:
diff --git a/packages/lexical-mark/src/MarkStateExtension.ts b/packages/lexical-mark/src/MarkStateExtension.ts
index d371069..e247608 100644
--- a/packages/lexical-mark/src/MarkStateExtension.ts
+++ b/packages/lexical-mark/src/MarkStateExtension.ts
@@ -161,8 +161,9 @@ export interface MarkStateConfig {
* To change it at runtime, for example when a thread is resolved or
* reopened, update the app's state and assign a new function to the
* `isMarkIDShown` output signal: the marked leaves are re-rendered (after
- * the pending update commits, when assigned during one). Changing the state that the current function reads without assigning a
- * new function does not re-render them.
+ * the pending update commits, when assigned during one). Changing the
+ * state that the current function reads without assigning a new function
+ * does not re-render them.
*/
isMarkIDShown?: (id: string) => boolean;
}
@@ -664,7 +665,7 @@ function filterShownMarkIDs(
ids: readonly string[],
isMarkIDShown: (id: string) => boolean,
): readonly string[] {
- return ids.length === 0 || isMarkIDShown === isEveryMarkIDShown
+ return isMarkIDShown === isEveryMarkIDShown
? ids
: ids.filter(id => isMarkIDShown(id));
}
@@ -674,14 +675,16 @@ function $decorateMarkIDs(
dom: HTMLElement,
editor: LexicalEditor,
): void {
- const dep = getPeerDependencyFromEditor<MarkStateExtensionType>(
- editor,
- MARK_STATE_EXTENSION_NAME,
- );
- const ids = filterShownMarkIDs(
- $readNodeMarkIDs(node),
- dep ? dep.output.isMarkIDShown.peek() : isEveryMarkIDShown,
- );
+ let ids = $readNodeMarkIDs(node);
+ if (ids.length > 0) {
+ const dep = getPeerDependencyFromEditor<MarkStateExtensionType>(
+ editor,
+ MARK_STATE_EXTENSION_NAME,
+ );
+ if (dep) {
+ ids = filterShownMarkIDs(ids, dep.output.isMarkIDShown.peek());
+ }
+ }
// @internal access with precedent (CodeNode, HorizontalRuleExtension): the
// render overrides receive the editor, not its theme
const {mark, markOverlap} = editor._config.theme;
@@ -2245,7 +2248,10 @@ function registerMarkIDShownRerender(
// @internal access: whether an update is in progress or waiting to
// commit, which the full reconcile would otherwise join
if (editor._pendingEditorState !== null) {
- schedule();
+ // Joins the pending update, and runs once it commits; the re-render
+ // is then queued as an update of its own
+ scheduled = true;
+ editor.update(() => {}, {onUpdate: rerender});
return;
}
editor.update($fullReconcile, {
@@ -2253,13 +2259,6 @@ function registerMarkIDShownRerender(
tag: SKIP_DOM_SELECTION_TAG,
});
};
- const schedule = () => {
- if (!scheduled) {
- scheduled = true;
- // After the commit of the pending update, which was scheduled first
- Promise.resolve().then(rerender);
- }
- };
const unregister = effect(() => {
const next = isMarkIDShown.value;
if (next !== prev) {…kStateExtension
The recommended way to resolve a comment with `MarkStateExtension` is to keep
its id in the text and flag the thread resolved in the app's own store (see
the Comments and Annotations docs). But the extension renders every id, so
resolved threads stay highlighted, and apps have no way to say which ids
render.
This adds an optional `isMarkIDShown?: (id: string) => boolean` config and an
`isMarkIDShown` output signal:
- A leaf gets the `mark` / `markOverlap` theme classes and the
`data-lexical-mark-ids` attribute only for the ids the filter returns `true`
for. The default shows every id, so existing editors render exactly as
before, and configs written without the field still type check (TypeScript
and Flow).
- Assigning a new function to the output signal re-renders the marked leaves
with a full reconcile, which reuses the existing nodes (the same mechanism
`DOMRenderExtension` uses when `disabled` flips): no node is changed, so
nothing syncs to collaborators or lands in the history. It is skipped when
the document has no marks, the editor has no root element, or the extension
is disabled (re-enabling renders with the current filter). Assigned while an
update is pending, the re-render waits for that update to commit, so the
edit is not mistaken for a `setEditorState` and inserted-text mark rules
still apply. The re-render is tagged `SKIP_DOM_SELECTION_TAG`, so it does not
pull the caret out of another editable such as a comment reply box.
- The filter only changes rendering: the ids stay in the document, and the
`$` functions, the `markIDNodeKeys` output and HTML export still see every
id.
Flow declarations and the Flow smoke test are updated, and `comments.md` gets
a "Resolving a thread" section.
New tests run against `main`'s `MarkStateExtension.ts`:
```
$ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateExtension.test.ts -t isMarkIDShown
× the default renders every id
× hidden ids are not rendered but stay in the document
× newly marked text follows the filter
× assigning a new filter at runtime re-renders the affected leaves
× a new filter re-renders nothing in a document without marks
× a filter assigned inside an edit re-renders after it, without changing it
× a new filter does not move the DOM selection out of another editable
× a filter changed while disabled applies when re-enabled
× a filter set before the root element is attached applies on mount
Test Files 1 failed (1)
Tests 9 failed | 101 skipped (110)
```
```
$ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateExtension.test.ts -t isMarkIDShown --reporter=verbose
✓ ... isMarkIDShown > the default renders every id 49ms
✓ ... isMarkIDShown > hidden ids are not rendered but stay in the document 5ms
✓ ... isMarkIDShown > newly marked text follows the filter 2ms
✓ ... isMarkIDShown > assigning a new filter at runtime re-renders the affected leaves 4ms
✓ ... isMarkIDShown > a new filter re-renders nothing in a document without marks 2ms
✓ ... isMarkIDShown > a filter assigned inside an edit re-renders after it, without changing it 3ms
✓ ... isMarkIDShown > a new filter does not move the DOM selection out of another editable 2ms
✓ ... isMarkIDShown > a filter changed while disabled applies when re-enabled 3ms
✓ ... isMarkIDShown > a filter set before the root element is attached applies on mount 2ms
Tests 9 passed | 101 skipped (110)
$ npx vitest run --project unit packages/lexical-mark
Tests 818 passed (818)
$ npx vitest run scripts/__tests__/unit/treeShakingSource.test.ts
Tests 346 passed (346)
$ pnpm run ci-check
Found 0 errors
```
Browser-mode tests and E2E were not run; the external-caret case is covered
in jsdom only.
…ners can queue edits
## Description
Review feedback on this PR (etrepum): the re-render checked only
`_pendingEditorState` before running its full reconcile. That field is null
during update listeners and `onUpdate` callbacks while `_updating` is still
true, so when a listener assigned a new `isMarkIDShown` and queued an edit,
the full reconcile joined that edit. The mark transform then treated the edit
as a state replacement (text typed at the end of a marked run became marked),
and `SKIP_DOM_SELECTION_TAG` suppressed its caret update.
- Applied the suggested patch: a re-render assigned during a pending update
joins it with an empty update and runs from its `onUpdate`; the decorator
skips the extension lookup for leaves without ids; a doc comment is
rewrapped.
- On top of it, when `_updating` is set with no pending state (an update or
command listener, or an `onUpdate` callback), the re-render waits a
microtask, after the queued updates have run, and checks again. The
suggested patch alone still let the reconcile join a listener's edit (the
new tests fail with it).
## Test plan
Two new tests: an update listener assigns a filter and queues an edit (in
either order); the typed text stays unmarked, the filter applies, and the DOM
caret moves past the typed text.
### Before
```
$ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateExtension.test.ts -t 'update listener'
× a filter assigned in an update listener with an edit re-renders after that edit, which keeps its caret update
× a filter assigned in an update listener after its edit re-renders after that edit, which keeps its caret update
Tests 2 failed | 110 skipped (112)
```
(The same two fail with only the suggested patch applied.)
### After
```
$ npx vitest run --project unit packages/lexical-mark
Test Files 13 passed (13)
Tests 906 passed (906)
$ pnpm run ci-check
Found 0 errors
```
7644510 to
52c6c99
Compare
…e][lexical-y] Bug Fix: Keep comment ids and NodeState when a block change moves or re-creates text ## Description `MarkStateExtension` gives inserted text its comment ids with a root transform that compares the blocks around the caret with the previous editor state. That comparison only covered the sibling blocks of the caret's block and treated a nested block (the items of a list) as one opaque unit. Text that a block change moved in from outside it had no counterpart, so it was taken for text typed into an existing node: it lost its own ids and got the ids shared by its neighbours. The core keeps the NodeState in these conversions; with the transform disabled, the ids survive. - Turning a lone list item into a paragraph, quote or heading (`$setBlocksType`) removed every comment id from its text, with or without `@lexical/y`. - Turning a paragraph into a list item that joins the list above it (`$insertList`) removed the comment from a link when the item above ended with the same text, or gave the moved text the comment of the item above (#9490). - Converting a list item to a highlighted code block, which re-creates the text in new nodes, lost its ids too. - Turning a highlighted code block into a paragraph lost them whenever the inserted-text rule could not run (with the code selected, or for pasted code): Prism and Shiki replace each code highlight node that leaves a code block with `$createTextNode(text)`, which drops its NodeState. The comparison now: - keeps the ids of a leaf that existed before the update and kept its text, wherever the update moved it, and of the text a moved TextNode kept at each end when the same update also typed into it (each run of inserted units between kept ones is an insertion, with the ids shared by its neighbours); - compares a nested block that the update changed by its text, like the blocks around it (an unchanged one stays a single unit, so an edit next to a large nested list does not read it); - also compares the following block when it lost its first children, as a list does when its first item is converted. `@lexical/code-prism` and `@lexical/code-shiki` now copy the NodeState of a code highlight node (flat states included) into the TextNode that replaces it, keeping any state that a TextNode replacement sets, so any NodeState survives leaving a code block, not only comment ids. A node that code moves (rather than creates) into the middle of a marked run now keeps exactly its own ids instead of taking the run's; `comments.md` says so, and that block changes keep every id. Independent of #9489 and #9496. It merges with #9489 without conflicts of its own (that PR's `comments.md` conflict with main is unrelated). With #9496 it has two one-line conflicts in `MarkStateExtension.ts`, at the two `$collectSegments` calls: #9496 adds a `flavor` first argument and this adds a `$isUnchangedBlock` last one, so both become `$collectSegments(flavor, windows, points, $isUnchangedBlock)`. Closes #9490 ## Test plan `MarkStateBlockConversion.test.ts` states the invariant (converting blocks keeps the ids of every character) over every source and target (paragraph, heading, quote, code with and without highlighting, bullet, number and check items, nested items as sources, no list as a target), with links, comments on part, inside a link, overlapping or on all of the text, neighbouring lists that the conversion merges with (including text that lines up and shared ids), the caret or a range at several places, text typed in the same update, and pasted blocks: 27,072 cases. Each also checks that the conversion happened. It includes both reports and a comment on code text turned into a paragraph; the lexical-y test round-trips the list item case through a Yjs document, and the code-prism and code-shiki tests check that NodeState (nested and flat) survives leaving a code block. ### Before New tests against `main`'s sources: ``` $ pnpm exec vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateBlockConversion.test.ts packages/lexical-y/src/__tests__/unit/MarkStateBlockType.test.ts packages/lexical-code-prism/src/__tests__/unit/CodePrismLeaveCodeNodeState.test.ts packages/lexical-code-shiki/src/__tests__/unit/CodeShikiLeaveCodeNodeState.test.ts FAIL ... > reported cases > a paragraph turned into a list item keeps the comment on a link - "a:c0", - "b:c0", - "c:c0", - "d:c0", + "a:", + "b:", + "c:", + "d:", FAIL ... > MarkStateExtension with @lexical/y > a list item with a comment turned into a paragraph keeps the comment Expected: "paragraph("alpha "[] "beta"["c1"])" Received: "paragraph("alpha beta"[])" FAIL ... CodePrismLeaveCodeNodeState.test.ts > code highlight nodes turned back into text when they leave a code block keep their NodeState AssertionError: expected [ [ true, 'note', '' ] ] to deeply equal [ [ true, 'note', 'kept' ] ] ... Test Files 4 failed (4) Tests 89 failed | 107 passed (196) ``` 3,804 of the 27,072 matrix cases fail, for example: ``` "bullet -> paragraph, plain, marks part, alone, selection 17: before a: l: p: h: a: : b:c1 e:c1 t:c1 a:c1 : g: a: m: m: a: : after a: l: p: h: a: : b: e: t: a: : g: a: m: m: a: :" ``` ### After ``` $ pnpm exec vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateBlockConversion.test.ts packages/lexical-y/src/__tests__/unit/MarkStateBlockType.test.ts packages/lexical-code-prism/src/__tests__/unit/CodePrismLeaveCodeNodeState.test.ts packages/lexical-code-shiki/src/__tests__/unit/CodeShikiLeaveCodeNodeState.test.ts Test Files 4 passed (4) Tests 196 passed (196) $ pnpm exec vitest run --project unit packages/lexical-y packages/lexical-mark/ packages/lexical-list packages/lexical-selection packages/lexical-code packages/lexical-table packages/lexical-rich-text packages/lexical-markdown Test Files 250 passed | 2 skipped (252) Tests 7251 passed | 16 expected fail | 3 skipped (7270) $ MARK_STATE_PROPERTY_SEEDS=400 MARK_STATE_PROPERTY_STEPS=120 pnpm exec vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts Tests 1 passed (1) $ pnpm run ci-check Found 0 errors ``` Unit tests only (Node/jsdom); no browser or E2E run. Not covered (the matrix skips them, with the reason): comment ids on part of a code highlighting token, and marked text that a range conversion merges into a highlighted code block, which re-tokenizing drops (#9491); and typing inside a link in the same update that turns it into highlighted code, where the highlighter puts the caret back at a wrong offset, so the typed text is not before the caret as the inserted-text rule needs.
…rs, one MarkStateExtension per kind of annotation Stacked on #9489 (`isMarkIDShown`), which should land first. `MarkStateExtension` maps ids to the text they cover, but nothing says what an id is: comments, suggestions and highlights all share the `markIds` key, the `mark` theme class and one `markIDNodeKeys` output, and every app diffs that output by hand to keep its own thread store in step. This adds mark flavors to `@lexical/mark`: - `defineMarkExtension({name, stateKey, attribute?, className?, overlapClassName?, config?})` makes one extension per kind of annotation. Each flavor works like `MarkStateExtension` on its own set-valued NodeState key, with its own attribute (default `data-lexical-<kebab key>`), classes, config (`isMarkIDShown`, `disabled`, `markableNodes`, `exportIDsToHTML`), output and listeners. Two flavors on the same text never see each other's ids. - `$addMarkID`, `$removeMarkID`, `$getMarkIDsAtSelection`, `$getNodeMarkIDs` and `$migrateMarkNodesToMarkState` take a flavor as an optional first argument: `$addMarkID(CommentMarks, 'c1', selection)`. Without one they act on `MarkStateExtension`, as before. The flavor-first form is the first overload, so the original signature stays the last one and `Parameters<typeof $addMarkID>` and the like do not change (a type test checks this). - `registerMarkIDsListener(editor, flavor, listener)` is called after each commit that changes which ids of a flavor are in the document, with `added`, `removed`, `ids` and the update's `tags`, and once right away when the document already has ids. When all of a comment's text is deleted its id is reported removed (orphan the thread); undo, redo or a paste reports it added again. A disabled flavor reports nothing, and reports the net change when enabled again. - `MarkBaseExtension` is the shared base every flavor depends on (the name `MarkExtension` is taken by the MarkNode extension). It keeps the editor's flavors by key (`flavors` output; `$getMarkIDsByFlavor(node)` reads all of them), throws at build when two flavors share a key or an attribute, and lets the inserted-text rules of the flavors tell a TextNode piece that another flavor's rule split off in this update from inserted content. Without that, text typed at the edge of a mark of one flavor joined a mark of the other (see the Before output). - Two flavors that share a class, or a flavor that uses a theme class of `MarkStateExtension`, do not remove it from each other. - `MarkStateExtension` is now the default flavor, on `markIds`, with the same name, config, output, attribute, theme classes and JSON. Its type gains `stateKey` and `attribute`. `MarkStateExtension.test.ts` is unchanged and passes. The rules are types where they can be: `CommentMarks.stateKey` has the type `'commentIds'`, and a `stateKey` that is not a literal, is empty, contains whitespace, or is `'markIds'` or `'__proto__'` is a type error whose message says how to fix it (the runtime checks the same). Duplicate keys or attributes in one editor can only be caught at build; that error names both flavors and the fix. `defineMarkExtension` is declared `@__NO_SIDE_EFFECTS__` and added to `PURE_FACTORY_FUNCTIONS`, so module-scope flavor definitions tree-shake. Changesets cover `@lexical/mark` and `@lexical/compiler`. Flow declarations and the Flow smoke test cover the new API. The Comments and Annotations docs get a "Mark flavors" section with a `Y.Map` thread store kept in sync through the listener. Collaboration needs no binding change: a flavor is one more NodeState key with the same set schema as `markIds`. `@lexical/yjs` syncs it as any NodeState. In `@lexical/y` (#9400) each flavor is its own `s:<stateKey>` format key, and with #9439 its own family stored one key per id, since this PR because `@lexical/y` is not on this branch; see the test plan. The new tests against #9489's branch: ``` $ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkFlavors.test.ts packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts FAIL |unit| packages/lexical-mark/src/__tests__/unit/MarkFlavors.test.ts TypeError: defineMarkExtension is not a function FAIL |unit| packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts TypeError: defineMarkExtension is not a function Test Files 2 failed (2) ``` The two-flavor property run with the shared split records turned off (each flavor's rule on its own), showing the cross-flavor interference they fix: ``` $ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts ✓ MarkStateExtension property test (1) × 40 random edit sequences of 30 steps keep the ids of every character + seed 1: document + got: ("axqb") / ("d" "cmro😃q"[c2,c5] "A"[c2]) / ("alau"[c2]) / ("f"[c2] "ubq") + want: ("axqb") / ("d" "cmro😃q"[c2,c5] "A") / ("alau"[c2]) / ("f"[c2] "ubq") ``` ``` $ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkFlavors.test.ts --reporter=verbose ✓ two flavors on the same text > each flavor sees only its own ids ✓ two flavors on the same text > each flavor renders its own classes and attribute ✓ two flavors on the same text > flavors that share a class do not remove it from each other ✓ two flavors on the same text > typing at the end of both marks gives the text the ids of both flavors by the same rule ✓ two flavors on the same text > typing inside both marks gives the text the ids of both flavors by the same rule ✓ two flavors on the same text > typing at the start of both marks gives the text the ids of both flavors by the same rule ✓ two flavors on the same text > text typed at the edge of one flavor joins the other where it is inside ✓ two flavors on the same text > text replacing a selection gets the ids all of it had, per flavor ✓ two flavors on the same text > pasted text keeps the ids of every flavor ✓ registerMarkIDsListener > reports added, removed (orphaned) and restored ids across undo and paste ✓ registerMarkIDsListener > a collaborator update is tagged ✓ registerMarkIDsListener > the first call lists the ids already in the document, and unregistering stops it ✓ registerMarkIDsListener > disabling reports nothing, enabling reports the net change ✓ registerMarkIDsListener > a listener registered while disabled gets every id when enabled ✓ registerMarkIDsListener > a listener that throws on its first call is not registered ✓ registerMarkIDsListener > a flavor disabled by another flavor listener in the same commit reports nothing ✓ registerMarkIDsListener > an editor without the flavor throws, naming the fix ✓ isMarkIDShown per flavor > a flavor filter hides only that flavor ✓ the default flavor > MarkStateExtension is the flavor on markIds ✓ the default flavor > the functions without a flavor act on MarkStateExtension, beside other flavors ✓ the default flavor > $migrateMarkNodesToMarkState can target a flavor ✓ serialization > JSON round trips the ids of every flavor ✓ serialization > ids of a flavor the editor lacks are kept as unknown state ✓ serialization > HTML round trips each flavor through its own attribute ✓ errors > two flavors with the same stateKey fail when the editor is built ✓ errors > two flavors with the same attribute fail when the editor is built ✓ errors > attributes that differ only in case clash ✓ errors > stateKey "" is rejected with the fix in the message ✓ errors > stateKey "a b" is rejected with the fix in the message ✓ errors > stateKey "markIds" is rejected with the fix in the message ✓ errors > stateKey "__proto__" is rejected with the fix in the message ✓ types > the definition types the flavor ✓ types > the original signatures stay the last overloads ✓ types > the type rules reject what the runtime rejects $ MARK_STATE_PROPERTY_SEEDS=3000 MARK_STATE_PROPERTY_STEPS=40 npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts ✓ MarkStateExtension property test (1) ✓ 3000 random edit sequences of 40 steps keep the ids of every character 54224ms ✓ MarkStateExtension property test with two mark flavors (1) ✓ 3000 random edit sequences of 40 steps keep the ids of every character 86535ms Tests 2 passed (2) $ npx vitest run --project unit packages/lexical-mark Test Files 13 passed (13) Tests 852 passed (852) $ npx vitest run scripts/__tests__/unit/treeShakingSource.test.ts packages/lexical-compiler Test Files 7 passed (7) Tests 570 passed (570) $ pnpm run test-unit Test Files 413 passed | 1 skipped (414) Tests 10208 passed | 4 expected fail | 2 skipped (10214) $ pnpm run build && pnpm run build-types (both exit 0) $ pnpm run ci-check Found 0 errors ``` `@lexical/y` check, not part of this PR: on a copy of the #9400 tree with this `MarkStateExtension.ts`, a two-peer test that adds a comment on one peer and a suggestion plus a default-flavor id on the other, on the same words, converges with all three, and removing the comment on one peer leaves the suggestion on both. The Yjs text holds `s:markIds`, `s:commentIds` and `s:suggestionIds` as separate format keys. The `@lexical/y` Slots, EmptyMarks, TypeAtMarkStart, Races, TypeOverSelection and FormatOnlyChanges suites pass there too (751 tests). Browser-mode tests and E2E were not run; the DOM checks run in jsdom.
…rs, one MarkStateExtension per kind of annotation Stacked on #9489 (`isMarkIDShown`), which should land first. `MarkStateExtension` maps ids to the text they cover, but nothing says what an id is: comments, suggestions and highlights all share the `markIds` key, the `mark` theme class and one `markIDNodeKeys` output, and every app diffs that output by hand to keep its own thread store in step. This adds mark flavors to `@lexical/mark`: - `defineMarkExtension({name, stateKey, attribute?, className?, overlapClassName?, config?})` makes one extension per kind of annotation. Each flavor works like `MarkStateExtension` on its own set-valued NodeState key, with its own attribute (default `data-lexical-<kebab key>`), classes, config (`isMarkIDShown`, `disabled`, `markableNodes`, `exportIDsToHTML`), output and listeners. Two flavors on the same text never see each other's ids. - `$addMarkID`, `$removeMarkID`, `$getMarkIDsAtSelection`, `$getNodeMarkIDs` and `$migrateMarkNodesToMarkState` take a flavor as an optional first argument: `$addMarkID(CommentMarks, 'c1', selection)`. Without one they act on `MarkStateExtension`, as before. The flavor-first form is the first overload, so the original signature stays the last one and `Parameters<typeof $addMarkID>` and the like do not change (a type test checks this). - `registerMarkIDsListener(editor, flavor, listener)` is called after each commit that changes which ids of a flavor are in the document, with `added`, `removed`, `ids` and the update's `tags`, and once right away when the document already has ids. When all of a comment's text is deleted its id is reported removed (orphan the thread); undo, redo or a paste reports it added again. A disabled flavor reports nothing, and reports the net change when enabled again. - `MarkBaseExtension` is the shared base every flavor depends on (the name `MarkExtension` is taken by the MarkNode extension). It keeps the editor's flavors by key (`flavors` output; `$getMarkIDsByFlavor(node)` reads all of them), throws at build when two flavors share a key or an attribute, and lets the inserted-text rules of the flavors tell a TextNode piece that another flavor's rule split off in this update from inserted content. Without that, text typed at the edge of a mark of one flavor joined a mark of the other (see the Before output). - Two flavors that share a class, or a flavor that uses a theme class of `MarkStateExtension`, do not remove it from each other. - `MarkStateExtension` is now the default flavor, on `markIds`, with the same name, config, output, attribute, theme classes and JSON. Its type gains `stateKey` and `attribute`. `MarkStateExtension.test.ts` is unchanged and passes. The rules are types where they can be: `CommentMarks.stateKey` has the type `'commentIds'`, and a `stateKey` that is not a literal, is empty, contains whitespace, or is `'markIds'` or `'__proto__'` is a type error whose message says how to fix it (the runtime checks the same). Duplicate keys or attributes in one editor can only be caught at build; that error names both flavors and the fix. `defineMarkExtension` is declared `@__NO_SIDE_EFFECTS__` and added to `PURE_FACTORY_FUNCTIONS`, so module-scope flavor definitions tree-shake. Changesets cover `@lexical/mark` and `@lexical/compiler`. Flow declarations and the Flow smoke test cover the new API. The Comments and Annotations docs get a "Mark flavors" section with a `Y.Map` thread store kept in sync through the listener. Collaboration needs no binding change: a flavor is one more NodeState key with the same set schema as `markIds`. `@lexical/yjs` syncs it as any NodeState. In `@lexical/y` (#9400) each flavor is its own `s:<stateKey>` format key, and with #9439 its own family stored one key per id, since this PR because `@lexical/y` is not on this branch; see the test plan. The new tests against #9489's branch: ``` $ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkFlavors.test.ts packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts FAIL |unit| packages/lexical-mark/src/__tests__/unit/MarkFlavors.test.ts TypeError: defineMarkExtension is not a function FAIL |unit| packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts TypeError: defineMarkExtension is not a function Test Files 2 failed (2) ``` The two-flavor property run with the shared split records turned off (each flavor's rule on its own), showing the cross-flavor interference they fix: ``` $ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts ✓ MarkStateExtension property test (1) × 40 random edit sequences of 30 steps keep the ids of every character + seed 1: document + got: ("axqb") / ("d" "cmro😃q"[c2,c5] "A"[c2]) / ("alau"[c2]) / ("f"[c2] "ubq") + want: ("axqb") / ("d" "cmro😃q"[c2,c5] "A") / ("alau"[c2]) / ("f"[c2] "ubq") ``` ``` $ npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkFlavors.test.ts --reporter=verbose ✓ two flavors on the same text > each flavor sees only its own ids ✓ two flavors on the same text > each flavor renders its own classes and attribute ✓ two flavors on the same text > flavors that share a class do not remove it from each other ✓ two flavors on the same text > typing at the end of both marks gives the text the ids of both flavors by the same rule ✓ two flavors on the same text > typing inside both marks gives the text the ids of both flavors by the same rule ✓ two flavors on the same text > typing at the start of both marks gives the text the ids of both flavors by the same rule ✓ two flavors on the same text > text typed at the edge of one flavor joins the other where it is inside ✓ two flavors on the same text > text replacing a selection gets the ids all of it had, per flavor ✓ two flavors on the same text > pasted text keeps the ids of every flavor ✓ registerMarkIDsListener > reports added, removed (orphaned) and restored ids across undo and paste ✓ registerMarkIDsListener > a collaborator update is tagged ✓ registerMarkIDsListener > the first call lists the ids already in the document, and unregistering stops it ✓ registerMarkIDsListener > disabling reports nothing, enabling reports the net change ✓ registerMarkIDsListener > a listener registered while disabled gets every id when enabled ✓ registerMarkIDsListener > a listener that throws on its first call is not registered ✓ registerMarkIDsListener > a flavor disabled by another flavor listener in the same commit reports nothing ✓ registerMarkIDsListener > an editor without the flavor throws, naming the fix ✓ isMarkIDShown per flavor > a flavor filter hides only that flavor ✓ the default flavor > MarkStateExtension is the flavor on markIds ✓ the default flavor > the functions without a flavor act on MarkStateExtension, beside other flavors ✓ the default flavor > $migrateMarkNodesToMarkState can target a flavor ✓ serialization > JSON round trips the ids of every flavor ✓ serialization > ids of a flavor the editor lacks are kept as unknown state ✓ serialization > HTML round trips each flavor through its own attribute ✓ errors > two flavors with the same stateKey fail when the editor is built ✓ errors > two flavors with the same attribute fail when the editor is built ✓ errors > attributes that differ only in case clash ✓ errors > stateKey "" is rejected with the fix in the message ✓ errors > stateKey "a b" is rejected with the fix in the message ✓ errors > stateKey "markIds" is rejected with the fix in the message ✓ errors > stateKey "__proto__" is rejected with the fix in the message ✓ types > the definition types the flavor ✓ types > the original signatures stay the last overloads ✓ types > the type rules reject what the runtime rejects $ MARK_STATE_PROPERTY_SEEDS=3000 MARK_STATE_PROPERTY_STEPS=40 npx vitest run --project unit packages/lexical-mark/src/__tests__/unit/MarkStateProperty.test.ts ✓ MarkStateExtension property test (1) ✓ 3000 random edit sequences of 40 steps keep the ids of every character 54224ms ✓ MarkStateExtension property test with two mark flavors (1) ✓ 3000 random edit sequences of 40 steps keep the ids of every character 86535ms Tests 2 passed (2) $ npx vitest run --project unit packages/lexical-mark Test Files 13 passed (13) Tests 852 passed (852) $ npx vitest run scripts/__tests__/unit/treeShakingSource.test.ts packages/lexical-compiler Test Files 7 passed (7) Tests 570 passed (570) $ pnpm run test-unit Test Files 413 passed | 1 skipped (414) Tests 10208 passed | 4 expected fail | 2 skipped (10214) $ pnpm run build && pnpm run build-types (both exit 0) $ pnpm run ci-check Found 0 errors ``` `@lexical/y` check, not part of this PR: on a copy of the #9400 tree with this `MarkStateExtension.ts`, a two-peer test that adds a comment on one peer and a suggestion plus a default-flavor id on the other, on the same words, converges with all three, and removing the comment on one peer leaves the suggestion on both. The Yjs text holds `s:markIds`, `s:commentIds` and `s:suggestionIds` as separate format keys. The `@lexical/y` Slots, EmptyMarks, TypeAtMarkStart, Races, TypeOverSelection and FormatOnlyChanges suites pass there too (751 tests). Browser-mode tests and E2E were not run; the DOM checks run in jsdom.
Description
The recommended way to resolve a comment with
MarkStateExtensionis to keepits id in the text and flag the thread resolved in the app's own store (see
the Comments and Annotations docs). But the extension renders every id, so
resolved threads stay highlighted, and apps have no way to say which ids
render.
This adds an optional
isMarkIDShown?: (id: string) => booleanconfig and anisMarkIDShownoutput signal:mark/markOverlaptheme classes and thedata-lexical-mark-idsattribute only for the ids the filter returnstruefor. The default shows every id, so existing editors render exactly as
before, and configs written without the field still type check (TypeScript
and Flow).
with a full reconcile, which reuses the existing nodes (the same mechanism
DOMRenderExtensionuses whendisabledflips): no node is changed, sonothing syncs to collaborators or lands in the history. It is skipped when
the document has no marks, the editor has no root element, or the extension
is disabled (re-enabling renders with the current filter). Assigned while an
update is pending, or in a listener that may queue edits, the re-render
waits for those updates to commit, so an edit is not mistaken for a
setEditorState, inserted-text mark rules still apply, and the edit keepsits caret update. The re-render is tagged
SKIP_DOM_SELECTION_TAG, so it does notpull the caret out of another editable such as a comment reply box.
$functions, themarkIDNodeKeysoutput and HTML export still see everyid.
Flow declarations and the Flow smoke test are updated, and
comments.mdgetsa "Resolving a thread" section.
Test plan
Before
New tests run against
main'sMarkStateExtension.ts:After
Browser-mode tests and E2E were not run; the external-caret case is covered
in jsdom only.