Skip to content

[lexical-playground] Bug Fix: a mention keeps the text format applied to it - #9035

Closed
LeSingh1 wants to merge 1 commit into
meta:mainfrom
LeSingh1:fix/mention-node-theme-classes
Closed

LeSingh1 wants to merge 1 commit into
meta:mainfrom
LeSingh1:fix/mention-node-theme-classes

Conversation

@LeSingh1

@LeSingh1 LeSingh1 commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Description

MentionNode.createDOM replaces the class name that TextNode.createDOM just set instead of adding to it:

createDOM(config: EditorConfig): HTMLElement {
  const dom = super.createDOM(config);
  dom.style.backgroundColor = mentionBackgroundColor;
  dom.className = 'mention';   // <- discards everything super applied
  dom.spellcheck = false;
  return dom;
}

super.createDOM renders the node's text formats through $createTextInnerDOM, which applies config.theme.text.* to that element. Every class-based format — underline, strikethrough, highlight, subscript, superscript, code, uppercase/lowercase/capitalize — is written onto it and then thrown away by the assignment.

MentionNode does not override updateDOM, so TextNode.updateDOM keeps writing those classes back. The two halves disagree, which is what makes this look intermittent rather than simply broken. Rendered on upstream/main:

<!-- created -->            <span class="mention" ...>Luke</span>
<!-- underline applied -->  <span class="mention theme-underline" ...>Luke</span>
<!-- then bold applied -->  <strong class="mention" ...>Luke</strong>

Underlining a mention works, because updateDOM handles it in place. Then press Ctrl+B: bold changes the HTML tag, so TextNode.updateDOM returns true before touching the DOM, the reconciler rebuilds the element through createDOM, and the underline class is gone — while the node state, the toolbar and exportDOM all still say underlined. The formatting also disappears on any other rebuild: pasting a formatted mention, undo/redo across it, reloading a saved document, or receiving it over collab.

Fixed with addClassNamesToElement, which is what the sibling SpecialTextNode in the same directory already does, and what KeywordNode needed for the same reason. The .mention class is unchanged, so the CSS still matches; formats are simply no longer dropped.

The hardcoded dom.style.backgroundColor on the line above has a related problem — it overrides a background colour set from the toolbar, which super.createDOM applied from this.__style — but fixing that means moving the colour into CSS, so I have left it out of this change.

