Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/lexical-deep-copy.md
Original file line number Diff line number Diff line change
@@ -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".
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import {
import {
$createParagraphNode,
$createTextNode,
$deepCopy,
$getRoot,
$getSelection,
$getSlot,
Expand All @@ -59,7 +60,6 @@ import {
$isParagraphNode,
$isRangeSelection,
$isTextNode,
$parseSerializedNode,
$setSelection,
configExtension,
DELETE_CHARACTER_COMMAND,
Expand All @@ -73,7 +73,6 @@ import {
OUTDENT_CONTENT_COMMAND,
REDO_COMMAND,
type SerializedEditorState,
type SerializedElementNode,
type SerializedLexicalNode,
UNDO_COMMAND,
} from 'lexical';
Expand Down Expand Up @@ -113,17 +112,6 @@ function $p(text: string): ElementNode {
return $createParagraphNode().append($createTextNode(text));
}

function $deepCopy<T extends LexicalNode>(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[] = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import {
$create,
$createParagraphNode,
$createTextNode,
$deepCopy,
$getRoot,
$getSelection,
$getState,
Expand All @@ -86,7 +87,6 @@ import {
PASTE_TAG,
REDO_COMMAND,
type SerializedEditorState,
type SerializedElementNode,
type SerializedLexicalNode,
UNDO_COMMAND,
} from 'lexical';
Expand Down Expand Up @@ -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<T extends LexicalNode>(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`);
Expand Down
51 changes: 50 additions & 1 deletion packages/lexical-website/docs/concepts/node-cloning.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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`?
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {$setBlocksType} from '@lexical/selection';
import {
$createParagraphNode,
$createTextNode,
$deepCopy,
$getRoot,
$getSelection,
INSERT_PARAGRAPH_COMMAND,
Expand All @@ -24,7 +25,6 @@ import {afterEach, describe, expect, test} from 'vitest';
import {
$block,
$caretAt,
$deepCopy,
$enter,
$join,
$type,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {$setBlocksType} from '@lexical/selection';
import {
$createParagraphNode,
$createTextNode,
$deepCopy,
$getRoot,
$getSelection,
$isElementNode,
Expand All @@ -45,7 +46,6 @@ import {afterEach, describe, expect, test} from 'vitest';
import {
$block,
$caretAt,
$deepCopy,
$enter,
$join,
$type,
Expand Down
15 changes: 0 additions & 15 deletions packages/lexical-yjs/src/__tests__/unit/utils/blockIdPeers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ import {
$isElementNode,
$isRangeSelection,
$isRootNode,
$parseSerializedNode,
COLLABORATION_TAG,
configExtension,
DELETE_CHARACTER_COMMAND,
Expand All @@ -48,8 +47,6 @@ import {
type LexicalEditor,
type LexicalNode,
type SerializedEditorState,
type SerializedElementNode,
type SerializedLexicalNode,
SKIP_COLLAB_TAG,
} from 'lexical';
import {
Expand Down Expand Up @@ -444,18 +441,6 @@ export function readIds(
}
}

/** A deep copy that keeps NodeState, as a Lexical-JSON paste does. */
export function $deepCopy<T extends LexicalNode>(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)) {
Expand Down
1 change: 1 addition & 0 deletions packages/lexical/flow/Lexical.js.flow
Original file line number Diff line number Diff line change
Expand Up @@ -1354,6 +1354,7 @@ declare export function $setFormatFromDOM<T extends ElementNode>(
declare export function $cloneWithProperties<T extends LexicalNode>(node: T): T;
declare export function $cloneWithPropertiesEphemeral<T extends LexicalNode>(node: T): T;
declare export function $copyNode<T extends LexicalNode>(node: T, skipReset?: boolean): T;
declare export function $deepCopy<T extends LexicalNode>(node: T): T;
declare export function $getDocument(): Document;
declare export function $getEditor(): LexicalEditor;
/** @internal */
Expand Down
75 changes: 75 additions & 0 deletions packages/lexical/src/LexicalUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -2103,6 +2106,78 @@ export function $copyNode<T extends LexicalNode>(
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<T extends LexicalNode>(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<string, SerializedLexicalNode> = {};
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')) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Optional: since the node passed in is always kept but excluded descendants are spliced here, a host whose required child excludes itself comes back without it. The playground's PageNode/PageContentNode pair both return true from excludeFromCopy(), so $deepCopy(page) yields a PageNode with bare paragraphs as children and getContentNode() throws on the detached copy (the PagesExtension transform repairs it only after insertion). Consider copying excluded descendants faithfully, or documenting that such a host must normalize its children, and add a test for whichever rule you keep.

$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<N extends LexicalNode>(node: N): N {
const editor = getActiveEditor();
Expand Down
Loading
Loading