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