Skip to content

[Breaking Change][lexical] Feature: Generalize captured selection via setDOMUnmanaged({captureSelection}) + root __lexicalKey_* stash - #8588

Merged
etrepum merged 1 commit into
meta:mainfrom
mayrang:feat/8584-generalize-captured-selection
May 30, 2026
Merged

etrepum merged 1 commit into
meta:mainfrom
mayrang:feat/8584-generalize-captured-selection

Conversation

@mayrang

@mayrang mayrang commented May 29, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Generalizes the "selection captured outside of Lexical" mechanism that #8582 added a partial dirty-flag guard for. Before this PR, only DecoratorNode subtrees could opt out of resolution force-syncing the DOM caret back to a managed Lexical position; DOMRenderExtension overrides and getDOMSlot widgets had no equivalent way to keep a native caret.

Closes #8584.

What changed

  • setDOMUnmanaged(elementDom, options?) accepts a captureSelection: true option that marks the subtree as selection-captured — analogous to a DecoratorNode subtree. Set-only; no clear path. Re-call with a different element to revoke.
  • isDOMCapturingSelection(dom) walks ancestors so any descendant of a marked subtree (e.g. an <input> inside a marked <div>) reports as captured. Replaces internal call sites of $isSelectionCapturedInDecorator in LexicalEvents (onPointerDown, $shouldPreventDefaultAndInsertText) and LexicalSelection ($internalResolveSelectionPoint dirty-flag check).
  • The reconciler now marks every DecoratorNode DOM with setDOMUnmanaged(dom, {captureSelection: true}), unifying decorator subtrees and extension-owned unmanaged subtrees behind a single check. $isSelectionCapturedInDecorator is removed (was internal-only, no index.ts re-export).
  • The root element now carries __lexicalKey_${editor._key} = 'root' (the consistency suggestion in the second half of Feature: Generalize captured selection #8584). $getNodeFromDOM, $getNearestNodeFromDOMNode, the mutation handler in $getNearestManagedNodePairFromDOMNode, and the dirty-flag check now share the unified key lookup; per-site editor.getRootElement() carveouts are removed. New clearNodeKeyOnDOMNode clears the stash on prevRootElement during resetEditor.

Backwards compatibility

$getNearestNodeFromDOMNode(rootElement) previously returned null; it now returns RootNode. Two existing call sites become more correct as a result:

  • lexical-clipboard $insertDataTransferForRichText — drop-on-root margin used to silently fail (null), now resolves to a paragraph at the root's child-index.
  • lexical-table $fixTableSelectionForSelectedTable — isFocusOutside used to evaluate as null && ... (falsy → no-op); now correctly evaluates as truthy when DOM selection extends onto the root, so a TableSelection automatically converts to a RangeSelection. Covered by a new e2e regression test.

External callers that relied on $getNearestNodeFromDOMNode(rootElement) returning null will need to update.

Test plan

  • pnpm tsc --noEmit -p tsconfig.json, pnpm flow, prettier, eslint clean.
  • Full unit suite (pnpm vitest run --project unit) — 141 files / 2776 pass / 1 skip / 0 fail. New file LexicalDOMCapturedSelection.test.ts (12 tests) covers default vs captureSelection: true, false as a no-op (does not clear), the descendant walk, the "descendant cannot opt out when ancestor is captured" subtree invariant, the decorator subtree case (BC preserved via reconciler marking), and the editor root case (root carries a key but is not captured).
  • LexicalEditor.test.tsx:393 — assertion updated to expect RootNode (the BC).
  • e2e regression locally on chromium (1.3s), firefox (1.9s), webkit (2.1s) — pnpm test-e2e-{browser} --grep 'TableSelection converts to RangeSelection'. Covers the $fixTableSelectionForSelectedTable path.
  • ~/Desktop/lexical-knowledge/scripts/lexical-prepush.sh exits 0.

Refs #8582.

@vercel

vercel Bot commented May 29, 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, Comment May 29, 2026 7:37pm
lexical-playground Ready Ready Preview, Comment May 29, 2026 7:37pm

Request Review

@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 May 29, 2026
@etrepum etrepum added the extended-tests Run extended e2e tests on a PR label May 29, 2026
Comment thread packages/lexical/src/LexicalUtils.ts Outdated
* @deprecated Use {@link $isSelectionCaptured} instead, which also covers
* subtrees marked via {@link setDOMUnmanaged} with `{captureSelection: true}`.
*/
export function $isSelectionCapturedInDecorator(node: Node): boolean {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this one needs to be deprecated, can just be removed. isSelectionCapturedInDecoratorInput is the only one with a public export

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed — confirmed not in index.ts or Lexical.js.flow.

Comment thread packages/lexical/src/LexicalUtils.ts Resolved
@potatowagon

Copy link
Copy Markdown
Contributor

Review: Generalize Captured Selection via setDOMUnmanaged({captureSelection}) + Root _lexicalKey* Stash

Reviewed by: Navi (AI review assistant for @potatowagon)

Summary

This is a significant architectural PR that generalizes how Lexical handles selection inside unmanaged DOM subtrees. Key changes:

  1. Root element key stash: The editor root element now gets __lexicalKey_* = 'root' stamped on it (via setNodeKeyOnDOMNode), so $getNearestNodeFromDOMNode(rootElement) resolves to RootNode instead of null.
  2. setDOMUnmanaged({captureSelection: true}): New option that marks an unmanaged subtree as owning its own window selection (like decorators do).
  3. isDOMCapturingSelection(): New exported utility that walks DOM ancestors checking for the capture flag, stopping at Lexical-node boundaries.
  4. Decorator unification: DecoratorNode DOM is now automatically marked with setDOMUnmanaged({captureSelection: true}) during reconciliation, unifying the decorator and extension-owned-widget codepaths.
  5. Removes $isSelectionCapturedInDecorator: Replaced by the more general isDOMCapturingSelection.

What I Verified

  • Root element key: The resetEditor function correctly stashes/clears the key on root element swap. The $getNearestManagedNodePairFromDOMNode function no longer needs a special dom === rootElement check — the key lookup handles it generically.
  • Walk termination: isDOMCapturingSelection correctly stops at Lexical-node DOM boundaries, preventing outer wrapper capture flags from leaking into the editor.
  • Backward compatibility: DecoratorNode behavior is preserved (test: "DecoratorNode subtree still returns true").
  • Test coverage: 196-line dedicated test file + e2e test for table selection conversion when DOM selection extends to root + updated existing tests.
  • CI status: All e2e and integration tests pass on all platforms.

Breaking Change Assessment

  • setDOMUnmanaged gains an optional second parameter — existing single-arg calls still work ✅
  • $getNearestNodeFromDOMNode(rootElement) now returns RootNode instead of null — any code relying on the old null behavior would break ⚠️
  • Removed export: $isSelectionCapturedInDecorator is gone — consumers must migrate to isDOMCapturingSelection ⚠️

Concerns

  • The PR title says "[Breaking Change]" — this should go through the project's breaking change process (version bump, migration guide).
  • The removal of $isSelectionCapturedInDecorator is a public API break. Is this function used by external consumers?
  • Active discussion with @etrepum on the approach — awaiting maintainer sign-off on the architectural direction.

Verdict

⚠️ Needs maintainer approval — the implementation is high quality with excellent test coverage, but this is a breaking API change that requires architectural sign-off. The generalization of captured selection is well-motivated and cleanly implemented.

Comment thread packages/lexical/src/LexicalUtils.ts Outdated

export function clearNodeKeyOnDOMNode(dom: Node, editor: LexicalEditor) {
const prop = `__lexicalKey_${editor._key}`;
(dom as Node & Record<typeof prop, NodeKey | undefined>)[prop] = undefined;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete would probably be better for clearing

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched to delete.

Comment thread packages/lexical/src/LexicalUtils.ts Outdated
Comment on lines +2302 to +2304
if (options && options.captureSelection) {
elementDom.__lexicalCapturedSelection = true;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason we only set this to true? We could set it whenever provided, e.g.

Suggested change
if (options && options.captureSelection) {
elementDom.__lexicalCapturedSelection = true;
}
if (options && options.captureSelection !== undefined) {
elementDom.__lexicalCapturedSelection = options.captureSelection;
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied. JSDoc reworded — false now clears, omit leaves as-is. The false does not clear test flipped to expect a clear.

Comment thread packages/lexical/src/LexicalUtils.ts Outdated
Comment on lines +2337 to +2340
let dom: Node | null = elementDom;
while (dom != null) {
if ((dom as Node & LexicalPrivateDOM).__lexicalCapturedSelection === true) {
return true;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let dom: Node | null = elementDom;
while (dom != null) {
if ((dom as Node & LexicalPrivateDOM).__lexicalCapturedSelection === true) {
return true;
let dom: (Node & LexicalPrivateDOM) | null = elementDom;
while (dom != null) {
if (dom.__lexicalCapturedSelection === true) {
return true;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied.

… setDOMUnmanaged({captureSelection}) + root __lexicalKey_* stash

Closes meta#8584.

Adds `captureSelection` option to `setDOMUnmanaged` so DOMRenderExtension overrides and `getDOMSlot` widgets can opt their subtrees into decorator-like selection capture. `isDOMCapturingSelection(dom)` walks ancestors so any descendant of a marked subtree reports as captured. The reconciler now marks every DecoratorNode DOM with `setDOMUnmanaged(dom, {captureSelection: true})`, unifying decorator subtrees and extension-owned unmanaged subtrees behind a single check — `$isSelectionCapturedInDecorator` is no longer needed and is removed.

`LexicalEvents` (`onPointerDown`, `$shouldPreventDefaultAndInsertText`) and `LexicalSelection` (`$internalResolveSelectionPoint` dirty-flag check) now route through `isDOMCapturingSelection`.

For consistency (the second half of meta#8584), the root element now carries \`__lexicalKey_\${editor._key} = 'root'\`. \`$getNodeFromDOM\`, \`$getNearestNodeFromDOMNode\`, the mutation handler in \`$getNearestManagedNodePairFromDOMNode\`, and the dirty-flag check share a single key lookup; per-site \`editor.getRootElement()\` carveouts are removed.

BC: \`$getNearestNodeFromDOMNode(rootElement)\` returns RootNode instead of null. Side effects in \`lexical-clipboard\` (drop-on-root resolves) and \`lexical-table\` (\`isFocusOutside\` correctly fires when DOM selection extends onto root; new e2e regression test added).
@etrepum
etrepum added this pull request to the merge queue May 30, 2026
Merged via the queue into meta:main with commit fd2e185 May 30, 2026
73 of 77 checks passed
potatowagon added a commit to potatowagon/lexical that referenced this pull request Jun 2, 2026
…y-editor typing smoke test

Replace LexicalRootMutation.test.tsx (which manufactured the failing state by
clearing the root `__lexicalKey_*` stash up front — a state normal typing
never reaches) with a black-box test that types into a freshly-mounted empty
editor via real `beforeinput` insertText events and asserts the text
reconciles.

Honest scoping (documented in the test): this guards the basic
"type into an empty editor -> text reconciles" contract, but it does NOT
reproduce the meta#8588 regression at the jsdom level — under jsdom the root stash
is present and resolution succeeds with or without the rootElement carveout,
so it passes on both pre- and post-meta#8588 code. The regression only surfaces in
a real browser, consistent with maintainer feedback that the failure depends on
browser-specific mutation/selection timing.

The rootElement-carveout fix in LexicalMutations/LexicalUtils is retained; the
internal sync e2e is the authoritative verification and will confirm or refute it.
@etrepum etrepum mentioned this pull request Jun 25, 2026
AlessioGr added a commit to payloadcms/payload that referenced this pull request Sep 11, 2026
Upgrades `lexical` and every installed `@lexical/*` package from
`0.41.0` to `0.50.0` for Payload 3.x. Updates the dependency pins,
lockfile, and `lexicalTargetVersion`.

Also exposes the 15 React entry points added on main in
[#17554](#17554) through
`@payloadcms/richtext-lexical/lexical/react/*`, so custom features can
use these APIs through Payload.

## Breaking changes

**No application changes or data migration are needed when using
Payload's built-in rich text features.**

If you maintain custom rich text features, check that they still compile
and that custom content loads, copies, and pastes correctly. Lexical
removed some older APIs, tightened TypeScript types, and changed how
custom nodes are loaded and copied. Tests that inspect the editor's HTML
may also need updated selectors or snapshots because Lexical adds some
internal markup.

**Do not install `lexical` or `@lexical/*` yourself for use with
Payload.** Remove any direct dependencies you added for the editor and
use Payload's re-exports from `@payloadcms/richtext-lexical/lexical` and
`@payloadcms/richtext-lexical/lexical/*`. Payload supplies the matching
versions; mixing versions can break the editor. This is the existing
[custom feature
requirement](https://payloadcms.com/docs/rich-text/custom-features).

The 3.x Markdown implementation and converter defaults are preserved.
This does not backport the v4 Markdown API changes.

## Breaking changes and Payload migrations

Reviewed
[0.42.0](https://github.com/facebook/lexical/releases/tag/v0.42.0),
[0.43.0](https://github.com/facebook/lexical/releases/tag/v0.43.0),
[0.44.0](https://github.com/facebook/lexical/releases/tag/v0.44.0),
[0.45.0](https://github.com/facebook/lexical/releases/tag/v0.45.0),
[0.46.0](https://github.com/facebook/lexical/releases/tag/v0.46.0),
[0.47.0](https://github.com/facebook/lexical/releases/tag/v0.47.0),
[0.48.0](https://github.com/facebook/lexical/releases/tag/v0.48.0),
[0.49.0](https://github.com/facebook/lexical/releases/tag/v0.49.0),
[0.50.0](https://github.com/facebook/lexical/releases/tag/v0.50.0).
Listed below are breaking API/type changes and behavior changes
explicitly identified as breaking in the release notes. Deprecations and
routine bug fixes are omitted. **Yes** means we had to change Payload
code; **No** means no Payload migration was required.

| Release | Breaking change | Required migration in Payload | Changes
made |
| ------- |
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| ----------------------------- |
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| 0.42 | [Experimental `hasFitNestedTables` moves out of the table
package into the
playground](meta/lexical#8210). | No | - |
| 0.42 | [The deprecated context-menu plugin is
removed](meta/lexical#8199). | Yes | Removed
the invalid `LexicalContextMenuPlugin` proxy and package export. Custom
consumers must use
`@payloadcms/richtext-lexical/lexical/react/LexicalNodeContextMenuPlugin`
and adapt to its node-context-menu API. |
| 0.43 | [Nested editors delegate asynchronously to their
parent](meta/lexical#8308), restoring the
behavior from before 0.42.0. | No | - |
| 0.45 | [`$getReconciledDirection` now inherits direction through
shadow-root nodes](meta/lexical#8479). | No
| - |
| 0.45 | [Backspace at the start of a non-empty block preserves the
current block type and
formatting](meta/lexical#8493). | No | - |
| 0.45 | [Moving nodes between parents adjusts selection
offsets](meta/lexical#8501). | No | - |
| 0.45 | [Markdown shortcuts can trigger when IME composition
commits](meta/lexical#8503). | No | - |
| 0.45 | [Rich/plain text automatically removes empty inline
elements](meta/lexical#8497). | No | - |
| 0.45 | [Triple-click selection normalization moves from core into
rich/plain text
registration](meta/lexical#8520). Editors
bypassing that registration must add
`NormalizeTripleClickSelectionExtension`. | No | - |
| 0.45 | [`DOMSlot` and the DOM rendering override APIs are
generalized](meta/lexical#8519); playground
`AutocompleteNode` is replaced by `VisibleLineBreakExtension`. | No | -
|
| 0.46 | [`static importJSON` widens its parameter to
`SerializedLexicalNode & Record<string,
unknown>`](#17554). Overrides
using serialized interfaces can fail TypeScript checks. | No | - |
| 0.46 | [Node lookups and traversal no longer infer unchecked subclass
types](meta/lexical#8661). Explicit
unchecked traversal generics are deprecated. | Yes | Removed the upload
drawer’s assumption that a node lookup returns `UploadNode`. Added
`$isUploadNode` before reading or updating upload data. |
| 0.46 | [DOM lookups of the editor root return `RootNode` instead of
`null`](meta/lexical#8588).
Selection-capture handling is also generalized beyond decorators. | No |
- |
| 0.46 | [`insertNodes` preserves leading line breaks, and managed line
breaks receive a DOM
marker](meta/lexical#8615). | No | - |
| 0.46 | [Experimental DOM-import rules register through node
extensions](meta/lexical#8662); the separate
per-package import extensions become deprecated aliases. | No | - |
| 0.46 | [Experimental named slots change the Yjs sync
signature](meta/lexical#8603):
`syncLexicalUpdateToYjsV2__EXPERIMENTAL` gains a `dirtyLeaves`
parameter. | No | - |
| 0.46 | [Copying an element through `NodeSelection` includes its
children](meta/lexical#8603), instead of
copying an empty shell. | No | - |
| 0.46 | [Previously deprecated exports are
removed](meta/lexical#8704): `toggleLink`,
`insertList`, `removeList`, and ContentEditable’s `Props` alias.
Replacements are `$toggleLink`, `$insertList`, `$removeList`, and
`ContentEditableProps`. | No | - |
| 0.47 | [React 17 support is
removed](meta/lexical#8782); React 18 or
later is required. | No | - |
| 0.47 | [Segmented text temporarily switches to normal mode during IME
composition while keeping its
DOM](meta/lexical#8784). Subclasses must
tolerate that temporary mode. | No | - |
| 0.49 | [Built-in nodes adopt
`$config()`](meta/lexical#8640). Direct
static `importJSON`, `importDOM`, `clone`, and `transform`
implementations change; `__type` becomes readonly and automatic node
construction needs zero-argument defaults. Custom static implementations
remain supported. | No | - |
| 0.49 | [`LexicalCommand<T>` checks its payload type more
strictly](meta/lexical#8877).
`LexicalCommand<unknown>` is no longer a safe catch-all. | Yes | Focus
and blur commands were incorrectly registered with `MouseEvent`. Removed
the explicit types so Lexical infers `FocusEvent`. |
| 0.50 | [Named-slot values cannot be replaced with
`LexicalNode.replace()`](meta/lexical#8938).
Block converters also [skip slot
values](meta/lexical#8905). | No | - |
| 0.50 | [Lexical JSON clipboard copying checks
`excludeFromCopy('clone')`, not
`'html'`](meta/lexical#8995). | No | - |

Also updated the copied table action menu for merged-cell bounds, header
toggles, and merge/unmerge selection, and fixed the upload alignment
test’s image selector. Formatting and diff checks pass for the upload
selector fix.

Verified all 15 new entry points through source and published export
maps with runtime imports and TypeScript checks. ESLint and formatting
checks pass.

## Previous Lexical upgrades

- [#15760](#15760) — 0.35.0 →
0.41.0
- [#13715](#13715) — 0.34.0 →
0.35.0
- [#13622](#13622) — 0.28.0 →
0.34.0

This branch was successfully deployed

2 active deployments
Preview – lexical — ce6dd0a1 Deployed May 29, 2026 by vercel[bot]
Preview – lexical-playground — ce6dd0a1 Deployed May 29, 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.

Feature: Generalize captured selection

3 participants