This file has two other open PRs of mine (#8969 on exportDOM, #8999 on $createMentionNode); all three touch different methods and do not overlap.

Test plan

New unit test packages/lexical-playground/__tests__/unit/MentionNodeTheme.test.ts. The theme gives a class only to underline, so that toggling bold isolates the tag-change rebuild.

Before

 ❯ packages/lexical-playground/__tests__/unit/MentionNodeTheme.test.ts (2 tests | 2 failed)
   × keeps the theme class of the format it was created with
     AssertionError: expected [ 'mention' ] to deeply equal [ 'mention', 'theme-underline' ]
   × keeps the theme class when a format change rebuilds the element
     AssertionError: expected [ 'mention' ] to deeply equal [ 'mention', 'theme-underline' ]

 Test Files  1 failed (1)
      Tests  2 failed (2)

After

 Test Files  1 passed (1)
      Tests  2 passed (2)

Package suite is unchanged:

$ npx vitest run packages/lexical-playground
 Test Files  19 passed (19)
      Tests  276 passed (276)

… to it

## Description

`MentionNode.createDOM` replaces the class name that `TextNode.createDOM` just set instead of adding to it:

```ts
createDOM(config: EditorConfig): HTMLElement {
  const dom = super.createDOM(config);
  dom.style.backgroundColor = mentionBackgroundColor;
  dom.className = 'mention';   // <- discards everything super applied
  dom.spellcheck = false;
  return dom;
}
```

`super.createDOM` renders the node's text formats through `$createTextInnerDOM`, which applies `config.theme.text.*` to that element. Every class-based format — underline, strikethrough, highlight, subscript, superscript, code, uppercase/lowercase/capitalize — is written onto it and then thrown away by the assignment.

`MentionNode` does not override `updateDOM`, so `TextNode.updateDOM` keeps writing those classes back. The two halves disagree, which is what makes this look intermittent rather than simply broken. Rendered on `upstream/main`:

```html
<!-- created -->            <span class="mention" ...>Luke</span>
<!-- underline applied -->  <span class="mention theme-underline" ...>Luke</span>
<!-- then bold applied -->  <strong class="mention" ...>Luke</strong>
```

Underlining a mention works, because `updateDOM` handles it in place. Then press Ctrl+B: bold changes the HTML tag, so `TextNode.updateDOM` returns `true` before touching the DOM, the reconciler rebuilds the element through `createDOM`, and the underline class is gone — while the node state, the toolbar and `exportDOM` all still say underlined. The formatting also disappears on any other rebuild: pasting a formatted mention, undo/redo across it, reloading a saved document, or receiving it over collab.

Fixed with `addClassNamesToElement`, which is what the sibling `SpecialTextNode` in the same directory already does, and what `KeywordNode` needed for the same reason. The `.mention` class is unchanged, so the CSS still matches; formats are simply no longer dropped.

The hardcoded `dom.style.backgroundColor` on the line above has a related problem — it overrides a background colour set from the toolbar, which `super.createDOM` applied from `this.__style` — but fixing that means moving the colour into CSS, so I have left it out of this change.

This file has two other open PRs of mine (meta#8969 on `exportDOM`, meta#8999 on `$createMentionNode`); all three touch different methods and do not overlap.

## Test plan

New unit test `packages/lexical-playground/__tests__/unit/MentionNodeTheme.test.ts`. The theme gives a class only to underline, so that toggling bold isolates the tag-change rebuild.

### Before

```
 ❯ packages/lexical-playground/__tests__/unit/MentionNodeTheme.test.ts (2 tests | 2 failed)
   × keeps the theme class of the format it was created with
     AssertionError: expected [ 'mention' ] to deeply equal [ 'mention', 'theme-underline' ]
   × keeps the theme class when a format change rebuilds the element
     AssertionError: expected [ 'mention' ] to deeply equal [ 'mention', 'theme-underline' ]

 Test Files  1 failed (1)
      Tests  2 failed (2)
```

### After

```
 Test Files  1 passed (1)
      Tests  2 passed (2)
```

Package suite is unchanged:

```
$ npx vitest run packages/lexical-playground
 Test Files  19 passed (19)
      Tests  276 passed (276)
```
@vercel

vercel Bot commented Aug 9, 2026

Copy link
Copy Markdown

@LeSingh1 is attempting to deploy a commit to the Meta Open Source Team on Vercel.

A member of the Team first needs to authorize it.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Aug 9, 2026
@mayrang

mayrang commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

These three — #9008 (KeywordNode), #9009 (EmojiNode), and this one — fix the same pattern in the same package and would be better as a single PR. As etrepum noted on #9027, splitting related fixes into a high volume of small PRs puts a lot of pressure on review resources and makes it harder for other contributors to get attention. Worth keeping in mind going forward.

@LeSingh1

LeSingh1 commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

@mayrang Agreed — #9008, #9009 and this are the same defect (createDOM overwriting the theme classes super just applied) in the same package, and should be one PR.

That is part of the consolidation etrepum asked for in #9027, so rather than reshuffle these three individually I will fold them into a single [lexical-playground] PR covering the whole createDOM/updateDOM class along with the rest of the queue. Thanks for reviewing them.

@LeSingh1

Copy link
Copy Markdown
Contributor Author

Consolidated into #9049 with the other two nodes that share this defect, per @mayrang's note on #9035 and @etrepum's on #9027. Same fix and same tests, one review.

@LeSingh1 LeSingh1 closed this Aug 10, 2026
This was referenced Aug 10, 2026
This was referenced Aug 10, 2026
LeSingh1 added a commit to LeSingh1/lexical that referenced this pull request Aug 10, 2026
…s, hit targets and shared state at the editor boundary

## Description

Four fixes for things that sit at the *edge* of an editor: a `HistoryState`
shared between two editors, overlays positioned over the editor DOM, and the
hit target of a block decorator. Each mis-handles a boundary — undo applied to
the wrong editor, an overlay whose position ignores an ancestor's CSS scale or
whose async callback lands after disposal, and a triple click that stops short
of an unselectable block.

To be upfront: this group is smaller-grained than the other consolidations. It
collects the fixes that did not belong to any of the larger defect classes, so
the shared thread is the editor boundary rather than a single root cause. The
four are independent — each bullet below can be reviewed and checked off on its
own.

- **meta#8953 — undo/redo applies to the editor that changed** (`getUndoEntry` /
  `getInverseEntry`, `packages/lexical-history/src/index.ts`). A shared
  `HistoryState` interleaves entries from several editors, but a push always
  recorded `historyState.current` — the state of whichever editor changed
  *last*. A change from a different editor therefore recorded a state that had
  not changed, so undo restored an editor to the state it was already in and the
  real change was dropped from the history. Now the pre-update state of the
  editor that actually changed is recorded, and the inverse entry is taken from
  that entry's own editor rather than from `current`, so undo and redo stay
  symmetric. An empty `EditorState` is skipped because it cannot be restored,
  mirroring the way an editor's first update is not undoable.

- **meta#8964 — triple click selects the paragraph before an embed block**
  (`.PlaygroundEditorTheme__embedBlock`,
  `packages/lexical-playground/src/themes/PlaygroundEditorTheme.css`). The theme
  class set `user-select: none` on the decorator wrapper itself, and a browser
  will not extend a triple click past an unselectable block, so triple clicking
  a paragraph immediately followed by an embed collapsed the selection to the
  start of that paragraph. `user-select` is inherited, so scoping the rule to
  the wrapper's children keeps the embed contents unselectable while leaving the
  decorator host and the wrapper selectable.

- **meta#8973 — the floating format toolbar stays aligned under CSS scale**
  (`getElementScale` and `setFloatingElemPosition`,
  `packages/lexical-playground/src/utils/`). `setFloatingElemPosition` mixed two
  coordinate spaces: the rects it reads are on-screen pixels, but the
  `translate()` it writes back is resolved in the anchor's own — unscaled —
  space. Under a CSS `scale()` on any ancestor the two differ by the scale
  factor, so the toolbar was placed at the wrong offset from the selection and
  the 10px/5px gaps were applied at the wrong size. The gaps are now scaled into
  on-screen pixels for the arithmetic and the final offset is divided back into
  the anchor's space. At scale 1 both factors are 1, so the computation is
  unchanged.

- **meta#9005 — `positionNodeOnRange` cleans up an invocation that lands after it
  was disposed of** (`packages/lexical-utils/src/positionNodeOnRange.ts`).
  `restart` was registered as a root listener but returned nothing, so Lexical
  was given no way to undo what an invocation did — even though `restart()`
  prepends a wrapper element and starts a `MutationObserver`. Root listeners are
  triggered from a snapshot of the registry, so a listener that an earlier
  listener in the same pass unregistered is still invoked once more; Lexical's
  escape hatch is to call the cleanup that invocation returned, which did not
  exist, leaving the wrapper in the document with nothing left to remove it.
  This is reachable straight from `selectionAlwaysOnDisplay`: change the root
  element while the selection is being marked and a stray highlight overlay is
  welded to the container, one more per root change. The root listener now
  returns `stop`, which is what the `RootListener` contract is for.

No API or serialization change in any of the four.

## Test plan

New unit tests in `@lexical/history` (shared `HistoryState` across two editors)
and `@lexical/utils` (both the direct `positionNodeOnRange` contract and the
`selectionAlwaysOnDisplay` symptom, each counting attached overlays), plus a new
browser-project test that asserts the floating toolbar's on-screen position at
scale 1 (the control), 0.5 and 2. meta#8964 is covered by
`BlockWithAlignableContents.spec.mjs`.

One existing test changed shape: `SharedHistoryExtension > can create a parent
editor` dispatched `UNDO_COMMAND` twice in a row to revert a single child-editor
edit, because the buggy push recorded a no-op entry that had to be undone first.
It now dispatches once. Its assertions are unchanged.

### Before

Source fixes reverted, new tests kept:

```
$ npx vitest run --project unit packages/lexical-history packages/lexical-utils
     × undo and redo apply to the editor that changed 7ms
     × can create a parent editor 182ms
     × removes the overlay of an invocation that lands after it was disposed of 72ms
     × leaves no overlay behind when the root element changed while marking 15ms
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 4 ⎯⎯⎯⎯⎯⎯⎯
AssertionError: expected LexicalEditor{ …(34) } to be LexicalEditor{ …(34) } // Object.is equality
AssertionError: expected 'Child editor. Updated!' to deeply equal 'Child editor'
AssertionError: expected 2 to be 1 // Object.is equality
AssertionError: expected 2 to be 1 // Object.is equality

 Test Files  2 failed | 17 passed (19)
      Tests  4 failed | 251 passed (255)

$ npx vitest run --project browser packages/lexical-playground/src/__tests__/browser/FloatingElemScale.test.ts
     × setFloatingElemPosition places the toolbar above the target at scale 0.5 84ms
     × setFloatingElemPosition places the toolbar above the target at scale 2 77ms
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯
AssertionError: expected 80 to be close to 145, received difference is 65, but expected 0.05
AssertionError: expected 1100 to be close to 580, received difference is 520, but expected 0.05

 Test Files  1 failed (1)
      Tests  2 failed | 1 passed (3)
```

The scale-1 control passes before and after, as intended.

### After

```
$ npx vitest run --project unit packages/lexical-history packages/lexical-utils packages/lexical-playground
 Test Files  39 passed (39)
      Tests  538 passed (538)

$ npx vitest run --project browser packages/lexical-playground/src/__tests__/browser/FloatingElemScale.test.ts
 Test Files  1 passed (1)
      Tests  3 passed (3)

$ npx playwright test --project=chromium HorizontalRule.spec.mjs BlockWithAlignableContents.spec.mjs
 17 passed

$ npx playwright test --project=firefox HorizontalRule.spec.mjs
 14 passed

$ npx tsc --noEmit -p .
(clean)
```

Supersedes meta#8953, meta#8964, meta#8973, meta#9005, consolidated per the review feedback on
meta#9027 and meta#9035.

meta#8967 was part of an earlier revision of this PR and has been dropped. It
selected a horizontal rule when a click landed in the blank space beside it, by
mapping the DOM caret offset onto the root element's raw child nodes. Those
children also include the zero-size `data-lexical-decorator-boundary` images
Lexical renders around block decorators, so the same click maps to a different
child in different browsers: for the two-adjacent-rules case in
`HorizontalRule.spec.mjs` (meta#6775) Chromium resolves to the boundary image and
Firefox to an `<hr>`. That made the existing meta#6775 assertion browser-dependent.
Getting this right needs a hit test against the rules' own geometry rather than
a caret offset, which is a different change and belongs in its own PR.
LeSingh1 added a commit to LeSingh1/lexical that referenced this pull request Aug 10, 2026
… grid indices, cell state and boundary selection

## Description

Eleven small table bugs, consolidated into one branch per the review feedback
on meta#9027 and meta#9035. They fall into three groups.

### 1. Grid geometry

Code that uses a row's child index where the table *grid* column index is
required, or that ignores a span. These agree only while every cell has
`colSpan === 1`/`rowSpan === 1`, so they are invisible until a table has merged
cells.

- `$insertTableColumnAtNode` (`packages/lexical-table/src/LexicalTableUtils.ts`)
  walked leftwards from the insertion column looking for the cell to insert
  after. When every grid position at or before the insertion column is covered
  by a `rowSpan` from an earlier row, the walk fell off the left edge and
  appended the new cell to the *end* of the row, so the inserted column did not
  line up. Replaced with the same left-to-right map scan `$unmergeCellNode`
  uses: track the last row-map entry with `startRow === i` at or before the
  insertion column, `insertAfter` it, or `$insertFirst` when the row owns
  nothing to the left. This also removes the labeled `continue`. (meta#8836)
- `toggleTableColumnIsHeader`
  (`packages/lexical-playground/src/plugins/TableActionMenuPlugin/index.tsx`)
  fed `$setTableColumnIsHeader`, which indexes `gridMap[row][columnIndex]`, the
  result of `$getTableColumnIndexFromTableCellNode` — the cell's index among its
  row's *children*. With an earlier spanning cell in the row, "Toggle column
  header" applied to a column left of the one clicked. It now reads
  `cellMap.startColumn` from `$computeTableMap`. (meta#9006)

### 2. Cell and table state

Transforms that rebuild a cell or its paragraph and drop what it carried, plus
the `dir` attribute being written onto an element that the export throws away.

- `$insertTableIntoGrid` (`LexicalTableUtils.ts`) copies the template cell's
  `backgroundColor` onto the destination cell but not `verticalAlign`, which
  was added to `TableCellNode` after that loop (meta#7077). Pasting a table with
  vertically aligned cells over an existing table dropped the alignment. (meta#9015)
- `$tableTransform` (`LexicalTablePluginHelpers.ts`) pads short rows out to the
  table width with `$createTableCellNode()` and no header state, so a short
  header row was repaired into a mix of `<th>` and `<td>`. The padding cells now
  inherit the `TableCellHeaderStates.ROW` bit from the row's last cell — the
  same reference `$insertTableColumnAtNode` uses when it appends a column. (meta#9023)
- `$unmergeCellNode` (`LexicalTableUtils.ts`) recomputes the header state of the
  cells it splits off, correctly, but gives them nothing else, so a filled
  merged cell unmerged into one filled cell and a run of blank ones. The split
  cells now keep the original's `backgroundColor` and `verticalAlign`, which is
  the cell's own presentation and not a description of its row or column. (meta#9025)
- `TableNode.exportDOM` (`LexicalTableNode.ts`) narrows the export to
  `element.querySelector('table')`. When scrollable tables are active
  `createDOM` returns the scroll wrapper `<div>`, which is where
  `ElementNode.exportDOM` writes `dir` — so the wrapper, and the direction with
  it, was thrown away. The direction is now re-applied to the `<table>`, which
  is where `$convertTableElement` reads it back. (meta#9029)
- `TableObserver.$clearText` (`LexicalTableObserver.ts`) emptied each selected
  cell by constructing a fresh `ParagraphNode`, so Backspace over a multi-cell
  selection also reset the format, style, direction and indent of those cells.
  It now `$copyNode`s the cell's existing paragraph, which carries the element
  state and returns a childless copy. (meta#9041)

### 3. Selection and caret at the table boundary

- The `KEY_ARROW_LEFT_COMMAND`/`KEY_ARROW_RIGHT_COMMAND` handlers in
  `registerRichText` (`packages/lexical-rich-text/src/index.ts`) had no
  equivalent of the `$isSelectionAtEndOfRoot`/`$isSelectionAtStartOfRoot` guards
  the up/down handlers already use. With a table as the last node of the
  document the key fell through to the native caret, which walks around the
  block cursor element, so the caret cycled: last cell → block cursor → root
  offset before the table → back into the last cell. A new
  `$isBlockCursorAtRootEdge` consumes the key when the collapsed element point
  sits at the root edge beside a child that needs a block cursor.
  Non-collapsed selections and block cursors that still have a sibling to move
  into are untouched. (meta#8949, fixes meta#7999)
- `$handleArrowKey` (`LexicalTableSelectionHelpers.ts`) armed the Firefox
  scrollable-table workaround (`setShouldCheckSelectionForTable`) on every
  ArrowDown. From the block cursor below a trailing table ArrowDown moves
  nothing, so the flag survived to be consumed by the next selection change —
  an ArrowUp back into the table — which snapped the caret to the first cell.
  A new `$isSelectionBeforeTable` arms it only when the focus is before the
  table in document order, the only side ArrowDown can enter from.
  (meta#8963, fixes meta#6822)
- `$deleteTableRowAtSelection` (`LexicalTableUtils.ts`) removes the table
  outright when the selection covers every row, but never moved the selection
  first, leaving a `TableSelection` anchored to detached nodes. Added the
  `grid.selectPrevious()` that `$deleteTableColumnAtSelection` and
  `TableObserver.$clearText` already do in their identical branches. (meta#9037)
- `$adjustFocusInDirection` (`LexicalTableSelectionHelpers.ts`) called
  `getCornerOrThrow` on the rect from `$computeTableCellRectBoundary`, which
  *grows* the rect until it contains every merged cell straddling an edge — so
  the anchor is not guaranteed to be at a corner, and Shift+Arrow killed the
  editor update with an invariant. `getCornerOrThrow` is replaced by
  `getAnchorCorner`, which falls back the same way `$extractRectCorners` 24
  lines below already does: to the corner opposite the focus, then to the
  top-left. (meta#9045)

## Test plan

Unit tests cover ten of the eleven fixes, two browser tests cover the
caret/arrow-key behaviour at the table boundary, and meta#9006 is a Playwright spec
(`packages/lexical-playground/__tests__/regression/7266-column-header-merged-cells.spec.mjs`).

### Before

Source fixes reverted, new tests kept:

```
$ npx vitest run --project unit packages/lexical-table packages/lexical-rich-text
     × pasting a table carries the cell backgroundColor and verticalAlign 6ms
     × a short header row is padded with header cells 5ms
     × extends the selection instead of throwing 73ms
     × keeps the paragraph format, style and direction of each cell 89ms
     × inserts the new cell in the correct column for rows spanned by a rowSpan cell 7ms
     × exports dir with scrollable tables active 31ms
     × leaves the selection outside the removed table 13ms
     × ArrowRight at the block cursor after the last block stays put 5ms
     × ArrowLeft at the block cursor before the first block stays put 1ms
     × the cells a merged cell splits into keep its backgroundColor and verticalAlign 13ms
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 10 ⎯⎯⎯⎯⎯⎯⎯

 Test Files  8 failed | 23 passed (31)
      Tests  10 failed | 291 passed (301)

$ npx vitest run --project browser packages/lexical-table/src/__tests__/browser/TableTrailingCaret.test.ts packages/lexical-table/src/__tests__/browser/Issue6822BlockCursorArrowKeys.test.ts
   × the caret stops beneath a trailing table instead of cycling around it 172ms
     × ArrowUp from the block cursor below a trailing table returns to the last row 380ms
     × ArrowUp from the block cursor below a table that is the only root child returns to the last row 355ms
 Test Files  2 failed (2)
      Tests  3 failed | 2 passed (5)
```

The remaining new cases pass on both sides of the change — the unstyled-unmerge,
short-body-row, non-wrapped-export, delete-every-column and
still-owns-a-cell-to-the-left cases — which is what pins each asymmetry rather
than the fix itself.

### After

```
$ npx vitest run --project unit packages/lexical-table packages/lexical-rich-text
 Test Files  31 passed (31)
      Tests  301 passed (301)

$ npx vitest run --project browser packages/lexical-table/src/__tests__/browser/TableTrailingCaret.test.ts packages/lexical-table/src/__tests__/browser/Issue6822BlockCursorArrowKeys.test.ts
 Test Files  2 passed (2)
      Tests  5 passed (5)

$ npx playwright test --project=chromium Tables.spec.mjs TablesHTMLCopyAndPaste.spec.mjs 7266-column-header-merged-cells.spec.mjs
 99 passed, 1 skipped

$ npx tsc --noEmit -p .
(clean)
```

Supersedes meta#8836, meta#8949, meta#8963, meta#9006, meta#9015, meta#9023, meta#9025, meta#9029, meta#9037,
meta#9041, meta#9045, consolidated per the review feedback on meta#9027 and meta#9035.

meta#9000 and meta#9011 were part of an earlier revision of this PR and have been
dropped, because each contradicted an existing e2e expectation rather than
extending it:

- meta#9000 imported `dir` in the `DOMImportExtension` table rules. Google Sheets
  emits `<table dir="ltr">` unconditionally, so `Copy + paste (Table - Google
  Sheets)` in `TablesHTMLCopyAndPaste.spec.mjs` went from `dir="auto"` to a
  pinned `dir="ltr"` on the table, and the rows below it stopped emitting
  `dir="auto"` at all. Honouring a pasted `dir` is a deliberate behaviour change
  for third-party HTML and needs its own PR.
- meta#9011 made the right-edge resizer widen the *last* grid column a merged cell
  spans instead of its first. `Resize merged cells width (2)` in
  `Tables.spec.mjs` pins the existing behaviour, and both variants widen the
  merged cell identically — they differ only in which unmerged column absorbs
  the change, so this is a behaviour preference that needs a maintainer call.
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 29, 2026
…ive when their inputs change

## Description

A React plugin or hook that reads editor state once, on the first render, and
then subscribes for future changes only reports a stale answer for everything
that happened before it subscribed — and never re-derives when the prop or
argument it was seeded from changes. `registerUpdateListener` and friends do not
fire on registration, an effect whose dependency list omits the prop that changed
never re-runs, and a value read off the editor at render time (`editor._editable`,
`editor.isEditable()`) is not a subscription at all. The same shape shows up on
the handler side: a command handler that claims the event when there is nothing
to act on, and a state update that clobbers the selection it was supposed to
leave alone.

Each of the fixes below re-derives (or resubscribes) from the input that actually
changed, and none of them changes behaviour when the inputs are stable.

- `CollaborationPlugin` (`packages/lexical-react/src/LexicalCollaborationPlugin.tsx`)
  guarded provider creation with an `isProviderInitialized` ref, so a changed
  `providerFactory`, `id` or `yjsDocMap` kept the old provider forever. The ref
  now records the inputs that produced the current provider, so a real change
  creates a new one while a StrictMode/remount re-run with unchanged inputs still
  does not.
- `useMenuAnchorRef` (`packages/lexical-react/src/shared/LexicalMenu.tsx`)
  positioned the absolutely-positioned anchor in document coordinates
  unconditionally. When a `parent` is passed it is normally positioned, so it —
  not the initial containing block — is the anchor's containing block, and the
  menu landed at the parent's own offset instead of at the caret. New
  `getContainingBlockOrigin()` resolves the real origin and the `toAnchorLeft`/
  `toAnchorTop` helpers translate every viewport coordinate through it, including
  the two flip-into-view branches. Fixes meta#6989.
- `DraggableBlockPlugin_EXPERIMENTAL`
  (`packages/lexical-react/src/LexicalDraggableBlockPlugin.tsx`) read
  `editor._editable` during render, which is not a subscription, so the handle
  did not appear or disappear on `setEditable()`. It now uses
  `useLexicalEditable()`.
- `LexicalMenu` (`packages/lexical-react/src/shared/LexicalMenu.tsx`) returned
  `true` from its `KEY_ARROW_DOWN_COMMAND`/`KEY_ARROW_UP_COMMAND` handlers even
  when `options` was empty — no menu is rendered in that case, so the arrow keys
  were swallowed and the caret stopped moving. Both handlers now return `false`
  when there is nothing to move through.
- `NodeContextMenuPlugin`
  (`packages/lexical-react/src/LexicalNodeContextMenuPlugin.tsx`) called
  `preventDefault()` and mounted its scroll-locking overlay before computing
  which items `$showOn` allows, so a node with no applicable items suppressed the
  browser's own context menu and showed an empty one. The filtering moved ahead
  of `preventDefault()` and the handler returns early when nothing is visible.
- `useLexicalIsTextContentEmpty`
  (`packages/lexical-react/src/useLexicalIsTextContentEmpty.ts`) seeded its state
  on the first render only, so a new `editor` or a new `trim` kept reporting the
  previous answer until the next update. The layout effect now re-derives the
  value before subscribing (and the initial `useState` is lazy, so it no longer
  reads the editor on every render).
- `useLexicalNodeSelection`
  (`packages/lexical-react/src/useLexicalNodeSelection.ts`) created an empty
  `NodeSelection` when asked to *de*select a node while the user held a
  `RangeSelection`, discarding their caret. Deselecting with no `NodeSelection`
  present is now a no-op.
- The playground's `TextFormatFloatingToolbar`
  (`packages/lexical-playground/src/plugins/FloatingTextFormatToolbarPlugin/index.tsx`)
  gated its buttons on `editor.isEditable()` read during render, so the toolbar
  kept its format buttons after `setEditable(false)`. It now uses
  `useLexicalEditable()`.
- `useCharacterLimit` (`packages/lexical-react/src/shared/useCharacterLimit.ts`)
  only ever counted inside `registerTextContentListener`, which does not fire on
  registration, so an editor that mounts with content reported the full budget
  remaining and left overflowing text unwrapped until the next keystroke. The
  body is extracted into `$updateCharacterLimit()` and called once before
  subscribing.
- `TreeView` (`packages/lexical-react/src/LexicalTreeView.tsx`) seeded
  `editorCurrentState` on the first render only and its effect had `editor` in
  the deps but never re-read the state, so a changed `editor` prop kept rendering
  the previous editor's tree. The effect re-reads `editor.getEditorState()`
  before subscribing, and is a `useLayoutEffect` to match
  `useCanShowPlaceholder`/`ContentEditableElement` and avoid a cascading render.

## Test plan

Nine new unit test files and one new browser test file, one per fix, each
asserting the stale value is re-derived (or that the handler declines to act);
`packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx`
gains a case for the provider swap. Every test fails on `main` with only the test
files applied and passes with the fixes.

### Before

Source fixes reverted, new tests kept:

```
$ npx vitest run --project unit packages/lexical-react packages/lexical-playground
     × leaves the native context menu alone when no item is shown 275ms
     × keeps a range selection when asked to deselect 88ms
     × hides its format buttons when the editor becomes read-only 206ms
     × counts the text that is already in the editor when it mounts 95ms
     × reports a full budget for an editor that is under the limit 8ms
     × counts in the charset it was given 6ms
     × follows setEditable 143ms
     × renders no drag handle for an editor that mounts read-only 17ms
     × lets ArrowDown through when there are no options 63ms
     × lets ArrowUp through when there are no options 4ms
     × provider is replaced when providerFactory changes 7ms
     × follows a change of the trim argument 19ms
     × follows a change of the editor 5ms
     × re-renders when the editor prop changes 14ms
 Test Files  9 failed | 49 passed (58)
      Tests  14 failed | 470 passed (484)

$ npx vitest run --project browser packages/lexical-react/src/__tests__/browser/useMenuAnchorRefPosition.test.tsx
     × anchors the menu at the caret when parent is a positioned element 147ms
     × anchors the menu at the caret when the positioned parent is scrolled 99ms
 Test Files  1 failed (1)
      Tests  2 failed | 1 passed (3)
```

### After

```
$ npx vitest run --project unit packages/lexical-react packages/lexical-playground
 Test Files  58 passed (58)
      Tests  484 passed (484)

$ npx vitest run --project browser packages/lexical-react/src/__tests__/browser/useMenuAnchorRefPosition.test.tsx
 Test Files  1 passed (1)
      Tests  3 passed (3)

$ npx tsc --noEmit -p .
(clean)
```

Supersedes meta#8965, meta#8968, meta#9012, meta#9017, meta#9022, meta#9024, meta#9026, meta#9030, meta#9033, meta#9040,
consolidated per the review feedback on meta#9027 and meta#9035.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants