]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/index.mjs
decfa4f22b11a9d7f9e521d0791a1b1779b44399
[bookstack] / resources / js / wysiwyg / index.mjs
1 import {
2     $createParagraphNode,
3     $getRoot,
4     $getSelection,
5     COMMAND_PRIORITY_LOW,
6     createCommand,
7     createEditor
8 } from 'lexical';
9 import {createEmptyHistoryState, registerHistory} from '@lexical/history';
10 import {registerRichText} from '@lexical/rich-text';
11 import {$getNearestBlockElementAncestorOrThrow, mergeRegister} from '@lexical/utils';
12 import {$generateNodesFromDOM} from '@lexical/html';
13 import {getNodesForPageEditor} from "./nodes/index.js";
14 import {$createCalloutNode, $isCalloutNode} from "./nodes/callout.js";
15 import {$setBlocksType} from "@lexical/selection";
16
17 export function createPageEditorInstance(editArea) {
18     const config = {
19         namespace: 'BookStackPageEditor',
20         nodes: getNodesForPageEditor(),
21         onError: console.error,
22     };
23
24     const startingHtml = editArea.innerHTML;
25     const parser = new DOMParser();
26     const dom = parser.parseFromString(startingHtml, 'text/html');
27
28     const editor = createEditor(config);
29     editor.setRootElement(editArea);
30
31     mergeRegister(
32         registerRichText(editor),
33         registerHistory(editor, createEmptyHistoryState(), 300),
34     );
35
36     editor.update(() => {
37         const startingNodes = $generateNodesFromDOM(editor, dom);
38         const root = $getRoot();
39         root.append(...startingNodes);
40     });
41
42     const debugView = document.getElementById('lexical-debug');
43     editor.registerUpdateListener(({editorState}) => {
44         console.log('editorState', editorState.toJSON());
45         debugView.textContent = JSON.stringify(editorState.toJSON(), null, 2);
46     });
47
48     // Todo - How can we store things like IDs and alignment?
49     //   Node overrides?
50     //   https://lexical.dev/docs/concepts/node-replacement
51
52     // Example of creating, registering and using a custom command
53
54     const SET_BLOCK_CALLOUT_COMMAND = createCommand();
55     editor.registerCommand(SET_BLOCK_CALLOUT_COMMAND, (category = 'info') => {
56         const selection = $getSelection();
57         const blockElement = $getNearestBlockElementAncestorOrThrow(selection.getNodes()[0]);
58         if ($isCalloutNode(blockElement)) {
59             $setBlocksType(selection, $createParagraphNode);
60         } else {
61             $setBlocksType(selection, () => $createCalloutNode(category));
62         }
63         return true;
64     }, COMMAND_PRIORITY_LOW);
65
66     const button = document.getElementById('lexical-button');
67     button.addEventListener('click', event => {
68         editor.dispatchCommand(SET_BLOCK_CALLOUT_COMMAND, 'info');
69     });
70 }