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