]> BookStack Code Mirror - bookstack/blob - resources/js/markdown/codemirror.ts
Merge pull request #5725 from BookStackApp/md_plaintext
[bookstack] / resources / js / markdown / codemirror.ts
1 import {EditorView, KeyBinding, ViewUpdate} from "@codemirror/view";
2 import {CodeModule} from "../global";
3 import {MarkdownEditorEventMap} from "./dom-handlers";
4 import {MarkdownEditorShortcutMap} from "./shortcuts";
5
6 /**
7  * Convert editor shortcuts to CodeMirror keybinding format.
8  */
9 export function shortcutsToKeyBindings(shortcuts: MarkdownEditorShortcutMap): KeyBinding[] {
10     const keyBindings = [];
11
12     const wrapAction = (action: () => void) => () => {
13         action();
14         return true;
15     };
16
17     for (const [shortcut, action] of Object.entries(shortcuts)) {
18         keyBindings.push({key: shortcut, run: wrapAction(action), preventDefault: true});
19     }
20
21     return keyBindings;
22 }
23
24 /**
25  * Initiate the codemirror instance for the Markdown editor.
26  */
27 export async function init(
28     input: HTMLTextAreaElement,
29     shortcuts: MarkdownEditorShortcutMap,
30     domEventHandlers: MarkdownEditorEventMap,
31     onChange: () => void
32 ): Promise<EditorView> {
33     const Code = await window.importVersioned('code') as CodeModule;
34
35     function onViewUpdate(v: ViewUpdate) {
36         if (v.docChanged) {
37             onChange();
38         }
39     }
40
41     const cm = Code.markdownEditor(
42         input,
43         onViewUpdate,
44         domEventHandlers,
45         shortcutsToKeyBindings(shortcuts),
46     );
47
48     // Add editor view to the window for easy access/debugging.
49     // Not part of official API/Docs
50     // @ts-ignore
51     window.mdEditorView = cm;
52
53     return cm;
54 }