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