From d145eca6e8df0d03dda7475701fc457f1baacc92 Mon Sep 17 00:00:00 2001 From: vishisht31 Date: Tue, 17 Nov 2026 23:29:45 +0530 Subject: [PATCH] [lexical][lexical-extension][lexical-yjs][lexical-website] Feature: Add $deepCopy to the public API $copyNode copies only the node itself, so duplicating a block with its content meant writing a recursive copy by hand. Three identical private $deepCopy helpers already existed in the BlockId tests. Add $deepCopy(node) to lexical. It returns a detached copy of the node and its whole subtree, named slots included, all with new keys. The copy is made by serializing the subtree and parsing it back, so it keeps everything a Lexical-JSON paste keeps, including NodeState: - resetOnCopyNodeFrom is not called and resetOnCopyNode state is kept, unlike $copyNode. - A descendant element whose excludeFromCopy('clone') returns true is left out and its children take its place, as with the clipboard. The node passed in and each slot value are always copied. - The RootNode cannot be copied: RootNode.importJSON returns the existing root, so parsing would append the copy to the live document. The private helpers in the BlockIdExtension and BlockId collab tests are replaced by the public export. The Node Cloning docs gain a $deepCopy section and a note on choosing between it and $copyNode. Closes #9898 --- .changeset/lexical-deep-copy.md | 11 + .../unit/BlockIdExtension.property.test.ts | 14 +- .../__tests__/unit/BlockIdExtension.test.ts | 14 +- .../docs/concepts/node-cloning.md | 51 +- .../src/__tests__/unit/BlockIdCollab.test.ts | 2 +- .../__tests__/unit/BlockIdCollabFuzz.test.ts | 2 +- .../src/__tests__/unit/utils/blockIdPeers.ts | 15 - packages/lexical/flow/Lexical.js.flow | 1 + packages/lexical/src/LexicalUtils.ts | 75 +++ .../__tests__/unit/LexicalDeepCopy.test.ts | 472 ++++++++++++++++++ packages/lexical/src/index.ts | 1 + 11 files changed, 614 insertions(+), 44 deletions(-) create mode 100644 .changeset/lexical-deep-copy.md create mode 100644 packages/lexical/src/__tests__/unit/LexicalDeepCopy.test.ts diff --git a/.changeset/lexical-deep-copy.md b/.changeset/lexical-deep-copy.md new file mode 100644 index 000000000000..9a4a018087ec --- /dev/null +++ b/.changeset/lexical-deep-copy.md @@ -0,0 +1,11 @@ +--- +'lexical': patch +--- + +[feature] Add `$deepCopy` to copy a node together with its children and slots + +`$copyNode` copies only the node itself. `$deepCopy(node)` returns a detached +copy of the node and its whole subtree, named slots included, all with new +keys. It keeps NodeState, like a Lexical-JSON paste, and leaves out +descendants that are excluded from clones. Use it for features such as +"Duplicate block". diff --git a/packages/lexical-extension/src/__tests__/unit/BlockIdExtension.property.test.ts b/packages/lexical-extension/src/__tests__/unit/BlockIdExtension.property.test.ts index c3bb647dc548..46a0a885b618 100644 --- a/packages/lexical-extension/src/__tests__/unit/BlockIdExtension.property.test.ts +++ b/packages/lexical-extension/src/__tests__/unit/BlockIdExtension.property.test.ts @@ -51,6 +51,7 @@ import { import { $createParagraphNode, $createTextNode, + $deepCopy, $getRoot, $getSelection, $getSlot, @@ -59,7 +60,6 @@ import { $isParagraphNode, $isRangeSelection, $isTextNode, - $parseSerializedNode, $setSelection, configExtension, DELETE_CHARACTER_COMMAND, @@ -73,7 +73,6 @@ import { OUTDENT_CONTENT_COMMAND, REDO_COMMAND, type SerializedEditorState, - type SerializedElementNode, type SerializedLexicalNode, UNDO_COMMAND, } from 'lexical'; @@ -113,17 +112,6 @@ function $p(text: string): ElementNode { return $createParagraphNode().append($createTextNode(text)); } -function $deepCopy(node: T): T { - const serialize = (n: LexicalNode): SerializedLexicalNode => { - const json = n.exportJSON(); - if ($isElementNode(n)) { - (json as SerializedElementNode).children = n.getChildren().map(serialize); - } - return json; - }; - return $parseSerializedNode(serialize(node)) as T; -} - /** Every node below the root in document order (slots before children). */ function $all(): LexicalNode[] { const out: LexicalNode[] = []; diff --git a/packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts b/packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts index 13799110158e..2249f154381c 100644 --- a/packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts +++ b/packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts @@ -63,6 +63,7 @@ import { $create, $createParagraphNode, $createTextNode, + $deepCopy, $getRoot, $getSelection, $getState, @@ -86,7 +87,6 @@ import { PASTE_TAG, REDO_COMMAND, type SerializedEditorState, - type SerializedElementNode, type SerializedLexicalNode, UNDO_COMMAND, } from 'lexical'; @@ -234,18 +234,6 @@ function $paragraph(text: string): ElementNode { return $createParagraphNode().append($createTextNode(text)); } -/** A deep copy that keeps NodeState, as a Lexical-JSON paste does. */ -function $deepCopy(node: T): T { - const serialize = (n: LexicalNode): SerializedLexicalNode => { - const json = n.exportJSON(); - if ($isElementNode(n)) { - (json as SerializedElementNode).children = n.getChildren().map(serialize); - } - return json; - }; - return $parseSerializedNode(serialize(node)) as T; -} - function $nth(index: number): ElementNode { const node = $getRoot().getChildAtIndex(index); assert($isElementNode(node), `child ${index} is an element`); diff --git a/packages/lexical-website/docs/concepts/node-cloning.md b/packages/lexical-website/docs/concepts/node-cloning.md index 68d4d0c970f7..a10ac72ca834 100644 --- a/packages/lexical-website/docs/concepts/node-cloning.md +++ b/packages/lexical-website/docs/concepts/node-cloning.md @@ -8,7 +8,8 @@ Lexical provides several ways to clone nodes, each serving a different purpose: 1. `static clone()` - Internal API for state management 2. `$copyNode()` - Public API for creating new nodes -3. `getWritable()` - Public API for node modifications +3. `$deepCopy()` - Public API for copying a node together with its subtree +4. `getWritable()` - Public API for node modifications ## The `clone` Method @@ -144,6 +145,49 @@ const copy = $copyNode(existingNode); someParent.append(duplicate); ``` +`$copyNode` is shallow: the copy has no children. To copy a node together +with everything inside it, use [`$deepCopy`](#using-deepcopy). + +## Using `$deepCopy` + +### What is `$deepCopy`? + +`$deepCopy` returns a copy of a node, its children and its named slots, +recursively, all with new keys. It works by serializing the subtree to +Lexical JSON and parsing it back, so the copy keeps everything a Lexical JSON +paste keeps, including [NodeState](./node-state.md). Like `$copyNode`, the +copy is detached and you insert it yourself. + +Because the copy is made from JSON, only what the node's `exportJSON` writes +is copied; anything it keeps only in memory is not. + +Unlike `$copyNode`, the copy is not reset: `resetOnCopyNodeFrom` is not +called, and NodeState declared with `resetOnCopyNode` keeps its value. A copied +list item stays checked and a copied block keeps its block id, just as it would +when pasted; an extension that needs unique values (such as `BlockIdExtension`) +fixes them when the copy is inserted. + +A descendant element whose `excludeFromCopy('clone')` returns `true` is left +out of the copy and its children take its place, the same as when copying to +the clipboard; that element's own NodeState and slots are not copied. The node +you pass in, and the value of each slot, are always copied. + +The `RootNode` cannot be copied; to copy a whole document, copy each of the +root's children. + +```typescript +// ✅ Correct: Duplicating a block with its content +const duplicate = $deepCopy(paragraph); +paragraph.insertAfter(duplicate); +``` + +### `$copyNode` or `$deepCopy`? + +- Use `$copyNode` when you want the node alone, for example to wrap or + replace a node and then move its existing children into the new one. +- Use `$deepCopy` when you want an independent duplicate of the whole + subtree, for example for a "Duplicate block" command. + ## Using `getWritable` ### What is `getWritable`? @@ -191,6 +235,11 @@ function $duplicateNode(node: MyCustomNode): MyCustomNode { return $copyNode(node); } +// ✅ Correct: Copying a node and its children +function $duplicateBlock(node: ElementNode): ElementNode { + return $deepCopy(node); +} + // ❌ Incorrect: Don't use clone function $duplicateNodeWrong(node: MyCustomNode): MyCustomNode { return node.constructor.clone(node); diff --git a/packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts b/packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts index 6bb1f196adfe..c1a25ae1806a 100644 --- a/packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts +++ b/packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts @@ -15,6 +15,7 @@ import {$setBlocksType} from '@lexical/selection'; import { $createParagraphNode, $createTextNode, + $deepCopy, $getRoot, $getSelection, INSERT_PARAGRAPH_COMMAND, @@ -24,7 +25,6 @@ import {afterEach, describe, expect, test} from 'vitest'; import { $block, $caretAt, - $deepCopy, $enter, $join, $type, diff --git a/packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts b/packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts index fb8bbd1b8dd1..57f06316ce73 100644 --- a/packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts +++ b/packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts @@ -33,6 +33,7 @@ import {$setBlocksType} from '@lexical/selection'; import { $createParagraphNode, $createTextNode, + $deepCopy, $getRoot, $getSelection, $isElementNode, @@ -45,7 +46,6 @@ import {afterEach, describe, expect, test} from 'vitest'; import { $block, $caretAt, - $deepCopy, $enter, $join, $type, diff --git a/packages/lexical-yjs/src/__tests__/unit/utils/blockIdPeers.ts b/packages/lexical-yjs/src/__tests__/unit/utils/blockIdPeers.ts index d5d83313df87..c3172f728693 100644 --- a/packages/lexical-yjs/src/__tests__/unit/utils/blockIdPeers.ts +++ b/packages/lexical-yjs/src/__tests__/unit/utils/blockIdPeers.ts @@ -38,7 +38,6 @@ import { $isElementNode, $isRangeSelection, $isRootNode, - $parseSerializedNode, COLLABORATION_TAG, configExtension, DELETE_CHARACTER_COMMAND, @@ -48,8 +47,6 @@ import { type LexicalEditor, type LexicalNode, type SerializedEditorState, - type SerializedElementNode, - type SerializedLexicalNode, SKIP_COLLAB_TAG, } from 'lexical'; import { @@ -444,18 +441,6 @@ export function readIds( } } -/** A deep copy that keeps NodeState, as a Lexical-JSON paste does. */ -export function $deepCopy(node: T): T { - const serialize = (n: LexicalNode): SerializedLexicalNode => { - const json = n.exportJSON(); - if ($isElementNode(n)) { - (json as SerializedElementNode).children = n.getChildren().map(serialize); - } - return json; - }; - return $parseSerializedNode(serialize(node)) as T; -} - export function $block(index: number): ElementNode { const node = $getRoot().getChildAtIndex(index); if (!$isElementNode(node)) { diff --git a/packages/lexical/flow/Lexical.js.flow b/packages/lexical/flow/Lexical.js.flow index 66058541cbd9..ab4a3ff40b7e 100644 --- a/packages/lexical/flow/Lexical.js.flow +++ b/packages/lexical/flow/Lexical.js.flow @@ -1354,6 +1354,7 @@ declare export function $setFormatFromDOM( declare export function $cloneWithProperties(node: T): T; declare export function $cloneWithPropertiesEphemeral(node: T): T; declare export function $copyNode(node: T, skipReset?: boolean): T; +declare export function $deepCopy(node: T): T; declare export function $getDocument(): Document; declare export function $getEditor(): LexicalEditor; /** @internal */ diff --git a/packages/lexical/src/LexicalUtils.ts b/packages/lexical/src/LexicalUtils.ts index 7f9cbbbe1e7d..2c0130c8bb0c 100644 --- a/packages/lexical/src/LexicalUtils.ts +++ b/packages/lexical/src/LexicalUtils.ts @@ -111,13 +111,16 @@ import { type PointType, type RangeSelection, } from './LexicalSelection'; +import {$exportNodeJSON} from './LexicalSerializedExport'; import { $getSlot, $getSlotHostKey, + $getSlotNames, $isSlotChild, $isSlotHost, } from './LexicalSlot'; import { + $parseSerializedNode, errorOnInfiniteTransforms, errorOnReadOnly, getActiveEditor, @@ -2103,6 +2106,78 @@ export function $copyNode( return copy; } +/** + * Returns a deep copy of node: the node itself, its children and its named + * slots, recursively, all with new keys. The copy is built by serializing the + * subtree and parsing it back, so it keeps everything a Lexical-JSON paste + * keeps (including NodeState). Like {@link $copyNode}, the copy is detached + * and must be separately added to the document. + * + * Unlike {@link $copyNode}, the copy is not reset: `resetOnCopyNodeFrom` is + * not called and NodeState declared with `resetOnCopyNode` keeps its value + * (a block id, a checked task), just as it would in a pasted copy. Properties + * that `exportJSON` does not write are not copied. + * + * A descendant ElementNode whose `excludeFromCopy('clone')` returns true is + * left out and its children take its place, as with the clipboard; its own + * NodeState and slots are not copied. The node passed in, and the value of + * each slot, are always copied. + * + * @param node - The node to be copied. It must not be the RootNode, which + * cannot be copied (copy its children instead). + * @returns The copy of the node and its subtree. + */ +export function $deepCopy(node: T): T { + // RootNode.importJSON returns the existing root rather than a new node, so + // parsing would append the copied children to the live document. + invariant( + !$isRootNode(node), + '$deepCopy: the RootNode cannot be copied, copy its children instead', + ); + return $parseSerializedNode($serializeForDeepCopy(node)) as T; +} + +// The same walk as $exportNodeToJSON in LexicalEditorState, plus the +// excludeFromCopy splice the clipboard export does; keep them in step. +function $serializeForDeepCopy(node: LexicalNode): SerializedLexicalNode { + const serializedNode = $exportNodeJSON(node) as SerializedLexicalNode; + if ($isElementNode(node)) { + const children: SerializedLexicalNode[] = []; + $appendDeepCopyChildren(node, children); + (serializedNode as SerializedLexicalNode & {children: unknown}).children = + children; + } + const slotNames = $getSlotNames(node); + if (slotNames.length > 0) { + const slots: Record = {}; + for (const name of slotNames) { + const slotNode = $getSlot(node, name); + invariant( + slotNode !== null, + '$deepCopy: Node %s has slot "%s" but it resolved to no node', + node.constructor.name, + name, + ); + slots[name] = $serializeForDeepCopy(slotNode); + } + serializedNode.$slots = slots; + } + return serializedNode; +} + +function $appendDeepCopyChildren( + parent: ElementNode, + target: SerializedLexicalNode[], +): void { + for (const child of parent.getChildren()) { + if ($isElementNode(child) && child.excludeFromCopy('clone')) { + $appendDeepCopyChildren(child, target); + } else { + target.push($serializeForDeepCopy(child)); + } + } +} + /** Applies any registered node replacement for the given node's type, returning the replacement node or the original if none is registered. */ export function $applyNodeReplacement(node: N): N { const editor = getActiveEditor(); diff --git a/packages/lexical/src/__tests__/unit/LexicalDeepCopy.test.ts b/packages/lexical/src/__tests__/unit/LexicalDeepCopy.test.ts new file mode 100644 index 000000000000..9f0a36f61a45 --- /dev/null +++ b/packages/lexical/src/__tests__/unit/LexicalDeepCopy.test.ts @@ -0,0 +1,472 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import {buildEditorFromExtensions} from '@lexical/extension'; +import {assert, describe, expect, test} from 'vitest'; + +import { + $copyNode, + $create, + $createParagraphNode, + $createTextNode, + $deepCopy, + $getRoot, + $getSlot, + $getSlotNames, + $getState, + $isElementNode, + $isParagraphNode, + $isTextNode, + $setSlot, + $setState, + createState, + DecoratorNode, + defineExtension, + ElementNode, + type LexicalNode, + type ParagraphNode, +} from '../..'; + +const colorState = createState('deep-copy-color', { + parse: v => (typeof v === 'string' ? v : ''), +}); + +// Reset by $copyNode, so it tells the two copies apart. +const resetState = createState('deep-copy-reset', { + parse: v => (typeof v === 'string' ? v : ''), + resetOnCopyNode: true, +}); + +// A block decorator, to check that slots on a non-element host are copied. +class SlotDecoratorNode extends DecoratorNode { + $config() { + return this.config('deep_copy_slot_decorator', {extends: DecoratorNode}); + } + createDOM(): HTMLElement { + return document.createElement('div'); + } + updateDOM(): boolean { + return false; + } + decorate(): null { + return null; + } +} + +// A shadow-root block used as a slot value. +class SlotContainerNode extends ElementNode { + $config() { + return this.config('deep_copy_slot_container', {extends: ElementNode}); + } + createDOM(): HTMLElement { + return document.createElement('div'); + } + updateDOM(): boolean { + return false; + } + isShadowRoot(): boolean { + return true; + } +} + +// An inline wrapper that asks to be dropped from clones, keeping its children. +class UncopiedWrapperNode extends ElementNode { + $config() { + return this.config('deep_copy_uncopied_wrapper', {extends: ElementNode}); + } + createDOM(): HTMLElement { + return document.createElement('span'); + } + updateDOM(): boolean { + return false; + } + isInline(): boolean { + return true; + } + excludeFromCopy(destination?: 'clone' | 'html'): boolean { + return destination === 'clone'; + } +} + +function buildEditor() { + return buildEditorFromExtensions( + defineExtension({ + $initialEditorState: null, + name: '[deep-copy]', + nodes: [SlotContainerNode, SlotDecoratorNode, UncopiedWrapperNode], + }), + ); +} + +/** The keys of node and everything below it, slots included. */ +function $keys(node: LexicalNode): string[] { + const keys = [node.getKey()]; + for (const name of $getSlotNames(node)) { + const slot = $getSlot(node, name); + assert(slot !== null, `slot ${name} resolves`); + keys.push(...$keys(slot)); + } + if ($isElementNode(node)) { + for (const child of node.getChildren()) { + keys.push(...$keys(child)); + } + } + return keys; +} + +function $title(text: string): SlotContainerNode { + return $create(SlotContainerNode).append( + $createParagraphNode().append($createTextNode(text)), + ); +} + +function $expectNoSharedKeys(original: LexicalNode, copy: LexicalNode) { + const originalKeys = new Set($keys(original)); + for (const key of $keys(copy)) { + expect(originalKeys.has(key)).toBe(false); + } +} + +describe('$deepCopy', () => { + test('copies the node and all of its descendants with new keys', () => { + using editor = buildEditor(); + editor.update( + () => { + const original = $createParagraphNode().append( + $createTextNode('Hello ').toggleFormat('bold'), + $createTextNode('world'), + ); + $getRoot().clear().append(original); + + const copy = $deepCopy(original); + $getRoot().append(copy); + + expect($isParagraphNode(copy)).toBe(true); + expect(copy.getTextContent()).toBe('Hello world'); + const [first, second] = copy.getChildren(); + assert($isTextNode(first) && $isTextNode(second)); + expect(first.hasFormat('bold')).toBe(true); + expect(second.hasFormat('bold')).toBe(false); + + const originalKeys = new Set($keys(original)); + for (const key of $keys(copy)) { + expect(originalKeys.has(key)).toBe(false); + } + }, + {discrete: true}, + ); + }); + + test('returns a detached copy that does not alias the original', () => { + using editor = buildEditor(); + editor.update( + () => { + const original = $createParagraphNode().append( + $createTextNode('original'), + ); + $getRoot().clear().append(original); + + const copy = $deepCopy(original); + expect(copy.getParent()).toBe(null); + + $getRoot().append(copy); + const text = copy.getFirstChild(); + assert($isTextNode(text)); + text.setTextContent('changed'); + + expect(original.getTextContent()).toBe('original'); + expect(copy.getTextContent()).toBe('changed'); + }, + {discrete: true}, + ); + }); + + test('keeps NodeState on the node and its descendants', () => { + using editor = buildEditor(); + editor.update( + () => { + const text = $setState($createTextNode('text'), colorState, 'blue'); + const original = $setState( + $createParagraphNode().append(text), + colorState, + 'red', + ); + $getRoot().clear().append(original); + + const copy = $deepCopy(original); + expect($getState(copy, colorState)).toBe('red'); + const copiedText = copy.getFirstChild(); + assert($isTextNode(copiedText)); + expect($getState(copiedText, colorState)).toBe('blue'); + }, + {discrete: true}, + ); + }); + + test('copies named slots', () => { + using editor = buildEditor(); + editor.update( + () => { + const original = $createParagraphNode().append($createTextNode('body')); + const title = $create(SlotContainerNode).append( + $createParagraphNode().append($createTextNode('Title')), + ); + $setSlot(original, 'title', title); + $getRoot().clear().append(original); + + const copy = $deepCopy(original); + $getRoot().append(copy); + + const copiedTitle = $getSlot(copy, 'title'); + assert(copiedTitle instanceof SlotContainerNode); + expect(copiedTitle).not.toBe(title); + expect(copiedTitle.getKey()).not.toBe(title.getKey()); + expect(copiedTitle.getTextContent()).toBe('Title'); + expect(copy.getTextContent()).toBe(original.getTextContent()); + // The original slot is untouched. + expect($getSlot(original, 'title')).toBe(title); + }, + {discrete: true}, + ); + }); + + test('drops descendants excluded from clones and keeps their children', () => { + using editor = buildEditor(); + editor.update( + () => { + const original = $createParagraphNode().append( + $createTextNode('a'), + $create(UncopiedWrapperNode).append( + $createTextNode('b'), + $createTextNode('c').toggleFormat('italic'), + ), + $createTextNode('d'), + ); + $getRoot().clear().append(original); + + const copy: ParagraphNode = $deepCopy(original); + $getRoot().append(copy); + + const children = copy.getChildren(); + expect(children.some(n => n instanceof UncopiedWrapperNode)).toBe( + false, + ); + expect(copy.getTextContent()).toBe('abcd'); + expect(original.getChildrenSize()).toBe(3); + }, + {discrete: true}, + ); + }); + + test('always copies the node passed in, even if it is excluded from clones', () => { + using editor = buildEditor(); + editor.update( + () => { + const wrapper = $create(UncopiedWrapperNode).append( + $createTextNode('inside'), + ); + $getRoot().clear().append($createParagraphNode().append(wrapper)); + + const copy = $deepCopy(wrapper); + expect(copy).toBeInstanceOf(UncopiedWrapperNode); + expect(copy.getTextContent()).toBe('inside'); + }, + {discrete: true}, + ); + }); + + test('copies a text node and an empty element', () => { + using editor = buildEditor(); + editor.update( + () => { + const text = $createTextNode('leaf').toggleFormat('bold'); + const empty = $createParagraphNode(); + $getRoot().clear().append($createParagraphNode().append(text), empty); + + const textCopy = $deepCopy(text); + assert($isTextNode(textCopy)); + expect(textCopy.getKey()).not.toBe(text.getKey()); + expect(textCopy.getTextContent()).toBe('leaf'); + expect(textCopy.hasFormat('bold')).toBe(true); + expect(textCopy.getParent()).toBe(null); + + const emptyCopy = $deepCopy(empty); + expect($isParagraphNode(emptyCopy)).toBe(true); + expect(emptyCopy.getKey()).not.toBe(empty.getKey()); + expect(emptyCopy.getChildrenSize()).toBe(0); + }, + {discrete: true}, + ); + }); + + test('copies slots on a decorator host', () => { + using editor = buildEditor(); + editor.update( + () => { + const original = $create(SlotDecoratorNode); + $setSlot(original, 'title', $title('Caption')); + $getRoot().clear().append(original); + + const copy = $deepCopy(original); + $getRoot().append(copy); + + expect(copy).toBeInstanceOf(SlotDecoratorNode); + const copiedTitle = $getSlot(copy, 'title'); + assert(copiedTitle instanceof SlotContainerNode); + expect(copiedTitle.getTextContent()).toBe('Caption'); + $expectNoSharedKeys(original, copy); + }, + {discrete: true}, + ); + }); + + test('copies slots nested inside slots and children, all with new keys', () => { + using editor = buildEditor(); + editor.update( + () => { + const inner = $createParagraphNode().append($createTextNode('inner')); + $setSlot(inner, 'note', $title('Note')); + const title = $create(SlotContainerNode).append(inner); + const original = $createParagraphNode().append($createTextNode('body')); + $setSlot(original, 'title', title); + $getRoot().clear().append(original); + + const copy = $deepCopy(original); + $getRoot().append(copy); + + const copiedTitle = $getSlot(copy, 'title'); + assert(copiedTitle instanceof SlotContainerNode); + const copiedInner = copiedTitle.getFirstChild(); + assert($isParagraphNode(copiedInner)); + // Text content includes slot text, so it is the note and then the body. + expect(copiedInner.getTextContent()).toBe(inner.getTextContent()); + const copiedNote = $getSlot(copiedInner, 'note'); + assert(copiedNote instanceof SlotContainerNode); + expect(copiedNote.getTextContent()).toBe('Note'); + expect($keys(copy)).toHaveLength($keys(original).length); + $expectNoSharedKeys(original, copy); + }, + {discrete: true}, + ); + }); + + test('does not reset state the way $copyNode does', () => { + using editor = buildEditor(); + editor.update( + () => { + const original = $setState( + $createParagraphNode().append( + $setState($createTextNode('text'), resetState, 'child'), + ), + resetState, + 'parent', + ); + $getRoot().clear().append(original); + + expect($getState($copyNode(original), resetState)).toBe(''); + + const copy = $deepCopy(original); + expect($getState(copy, resetState)).toBe('parent'); + const copiedText = copy.getFirstChild(); + assert($isTextNode(copiedText)); + expect($getState(copiedText, resetState)).toBe('child'); + }, + {discrete: true}, + ); + }); + + test('drops the slots and state of a descendant excluded from clones', () => { + using editor = buildEditor(); + editor.update( + () => { + const wrapper = $setState( + $create(UncopiedWrapperNode).append($createTextNode('kept')), + colorState, + 'red', + ); + $setSlot(wrapper, 'title', $title('dropped')); + const original = $createParagraphNode().append(wrapper); + $getRoot().clear().append(original); + + const copy = $deepCopy(original); + $getRoot().append(copy); + + const [child] = copy.getChildren(); + assert($isTextNode(child)); + expect(child.getTextContent()).toBe('kept'); + // The wrapper's slot and state must not move onto the copied parent. + expect($getSlotNames(copy)).toEqual([]); + expect($getState(copy, colorState)).toBe(''); + // Text content includes slot text, so a leaked slot would show here. + expect(copy.getTextContent()).toBe('kept'); + expect(copy.getChildrenSize()).toBe(1); + // The original still has its wrapper and slot. + expect($getSlot(wrapper, 'title')).not.toBe(null); + }, + {discrete: true}, + ); + }); + + test('leaves the original untouched when the copy is never inserted', () => { + using editor = buildEditor(); + editor.update( + () => { + const original = $createParagraphNode().append( + $createTextNode('a'), + $createTextNode('b').toggleFormat('bold'), + ); + $setSlot(original, 'title', $title('Title')); + $getRoot().clear().append(original); + const keysBefore = $keys(original); + + $deepCopy(original); + + expect($keys(original)).toEqual(keysBefore); + for (const child of original.getChildren()) { + expect(child.getParent()).toBe(original); + } + expect($getRoot().getChildren()).toEqual([original]); + }, + {discrete: true}, + ); + }); + + test('refuses to copy the RootNode and leaves the document unchanged', () => { + using editor = buildEditor(); + editor.update( + () => { + const paragraph = $createParagraphNode().append($createTextNode('x')); + $getRoot().clear().append(paragraph); + + expect(() => $deepCopy($getRoot())).toThrow( + /the RootNode cannot be copied/, + ); + expect($getRoot().getChildren()).toEqual([paragraph]); + expect($getRoot().getTextContent()).toBe('x'); + }, + {discrete: true}, + ); + }); + + test('throws in a read-only context', () => { + using editor = buildEditor(); + editor.update( + () => { + $getRoot() + .clear() + .append($createParagraphNode().append($createTextNode('x'))); + }, + {discrete: true}, + ); + editor.read(() => { + const paragraph = $getRoot().getFirstChild(); + assert(paragraph !== null); + expect(() => $deepCopy(paragraph)).toThrow(/read-only/); + }); + }); +}); diff --git a/packages/lexical/src/index.ts b/packages/lexical/src/index.ts index f48ba2ec6be5..b3dd0ee401c8 100644 --- a/packages/lexical/src/index.ts +++ b/packages/lexical/src/index.ts @@ -388,6 +388,7 @@ export { $copyNode, $create, $createChildrenArray, + $deepCopy, $findMatchingParent, $getAdjacentNode, $getDocument,