Skip to content

[lexical] Bug Fix: insertText no longer throws when the caret is inside a segmented TextNode - #9104

Merged
etrepum merged 2 commits into
meta:mainfrom
Om-singhaI:fix/segmented-insert-text-stale-anchor
Aug 29, 2026
Merged

etrepum merged 2 commits into
meta:mainfrom
Om-singhaI:fix/segmented-insert-text-stale-anchor

Conversation

@Om-singhaI

Copy link
Copy Markdown
Contributor

[lexical] Bug Fix: insertText no longer throws when the caret is inside a segmented TextNode

Description

Current behavior: typing one character with the caret anywhere strictly inside a segmented TextNode throws Expected node N to have a parent. out of RangeSelection.insertText. The character is dropped and the document is left untouched.

editor.update(() => {
  const segmented = $createTextNode('JohnSmith').setMode('segmented');
  $getRoot().clear().append($createParagraphNode().append(segmented));
  segmented.select(4, 4).insertText('X');
}, {discrete: true});

// Error: Expected node 2 to have a parent.
//   at TextNode.getParentOrThrow (LexicalNode.ts:1062)
//   at RangeSelection.insertText (LexicalSelection.ts:944)
//   at RangeSelection.insertText (LexicalSelection.ts:973)
// the paragraph still reads JohnSmith

Expected, and what this PR produces: JohnXSmith, the node no longer segmented, caret collapsed at offset 5.

That is also what the documentation promises. packages/lexical-website/docs/concepts/nodes.mdx describes segmented mode as one where the node "is editable although node becomes non-segmented once its content is updated".

This is reached by an ordinary keystroke, not only by API callers. $shouldPreventDefaultAndInsertText counts $isTokenOrSegmented(anchorNode) among the reasons to preventDefault (packages/lexical/src/LexicalEvents.ts), so a caret on a segmented node routes the character through CONTROLLED_TEXT_INSERTION_COMMAND, and the rich text handler for that command calls selection.insertText(...) on $getSelection() (packages/lexical-rich-text/src/index.ts). That is the call that throws, and because the selection there is the current one it is the exact shape the repro above uses. Segmented mode is the usual way to build mention and entity nodes, and the playground's own MentionNode opts into it (mentionNode.setMode('segmented')), so putting the caret inside a mention and typing raises an uncaught invariant and fires the editor's onError. Applications with mentions, chips, or hashtags as entities are affected.

Mechanism

Inside the needsRedirect branch of insertText, a segmented node with the caret inside it is converted to a plain TextNode and then insertText recurses. The branch without composition did:

const replacement = $createTextNode(anchorNode.getTextContent());
replacement.setFormat(format);
replacement.setStyle(style);
anchorNode.replace(replacement);
replacement.select(offset, offset);

LexicalNode.replace() clones the active selection when it is entered and commits that clone with $setSelection before it returns, so once it returns the editor's current selection is a different object from this. TextNode.select() then repositions whatever $getSelection() gives it, which is that clone, and this is left pointing at the segmented node replace() has just detached. The recursive this.insertText(text) runs against the stale anchor, anchorNode.getParentOrThrow() finds no parent, and the invariant fires.

I confirmed the object identity directly rather than inferring it. Immediately after replace() returns, with the caret at offset 4 of JohnSmith: the segmented node is key 46 and detached, this.anchor.key is still 46, $getSelection() === this is false, and the current selection anchors on key 48, the replacement.

The branch with composition is unaffected because setMode('normal') keeps the same node key attached, which is why the asymmetry went unnoticed.

The three existing tests in describe('Segmented node composition (#5065)') all call insertText(''), and the empty string is exactly the value that skips if (text !== '') { this.insertText(text) }, so the recursion is never exercised.

Regression window

The recursion arrived with #8870, which was titled a refactor. Before it, this branch assigned firstNode = textNode and carried on inline in the same call, so there was no stale this to go wrong. I ran the same offset sweep against its parent commit and every offset inserted correctly there; the numbers are in the test plan below.

The change

It moves this onto the replacement before recursing, and makes it current again when it was current on entry. That is the same sequence removeText() already performs a few lines further down the same file:

const isCurrentSelection = $getSelection() === this;
...
if (isCurrentSelection && $getSelection() !== this) {
  $setSelection(this);
}

One deliberate difference worth flagging for review: replacement.select(offset, offset) is dropped rather than kept alongside the new positioning. When this is the current selection, which is the case on the keystroke path above, the two are equivalent. When it is not, the old line reached past this and moved an unrelated active selection onto the replacement, or installed a new one when there was no selection at all; now an existing selection stays where replace() left it and a null selection stays null. The composition key transfer inside TextNode.select() cannot apply here either, since this branch only runs when $getCompositionKey() is null.

Test plan

Before

Sweeping every caret offset of a nine character segmented node on main, inserting one character at each:

offset=0  ok    XJohnSmith
offset=1  Error: Expected node 10 to have a parent.
offset=2  Error: Expected node 14 to have a parent.
offset=3  Error: Expected node 18 to have a parent.
offset=4  Error: Expected node 22 to have a parent.
offset=5  Error: Expected node 26 to have a parent.
offset=6  Error: Expected node 30 to have a parent.
offset=7  Error: Expected node 34 to have a parent.
offset=8  Error: Expected node 38 to have a parent.
offset=9  ok    JohnSmithX

Every interior offset throws. The two boundaries are fine because they take the other paths out of needsRedirect. The same sweep against the parent of #8870 returns no error at any offset and gives JohnXSmith at offset 4, so this is a behavior that regressed rather than one that was never there.

The new test is insertText without composition types into a segmented node, added next to the existing non composition test in describe('Segmented node composition (#5065)'). Reverting only packages/lexical/src/LexicalSelection.ts to its previous state and keeping the test:

 × insertText without composition types into a segmented node 7ms

 FAIL  |unit| packages/lexical/src/__tests__/unit/LexicalSelection.test.ts > Segmented node composition (#5065) > insertText without composition types into a segmented node
Error: Expected node 164 to have a parent.
 ❯ invariant packages/lexical-internal/src/invariant.ts:28:9
 ❯ TextNode.getParentOrThrow packages/lexical/src/LexicalNode.ts:1062:7
 ❯ RangeSelection.insertText packages/lexical/src/LexicalSelection.ts:944:37
 ❯ RangeSelection.insertText packages/lexical/src/LexicalSelection.ts:973:16

 Test Files  1 failed (1)
      Tests  1 failed | 94 passed (95)

The two insertText frames in that stack are the recursion described above.

After

Restoring the change, the same file is green:

 Test Files  1 passed (1)
      Tests  95 passed (95)

vitest --project unit --project scripts-unit --no-watch over the whole repository:

 Test Files  271 passed (271)
      Tests  5435 passed | 1 skipped (5436)

The one skipped test predates this change. tsc, eslint ./, prettier --list-different . and the flow check are all clean. The browser, integration and e2e suites were not run.

@vercel

vercel Bot commented Aug 28, 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 28, 2026 8:34pm
lexical-playground Ready Ready Preview Aug 28, 2026 8:34pm

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 Aug 28, 2026
@etrepum etrepum added the extended-tests Run extended e2e tests on a PR label Aug 28, 2026
@etrepum
etrepum added this pull request to the merge queue Aug 29, 2026
Merged via the queue into meta:main with commit bec2dfe Aug 29, 2026
44 checks passed
@etrepum etrepum mentioned this pull request Aug 31, 2026

This branch was successfully deployed

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

2 participants