diff --git a/packages/lexical/src/nodes/LexicalTextNode.ts b/packages/lexical/src/nodes/LexicalTextNode.ts index c735a945099..03568abe7e5 100644 --- a/packages/lexical/src/nodes/LexicalTextNode.ts +++ b/packages/lexical/src/nodes/LexicalTextNode.ts @@ -935,7 +935,7 @@ export class TextNode extends LexicalNode { return [self]; } const firstPart = parts[0]; - const parent = self.getParentOrThrow(); + const parent = self.getParent(); let writableNode; const format = self.getFormat(); const style = self.getStyle(); @@ -1005,23 +1005,25 @@ export class TextNode extends LexicalNode { } // Insert the nodes into the parent's children - internalMarkSiblingsAsDirty(this); - const writableParent = parent.getWritable(); - const insertionIndex = this.getIndexWithinParent(); - if (hasReplacedSelf) { - writableParent.splice(insertionIndex, 0, splitNodes); - this.remove(); - } else { - writableParent.splice(insertionIndex, 1, splitNodes); - } + if (parent !== null) { + internalMarkSiblingsAsDirty(this); + const writableParent = parent.getWritable(); + const insertionIndex = this.getIndexWithinParent(); + if (hasReplacedSelf) { + writableParent.splice(insertionIndex, 0, splitNodes); + this.remove(); + } else { + writableParent.splice(insertionIndex, 1, splitNodes); + } - if ($isRangeSelection(selection)) { - $updateElementSelectionOnCreateDeleteNode( - selection, - parent, - insertionIndex, - partsLength - 1, - ); + if ($isRangeSelection(selection)) { + $updateElementSelectionOnCreateDeleteNode( + selection, + parent, + insertionIndex, + partsLength - 1, + ); + } } return splitNodes; diff --git a/packages/lexical/src/nodes/__tests__/unit/LexicalTextNode.test.tsx b/packages/lexical/src/nodes/__tests__/unit/LexicalTextNode.test.tsx index b034c96814a..37191abc831 100644 --- a/packages/lexical/src/nodes/__tests__/unit/LexicalTextNode.test.tsx +++ b/packages/lexical/src/nodes/__tests__/unit/LexicalTextNode.test.tsx @@ -582,6 +582,18 @@ describe('LexicalTextNode tests', () => { }); }, ); + + test('with detached parent', async () => { + await update(() => { + const textNode = $createTextNode('foo'); + const splits = textNode.splitText(1, 2); + expect(splits.map((split) => split.getTextContent())).toEqual([ + 'f', + 'o', + 'o', + ]); + }); + }); }); describe('createDOM()', () => {