]> BookStack Code Mirror - bookstack/blob - resources/js/markdown/dom-handlers.ts
Merge pull request #5731 from BookStackApp/lexical_jul25
[bookstack] / resources / js / markdown / dom-handlers.ts
1 import {Clipboard} from "../services/clipboard";
2 import {MarkdownEditor} from "./index.mjs";
3 import {debounce} from "../services/util";
4
5
6 export type MarkdownEditorEventMap = Record<string, (event: any) => void>;
7
8 export function getMarkdownDomEventHandlers(editor: MarkdownEditor): MarkdownEditorEventMap {
9
10     const onScrollDebounced = debounce(editor.actions.syncDisplayPosition.bind(editor.actions), 100, false);
11     let syncActive = editor.settings.get('scrollSync');
12     editor.settings.onChange('scrollSync', val => {
13         syncActive = val;
14     });
15
16     return {
17         // Handle scroll to sync display view
18         scroll: (event: Event) => syncActive && onScrollDebounced(event),
19         // Handle image & content drag n drop
20         drop: (event: DragEvent) => {
21             if (!event.dataTransfer) {
22                 return;
23             }
24
25             const templateId = event.dataTransfer.getData('bookstack/template');
26             if (templateId) {
27                 event.preventDefault();
28                 editor.actions.insertTemplate(templateId, event);
29             }
30
31             const clipboard = new Clipboard(event.dataTransfer);
32             const clipboardImages = clipboard.getImages();
33             if (clipboardImages.length > 0) {
34                 event.stopPropagation();
35                 event.preventDefault();
36                 editor.actions.insertClipboardImages(clipboardImages, event);
37             }
38         },
39         // Handle dragover event to allow as drop-target in chrome
40         dragover: (event: DragEvent) => {
41             event.preventDefault();
42         },
43         // Handle image paste
44         paste: (event: ClipboardEvent) => {
45             if (!event.clipboardData) {
46                 return;
47             }
48
49             const clipboard = new Clipboard(event.clipboardData);
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 }