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