Repository navigation
[Breaking Change][lexical] Bug Fix: Adjust selection when removeFromParent callers move a node out of its parent - #8501
Conversation
…e a node out of its parent `removeFromParent` is a low-level pointer-only operation that does not touch the editor's selection. `replace`, `insertAfter`, and `insertBefore` call it as part of moving a node from one parent to another, but they did not adjust element-anchored offsets in the old parent, leaving them stale (and sometimes out of range) once the old parent's child count dropped. Each of the three call sites now captures the moved node's old parent and index before `removeFromParent`, then calls `$updateElementSelectionOnCreateDeleteNode(..., -1)` so any element-anchored offset past the removed index shifts by one. The existing post-insertion adjustment is unchanged, so within-parent moves also stay in range. `removeFromParent` keeps its signature; its JSDoc now documents the caller contract. Closes meta#6031.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
It might make sense to extend this sort of behavior to other methods, e.g. replace which currently has a $moveSelectionPointToEnd workaround that we are probably better off not having because other functions end up having to undo it like $setBlocksType const parent = $createParagraphNode().append($createLineBreakNode(), $createLineBreakNode(), $createLineBreakNode());
$getRoot().clear().append(parent);
parent.select(1,1);
const newParent = $createParagraphNode().append('before');
const prevSize = newParent.getChildrenSize();
parent.replace(newParent, true);
const selection = $getSelection();
assert($isRangeSelection(selection));
expect(selection.isCollapsed()).toBe(true);
expect(selection.anchor).toMatchObject({key: newParent.getKey(), offset: prevSize + 1}); |
…aps element-anchored points by prevSize + originalOffset Per meta#8501 review feedback (meta#8501 (comment)): extend the selection-tracks-node-mutation pattern from meta#6031 to `replace`'s element-anchored case. Previously, an element-anchored point on the replaced node was relocated to the receiver's last descendant via `$moveSelectionPointToEnd`, losing the relative position. The point now maps to `{key: other.__key, offset: prevSize + originalOffset, type: 'element'}` where `prevSize = other.getChildrenSize()` before the children transfer. Receivers with no pre-existing children (`$setBlocksType`'s freshly-created receivers) see `prevSize = 0`, so the original offset is preserved end-to-end. Falls back to the legacy `$moveSelectionPointToEnd` for `!includeChildren` (children destroyed, no relative position to preserve) and for non-element points (text-anchored selections inside transferred children follow their text node's key, which is preserved across the transfer). Tests cover the maintainer's snippet plus non-collapsed, text-anchored, !includeChildren-legacy, and prevSize=0 shapes.
|
Applied the Held back on the |
|
I think that's a good rationale for a follow-up, and maybe while we're in there it would make sense to do some general cleanup/optimization by using |
|
Thanks — tried the swap locally on the |
…ntralize replace-area selection mapping + bulk splice Follow-up to meta#8501. The base LexicalNode.replace now maps element-anchored selections from the replaced node to {key: replacement, offset: prevSize + originalOffset, type: 'element'}. Two pieces were held back for this PR: the same mapping in ListItemNode.replace (an override that bypasses super.replace), and removal of the \$setBlocksType workaround that compensated for the lossy pre-meta#8501 behavior. ListItemNode.replace now mirrors the base prevSize + offset mapping in the includeChildren branch. The mapping runs before the trailing this.remove() so the subsequent \$removeNode → moveSelectionPointToSibling sees anchor/focus already redirected and is a no-op for those points. Text-anchored selections inside transferred children follow their text node's key across the children move, so no extra mapping is needed there. \$setBlocksType drops the cloned-newSelection + per-iteration override + selection.is(\$getSelection()) commit. Both replace paths now handle the mapping, making the caller-side workaround redundant. getChildren().forEach(parent.append) patterns collapse to parent.splice(parent.getChildrenSize(), 0, getChildren()) at four sites: base LexicalNode.replace, ListItemNode.replace, \$setBlocksType's wrap branch, and \$toggleLink's unlink branch. Since append is splice-of-1, this is one bookkeeping pass instead of N. \$toggleLink also switches to parentLink.getParentOrThrow() to keep the existence assertion loud.
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
Description
LexicalNode.prototype.replace,insertAfter, andinsertBeforemove a node from one parent to another by calling the internalremoveFromParenthelper, then re-wiring the node into its new home.removeFromParentis a low-level pointer-only operation that does not touch the editor's selection, and the three callers also did not adjust element-anchored offsets in the old parent. An{key: oldParentKey, type: 'element', offset: N}selection withN > removedIndexwas left pointing past the now-shrunk parent's last child, sometimes out of range entirely (e.g. cursor at end of source, mover at index 0).Each caller now captures the moved node's old parent and index before
removeFromParent, then calls$updateElementSelectionOnCreateDeleteNode(selection, oldParent, oldIndex, -1)so element-anchored offsets past the removed index shift by one. The existing post-insertion+1adjustment ininsertBefore/insertAfteris unchanged, so within-parent moves stay in range throughout — previously the cursor at end of source went out of range while the parent was momentarily shrunk before the re-insertion.The fix lives in the callers rather than
removeFromParentbecause importing$updateElementSelectionOnCreateDeleteNodeintoLexicalUtils.tscreates a circular dependency withLexicalSelection.ts(fails atTabNode extends TextNodeload withClass extends value undefined).removeFromParentkeeps its signature; its JSDoc now documents the caller contract and points at the four call sites ($removeNode,replace,insertBefore,insertAfter) that follow the pattern.Per review feedback (#8501 (comment)) the same selection-tracks-node-mutation pattern is also applied inside
replace's element-anchored case: instead of$moveSelectionPointToEndrelocating the point to the receiver's last descendant, the point now maps to{key: other.__key, offset: prevSize + originalOffset, type: 'element'}whereprevSizeisother.getChildrenSize()before the children transfer. Receivers with no pre-existing children (e.g.$setBlocksType's freshly-created receivers) seeprevSize = 0so the original offset is preserved end-to-end.$moveSelectionPointToEndstays as the fallback for!includeChildren(children destroyed, no relative position to preserve) and non-element points (text-anchored selections inside transferred children follow their text node's key, preserved across the transfer).Breaking Change
Public methods now adjust the editor's selection differently after a node move:
replace/insertAfter/insertBefore. Previously, an element-anchored selection in the source parent withoffset > removedIndexwas left unadjusted, sometimes pointing past the parent's last child. Now the offset shifts by-1. Downstream code that read$getSelection()immediately after one of these calls and relied on the stale offset will observe a different value.insertBefore/insertAfter/replace. Previously the cursor at the end of the parent could briefly be left out of range whileremoveFromParentshrank the parent before the re-insertion grew it back. Now the pre-removal-1shift composes with the existing post-insertion+1, so element-anchored offsets stay in range. Forreplace, this also means a within-parent cursor past the removed slot now shifts by-1instead of staying put, matching the cross-parent case.replace(other, true)with an element-anchored point on the replaced node. Previously,$moveSelectionPointToEndrelocated the point to the receiver's last descendant, losing the relative position. Now the point maps to{key: other.__key, offset: prevSize + originalOffset, type: 'element'}whereprevSize = other.getChildrenSize()before the children transfer. Receivers with no pre-existing children (e.g.$setBlocksType's freshly-created receivers) seeprevSize = 0, so the original offset is preserved. The legacy$moveSelectionPointToEndfallback is kept for!includeChildrenand non-element points (where there's no children-mapping to preserve).Closes #6031
Test plan
pnpm vitest run --project unit— 114 files / 2540 tests pass. ExistingElement-anchored selection on old parent (#6031)block plus the newreplace(other, includeChildren) selection mappingblock inLexicalNode.test.ts:test.forover the three methods covering: cross-parent past-boundary shift / boundary preservation / non-collapsed selection / unrelated-parent untouched /restoreSelection: falseskip / within-parent no-op end-cursor preservation.replaceselection mapping block — element-anchored point maps toprevSize + originalOffset(etrepum's snippet) / non-collapsed anchor+focus both shift / text-anchored selection inside transferred children unaffected /!includeChildrenfalls back to legacy$moveSelectionPointToEnd/ fresh-receiver (prevSize=0) preserves original offset.pnpm tsc --noEmit -p tsconfig.jsonclean.