]> BookStack Code Mirror - bookstack/blobdiff - resources/js/wysiwyg/index.ts
Perms: Fixed some issues made when adding transactions
[bookstack] / resources / js / wysiwyg / index.ts
index 266866c62519c62cbd27d6d33abca490e9141c1c..7ecf91d230e4fa1671108306a611ee0f0e4f12c7 100644 (file)
-import {
-    $createParagraphNode,
-    $getRoot,
-    $getSelection,
-    COMMAND_PRIORITY_LOW,
-    createCommand,
-    createEditor, CreateEditorArgs,
-} from 'lexical';
+import {$getSelection, createEditor, CreateEditorArgs, LexicalEditor} from 'lexical';
 import {createEmptyHistoryState, registerHistory} from '@lexical/history';
 import {registerRichText} from '@lexical/rich-text';
-import {$getNearestBlockElementAncestorOrThrow, mergeRegister} from '@lexical/utils';
-import {$generateNodesFromDOM} from '@lexical/html';
-import {$setBlocksType} from '@lexical/selection';
-import {getNodesForPageEditor} from './nodes';
-import {$createCalloutNode, $isCalloutNode, CalloutCategory} from './nodes/callout';
+import {mergeRegister} from '@lexical/utils';
+import {getNodesForPageEditor, registerCommonNodeMutationListeners} from './nodes';
+import {buildEditorUI} from "./ui";
+import {getEditorContentAsHtml, setEditorContentFromHtml} from "./utils/actions";
+import {registerTableResizer} from "./ui/framework/helpers/table-resizer";
+import {EditorUiContext} from "./ui/framework/core";
+import {listen as listenToCommonEvents} from "./services/common-events";
+import {registerDropPasteHandling} from "./services/drop-paste-handling";
+import {registerTaskListHandler} from "./ui/framework/helpers/task-list-handler";
+import {registerTableSelectionHandler} from "./ui/framework/helpers/table-selection-handler";
+import {el} from "./utils/dom";
+import {registerShortcuts} from "./services/shortcuts";
+import {registerNodeResizer} from "./ui/framework/helpers/node-resizer";
+import {registerKeyboardHandling} from "./services/keyboard-handling";
+import {registerAutoLinks} from "./services/auto-links";
 
-export function createPageEditorInstance(editArea: HTMLElement) {
+export function createPageEditorInstance(container: HTMLElement, htmlContent: string, options: Record<string, any> = {}): SimpleWysiwygEditorInterface {
     const config: CreateEditorArgs = {
         namespace: 'BookStackPageEditor',
         nodes: getNodesForPageEditor(),
         onError: console.error,
+        theme: {
+            text: {
+                bold: 'editor-theme-bold',
+                code: 'editor-theme-code',
+                italic: 'editor-theme-italic',
+                strikethrough: 'editor-theme-strikethrough',
+                subscript: 'editor-theme-subscript',
+                superscript: 'editor-theme-superscript',
+                underline: 'editor-theme-underline',
+                underlineStrikethrough: 'editor-theme-underline-strikethrough',
+            }
+        }
     };
 
-    const startingHtml = editArea.innerHTML;
-    const parser = new DOMParser();
-    const dom = parser.parseFromString(startingHtml, 'text/html');
+    const editArea = el('div', {
+        contenteditable: 'true',
+        class: 'editor-content-area page-content',
+    });
+    const editWrap = el('div', {
+        class: 'editor-content-wrap',
+    }, [editArea]);
+
+    container.append(editWrap);
+    container.classList.add('editor-container');
+    container.setAttribute('dir', options.textDirection);
+    if (options.darkMode) {
+        container.classList.add('editor-dark');
+    }
 
     const editor = createEditor(config);
     editor.setRootElement(editArea);
+    const context: EditorUiContext = buildEditorUI(container, editArea, editWrap, editor, options);
 
     mergeRegister(
         registerRichText(editor),
         registerHistory(editor, createEmptyHistoryState(), 300),
+        registerShortcuts(context),
+        registerKeyboardHandling(context),
+        registerTableResizer(editor, editWrap),
+        registerTableSelectionHandler(editor),
+        registerTaskListHandler(editor, editArea),
+        registerDropPasteHandling(context),
+        registerNodeResizer(context),
+        registerAutoLinks(editor),
     );
 
-    editor.update(() => {
-        const startingNodes = $generateNodesFromDOM(editor, dom);
-        const root = $getRoot();
-        root.append(...startingNodes);
-    });
+    listenToCommonEvents(editor);
 
-    const debugView = document.getElementById('lexical-debug');
-    editor.registerUpdateListener(({editorState}) => {
-        console.log('editorState', editorState.toJSON());
-        debugView.textContent = JSON.stringify(editorState.toJSON(), null, 2);
-    });
+    setEditorContentFromHtml(editor, htmlContent);
 
-    // Todo - How can we store things like IDs and alignment?
-    //   Node overrides?
-    //   https://lexical.dev/docs/concepts/node-replacement
+    const debugView = document.getElementById('lexical-debug');
+    if (debugView) {
+        debugView.hidden = true;
+        editor.registerUpdateListener(({dirtyElements, dirtyLeaves, editorState, prevEditorState}) => {
+            // Debug logic
+            // console.log('editorState', editorState.toJSON());
+            debugView.textContent = JSON.stringify(editorState.toJSON(), null, 2);
+        });
+    }
 
-    // Example of creating, registering and using a custom command
+    // @ts-ignore
+    window.debugEditorState = () => {
+        return editor.getEditorState().toJSON();
+    };
 
-    const SET_BLOCK_CALLOUT_COMMAND = createCommand();
-    editor.registerCommand(SET_BLOCK_CALLOUT_COMMAND, (category: CalloutCategory = 'info') => {
-        const selection = $getSelection();
-        const blockElement = $getNearestBlockElementAncestorOrThrow(selection.getNodes()[0]);
-        if ($isCalloutNode(blockElement)) {
-            $setBlocksType(selection, $createParagraphNode);
-        } else {
-            $setBlocksType(selection, () => $createCalloutNode(category));
-        }
-        return true;
-    }, COMMAND_PRIORITY_LOW);
+    registerCommonNodeMutationListeners(context);
 
-    const button = document.getElementById('lexical-button');
-    button.addEventListener('click', event => {
-        editor.dispatchCommand(SET_BLOCK_CALLOUT_COMMAND, 'info');
-    });
+    return new SimpleWysiwygEditorInterface(editor);
 }
+
+export class SimpleWysiwygEditorInterface {
+    protected editor: LexicalEditor;
+
+    constructor(editor: LexicalEditor) {
+        this.editor = editor;
+    }
+
+    async getContentAsHtml(): Promise<string> {
+        return await getEditorContentAsHtml(this.editor);
+    }
+}
\ No newline at end of file