]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/index.ts
Lexical: Added custom id-supporting paragraph blocks
[bookstack] / resources / js / wysiwyg / index.ts
1 import {
2     $createParagraphNode,
3     $getRoot,
4     $getSelection,
5     COMMAND_PRIORITY_LOW,
6     createCommand,
7     createEditor, CreateEditorArgs,
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 {$setBlocksType} from '@lexical/selection';
14 import {getNodesForPageEditor} from './nodes';
15 import {$createCalloutNode, $isCalloutNode, CalloutCategory} from './nodes/callout';
16
17 export function createPageEditorInstance(editArea: HTMLElement) {
18     const config: CreateEditorArgs = {
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     // Example of creating, registering and using a custom command
49
50     const SET_BLOCK_CALLOUT_COMMAND = createCommand();
51     editor.registerCommand(SET_BLOCK_CALLOUT_COMMAND, (category: CalloutCategory = 'info') => {
52         const selection = $getSelection();
53         const blockElement = $getNearestBlockElementAncestorOrThrow(selection.getNodes()[0]);
54         if ($isCalloutNode(blockElement)) {
55             $setBlocksType(selection, $createParagraphNode);
56         } else {
57             $setBlocksType(selection, () => $createCalloutNode(category));
58         }
59         return true;
60     }, COMMAND_PRIORITY_LOW);
61
62     const button = document.getElementById('lexical-button');
63     button.addEventListener('click', event => {
64         editor.dispatchCommand(SET_BLOCK_CALLOUT_COMMAND, 'info');
65     });
66 }