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