]> BookStack Code Mirror - bookstack/blob - resources/js/markdown/codemirror.js
b615e666bd7a1dc2ba6b39e6f1c4a33b5fa37a48
[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 => syncActive = val);
25
26     const domEventHandlers = {
27         // Handle scroll to sync display view
28         scroll: event => syncActive && onScrollDebounced(event),
29         // Handle image & content drag n drop
30         drop: event => {
31             const templateId = event.dataTransfer.getData('bookstack/template');
32             if (templateId) {
33                 event.preventDefault();
34                 editor.actions.insertTemplate(templateId, event.pageX, event.pageY);
35             }
36
37             const clipboard = new Clipboard(event.dataTransfer);
38             const clipboardImages = clipboard.getImages();
39             if (clipboardImages.length > 0) {
40                 event.stopPropagation();
41                 event.preventDefault();
42                 editor.actions.insertClipboardImages(clipboardImages, event.pageX, event.pageY);
43             }
44         },
45         // Handle image paste
46         paste: event => {
47             const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
48
49             // Don't handle the event ourselves if no items exist of contains table-looking data
50             if (!clipboard.hasItems() || clipboard.containsTabularData()) {
51                 return;
52             }
53
54             const images = clipboard.getImages();
55             for (const image of images) {
56                 editor.actions.uploadImage(image);
57             }
58         },
59     };
60
61     const cm = Code.markdownEditor(
62         editor.config.inputEl,
63         onViewUpdate,
64         domEventHandlers,
65         provideKeyBindings(editor),
66     );
67
68     // Add editor view to window for easy access/debugging.
69     // Not part of official API/Docs
70     window.mdEditorView = cm;
71
72     return cm;
73 }