]> BookStack Code Mirror - bookstack/blob - resources/js/components/wysiwyg-editor.js
Made further tweaks to align with current editor
[bookstack] / resources / js / components / wysiwyg-editor.js
1 import Code from "../services/code";
2 import DrawIO from "../services/drawio";
3 import Clipboard from "../services/clipboard";
4
5 /**
6  * Handle pasting images from clipboard.
7  * @param {ClipboardEvent} event
8  * @param {WysiwygEditor} wysiwygComponent
9  * @param editor
10  */
11 function editorPaste(event, editor, wysiwygComponent) {
12     const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
13
14     // Don't handle the event ourselves if no items exist of contains table-looking data
15     if (!clipboard.hasItems() || clipboard.containsTabularData()) {
16         return;
17     }
18
19     const images = clipboard.getImages();
20     for (const imageFile of images) {
21
22         const id = "image-" + Math.random().toString(16).slice(2);
23         const loadingImage = window.baseUrl('/loading.gif');
24         event.preventDefault();
25
26         setTimeout(() => {
27             editor.insertContent(`<p><img src="${loadingImage}" id="${id}"></p>`);
28
29             uploadImageFile(imageFile, wysiwygComponent).then(resp => {
30                 const safeName = resp.name.replace(/"/g, '');
31                 const newImageHtml = `<img src="${resp.thumbs.display}" alt="${safeName}" />`;
32
33                 const newEl = editor.dom.create('a', {
34                     target: '_blank',
35                     href: resp.url,
36                 }, newImageHtml);
37
38                 editor.dom.replace(newEl, id);
39             }).catch(err => {
40                 editor.dom.remove(id);
41                 window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
42                 console.log(err);
43             });
44         }, 10);
45     }
46 }
47
48 /**
49  * Upload an image file to the server
50  * @param {File} file
51  * @param {WysiwygEditor} wysiwygComponent
52  */
53 async function uploadImageFile(file, wysiwygComponent) {
54     if (file === null || file.type.indexOf('image') !== 0) {
55         throw new Error(`Not an image file`);
56     }
57
58     let ext = 'png';
59     if (file.name) {
60         let fileNameMatches = file.name.match(/\.(.+)$/);
61         if (fileNameMatches.length > 1) ext = fileNameMatches[1];
62     }
63
64     const remoteFilename = "image-" + Date.now() + "." + ext;
65     const formData = new FormData();
66     formData.append('file', file, remoteFilename);
67     formData.append('uploaded_to', wysiwygComponent.pageId);
68
69     const resp = await window.$http.post(window.baseUrl('/images/gallery'), formData);
70     return resp.data;
71 }
72
73 function registerEditorShortcuts(editor) {
74     // Headers
75     for (let i = 1; i < 5; i++) {
76         editor.shortcuts.add('meta+' + i, '', ['FormatBlock', false, 'h' + (i+1)]);
77     }
78
79     // Other block shortcuts
80     editor.shortcuts.add('meta+5', '', ['FormatBlock', false, 'p']);
81     editor.shortcuts.add('meta+d', '', ['FormatBlock', false, 'p']);
82     editor.shortcuts.add('meta+6', '', ['FormatBlock', false, 'blockquote']);
83     editor.shortcuts.add('meta+q', '', ['FormatBlock', false, 'blockquote']);
84     editor.shortcuts.add('meta+7', '', ['codeeditor', false, 'pre']);
85     editor.shortcuts.add('meta+e', '', ['codeeditor', false, 'pre']);
86     editor.shortcuts.add('meta+8', '', ['FormatBlock', false, 'code']);
87     editor.shortcuts.add('meta+shift+E', '', ['FormatBlock', false, 'code']);
88
89     // Save draft shortcut
90     editor.shortcuts.add('meta+S', '', () => {
91         window.$events.emit('editor-save-draft');
92     });
93
94     // Save page shortcut
95     editor.shortcuts.add('meta+13', '', () => {
96         window.$events.emit('editor-save-page');
97     });
98
99     // Loop through callout styles
100     editor.shortcuts.add('meta+9', '', function() {
101         const selectedNode = editor.selection.getNode();
102         const callout = selectedNode ? selectedNode.closest('.callout') : null;
103
104         const formats = ['info', 'success', 'warning', 'danger'];
105         const currentFormatIndex = formats.findIndex(format => callout && callout.classList.contains(format));
106         const newFormatIndex = (currentFormatIndex + 1) % formats.length;
107         const newFormat = formats[newFormatIndex];
108
109         editor.formatter.apply('callout' + newFormat);
110     });
111
112 }
113
114 /**
115  * Load custom HTML head content from the settings into the editor.
116  * @param editor
117  */
118 function loadCustomHeadContent(editor) {
119     window.$http.get(window.baseUrl('/custom-head-content')).then(resp => {
120         if (!resp.data) return;
121         let head = editor.getDoc().querySelector('head');
122         head.innerHTML += resp.data;
123     });
124 }
125
126 /**
127  * Create and enable our custom code plugin
128  */
129 function codePlugin() {
130
131     function elemIsCodeBlock(elem) {
132         return elem.className === 'CodeMirrorContainer';
133     }
134
135     function showPopup(editor) {
136         const selectedNode = editor.selection.getNode();
137
138         if (!elemIsCodeBlock(selectedNode)) {
139             const providedCode = editor.selection.getNode().textContent;
140             window.components.first('code-editor').open(providedCode, '', (code, lang) => {
141                 const wrap = document.createElement('div');
142                 wrap.innerHTML = `<pre><code class="language-${lang}"></code></pre>`;
143                 wrap.querySelector('code').innerText = code;
144
145                 editor.formatter.toggle('pre');
146                 const node = editor.selection.getNode();
147                 editor.dom.setHTML(node, wrap.querySelector('pre').innerHTML);
148                 editor.fire('SetContent');
149
150                 editor.focus()
151             });
152             return;
153         }
154
155         const lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
156         const currentCode = selectedNode.querySelector('textarea').textContent;
157
158         window.components.first('code-editor').open(currentCode, lang, (code, lang) => {
159             const editorElem = selectedNode.querySelector('.CodeMirror');
160             const cmInstance = editorElem.CodeMirror;
161             if (cmInstance) {
162                 Code.setContent(cmInstance, code);
163                 Code.setMode(cmInstance, lang, code);
164             }
165             const textArea = selectedNode.querySelector('textarea');
166             if (textArea) textArea.textContent = code;
167             selectedNode.setAttribute('data-lang', lang);
168
169             editor.focus()
170         });
171     }
172
173     function codeMirrorContainerToPre(codeMirrorContainer) {
174         const textArea = codeMirrorContainer.querySelector('textarea');
175         const code = textArea.textContent;
176         const lang = codeMirrorContainer.getAttribute('data-lang');
177
178         codeMirrorContainer.removeAttribute('contentEditable');
179         const pre = document.createElement('pre');
180         const codeElem = document.createElement('code');
181         codeElem.classList.add(`language-${lang}`);
182         codeElem.textContent = code;
183         pre.appendChild(codeElem);
184
185         codeMirrorContainer.parentElement.replaceChild(pre, codeMirrorContainer);
186     }
187
188     window.tinymce.PluginManager.add('codeeditor', function(editor, url) {
189
190         const $ = editor.$;
191
192         editor.ui.registry.addIcon('codeblock', '<svg width="24" height="24"><path d="M4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 0 1-1-1V4c0-.6.4-1 1-1Zm1 2v14h14V5Z"/><path d="M11.103 15.423c.277.277.277.738 0 .922a.692.692 0 0 1-1.106 0l-4.057-3.78a.738.738 0 0 1 0-1.107l4.057-3.872c.276-.277.83-.277 1.106 0a.724.724 0 0 1 0 1.014L7.6 12.012ZM12.897 8.577c-.245-.312-.2-.675.08-.955.28-.281.727-.27 1.027.033l4.057 3.78a.738.738 0 0 1 0 1.107l-4.057 3.872c-.277.277-.83.277-1.107 0a.724.724 0 0 1 0-1.014l3.504-3.412z"/></svg>')
193
194         editor.ui.registry.addButton('codeeditor', {
195             title: 'Insert code block',
196             icon: 'codeblock',
197             onAction() {
198                 editor.execCommand('codeeditor');
199             }
200         });
201
202         editor.addCommand('codeeditor', () => {
203             showPopup(editor);
204         });
205
206         // Convert
207         editor.on('PreProcess', function (e) {
208             $('div.CodeMirrorContainer', e.node).each((index, elem) => {
209                 codeMirrorContainerToPre(elem);
210             });
211         });
212
213         editor.on('dblclick', event => {
214             let selectedNode = editor.selection.getNode();
215             if (!elemIsCodeBlock(selectedNode)) return;
216             showPopup(editor);
217         });
218
219         function parseCodeMirrorInstances() {
220
221             // Recover broken codemirror instances
222             $('.CodeMirrorContainer').filter((index ,elem) => {
223                 return typeof elem.querySelector('.CodeMirror').CodeMirror === 'undefined';
224             }).each((index, elem) => {
225                 codeMirrorContainerToPre(elem);
226             });
227
228             const codeSamples = $('body > pre').filter((index, elem) => {
229                 return elem.contentEditable !== "false";
230             });
231
232             codeSamples.each((index, elem) => {
233                 Code.wysiwygView(elem);
234             });
235         }
236
237         editor.on('init', function() {
238             // Parse code mirror instances on init, but delay a little so this runs after
239             // initial styles are fetched into the editor.
240             editor.undoManager.transact(function () {
241                 parseCodeMirrorInstances();
242             });
243             // Parsed code mirror blocks when content is set but wait before setting this handler
244             // to avoid any init 'SetContent' events.
245             setTimeout(() => {
246                 editor.on('SetContent', () => {
247                     setTimeout(parseCodeMirrorInstances, 100);
248                 });
249             }, 200);
250         });
251
252     });
253 }
254
255 function drawIoPlugin(drawioUrl, isDarkMode, pageId, wysiwygComponent) {
256
257     let pageEditor = null;
258     let currentNode = null;
259
260     function isDrawing(node) {
261         return node.hasAttribute('drawio-diagram');
262     }
263
264     function showDrawingManager(mceEditor, selectedNode = null) {
265         pageEditor = mceEditor;
266         currentNode = selectedNode;
267         // Show image manager
268         window.ImageManager.show(function (image) {
269             if (selectedNode) {
270                 let imgElem = selectedNode.querySelector('img');
271                 pageEditor.dom.setAttrib(imgElem, 'src', image.url);
272                 pageEditor.dom.setAttrib(selectedNode, 'drawio-diagram', image.id);
273             } else {
274                 let imgHTML = `<div drawio-diagram="${image.id}" contenteditable="false"><img src="${image.url}"></div>`;
275                 pageEditor.insertContent(imgHTML);
276             }
277         }, 'drawio');
278     }
279
280     function showDrawingEditor(mceEditor, selectedNode = null) {
281         pageEditor = mceEditor;
282         currentNode = selectedNode;
283         DrawIO.show(drawioUrl, drawingInit, updateContent);
284     }
285
286     async function updateContent(pngData) {
287         const id = "image-" + Math.random().toString(16).slice(2);
288         const loadingImage = window.baseUrl('/loading.gif');
289
290         const handleUploadError = (error) => {
291             if (error.status === 413) {
292                 window.$events.emit('error', wysiwygComponent.serverUploadLimitText);
293             } else {
294                 window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
295             }
296             console.log(error);
297         };
298
299         // Handle updating an existing image
300         if (currentNode) {
301             DrawIO.close();
302             let imgElem = currentNode.querySelector('img');
303             try {
304                 const img = await DrawIO.upload(pngData, pageId);
305                 pageEditor.dom.setAttrib(imgElem, 'src', img.url);
306                 pageEditor.dom.setAttrib(currentNode, 'drawio-diagram', img.id);
307             } catch (err) {
308                 handleUploadError(err);
309             }
310             return;
311         }
312
313         setTimeout(async () => {
314             pageEditor.insertContent(`<div drawio-diagram contenteditable="false"><img src="${loadingImage}" id="${id}"></div>`);
315             DrawIO.close();
316             try {
317                 const img = await DrawIO.upload(pngData, pageId);
318                 pageEditor.dom.setAttrib(id, 'src', img.url);
319                 pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', img.id);
320             } catch (err) {
321                 pageEditor.dom.remove(id);
322                 handleUploadError(err);
323             }
324         }, 5);
325     }
326
327
328     function drawingInit() {
329         if (!currentNode) {
330             return Promise.resolve('');
331         }
332
333         let drawingId = currentNode.getAttribute('drawio-diagram');
334         return DrawIO.load(drawingId);
335     }
336
337     window.tinymce.PluginManager.add('drawio', function(editor, url) {
338
339         editor.addCommand('drawio', () => {
340             const selectedNode = editor.selection.getNode();
341             showDrawingEditor(editor, isDrawing(selectedNode) ? selectedNode : null);
342         });
343
344         // editor.ui.registry.addIcon('diagram', `<svg height="24" width="24" fill="${isDarkMode ? '#BBB' : '#000000'}"  ><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"/></svg>`)
345         editor.ui.registry.addIcon('diagram', `<svg width="24" height="24" fill="${isDarkMode ? '#BBB' : '#000000'}" xmlns="http://www.w3.org/2000/svg"><path d="M20.716 7.639V2.845h-4.794v1.598h-7.99V2.845H3.138v4.794h1.598v7.99H3.138v4.794h4.794v-1.598h7.99v1.598h4.794v-4.794h-1.598v-7.99zM4.736 4.443h1.598V6.04H4.736zm1.598 14.382H4.736v-1.598h1.598zm9.588-1.598h-7.99v-1.598H6.334v-7.99h1.598V6.04h7.99v1.598h1.598v7.99h-1.598zm3.196 1.598H17.52v-1.598h1.598zM17.52 6.04V4.443h1.598V6.04zm-4.21 7.19h-2.79l-.582 1.599H8.643l2.717-7.191h1.119l2.724 7.19h-1.302zm-2.43-1.006h2.086l-1.039-3.06z"/></svg>`)
346
347         editor.ui.registry.addSplitButton('drawio', {
348             tooltip: 'Drawing',
349             icon: 'diagram',
350             onAction() {
351                 editor.execCommand('drawio');
352             },
353             fetch(callback) {
354                 callback([
355                     {
356                         type: 'choiceitem',
357                         text: 'Drawing Manager',
358                         value: 'drawing-manager',
359                     }
360                 ]);
361             },
362             onItemAction(api, value) {
363                 if (value === 'drawing-manager') {
364                     const selectedNode = editor.selection.getNode();
365                     showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
366                 }
367             }
368         });
369
370         editor.on('dblclick', event => {
371             let selectedNode = editor.selection.getNode();
372             if (!isDrawing(selectedNode)) return;
373             showDrawingEditor(editor, selectedNode);
374         });
375
376         editor.on('SetContent', function () {
377             const drawings = editor.$('body > div[drawio-diagram]');
378             if (!drawings.length) return;
379
380             editor.undoManager.transact(function () {
381                 drawings.each((index, elem) => {
382                     elem.setAttribute('contenteditable', 'false');
383                 });
384             });
385         });
386
387     });
388 }
389
390 function customHrPlugin() {
391     window.tinymce.PluginManager.add('customhr', function (editor) {
392         editor.addCommand('InsertHorizontalRule', function () {
393             let hrElem = document.createElement('hr');
394             let cNode = editor.selection.getNode();
395             let parentNode = cNode.parentNode;
396             parentNode.insertBefore(hrElem, cNode);
397         });
398
399         editor.ui.registry.addButton('hr', {
400             icon: 'horizontal-rule',
401             tooltip: 'Horizontal line',
402             onAction() {
403                 editor.execCommand('InsertHorizontalRule');
404             }
405         });
406
407         editor.ui.registry.addMenuItem('hr', {
408             icon: 'horizontal-rule',
409             text: 'Horizontal line',
410             context: 'insert',
411             onAction() {
412                 editor.execCommand('InsertHorizontalRule');
413             }
414         });
415     });
416 }
417
418
419 function listenForBookStackEditorEvents(editor) {
420
421     // Replace editor content
422     window.$events.listen('editor::replace', ({html}) => {
423         editor.setContent(html);
424     });
425
426     // Append editor content
427     window.$events.listen('editor::append', ({html}) => {
428         const content = editor.getContent() + html;
429         editor.setContent(content);
430     });
431
432     // Prepend editor content
433     window.$events.listen('editor::prepend', ({html}) => {
434         const content = html + editor.getContent();
435         editor.setContent(content);
436     });
437
438     // Insert editor content at the current location
439     window.$events.listen('editor::insert', ({html}) => {
440         editor.insertContent(html);
441     });
442
443     // Focus on the editor
444     window.$events.listen('editor::focus', () => {
445         editor.focus();
446     });
447 }
448
449 class WysiwygEditor {
450
451     setup() {
452         this.elem = this.$el;
453
454         this.pageId = this.$opts.pageId;
455         this.textDirection = this.$opts.textDirection;
456         this.imageUploadErrorText = this.$opts.imageUploadErrorText;
457         this.serverUploadLimitText = this.$opts.serverUploadLimitText;
458         this.isDarkMode = document.documentElement.classList.contains('dark-mode');
459
460         this.plugins = "image imagetools table paste link autolink fullscreen code customhr autosave lists codeeditor media";
461         this.loadPlugins();
462
463         this.tinyMceConfig = this.getTinyMceConfig();
464         window.$events.emitPublic(this.elem, 'editor-tinymce::pre-init', {config: this.tinyMceConfig});
465         window.tinymce.init(this.tinyMceConfig);
466     }
467
468     loadPlugins() {
469         codePlugin();
470         customHrPlugin();
471
472         const drawioUrlElem = document.querySelector('[drawio-url]');
473         if (drawioUrlElem) {
474             const url = drawioUrlElem.getAttribute('drawio-url');
475             drawIoPlugin(url, this.isDarkMode, this.pageId, this);
476             this.plugins += ' drawio';
477         }
478
479         if (this.textDirection === 'rtl') {
480             this.plugins += ' directionality'
481         }
482     }
483
484     getToolBar() {
485         const textDirPlugins = this.textDirection === 'rtl' ? 'ltr rtl' : '';
486         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 codeeditor drawio media | removeformat code ${textDirPlugins} fullscreen`
487     }
488
489     getTinyMceConfig() {
490
491         const context = this;
492
493         return {
494             width: '100%',
495             height: '100%',
496             selector: '#html-editor',
497             content_css: [
498                 window.baseUrl('/dist/styles.css'),
499             ],
500             branding: false,
501             skin: this.isDarkMode ? 'oxide-dark' : 'oxide',
502             body_class: 'page-content',
503             browser_spellcheck: true,
504             relative_urls: false,
505             directionality : this.textDirection,
506             remove_script_host: false,
507             document_base_url: window.baseUrl('/'),
508             end_container_on_empty_block: true,
509             statusbar: false,
510             menubar: false,
511             paste_data_images: false,
512             extended_valid_elements: 'pre[*],svg[*],div[drawio-diagram]',
513             automatic_uploads: false,
514             valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre],+div[img]",
515             plugins: this.plugins,
516             imagetools_toolbar: 'imageoptions',
517             contextmenu: false,
518             toolbar: this.getToolBar(),
519             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;}`,
520             style_formats: [
521                 {title: "Header Large", format: "h2", preview: 'color: blue;'},
522                 {title: "Header Medium", format: "h3"},
523                 {title: "Header Small", format: "h4"},
524                 {title: "Header Tiny", format: "h5"},
525                 {title: "Paragraph", format: "p", exact: true, classes: ''},
526                 {title: "Blockquote", format: "blockquote"},
527                 {title: "Inline Code", inline: "code"},
528                 {title: "Callouts", items: [
529                         {title: "Info", format: 'calloutinfo'},
530                         {title: "Success", format: 'calloutsuccess'},
531                         {title: "Warning", format: 'calloutwarning'},
532                         {title: "Danger", format: 'calloutdanger'}
533                     ]},
534             ],
535             style_formats_merge: false,
536             media_alt_source: false,
537             media_poster: false,
538             formats: {
539                 codeeditor: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div'},
540                 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
541                 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
542                 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
543                 calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
544                 calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
545                 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
546                 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
547             },
548             file_picker_types: 'file image',
549             file_picker_callback(callback, value, meta) {
550
551                 // field_name, url, type, win
552                 if (meta.filetype === 'file') {
553                     window.EntitySelectorPopup.show(entity => {
554                         callback(entity.link, {
555                             text: entity.name,
556                             title: entity.name,
557                         });
558                     });
559                 }
560
561                 if (meta.filetype === 'image') {
562                     // Show image manager
563                     window.ImageManager.show(function (image) {
564                         callback(image.url, {alt: image.name});
565                     }, 'gallery');
566                 }
567
568             },
569             paste_preprocess(plugin, args) {
570                 let content = args.content;
571                 if (content.indexOf('<img src="file://') !== -1) {
572                     args.content = '';
573                 }
574             },
575             init_instance_callback(editor) {
576                 loadCustomHeadContent(editor);
577             },
578             setup(editor) {
579
580                 editor.on('ExecCommand change input NodeChange ObjectResized', editorChange);
581
582                 editor.on('init', () => {
583                     editorChange();
584                     // Scroll to the content if needed.
585                     const queryParams = (new URL(window.location)).searchParams;
586                     const scrollId = queryParams.get('content-id');
587                     if (scrollId) {
588                         scrollToText(scrollId);
589                     }
590
591                     // Override for touch events to allow scroll on mobile
592                     const container = editor.getContainer();
593                     const toolbarButtons = container.querySelectorAll('.mce-btn');
594                     for (let button of toolbarButtons) {
595                         button.addEventListener('touchstart', event => {
596                             event.stopPropagation();
597                         });
598                     }
599                     window.editor = editor;
600                 });
601
602                 function editorChange() {
603                     const content = editor.getContent();
604                     if (context.isDarkMode) {
605                         editor.contentDocument.documentElement.classList.add('dark-mode');
606                     }
607                     window.$events.emit('editor-html-change', content);
608                 }
609
610                 function scrollToText(scrollId) {
611                     const element = editor.dom.get(encodeURIComponent(scrollId).replace(/!/g, '%21'));
612                     if (!element) {
613                         return;
614                     }
615
616                     // scroll the element into the view and put the cursor at the end.
617                     element.scrollIntoView();
618                     editor.selection.select(element, true);
619                     editor.selection.collapse(false);
620                     editor.focus();
621                 }
622
623                 listenForBookStackEditorEvents(editor);
624
625                 // TODO - Update to standardise across both editors
626                 // Use events within listenForBookStackEditorEvents instead (Different event signature)
627                 window.$events.listen('editor-html-update', html => {
628                     editor.setContent(html);
629                     editor.selection.select(editor.getBody(), true);
630                     editor.selection.collapse(false);
631                     editorChange(html);
632                 });
633
634                 registerEditorShortcuts(editor);
635
636                 let wrap;
637                 let draggedContentEditable;
638
639                 function hasTextContent(node) {
640                     return node && !!( node.textContent || node.innerText );
641                 }
642
643                 editor.on('dragstart', function () {
644                     let node = editor.selection.getNode();
645
646                     if (node.nodeName === 'IMG') {
647                         wrap = editor.dom.getParent(node, '.mceTemp');
648
649                         if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
650                             wrap = node.parentNode;
651                         }
652                     }
653
654                     // Track dragged contenteditable blocks
655                     if (node.hasAttribute('contenteditable') && node.getAttribute('contenteditable') === 'false') {
656                         draggedContentEditable = node;
657                     }
658
659                 });
660
661                 // Custom drop event handling
662                 editor.on('drop', function (event) {
663                     let dom = editor.dom,
664                         rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
665
666                     // Template insertion
667                     const templateId = event.dataTransfer && event.dataTransfer.getData('bookstack/template');
668                     if (templateId) {
669                         event.preventDefault();
670                         window.$http.get(`/templates/${templateId}`).then(resp => {
671                             editor.selection.setRng(rng);
672                             editor.undoManager.transact(function () {
673                                 editor.execCommand('mceInsertContent', false, resp.data.html);
674                             });
675                         });
676                     }
677
678                     // Don't allow anything to be dropped in a captioned image.
679                     if (dom.getParent(rng.startContainer, '.mceTemp')) {
680                         event.preventDefault();
681                     } else if (wrap) {
682                         event.preventDefault();
683
684                         editor.undoManager.transact(function () {
685                             editor.selection.setRng(rng);
686                             editor.selection.setNode(wrap);
687                             dom.remove(wrap);
688                         });
689                     }
690
691                     // Handle contenteditable section drop
692                     if (!event.isDefaultPrevented() && draggedContentEditable) {
693                         event.preventDefault();
694                         editor.undoManager.transact(function () {
695                             const selectedNode = editor.selection.getNode();
696                             const range = editor.selection.getRng();
697                             const selectedNodeRoot = selectedNode.closest('body > *');
698                             if (range.startOffset > (range.startContainer.length / 2)) {
699                                 editor.$(selectedNodeRoot).after(draggedContentEditable);
700                             } else {
701                                 editor.$(selectedNodeRoot).before(draggedContentEditable);
702                             }
703                         });
704                     }
705
706                     // Handle image insert
707                     if (!event.isDefaultPrevented()) {
708                         editorPaste(event, editor, context);
709                     }
710
711                     wrap = null;
712                 });
713
714                 // Custom Image picker button
715                 editor.ui.registry.addButton('image-insert', {
716                     title: 'Insert an image',
717                     icon: 'image',
718                     tooltip: 'Insert an image',
719                     onAction() {
720                         window.ImageManager.show(function (image) {
721                             const imageUrl = image.thumbs.display || image.url;
722                             let html = `<a href="${image.url}" target="_blank">`;
723                             html += `<img src="${imageUrl}" alt="${image.name}">`;
724                             html += '</a>';
725                             editor.execCommand('mceInsertContent', false, html);
726                         }, 'gallery');
727                     }
728                 });
729
730                 // Paste image-uploads
731                 editor.on('paste', event => editorPaste(event, editor, context));
732
733                 // Custom handler hook
734                 window.$events.emitPublic(context.elem, 'editor-tinymce::setup', {editor});
735             }
736         };
737     }
738
739 }
740
741 export default WysiwygEditor;