1 import {$isElementNode, LexicalEditor, LexicalNode, SerializedLexicalNode} from "lexical";
3 type SerializedLexicalNodeWithChildren = {
4 node: SerializedLexicalNode,
5 children: SerializedLexicalNodeWithChildren[],
8 function serializeNodeRecursive(node: LexicalNode): SerializedLexicalNodeWithChildren {
9 const childNodes = $isElementNode(node) ? node.getChildren() : [];
11 node: node.exportJSON(),
12 children: childNodes.map(n => serializeNodeRecursive(n)),
16 function unserializeNodeRecursive(editor: LexicalEditor, {node, children}: SerializedLexicalNodeWithChildren): LexicalNode|null {
17 const instance = editor._nodes.get(node.type)?.klass.importJSON(node);
22 const childNodes = children.map(child => unserializeNodeRecursive(editor, child));
23 for (const child of childNodes) {
24 if (child && $isElementNode(instance)) {
25 instance.append(child);
32 export class NodeClipboard<T extends LexicalNode> {
33 protected store: SerializedLexicalNodeWithChildren[] = [];
35 set(...nodes: LexicalNode[]): void {
36 this.store.splice(0, this.store.length);
37 for (const node of nodes) {
38 this.store.push(serializeNodeRecursive(node));
42 get(editor: LexicalEditor): T[] {
43 return this.store.map(json => unserializeNodeRecursive(editor, json)).filter((node) => {
49 return this.store.length;