]> BookStack Code Mirror - bookstack/blob - resources/js/markdown/codemirror.js
Fixed md editor refactoring issues after manual test
[bookstack] / resources / js / markdown / codemirror.js
1 import {provide as provideShortcuts} 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     const cm = Code.markdownEditor(editor.config.inputEl);
13
14     // Will force to remain as ltr for now due to issues when HTML is in editor.
15     cm.setOption('direction', 'ltr');
16     // Register shortcuts
17     cm.setOption('extraKeys', provideShortcuts(editor, Code.getMetaKey()));
18
19
20     // Register codemirror events
21
22     // Update data on content change
23     cm.on('change', (instance, changeObj) => editor.actions.updateAndRender());
24
25     // Handle scroll to sync display view
26     const onScrollDebounced = debounce(editor.actions.syncDisplayPosition.bind(editor.actions), 100, false);
27     cm.on('scroll', instance => onScrollDebounced(instance));
28
29     // Handle image paste
30     cm.on('paste', (cm, event) => {
31         const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
32
33         // Don't handle the event ourselves if no items exist of contains table-looking data
34         if (!clipboard.hasItems() || clipboard.containsTabularData()) {
35             return;
36         }
37
38         const images = clipboard.getImages();
39         for (const image of images) {
40             editor.actions.uploadImage(image);
41         }
42     });
43
44     // Handle image & content drag n drop
45     cm.on('drop', (cm, event) => {
46
47         const templateId = event.dataTransfer.getData('bookstack/template');
48         if (templateId) {
49             event.preventDefault();
50             editor.actions.insertTemplate(templateId, event.pageX, event.pageY);
51         }
52
53         const clipboard = new Clipboard(event.dataTransfer);
54         const clipboardImages = clipboard.getImages();
55         if (clipboardImages.length > 0) {
56             event.stopPropagation();
57             event.preventDefault();
58             editor.actions.insertClipboardImages(clipboardImages);
59         }
60
61     });
62
63     return cm;
64 }