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