]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/utils/actions.ts
Lexical: Changed table esacpe handling
[bookstack] / resources / js / wysiwyg / utils / actions.ts
1 import {$getRoot, $getSelection, LexicalEditor} from "lexical";
2 import {$generateHtmlFromNodes} from "@lexical/html";
3 import {$htmlToBlockNodes} from "./nodes";
4
5 export function setEditorContentFromHtml(editor: LexicalEditor, html: string) {
6     editor.update(() => {
7         // Empty existing
8         const root = $getRoot();
9         for (const child of root.getChildren()) {
10             child.remove(true);
11         }
12
13         const nodes = $htmlToBlockNodes(editor, html);
14         root.append(...nodes);
15     });
16 }
17
18 export function appendHtmlToEditor(editor: LexicalEditor, html: string) {
19     editor.update(() => {
20         const root = $getRoot();
21         const nodes = $htmlToBlockNodes(editor, html);
22         root.append(...nodes);
23     });
24 }
25
26 export function prependHtmlToEditor(editor: LexicalEditor, html: string) {
27     editor.update(() => {
28         const root = $getRoot();
29         const nodes = $htmlToBlockNodes(editor, html);
30         let reference = root.getChildren()[0];
31         for (let i = nodes.length - 1; i >= 0; i--) {
32             if (reference) {
33                 reference.insertBefore(nodes[i]);
34             } else {
35                 root.append(nodes[i])
36             }
37             reference = nodes[i];
38         }
39     });
40 }
41
42 export function insertHtmlIntoEditor(editor: LexicalEditor, html: string) {
43     editor.update(() => {
44         const selection = $getSelection();
45         const nodes = $htmlToBlockNodes(editor, html);
46
47         const reference = selection?.getNodes()[0];
48         const referencesParents = reference?.getParents() || [];
49         const topLevel = referencesParents[referencesParents.length - 1];
50         if (topLevel && reference) {
51             for (let i = nodes.length - 1; i >= 0; i--) {
52                 reference.insertAfter(nodes[i]);
53             }
54         }
55     });
56 }
57
58 export function getEditorContentAsHtml(editor: LexicalEditor): Promise<string> {
59     return new Promise((resolve, reject) => {
60         editor.getEditorState().read(() => {
61             const html = $generateHtmlFromNodes(editor);
62             resolve(html);
63         });
64     });
65 }
66
67 export function focusEditor(editor: LexicalEditor) {
68     editor.focus(() => {}, {defaultSelection: "rootStart"});
69 }