]> BookStack Code Mirror - bookstack/blob - resources/js/components/wysiwyg-editor.js
Merge branch 'api-endpoint-users' into users_api
[bookstack] / resources / js / components / wysiwyg-editor.js
1 import Code from "../services/code";
2 import DrawIO from "../services/drawio";
3 import Clipboard from "../services/clipboard";
4
5 /**
6  * Handle pasting images from clipboard.
7  * @param {ClipboardEvent} event
8  * @param {WysiwygEditor} wysiwygComponent
9  * @param editor
10  */
11 function editorPaste(event, editor, wysiwygComponent) {
12     const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
13
14     // Don't handle the event ourselves if no items exist of contains table-looking data
15     if (!clipboard.hasItems() || clipboard.containsTabularData()) {
16         return;
17     }
18
19     const images = clipboard.getImages();
20     for (const imageFile of images) {
21
22         const id = "image-" + Math.random().toString(16).slice(2);
23         const loadingImage = window.baseUrl('/loading.gif');
24         event.preventDefault();
25
26         setTimeout(() => {
27             editor.insertContent(`<p><img src="${loadingImage}" id="${id}"></p>`);
28
29             uploadImageFile(imageFile, wysiwygComponent).then(resp => {
30                 const safeName = resp.name.replace(/"/g, '');
31                 const newImageHtml = `<img src="${resp.thumbs.display}" alt="${safeName}" />`;
32
33                 const newEl = editor.dom.create('a', {
34                     target: '_blank',
35                     href: resp.url,
36                 }, newImageHtml);
37
38                 editor.dom.replace(newEl, id);
39             }).catch(err => {
40                 editor.dom.remove(id);
41                 window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
42                 console.log(err);
43             });
44         }, 10);
45     }
46 }
47
48 /**
49  * Upload an image file to the server
50  * @param {File} file
51  * @param {WysiwygEditor} wysiwygComponent
52  */
53 async function uploadImageFile(file, wysiwygComponent) {
54     if (file === null || file.type.indexOf('image') !== 0) {
55         throw new Error(`Not an image file`);
56     }
57
58     let ext = 'png';
59     if (file.name) {
60         let fileNameMatches = file.name.match(/\.(.+)$/);
61         if (fileNameMatches.length > 1) ext = fileNameMatches[1];
62     }
63
64     const remoteFilename = "image-" + Date.now() + "." + ext;
65     const formData = new FormData();
66     formData.append('file', file, remoteFilename);
67     formData.append('uploaded_to', wysiwygComponent.pageId);
68
69     const resp = await window.$http.post(window.baseUrl('/images/gallery'), formData);
70     return resp.data;
71 }
72
73 function registerEditorShortcuts(editor) {
74     // Headers
75     for (let i = 1; i < 5; i++) {
76         editor.shortcuts.add('meta+' + i, '', ['FormatBlock', false, 'h' + (i+1)]);
77     }
78
79     // Other block shortcuts
80     editor.shortcuts.add('meta+5', '', ['FormatBlock', false, 'p']);
81     editor.shortcuts.add('meta+d', '', ['FormatBlock', false, 'p']);
82     editor.shortcuts.add('meta+6', '', ['FormatBlock', false, 'blockquote']);
83     editor.shortcuts.add('meta+q', '', ['FormatBlock', false, 'blockquote']);
84     editor.shortcuts.add('meta+7', '', ['codeeditor', false, 'pre']);
85     editor.shortcuts.add('meta+e', '', ['codeeditor', false, 'pre']);
86     editor.shortcuts.add('meta+8', '', ['FormatBlock', false, 'code']);
87     editor.shortcuts.add('meta+shift+E', '', ['FormatBlock', false, 'code']);
88
89     // Save draft shortcut
90     editor.shortcuts.add('meta+S', '', () => {
91         window.$events.emit('editor-save-draft');
92     });
93
94     // Save page shortcut
95     editor.shortcuts.add('meta+13', '', () => {
96         window.$events.emit('editor-save-page');
97     });
98
99     // Loop through callout styles
100     editor.shortcuts.add('meta+9', '', function() {
101         const selectedNode = editor.selection.getNode();
102         const callout = selectedNode ? selectedNode.closest('.callout') : null;
103
104         const formats = ['info', 'success', 'warning', 'danger'];
105         const currentFormatIndex = formats.findIndex(format => callout && callout.classList.contains(format));
106         const newFormatIndex = (currentFormatIndex + 1) % formats.length;
107         const newFormat = formats[newFormatIndex];
108
109         editor.formatter.apply('callout' + newFormat);
110     });
111
112 }
113
114 /**
115  * Load custom HTML head content from the settings into the editor.
116  * @param editor
117  */
118 function loadCustomHeadContent(editor) {
119     window.$http.get(window.baseUrl('/custom-head-content')).then(resp => {
120         if (!resp.data) return;
121         let head = editor.getDoc().querySelector('head');
122         head.innerHTML += resp.data;
123     });
124 }
125
126 /**
127  * Create and enable our custom code plugin
128  */
129 function codePlugin() {
130
131     function elemIsCodeBlock(elem) {
132         return elem.className === 'CodeMirrorContainer';
133     }
134
135     function showPopup(editor) {
136         const selectedNode = editor.selection.getNode();
137
138         if (!elemIsCodeBlock(selectedNode)) {
139             const providedCode = editor.selection.getNode().textContent;
140             window.components.first('code-editor').open(providedCode, '', (code, lang) => {
141                 const wrap = document.createElement('div');
142                 wrap.innerHTML = `<pre><code class="language-${lang}"></code></pre>`;
143                 wrap.querySelector('code').innerText = code;
144
145                 editor.formatter.toggle('pre');
146                 const node = editor.selection.getNode();
147                 editor.dom.setHTML(node, wrap.querySelector('pre').innerHTML);
148                 editor.fire('SetContent');
149
150                 editor.focus()
151             });
152             return;
153         }
154
155         const lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
156         const currentCode = selectedNode.querySelector('textarea').textContent;
157
158         window.components.first('code-editor').open(currentCode, lang, (code, lang) => {
159             const editorElem = selectedNode.querySelector('.CodeMirror');
160             const cmInstance = editorElem.CodeMirror;
161             if (cmInstance) {
162                 Code.setContent(cmInstance, code);
163                 Code.setMode(cmInstance, lang, code);
164             }
165             const textArea = selectedNode.querySelector('textarea');
166             if (textArea) textArea.textContent = code;
167             selectedNode.setAttribute('data-lang', lang);
168
169             editor.focus()
170         });
171     }
172
173     function codeMirrorContainerToPre(codeMirrorContainer) {
174         const textArea = codeMirrorContainer.querySelector('textarea');
175         const code = textArea.textContent;
176         const lang = codeMirrorContainer.getAttribute('data-lang');
177
178         codeMirrorContainer.removeAttribute('contentEditable');
179         const pre = document.createElement('pre');
180         const codeElem = document.createElement('code');
181         codeElem.classList.add(`language-${lang}`);
182         codeElem.textContent = code;
183         pre.appendChild(codeElem);
184
185         codeMirrorContainer.parentElement.replaceChild(pre, codeMirrorContainer);
186     }
187
188     window.tinymce.PluginManager.add('codeeditor', function(editor, url) {
189
190         const $ = editor.$;
191
192         editor.addButton('codeeditor', {
193             text: 'Code block',
194             icon: false,
195             cmd: 'codeeditor'
196         });
197
198         editor.addCommand('codeeditor', () => {
199             showPopup(editor);
200         });
201
202         // Convert
203         editor.on('PreProcess', function (e) {
204             $('div.CodeMirrorContainer', e.node).each((index, elem) => {
205                 codeMirrorContainerToPre(elem);
206             });
207         });
208
209         editor.on('dblclick', event => {
210             let selectedNode = editor.selection.getNode();
211             if (!elemIsCodeBlock(selectedNode)) return;
212             showPopup(editor);
213         });
214
215         function parseCodeMirrorInstances() {
216
217             // Recover broken codemirror instances
218             $('.CodeMirrorContainer').filter((index ,elem) => {
219                 return typeof elem.querySelector('.CodeMirror').CodeMirror === 'undefined';
220             }).each((index, elem) => {
221                 codeMirrorContainerToPre(elem);
222             });
223
224             const codeSamples = $('body > pre').filter((index, elem) => {
225                 return elem.contentEditable !== "false";
226             });
227
228             codeSamples.each((index, elem) => {
229                 Code.wysiwygView(elem);
230             });
231         }
232
233         editor.on('init', function() {
234             // Parse code mirror instances on init, but delay a little so this runs after
235             // initial styles are fetched into the editor.
236             editor.undoManager.transact(function () {
237                 parseCodeMirrorInstances();
238             });
239             // Parsed code mirror blocks when content is set but wait before setting this handler
240             // to avoid any init 'SetContent' events.
241             setTimeout(() => {
242                 editor.on('SetContent', () => {
243                     setTimeout(parseCodeMirrorInstances, 100);
244                 });
245             }, 200);
246         });
247
248     });
249 }
250
251 function drawIoPlugin(drawioUrl, isDarkMode, pageId, wysiwygComponent) {
252
253     let pageEditor = null;
254     let currentNode = null;
255
256     function isDrawing(node) {
257         return node.hasAttribute('drawio-diagram');
258     }
259
260     function showDrawingManager(mceEditor, selectedNode = null) {
261         pageEditor = mceEditor;
262         currentNode = selectedNode;
263         // Show image manager
264         window.ImageManager.show(function (image) {
265             if (selectedNode) {
266                 let imgElem = selectedNode.querySelector('img');
267                 pageEditor.dom.setAttrib(imgElem, 'src', image.url);
268                 pageEditor.dom.setAttrib(selectedNode, 'drawio-diagram', image.id);
269             } else {
270                 let imgHTML = `<div drawio-diagram="${image.id}" contenteditable="false"><img src="${image.url}"></div>`;
271                 pageEditor.insertContent(imgHTML);
272             }
273         }, 'drawio');
274     }
275
276     function showDrawingEditor(mceEditor, selectedNode = null) {
277         pageEditor = mceEditor;
278         currentNode = selectedNode;
279         DrawIO.show(drawioUrl, drawingInit, updateContent);
280     }
281
282     async function updateContent(pngData) {
283         const id = "image-" + Math.random().toString(16).slice(2);
284         const loadingImage = window.baseUrl('/loading.gif');
285
286         const handleUploadError = (error) => {
287             if (error.status === 413) {
288                 window.$events.emit('error', wysiwygComponent.serverUploadLimitText);
289             } else {
290                 window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
291             }
292             console.log(error);
293         };
294
295         // Handle updating an existing image
296         if (currentNode) {
297             DrawIO.close();
298             let imgElem = currentNode.querySelector('img');
299             try {
300                 const img = await DrawIO.upload(pngData, pageId);
301                 pageEditor.dom.setAttrib(imgElem, 'src', img.url);
302                 pageEditor.dom.setAttrib(currentNode, 'drawio-diagram', img.id);
303             } catch (err) {
304                 handleUploadError(err);
305             }
306             return;
307         }
308
309         setTimeout(async () => {
310             pageEditor.insertContent(`<div drawio-diagram contenteditable="false"><img src="${loadingImage}" id="${id}"></div>`);
311             DrawIO.close();
312             try {
313                 const img = await DrawIO.upload(pngData, pageId);
314                 pageEditor.dom.setAttrib(id, 'src', img.url);
315                 pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', img.id);
316             } catch (err) {
317                 pageEditor.dom.remove(id);
318                 handleUploadError(err);
319             }
320         }, 5);
321     }
322
323
324     function drawingInit() {
325         if (!currentNode) {
326             return Promise.resolve('');
327         }
328
329         let drawingId = currentNode.getAttribute('drawio-diagram');
330         return DrawIO.load(drawingId);
331     }
332
333     window.tinymce.PluginManager.add('drawio', function(editor, url) {
334
335         editor.addCommand('drawio', () => {
336             const selectedNode = editor.selection.getNode();
337             showDrawingEditor(editor, isDrawing(selectedNode) ? selectedNode : null);
338         });
339
340         editor.addButton('drawio', {
341             type: 'splitbutton',
342             tooltip: 'Drawing',
343             image: `data:image/svg+xml;base64,${btoa(`<svg viewBox="0 0 24 24" fill="${isDarkMode ? '#BBB' : '#000000'}"  xmlns="http://www.w3.org/2000/svg">
344     <path d="M23 7V1h-6v2H7V1H1v6h2v10H1v6h6v-2h10v2h6v-6h-2V7h2zM3 3h2v2H3V3zm2 18H3v-2h2v2zm12-2H7v-2H5V7h2V5h10v2h2v10h-2v2zm4 2h-2v-2h2v2zM19 5V3h2v2h-2zm-5.27 9h-3.49l-.73 2H7.89l3.4-9h1.4l3.41 9h-1.63l-.74-2zm-3.04-1.26h2.61L12 8.91l-1.31 3.83z"/>
345     <path d="M0 0h24v24H0z" fill="none"/>
346 </svg>`)}`,
347             cmd: 'drawio',
348             menu: [
349                 {
350                     text: 'Drawing Manager',
351                     onclick() {
352                         let selectedNode = editor.selection.getNode();
353                         showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
354                     }
355                 }
356             ]
357         });
358
359         editor.on('dblclick', event => {
360             let selectedNode = editor.selection.getNode();
361             if (!isDrawing(selectedNode)) return;
362             showDrawingEditor(editor, selectedNode);
363         });
364
365         editor.on('SetContent', function () {
366             const drawings = editor.$('body > div[drawio-diagram]');
367             if (!drawings.length) return;
368
369             editor.undoManager.transact(function () {
370                 drawings.each((index, elem) => {
371                     elem.setAttribute('contenteditable', 'false');
372                 });
373             });
374         });
375
376     });
377 }
378
379 function customHrPlugin() {
380     window.tinymce.PluginManager.add('customhr', function (editor) {
381         editor.addCommand('InsertHorizontalRule', function () {
382             let hrElem = document.createElement('hr');
383             let cNode = editor.selection.getNode();
384             let parentNode = cNode.parentNode;
385             parentNode.insertBefore(hrElem, cNode);
386         });
387
388         editor.addButton('hr', {
389             icon: 'hr',
390             tooltip: 'Horizontal line',
391             cmd: 'InsertHorizontalRule'
392         });
393
394         editor.addMenuItem('hr', {
395             icon: 'hr',
396             text: 'Horizontal line',
397             cmd: 'InsertHorizontalRule',
398             context: 'insert'
399         });
400     });
401 }
402
403
404 function listenForBookStackEditorEvents(editor) {
405
406     // Replace editor content
407     window.$events.listen('editor::replace', ({html}) => {
408         editor.setContent(html);
409     });
410
411     // Append editor content
412     window.$events.listen('editor::append', ({html}) => {
413         const content = editor.getContent() + html;
414         editor.setContent(content);
415     });
416
417     // Prepend editor content
418     window.$events.listen('editor::prepend', ({html}) => {
419         const content = html + editor.getContent();
420         editor.setContent(content);
421     });
422
423     // Insert editor content at the current location
424     window.$events.listen('editor::insert', ({html}) => {
425         editor.insertContent(html);
426     });
427
428     // Focus on the editor
429     window.$events.listen('editor::focus', () => {
430         editor.focus();
431     });
432 }
433
434 class WysiwygEditor {
435
436     setup() {
437         this.elem = this.$el;
438
439         this.pageId = this.$opts.pageId;
440         this.textDirection = this.$opts.textDirection;
441         this.imageUploadErrorText = this.$opts.imageUploadErrorText;
442         this.serverUploadLimitText = this.$opts.serverUploadLimitText;
443         this.isDarkMode = document.documentElement.classList.contains('dark-mode');
444
445         this.plugins = "image imagetools table textcolor paste link autolink fullscreen code customhr autosave lists codeeditor media";
446         this.loadPlugins();
447
448         this.tinyMceConfig = this.getTinyMceConfig();
449         window.$events.emitPublic(this.elem, 'editor-tinymce::pre-init', {config: this.tinyMceConfig});
450         window.tinymce.init(this.tinyMceConfig);
451     }
452
453     loadPlugins() {
454         codePlugin();
455         customHrPlugin();
456
457         const drawioUrlElem = document.querySelector('[drawio-url]');
458         if (drawioUrlElem) {
459             const url = drawioUrlElem.getAttribute('drawio-url');
460             drawIoPlugin(url, this.isDarkMode, this.pageId, this);
461             this.plugins += ' drawio';
462         }
463
464         if (this.textDirection === 'rtl') {
465             this.plugins += ' directionality'
466         }
467     }
468
469     getToolBar() {
470         const textDirPlugins = this.textDirection === 'rtl' ? 'ltr rtl' : '';
471         return `undo redo | styleselect | bold italic underline strikethrough superscript subscript | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | table image-insert link hr drawio media | removeformat code ${textDirPlugins} fullscreen`
472     }
473
474     getTinyMceConfig() {
475
476         const context = this;
477
478         return {
479             selector: '#html-editor',
480             content_css: [
481                 window.baseUrl('/dist/styles.css'),
482             ],
483             branding: false,
484             skin: this.isDarkMode ? 'dark' : 'lightgray',
485             body_class: 'page-content',
486             browser_spellcheck: true,
487             relative_urls: false,
488             directionality : this.textDirection,
489             remove_script_host: false,
490             document_base_url: window.baseUrl('/'),
491             end_container_on_empty_block: true,
492             statusbar: false,
493             menubar: false,
494             paste_data_images: false,
495             extended_valid_elements: 'pre[*],svg[*],div[drawio-diagram]',
496             automatic_uploads: false,
497             valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre],+div[img]",
498             plugins: this.plugins,
499             imagetools_toolbar: 'imageoptions',
500             toolbar: this.getToolBar(),
501             content_style: `html, body, html.dark-mode {background: ${this.isDarkMode ? '#222' : '#fff'};} body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}`,
502             style_formats: [
503                 {title: "Header Large", format: "h2"},
504                 {title: "Header Medium", format: "h3"},
505                 {title: "Header Small", format: "h4"},
506                 {title: "Header Tiny", format: "h5"},
507                 {title: "Paragraph", format: "p", exact: true, classes: ''},
508                 {title: "Blockquote", format: "blockquote"},
509                 {title: "Code Block", icon: "code", cmd: 'codeeditor', format: 'codeeditor'},
510                 {title: "Inline Code", icon: "code", inline: "code"},
511                 {title: "Callouts", items: [
512                         {title: "Info", format: 'calloutinfo'},
513                         {title: "Success", format: 'calloutsuccess'},
514                         {title: "Warning", format: 'calloutwarning'},
515                         {title: "Danger", format: 'calloutdanger'}
516                     ]},
517             ],
518             style_formats_merge: false,
519             media_alt_source: false,
520             media_poster: false,
521             formats: {
522                 codeeditor: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div'},
523                 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
524                 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
525                 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
526                 calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
527                 calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
528                 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
529                 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
530             },
531             file_browser_callback: function (field_name, url, type, win) {
532
533                 if (type === 'file') {
534                     window.EntitySelectorPopup.show(function(entity) {
535                         const originalField = win.document.getElementById(field_name);
536                         originalField.value = entity.link;
537                         const mceForm = originalField.closest('.mce-form');
538                         const inputs = mceForm.querySelectorAll('input');
539
540                         // Set text to display if not empty
541                         if (!inputs[1].value) {
542                             inputs[1].value = entity.name;
543                         }
544
545                         // Set title field
546                         inputs[2].value = entity.name;
547                     });
548                 }
549
550                 if (type === 'image') {
551                     // Show image manager
552                     window.ImageManager.show(function (image) {
553
554                         // Set popover link input to image url then fire change event
555                         // to ensure the new value sticks
556                         win.document.getElementById(field_name).value = image.url;
557                         if ("createEvent" in document) {
558                             let evt = document.createEvent("HTMLEvents");
559                             evt.initEvent("change", false, true);
560                             win.document.getElementById(field_name).dispatchEvent(evt);
561                         } else {
562                             win.document.getElementById(field_name).fireEvent("onchange");
563                         }
564
565                         // Replace the actively selected content with the linked image
566                         const imageUrl = image.thumbs.display || image.url;
567                         let html = `<a href="${image.url}" target="_blank">`;
568                         html += `<img src="${imageUrl}" alt="${image.name}">`;
569                         html += '</a>';
570                         win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
571                     }, 'gallery');
572                 }
573
574             },
575             paste_preprocess: function (plugin, args) {
576                 let content = args.content;
577                 if (content.indexOf('<img src="file://') !== -1) {
578                     args.content = '';
579                 }
580             },
581             init_instance_callback: function(editor) {
582                 loadCustomHeadContent(editor);
583             },
584             setup: function (editor) {
585
586                 editor.on('ExecCommand change input NodeChange ObjectResized', editorChange);
587
588                 editor.on('init', () => {
589                     editorChange();
590                     // Scroll to the content if needed.
591                     const queryParams = (new URL(window.location)).searchParams;
592                     const scrollId = queryParams.get('content-id');
593                     if (scrollId) {
594                         scrollToText(scrollId);
595                     }
596
597                     // Override for touch events to allow scroll on mobile
598                     const container = editor.getContainer();
599                     const toolbarButtons = container.querySelectorAll('.mce-btn');
600                     for (let button of toolbarButtons) {
601                         button.addEventListener('touchstart', event => {
602                             event.stopPropagation();
603                         });
604                     }
605                     window.editor = editor;
606                 });
607
608                 function editorChange() {
609                     const content = editor.getContent();
610                     if (context.isDarkMode) {
611                         editor.contentDocument.documentElement.classList.add('dark-mode');
612                     }
613                     window.$events.emit('editor-html-change', content);
614                 }
615
616                 function scrollToText(scrollId) {
617                     const element = editor.dom.get(encodeURIComponent(scrollId).replace(/!/g, '%21'));
618                     if (!element) {
619                         return;
620                     }
621
622                     // scroll the element into the view and put the cursor at the end.
623                     element.scrollIntoView();
624                     editor.selection.select(element, true);
625                     editor.selection.collapse(false);
626                     editor.focus();
627                 }
628
629                 listenForBookStackEditorEvents(editor);
630
631                 // TODO - Update to standardise across both editors
632                 // Use events within listenForBookStackEditorEvents instead (Different event signature)
633                 window.$events.listen('editor-html-update', html => {
634                     editor.setContent(html);
635                     editor.selection.select(editor.getBody(), true);
636                     editor.selection.collapse(false);
637                     editorChange(html);
638                 });
639
640                 registerEditorShortcuts(editor);
641
642                 let wrap;
643                 let draggedContentEditable;
644
645                 function hasTextContent(node) {
646                     return node && !!( node.textContent || node.innerText );
647                 }
648
649                 editor.on('dragstart', function () {
650                     let node = editor.selection.getNode();
651
652                     if (node.nodeName === 'IMG') {
653                         wrap = editor.dom.getParent(node, '.mceTemp');
654
655                         if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
656                             wrap = node.parentNode;
657                         }
658                     }
659
660                     // Track dragged contenteditable blocks
661                     if (node.hasAttribute('contenteditable') && node.getAttribute('contenteditable') === 'false') {
662                         draggedContentEditable = node;
663                     }
664
665                 });
666
667                 // Custom drop event handling
668                 editor.on('drop', function (event) {
669                     let dom = editor.dom,
670                         rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
671
672                     // Template insertion
673                     const templateId = event.dataTransfer && event.dataTransfer.getData('bookstack/template');
674                     if (templateId) {
675                         event.preventDefault();
676                         window.$http.get(`/templates/${templateId}`).then(resp => {
677                             editor.selection.setRng(rng);
678                             editor.undoManager.transact(function () {
679                                 editor.execCommand('mceInsertContent', false, resp.data.html);
680                             });
681                         });
682                     }
683
684                     // Don't allow anything to be dropped in a captioned image.
685                     if (dom.getParent(rng.startContainer, '.mceTemp')) {
686                         event.preventDefault();
687                     } else if (wrap) {
688                         event.preventDefault();
689
690                         editor.undoManager.transact(function () {
691                             editor.selection.setRng(rng);
692                             editor.selection.setNode(wrap);
693                             dom.remove(wrap);
694                         });
695                     }
696
697                     // Handle contenteditable section drop
698                     if (!event.isDefaultPrevented() && draggedContentEditable) {
699                         event.preventDefault();
700                         editor.undoManager.transact(function () {
701                             const selectedNode = editor.selection.getNode();
702                             const range = editor.selection.getRng();
703                             const selectedNodeRoot = selectedNode.closest('body > *');
704                             if (range.startOffset > (range.startContainer.length / 2)) {
705                                 editor.$(selectedNodeRoot).after(draggedContentEditable);
706                             } else {
707                                 editor.$(selectedNodeRoot).before(draggedContentEditable);
708                             }
709                         });
710                     }
711
712                     // Handle image insert
713                     if (!event.isDefaultPrevented()) {
714                         editorPaste(event, editor, context);
715                     }
716
717                     wrap = null;
718                 });
719
720                 // Custom Image picker button
721                 editor.addButton('image-insert', {
722                     title: 'My title',
723                     icon: 'image',
724                     tooltip: 'Insert an image',
725                     onclick: function () {
726                         window.ImageManager.show(function (image) {
727                             const imageUrl = image.thumbs.display || image.url;
728                             let html = `<a href="${image.url}" target="_blank">`;
729                             html += `<img src="${imageUrl}" alt="${image.name}">`;
730                             html += '</a>';
731                             editor.execCommand('mceInsertContent', false, html);
732                         }, 'gallery');
733                     }
734                 });
735
736                 // Paste image-uploads
737                 editor.on('paste', event => editorPaste(event, editor, context));
738
739                 // Custom handler hook
740                 window.$events.emitPublic(context.elem, 'editor-tinymce::setup', {editor});
741             }
742         };
743     }
744
745 }
746
747 export default WysiwygEditor;