]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/utils/node-clipboard.ts
Opensearch: Fixed XML declaration when php short tags enabled
[bookstack] / resources / js / wysiwyg / utils / node-clipboard.ts
1 import {$isElementNode, LexicalEditor, LexicalNode, SerializedLexicalNode} from "lexical";
2
3 type SerializedLexicalNodeWithChildren = {
4     node: SerializedLexicalNode,
5     children: SerializedLexicalNodeWithChildren[],
6 };
7
8 function serializeNodeRecursive(node: LexicalNode): SerializedLexicalNodeWithChildren {
9     const childNodes = $isElementNode(node) ? node.getChildren() : [];
10     return {
11         node: node.exportJSON(),
12         children: childNodes.map(n => serializeNodeRecursive(n)),
13     };
14 }
15
16 function unserializeNodeRecursive(editor: LexicalEditor, {node, children}: SerializedLexicalNodeWithChildren): LexicalNode|null {
17     const instance = editor._nodes.get(node.type)?.klass.importJSON(node);
18     if (!instance) {
19         return null;
20     }
21
22     const childNodes = children.map(child => unserializeNodeRecursive(editor, child));
23     for (const child of childNodes) {
24         if (child && $isElementNode(instance)) {
25             instance.append(child);
26         }
27     }
28
29     return instance;
30 }
31
32 export class NodeClipboard<T extends LexicalNode> {
33     protected store: SerializedLexicalNodeWithChildren[] = [];
34
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));
39         }
40     }
41
42     get(editor: LexicalEditor): T[] {
43         return this.store.map(json => unserializeNodeRecursive(editor, json)).filter((node) => {
44             return node !== null;
45         }) as T[];
46     }
47
48     size(): number {
49         return this.store.length;
50     }
51 }