]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/index.ts
c4403773bf2a93f6dfb3551da78bc10493643766
[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
46     container.append(editWrap);
47     container.classList.add('editor-container');
48     container.setAttribute('dir', options.textDirection);
49     if (options.darkMode) {
50         container.classList.add('editor-dark');
51     }
52
53     const editor = createEditor(config);
54     editor.setRootElement(editArea);
55     const context: EditorUiContext = buildEditorUI(container, editArea, editWrap, editor, options);
56
57     mergeRegister(
58         registerRichText(editor),
59         registerHistory(editor, createEmptyHistoryState(), 300),
60         registerShortcuts(context),
61         registerKeyboardHandling(context),
62         registerTableResizer(editor, editWrap),
63         registerTableSelectionHandler(editor),
64         registerTaskListHandler(editor, editArea),
65         registerDropPasteHandling(context),
66         registerNodeResizer(context),
67     );
68
69     listenToCommonEvents(editor);
70
71     setEditorContentFromHtml(editor, htmlContent);
72
73     const debugView = document.getElementById('lexical-debug');
74     if (debugView) {
75         debugView.hidden = true;
76     }
77
78     let changeFromLoading = true;
79     editor.registerUpdateListener(({dirtyElements, dirtyLeaves, editorState, prevEditorState}) => {
80         // Watch for selection changes to update the UI on change
81         // Used to be done via SELECTION_CHANGE_COMMAND but this would not always emit
82         // for all selection changes, so this proved more reliable.
83         const selectionChange = !(prevEditorState._selection?.is(editorState._selection) || false);
84         if (selectionChange) {
85             editor.update(() => {
86                 const selection = $getSelection();
87                 context.manager.triggerStateUpdate({
88                     editor, selection,
89                 });
90             });
91         }
92
93         // Emit change event to component system (for draft detection) on actual user content change
94         if (dirtyElements.size > 0 || dirtyLeaves.size > 0) {
95             if (changeFromLoading) {
96                 changeFromLoading = false;
97             } else {
98                 window.$events.emit('editor-html-change', '');
99             }
100         }
101
102         // Debug logic
103         // console.log('editorState', editorState.toJSON());
104         if (debugView) {
105             debugView.textContent = JSON.stringify(editorState.toJSON(), null, 2);
106         }
107     });
108
109     // @ts-ignore
110     window.debugEditorState = () => {
111         console.log(editor.getEditorState().toJSON());
112     };
113
114     registerCommonNodeMutationListeners(context);
115
116     return new SimpleWysiwygEditorInterface(editor);
117 }
118
119 export class SimpleWysiwygEditorInterface {
120     protected editor: LexicalEditor;
121
122     constructor(editor: LexicalEditor) {
123         this.editor = editor;
124     }
125
126     async getContentAsHtml(): Promise<string> {
127         return await getEditorContentAsHtml(this.editor);
128     }
129 }