]> BookStack Code Mirror - bookstack/blob - resources/js/markdown/codemirror.js
9d54c19d754b52b6489bc9aad5bdb7299f4d8542
[bookstack] / resources / js / markdown / codemirror.js
1 import {provideKeyBindings} from './shortcuts';
2 import {debounce} from '../services/util';
3 import {Clipboard} from '../services/clipboard';
4
5 /**
6  * Initiate the codemirror instance for the markdown editor.
7  * @param {MarkdownEditor} editor
8  * @returns {Promise<void>}
9  */
10 export async function init(editor) {
11     const Code = await window.importVersioned('code');
12
13     /**
14      * @param {ViewUpdate} v
15      */
16     function onViewUpdate(v) {
17         if (v.docChanged) {
18             editor.actions.updateAndRender();
19         }
20     }
21
22     const onScrollDebounced = debounce(editor.actions.syncDisplayPosition.bind(editor.actions), 100, false);
23     let syncActive = editor.settings.get('scrollSync');
24     editor.settings.onChange('scrollSync', val => {
25         syncActive = val;
26     });
27
28     const domEventHandlers = {
29         // Handle scroll to sync display view
30         scroll: event => syncActive && onScrollDebounced(event),
31         // Handle image & content drag n drop
32         drop: event => {
33             const templateId = event.dataTransfer.getData('bookstack/template');
34             if (templateId) {
35                 event.preventDefault();
36                 editor.actions.insertTemplate(templateId, event.pageX, event.pageY);
37             }
38
39             const clipboard = new Clipboard(event.dataTransfer);
40             const clipboardImages = clipboard.getImages();
41             if (clipboardImages.length > 0) {
42                 event.stopPropagation();
43                 event.preventDefault();
44                 editor.actions.insertClipboardImages(clipboardImages, event.pageX, event.pageY);
45             }
46         },
47         // Handle image paste
48         paste: event => {
49             const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
50
51             // Don't handle the event ourselves if no items exist of contains table-looking data
52             if (!clipboard.hasItems() || clipboard.containsTabularData()) {
53                 return;
54             }
55
56             const images = clipboard.getImages();
57             for (const image of images) {
58                 editor.actions.uploadImage(image);
59             }
60         },
61     };
62
63     const cm = Code.markdownEditor(
64         editor.config.inputEl,
65         onViewUpdate,
66         domEventHandlers,
67         provideKeyBindings(editor),
68     );
69
70     // Add editor view to window for easy access/debugging.
71     // Not part of official API/Docs
72     window.mdEditorView = cm;
73
74     return cm;
75 }