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