Skip to content

[lexical-react][lexical-playground] Bug Fix: plugins and hooks re-derive when their inputs change - #9051

Merged
etrepum merged 13 commits into
meta:mainfrom
LeSingh1:consol/react-plugin-resubscribe
Aug 30, 2026
Merged

etrepum merged 13 commits into
meta:mainfrom
LeSingh1:consol/react-plugin-resubscribe

Conversation

@LeSingh1

Copy link
Copy Markdown
Contributor

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 Bug: Menu Selection and Scrolling Misbehavior in Limited Lexical Editor Space #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 deselect 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 #8965, #8968, #9012, #9017, #9022, #9024, #9026, #9030, #9033, #9040,
consolidated per the review feedback on #9027 and #9035.

…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.
@vercel

vercel Bot commented Aug 10, 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.

@vercel

vercel Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lexical Ready Ready Preview Aug 30, 2026 5:51pm
lexical-playground Ready Ready Preview Aug 30, 2026 5:51pm

Request Review

@etrepum

etrepum commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

A lint rule changed since this PR was opened so you'll need to apply pnpm run lint:fix to this (and probably your other PRs) in order to pass integrity checks

@etrepum

etrepum commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator

This one also has failing browser tests

… replaced

## Description

meta#9051 makes `CollaborationPlugin` build a new `Provider` when `providerFactory`,
`id` or `yjsDocMap` change. The `Binding` did not follow. It was guarded by an
`isBindingInitialized` ref, and because React runs an effect's cleanup before
every re-run, a change to any of that effect's dependencies destroyed the
`Binding` and then took the early return -- leaving a destroyed `Binding` in
state. That fires on the very case meta#9051 set out to fix: swapping
`providerFactory` changes `provider`, which is one of those dependencies.

Changing `id` was worse: the new document was created and the `Provider` swapped,
but nothing was ever bound to it, so edits reached neither document.

The two effects are now one. Provider, document and `Binding` are built together
and set in a single commit, so the components below always see a consistent set
-- staged across renders, `useProvider()` connects once for the new `Provider`
and again for the new `Binding`.

The guard survives, because `providerFactory` must not be called twice under
StrictMode, but the inputs it compares now match the dependency list exactly, so
there is no dependency that can tear the session down and then be skipped.
`excludedProperties` and `rootName` are in neither list: they are read once when
the `Binding` is built, exactly as before, so a caller passing a fresh object
each render keeps its connection rather than churning it.

