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