]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/drop-paste-handling.js
0529f6b6cdd110f00335b3a5c2785df608e7fe71
[bookstack] / resources / js / wysiwyg / drop-paste-handling.js
1 import Clipboard from "../services/clipboard";
2
3 let wrap;
4 let draggedContentEditable;
5
6 function hasTextContent(node) {
7     return node && !!(node.textContent || node.innerText);
8 }
9
10 /**
11  * Handle pasting images from clipboard.
12  * @param {Editor} editor
13  * @param {WysiwygConfigOptions} options
14  * @param {ClipboardEvent|DragEvent} event
15  */
16 function paste(editor, options, event) {
17     const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
18
19     // Don't handle the event ourselves if no items exist of contains table-looking data
20     if (!clipboard.hasItems() || clipboard.containsTabularData()) {
21         return;
22     }
23
24     const images = clipboard.getImages();
25     for (const imageFile of images) {
26
27         const id = "image-" + Math.random().toString(16).slice(2);
28         const loadingImage = window.baseUrl('/loading.gif');
29         event.preventDefault();
30
31         setTimeout(() => {
32             editor.insertContent(`<p><img src="${loadingImage}" id="${id}"></p>`);
33
34             uploadImageFile(imageFile, options.pageId).then(resp => {
35                 const safeName = resp.name.replace(/"/g, '');
36                 const newImageHtml = `<img src="${resp.thumbs.display}" alt="${safeName}" />`;
37
38                 const newEl = editor.dom.create('a', {
39                     target: '_blank',
40                     href: resp.url,
41                 }, newImageHtml);
42
43                 editor.dom.replace(newEl, id);
44             }).catch(err => {
45                 editor.dom.remove(id);
46                 window.$events.emit('error', options.translations.imageUploadErrorText);
47                 console.log(err);
48             });
49         }, 10);
50     }
51 }
52
53 /**
54  * Upload an image file to the server
55  * @param {File} file
56  * @param {int} pageId
57  */
58 async function uploadImageFile(file, pageId) {
59     if (file === null || file.type.indexOf('image') !== 0) {
60         throw new Error(`Not an image file`);
61     }
62
63     const remoteFilename = file.name || `image-${Date.now()}.png`;
64     const formData = new FormData();
65     formData.append('file', file, remoteFilename);
66     formData.append('uploaded_to', pageId);
67
68     const resp = await window.$http.post(window.baseUrl('/images/gallery'), formData);
69     return resp.data;
70 }
71
72 /**
73  * @param {Editor} editor
74  * @param {WysiwygConfigOptions} options
75  */
76 function dragStart(editor, options) {
77     let node = editor.selection.getNode();
78
79     if (node.nodeName === 'IMG') {
80         wrap = editor.dom.getParent(node, '.mceTemp');
81
82         if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
83             wrap = node.parentNode;
84         }
85     }
86
87     // Track dragged contenteditable blocks
88     if (node.hasAttribute('contenteditable') && node.getAttribute('contenteditable') === 'false') {
89         draggedContentEditable = node;
90     }
91 }
92
93 /**
94  * @param {Editor} editor
95  * @param {WysiwygConfigOptions} options
96  * @param {DragEvent} event
97  */
98 function drop(editor, options, event) {
99     let dom = editor.dom,
100         rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
101
102     // Template insertion
103     const templateId = event.dataTransfer && event.dataTransfer.getData('bookstack/template');
104     if (templateId) {
105         event.preventDefault();
106         window.$http.get(`/templates/${templateId}`).then(resp => {
107             editor.selection.setRng(rng);
108             editor.undoManager.transact(function () {
109                 editor.execCommand('mceInsertContent', false, resp.data.html);
110             });
111         });
112     }
113
114     // Don't allow anything to be dropped in a captioned image.
115     if (dom.getParent(rng.startContainer, '.mceTemp')) {
116         event.preventDefault();
117     } else if (wrap) {
118         event.preventDefault();
119
120         editor.undoManager.transact(function () {
121             editor.selection.setRng(rng);
122             editor.selection.setNode(wrap);
123             dom.remove(wrap);
124         });
125     }
126
127     // Handle contenteditable section drop
128     if (!event.isDefaultPrevented() && draggedContentEditable) {
129         event.preventDefault();
130         editor.undoManager.transact(function () {
131             const selectedNode = editor.selection.getNode();
132             const range = editor.selection.getRng();
133             const selectedNodeRoot = selectedNode.closest('body > *');
134             if (range.startOffset > (range.startContainer.length / 2)) {
135                 editor.$(selectedNodeRoot).after(draggedContentEditable);
136             } else {
137                 editor.$(selectedNodeRoot).before(draggedContentEditable);
138             }
139         });
140     }
141
142     // Handle image insert
143     if (!event.isDefaultPrevented()) {
144         paste(editor, options, event);
145     }
146
147     wrap = null;
148 }
149
150 /**
151  * @param {Editor} editor
152  * @param {WysiwygConfigOptions} options
153  */
154 export function listenForDragAndPaste(editor, options) {
155     editor.on('dragstart', () => dragStart(editor, options));
156     editor.on('drop',  event => drop(editor, options, event));
157     editor.on('paste', event => paste(editor, options, event));
158 }