No public API changes: `CollaborationPluginProps` is untouched, and
`YjsCollaborationCursors` is module-private. The `doc` state is now write-only
and kept solely for the legacy 'reload' callback (meta#1409); rebinding on reload is
a pre-existing gap this does not close.

## Test plan

### Before

The new test, against meta#9051 as submitted -- nothing is ever bound to the second
document, so `root` does not exist on it:

```
$ npx vitest run --project unit \
    packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx
 × the binding follows the id onto the new document
AssertionError: expected undefined to be defined
 Tests  1 failed | 2 passed (3)
```

Against `main` (before meta#9051), the id change is ignored outright:

```
 × provider is replaced when providerFactory changes
 × the binding follows the id onto the new document
AssertionError: expected "vi.fn()" to be called 1 times, but got 0 times
 Tests  2 failed | 1 passed (3)
```

### After

```
$ npx vitest run --project unit \
    packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx
 Test Files  1 passed (1)
      Tests  3 passed (3)

$ pnpm run test-unit
 Test Files  293 passed (293)
      Tests  5513 passed | 1 skipped (5514)

$ pnpm run test-browser
 Test Files  21 passed (21)
      Tests  142 passed | 1 skipped (143)

$ pnpm run ci-check
No errors!
```

`provider is replaced when providerFactory changes` still asserts exactly one
`connect()` on the replacement provider, which is what the single-commit update
preserves. The collab E2E suite needs a websocket server and was not run here.

Co-Authored-By: Claude Opus <[email protected]>
…el tolerance

## Description

`useMenuAnchorRefPosition.test.tsx` asserted `parent.scrollTop === 250` after
assigning 250. Chromium reports the integer back; Firefox resolves the scroll
offset to a fractional device pixel and reports 250.13333129882812, so all three
Firefox browser-test jobs failed on that line rather than on anything the test
is actually about.

The scroll offset is now only asserted to be non-zero -- what the test needs is
that the parent is scrolled, not by exactly how much -- and the position
assertions compare with `toBeCloseTo(_, 0)` instead of `Math.round(...)`, so
sub-pixel differences between engines cannot turn into a failure either. The
anchor still has to land on the caret, which is what the test is for: the
containing-block correction cancels the fractional scroll offset exactly.

## Test plan

### Before

```
 FAIL  browser (firefox) packages/lexical-react/src/__tests__/browser/useMenuAnchorRefPosition.test.tsx
   > useMenuAnchorRef positioning (browser) > anchors the menu at the caret when the positioned parent is scrolled
AssertionError: expected 250.13333129882812 to be 250 // Object.is equality
```

### After

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

Firefox itself could not be exercised here -- only the chromium Playwright
browser is installed in this environment -- so the fix is verified on chromium
and against the reported Firefox assertion text.

Co-Authored-By: Claude Opus <[email protected]>
…menu's containing block from its parent

## Description

Two changes, both driven by the collab e2e failures on this branch
(`SelectBlock > Select within nested editor` and
`Toolbar > Insert image caption + table`).

**Reverts the Binding rebuild.** Making `CollaborationPlugin` rebuild its
`Binding` when the Provider is replaced leaves a nested collab editor with a
duplicate empty paragraph. `onBootstrap` is a dependency of the effect in
`useYjsCollaboration` that subscribes to the Provider, so every new `Binding`
identity re-subscribes and bootstraps the document a second time; the image
caption editor ends up with

```
root
├ paragraph
| └ text "caption text"
└ paragraph        <- duplicate
```

Measured on a local collab e2e rig (prod playground + y-websocket + chromium),
repeating the flakier of the two tests:

| build | failures |
| --- | --- |
| main | 0/20 |
| this PR alone | 0/12 |
| PR + Binding rebuilt in the Provider's effect | 10/16 |
| PR + Binding rebuilt in its own effect | 7/24 |
| PR + Binding rebuilt only on provider/id change | 3/24 |
| PR + rebuild reverted (this commit) | 1/24 |

Narrowing what may rebuild the `Binding` reduces the rate but does not remove
it: any rebuild at all re-bootstraps. A real fix has to make bootstrap
idempotent across `Binding` identities in `useYjsCollaboration`, which is a
larger change than this PR should carry, so the plugin goes back to the
version in this PR and the stale-Binding bug stays open. It is pre-existing on
main, not introduced here: `isBindingInitialized` makes the effect's cleanup
destroy the `Binding` and then skip recreating it whenever one of its
dependencies changes.

**Resolves the menu's containing block from its parent.** The previous approach
attached the anchor before measuring, which also un-suppressed the flip logic
that had been silently reading a zero-sized rect -- a wider behavior change than
intended. `getContainingBlockOrigin()` now walks up from the element the anchor
is appended to instead of reading the detached anchor's `offsetParent`, so it
works without touching attach order or what gets measured.

## Test plan

### Before

```
$ npx playwright test --project=chromium -g "Select within nested editor" \
    --repeat-each=24 --retries=0   # E2E_EDITOR_MODE=rich-text-with-collab
  7 failed
  17 passed
```

### After

```
$ npx playwright test --project=chromium --repeat-each=12 --retries=0 \
    -g "Select within nested editor|Insert image caption . table"
  1 failed
  23 passed

$ pnpm run test-unit
 Test Files  293 passed (293)
      Tests  5512 passed | 1 skipped (5513)

$ pnpm run test-browser
 Test Files  21 passed (21)
      Tests  142 passed | 1 skipped (143)

$ pnpm run ci-check
No errors!
```

The remaining 1/24 matches the baseline that main (0/20) and this PR (0/12)
also show at these sample sizes; the regression was 10/16 and 7/24. Local e2e
was chromium-only -- firefox is not installed in this environment.

Co-Authored-By: Claude Opus <[email protected]>
…-only context menus

## Description

The remaining review findings on this PR, which extend the pattern it is
already fixing -- a menu that has nothing to show should not consume input.

**Escape.** `LexicalMenu` now returns `false` from `KEY_ESCAPE_COMMAND` when the
option list is empty, the way this PR already made the arrow keys behave. An
empty list renders no menu, so there is nothing on screen to dismiss and Escape
has to keep propagating to whatever would otherwise handle it.

**Separator-only context menus.** `NodeContextMenuPlugin` suppressed the native
context menu whenever `visibleItems` was non-empty, but separators carry no
`$showOn` and so survive the filter even when every option is hidden -- a menu
of nothing but dividers. It now requires at least one non-separator item.

**`useLexicalNodeSelection` docs.** This PR made `setSelected(false)` a no-op
when the selection is not a NodeSelection, which is right -- creating an empty
NodeSelection to deselect would discard the user's caret -- but it means
`isSelected` stays `true` while a RangeSelection still covers the node, since
`node.isSelected()` is true for those. Documented on the hook, pointing callers
at `clearSelected`.

## Test plan

### Before

Both new cases fail against the unfixed source:

```
$ npx vitest run --project unit \
    packages/lexical-react/src/__tests__/unit/LexicalMenuEmptyOptions.test.tsx \
    packages/lexical-react/src/__tests__/unit/LexicalNodeContextMenuPlugin.test.tsx
 × leaves the native context menu alone when only separators remain
 × lets Escape through when there are no options
AssertionError: expected true to be false // Object.is equality
AssertionError: expected true to be false // Object.is equality
 Tests  2 failed | 7 passed (9)
```

### After

```
$ pnpm run test-unit
 Test Files  293 passed (293)
      Tests  5515 passed | 1 skipped (5516)

$ pnpm run test-browser
 Test Files  21 passed (21)
      Tests  142 passed | 1 skipped (143)

$ pnpm run ci-check
No errors!
```

Collab e2e (prod playground + y-websocket + chromium), the two tests that were
failing on this branch, 12 runs each:

```
$ npx playwright test --project=chromium --repeat-each=12 --retries=0 \
    -g "Select within nested editor|Insert image caption . table"
  1 failed
  23 passed
```

which is the rate main (0/20) and this PR (0/12) also show at these sample
sizes. Local e2e was chromium-only; firefox is not installed in this
environment.

Co-Authored-By: Claude Opus <[email protected]>
Conflict in packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx,
where both sides added to the same file: meta#9057 on main added the bootstrap
sync tests and their createSyncedProvider/$appendInitialContent helpers, and
this branch added `provider is replaced when providerFactory changes` and its
createTestProvider helper. Both sets are kept -- they cover different things
and neither replaces the other. The `import type {Provider}` this branch added
is already on main, so only the helper and the test needed re-applying.
…d stop dead-clicking selection toggles

## Description

Four defects found by review of this branch.

**A `providerFactory` declared inline permanently disconnected the editor.**
Keying the provider effect on `providerFactory` identity means an inline arrow
-- the shape this package's own test harness uses at
`packages/lexical-react/src/__tests__/utils/index.tsx` -- has a fresh identity
on every render, so the effect's cleanup disconnected the live provider on
every parent render. When such a factory hands back a cached provider,
`setProvider()` then bails on the identical value, nothing re-runs, and the
editor stays disconnected for good. The old provider is now disconnected from
the creation path and only when a different provider actually replaces it, with
an unmount-only effect for the final teardown.

**`setSelected(false)` became a dead click.** Making it a no-op whenever the
selection is not a NodeSelection also disabled the
`clearSelection(); setSelected(!isSelected)` toggle used by
`LexicalHorizontalRuleNode`, `LexicalBlockWithAlignableContents` and five
playground decorators: `isSelected()` is true for a RangeSelection covering the
node, so after Ctrl+A the toggle arrives with `false`, does nothing, and the
node can never be selected. The no-op is now limited to the case it was meant
for -- deselecting a node the selection does not cover, where creating an empty
NodeSelection would discard the caret for no benefit -- and a covered node is
deselected as before. The docstring is corrected too: it pointed at
`clearSelected`, which is itself guarded by `$isNodeSelection` and does nothing
under a RangeSelection.

**Empty-menu key pass-through assumed the default renderer.** Letting the arrow
keys and Escape through when the option list is empty is only safe for
`defaultMenuRenderFn`. A `menuRenderFn` is public and is invoked whatever the
options look like, so a custom "no results" panel could no longer be dismissed
with Escape and the arrows moved the caret underneath it. The pass-through is
now conditional on the default renderer being in use.

**`getContainingBlockOrigin` only looked at `position`.** A `transform`,
`perspective`, `filter`, `backdrop-filter`, `contain` or a matching
`will-change` establishes a containing block on an otherwise statically
positioned element, so a transformed wrapper between the anchor's parent and
the nearest positioned ancestor left the menu offset by that element's position.

## Test plan

### Before

Five new cases fail against the unfixed source:

```
$ npx vitest run --project unit \
    packages/lexical-react/src/__tests__/unit/useLexicalNodeSelection.test.tsx \
    packages/lexical-react/src/__tests__/unit/LexicalMenuEmptyOptions.test.tsx \
    packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx
 × deselects a node the range selection does cover
 × an inline providerFactory keeps its provider connected
 × still consumes ArrowDown when a custom renderer draws an empty menu
 × still consumes ArrowUp when a custom renderer draws an empty menu
 × still consumes Escape when a custom renderer draws an empty menu
AssertionError: expected 2 to be +0 // Object.is equality
AssertionError: expected false to be true // Object.is equality
AssertionError: expected true to be false // Object.is equality
 Tests  5 failed | 15 passed (20)
```

### After

```
$ pnpm run test-unit
 Test Files  300 passed (300)
      Tests  5566 passed | 1 skipped (5567)

$ pnpm run test-browser
 Test Files  22 passed (22)
      Tests  146 passed | 1 skipped (147)

$ pnpm run ci-check
No errors!
```

Collab e2e (prod playground + y-websocket + chromium), the two nested-editor
tests that this branch has been failing, 12 runs each, twice:

```
$ npx playwright test --project=chromium --repeat-each=12 --retries=0 \
    -g "Select within nested editor|Insert image caption . table"
  2 failed / 22 passed
  24 passed
```

Matching the rate main (0/20) and this PR (0/12) show at these sample sizes.

The review also flagged that replacing the Provider destroys the Binding
without rebuilding it. That is left alone deliberately. The Binding is the live
mapping between the editor tree and the Yjs tree, so it cannot be rebuilt --
a fresh one starts with an empty collabNodeMap and the next update writes the
whole document into Yjs again -- and destroying it only on unmount instead
measured 5 failures in the same 24 runs above, against 2 and 0 for the state
committed here. Every variant tried made those nested-editor tests worse, so
the fix belongs with re-hydration support in `@lexical/yjs` rather than here.

Local e2e was chromium-only; firefox is not installed in this environment.

Co-Authored-By: Claude Opus <[email protected]>
@etrepum
etrepum enabled auto-merge August 30, 2026 17:52
@etrepum
etrepum added this pull request to the merge queue Aug 30, 2026
Merged via the queue into meta:main with commit d596c9e Aug 30, 2026
40 checks passed
@etrepum etrepum mentioned this pull request Aug 31, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — 44e9ff0c Deployed Aug 30, 2026 by vercel[bot]
Preview – lexical-playground — 44e9ff0c Deployed Aug 30, 2026 by vercel[bot]
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. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Menu Selection and Scrolling Misbehavior in Limited Lexical Editor Space

3 participants