]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/index.ts
Lexical: Added single node backspace/delete support
[bookstack] / resources / js / wysiwyg / index.ts
1 import {$getSelection, createEditor, CreateEditorArgs, isCurrentlyReadOnlyMode, LexicalEditor} from 'lexical';
2 import {createEmptyHistoryState, registerHistory} from '@lexical/history';
3 import {registerRichText} from '@lexical/rich-text';
4 import {mergeRegister} from '@lexical/utils';
5 import {getNodesForPageEditor, registerCommonNodeMutationListeners} from './nodes';
6 import {buildEditorUI} from "./ui";
7 import {getEditorContentAsHtml, setEditorContentFromHtml} from "./utils/actions";
8 import {registerTableResizer} from "./ui/framework/helpers/table-resizer";
9 import {EditorUiContext} from "./ui/framework/core";
10 import {listen as listenToCommonEvents} from "./services/common-events";
11 import {registerDropPasteHandling} from "./services/drop-paste-handling";
12 import {registerTaskListHandler} from "./ui/framework/helpers/task-list-handler";
13 import {registerTableSelectionHandler} from "./ui/framework/helpers/table-selection-handler";
14 import {el} from "./utils/dom";
15 import {registerShortcuts} from "./services/shortcuts";
16 import {registerNodeResizer} from "./ui/framework/helpers/node-resizer";
17 import {registerKeyboardHandling} from "./services/keyboard-handling";
18
19 export function createPageEditorInstance(container: HTMLElement, htmlContent: string, options: Record<string, any> = {}): SimpleWysiwygEditorInterface {
20     const config: CreateEditorArgs = {
21         namespace: 'BookStackPageEditor',
22         nodes: getNodesForPageEditor(),
23         onError: console.error,
24         theme: {
25             text: {
26                 bold: 'editor-theme-bold',
27                 code: 'editor-theme-code',
28                 italic: 'editor-theme-italic',
29                 strikethrough: 'editor-theme-strikethrough',
30                 subscript: 'editor-theme-subscript',
31                 superscript: 'editor-theme-superscript',
32                 underline: 'editor-theme-underline',
33                 underlineStrikethrough: 'editor-theme-underline-strikethrough',
34             }
35         }
36     };
37
38     const editArea = el('div', {
39         contenteditable: 'true',
40         class: 'editor-content-area page-content',
41     });
42     const editWrap = el('div', {
43         class: 'editor-content-wrap',
44     }, [editArea]);
45     container.append(editWrap);
46     container.classList.add('editor-container');
47
48     const editor = createEditor(config);
49     editor.setRootElement(editArea);
50     const context: EditorUiContext = buildEditorUI(container, editArea, editWrap, editor, options);
51
52     mergeRegister(
53         registerRichText(editor),
54         registerHistory(editor, createEmptyHistoryState(), 300),
55         registerShortcuts(context),
56         registerKeyboardHandling(context),
57         registerTableResizer(editor, editWrap),
58         registerTableSelectionHandler(editor),
59         registerTaskListHandler(editor, editArea),
60         registerDropPasteHandling(context),
61         registerNodeResizer(context),
62     );
63
64     listenToCommonEvents(editor);
65
66     setEditorContentFromHtml(editor, htmlContent);
67
68     const debugView = document.getElementById('lexical-debug');
69     if (debugView) {
70         debugView.hidden = true;
71     }
72
73     let changeFromLoading = true;
74     editor.registerUpdateListener(({dirtyElements, dirtyLeaves, editorState, prevEditorState}) => {
75         // Watch for selection changes to update the UI on change
76         // Used to be done via SELECTION_CHANGE_COMMAND but this would not always emit
77         // for all selection changes, so this proved more reliable.
78         const selectionChange = !(prevEditorState._selection?.is(editorState._selection) || false);
79         if (selectionChange) {
80             editor.update(() => {
81                 const selection = $getSelection();
82                 context.manager.triggerStateUpdate({
83                     editor, selection,
84                 });
85             });
86         }
87
88         // Emit change event to component system (for draft detection) on actual user content change
89         if (dirtyElements.size > 0 || dirtyLeaves.size > 0) {
90             if (changeFromLoading) {
91                 changeFromLoading = false;
92             } else {
93                 window.$events.emit('editor-html-change', '');
94             }
95         }
96
97         // Debug logic
98         // console.log('editorState', editorState.toJSON());
99         if (debugView) {
100             debugView.textContent = JSON.stringify(editorState.toJSON(), null, 2);
101         }
102     });
103
104     // @ts-ignore
105     window.debugEditorState = () => {
106         console.log(editor.getEditorState().toJSON());
107     };
108
109     registerCommonNodeMutationListeners(context);
110
111     return new SimpleWysiwygEditorInterface(editor);
112 }
113
114 export class SimpleWysiwygEditorInterface {
115     protected editor: LexicalEditor;
116
117     constructor(editor: LexicalEditor) {
118         this.editor = editor;
119     }
120
121     async getContentAsHtml(): Promise<string> {
122         return await getEditorContentAsHtml(this.editor);
123     }
124 }