]> BookStack Code Mirror - bookstack/blob - resources/assets/js/components/wysiwyg-editor.js
Started work on revisions in image manager
[bookstack] / resources / assets / js / components / wysiwyg-editor.js
1 const Code = require('../services/code');
2 const DrawIO = require('../services/drawio');
3
4 /**
5  * Handle pasting images from clipboard.
6  * @param {ClipboardEvent} event
7  * @param editor
8  */
9 function editorPaste(event, editor) {
10     if (!event.clipboardData || !event.clipboardData.items) return;
11     let items = event.clipboardData.items;
12
13     for (let i = 0; i < items.length; i++) {
14         if (items[i].type.indexOf("image") === -1) continue;
15         event.preventDefault();
16
17         let id = "image-" + Math.random().toString(16).slice(2);
18         let loadingImage = window.baseUrl('/loading.gif');
19         let file = items[i].getAsFile();
20         setTimeout(() => {
21             editor.insertContent(`<p><img src="${loadingImage}" id="${id}"></p>`);
22             uploadImageFile(file).then(resp => {
23                 editor.dom.setAttrib(id, 'src', resp.thumbs.display);
24             }).catch(err => {
25                 editor.dom.remove(id);
26                 window.$events.emit('error', trans('errors.image_upload_error'));
27                 console.log(err);
28             });
29         }, 10);
30     }
31 }
32
33 /**
34  * Upload an image file to the server
35  * @param {File} file
36  */
37 function uploadImageFile(file) {
38     if (file === null || file.type.indexOf('image') !== 0) return Promise.reject(`Not an image file`);
39
40     let ext = 'png';
41     if (file.name) {
42         let fileNameMatches = file.name.match(/\.(.+)$/);
43         if (fileNameMatches.length > 1) ext = fileNameMatches[1];
44     }
45
46     let remoteFilename = "image-" + Date.now() + "." + ext;
47     let formData = new FormData();
48     formData.append('file', file, remoteFilename);
49
50     return window.$http.post(window.baseUrl('/images/gallery/upload'), formData).then(resp => (resp.data));
51 }
52
53 function registerEditorShortcuts(editor) {
54     // Headers
55     for (let i = 1; i < 5; i++) {
56         editor.shortcuts.add('meta+' + i, '', ['FormatBlock', false, 'h' + (i+1)]);
57     }
58
59     // Other block shortcuts
60     editor.shortcuts.add('meta+5', '', ['FormatBlock', false, 'p']);
61     editor.shortcuts.add('meta+d', '', ['FormatBlock', false, 'p']);
62     editor.shortcuts.add('meta+6', '', ['FormatBlock', false, 'blockquote']);
63     editor.shortcuts.add('meta+q', '', ['FormatBlock', false, 'blockquote']);
64     editor.shortcuts.add('meta+7', '', ['codeeditor', false, 'pre']);
65     editor.shortcuts.add('meta+e', '', ['codeeditor', false, 'pre']);
66     editor.shortcuts.add('meta+8', '', ['FormatBlock', false, 'code']);
67     editor.shortcuts.add('meta+shift+E', '', ['FormatBlock', false, 'code']);
68
69     // Save draft shortcut
70     editor.shortcuts.add('meta+S', '', () => {
71         window.$events.emit('editor-save-draft');
72     });
73
74     // Save page shortcut
75     editor.shortcuts.add('meta+13', '', () => {
76         window.$events.emit('editor-save-page');
77     });
78
79     // Loop through callout styles
80     editor.shortcuts.add('meta+9', '', function() {
81         let selectedNode = editor.selection.getNode();
82         let formats = ['info', 'success', 'warning', 'danger'];
83
84         if (!selectedNode || selectedNode.className.indexOf('callout') === -1) {
85             editor.formatter.apply('calloutinfo');
86             return;
87         }
88
89         for (let i = 0; i < formats.length; i++) {
90             if (selectedNode.className.indexOf(formats[i]) === -1) continue;
91             let newFormat = (i === formats.length -1) ? formats[0] : formats[i+1];
92             editor.formatter.apply('callout' + newFormat);
93             return;
94         }
95         editor.formatter.apply('p');
96     });
97
98 }
99
100 /**
101  * Load custom HTML head content from the settings into the editor.
102  * @param editor
103  */
104 function loadCustomHeadContent(editor) {
105     window.$http.get(window.baseUrl('/custom-head-content')).then(resp => {
106         if (!resp.data) return;
107         let head = editor.getDoc().querySelector('head');
108         head.innerHTML += resp.data;
109     });
110 }
111
112 /**
113  * Create and enable our custom code plugin
114  */
115 function codePlugin() {
116
117     function elemIsCodeBlock(elem) {
118         return elem.className === 'CodeMirrorContainer';
119     }
120
121     function showPopup(editor) {
122         let selectedNode = editor.selection.getNode();
123
124         if (!elemIsCodeBlock(selectedNode)) {
125             let providedCode = editor.selection.getNode().textContent;
126             window.vues['code-editor'].open(providedCode, '', (code, lang) => {
127                 let wrap = document.createElement('div');
128                 wrap.innerHTML = `<pre><code class="language-${lang}"></code></pre>`;
129                 wrap.querySelector('code').innerText = code;
130
131                 editor.formatter.toggle('pre');
132                 let node = editor.selection.getNode();
133                 editor.dom.setHTML(node, wrap.querySelector('pre').innerHTML);
134                 editor.fire('SetContent');
135             });
136             return;
137         }
138
139         let lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
140         let currentCode = selectedNode.querySelector('textarea').textContent;
141
142         window.vues['code-editor'].open(currentCode, lang, (code, lang) => {
143             let editorElem = selectedNode.querySelector('.CodeMirror');
144             let cmInstance = editorElem.CodeMirror;
145             if (cmInstance) {
146                 Code.setContent(cmInstance, code);
147                 Code.setMode(cmInstance, lang);
148             }
149             let textArea = selectedNode.querySelector('textarea');
150             if (textArea) textArea.textContent = code;
151             selectedNode.setAttribute('data-lang', lang);
152         });
153     }
154
155     function codeMirrorContainerToPre($codeMirrorContainer) {
156         let textArea = $codeMirrorContainer[0].querySelector('textarea');
157         let code = textArea.textContent;
158         let lang = $codeMirrorContainer[0].getAttribute('data-lang');
159
160         $codeMirrorContainer.removeAttr('contentEditable');
161         let $pre = $('<pre></pre>');
162         $pre.append($('<code></code>').each((index, elem) => {
163             // Needs to be textContent since innerText produces BR:s
164             elem.textContent = code;
165         }).attr('class', `language-${lang}`));
166         $codeMirrorContainer.replaceWith($pre);
167     }
168
169     window.tinymce.PluginManager.add('codeeditor', function(editor, url) {
170
171         let $ = editor.$;
172
173         editor.addButton('codeeditor', {
174             text: 'Code block',
175             icon: false,
176             cmd: 'codeeditor'
177         });
178
179         editor.addCommand('codeeditor', () => {
180             showPopup(editor);
181         });
182
183         // Convert
184         editor.on('PreProcess', function (e) {
185             $('div.CodeMirrorContainer', e.node).
186             each((index, elem) => {
187                 let $elem = $(elem);
188                 codeMirrorContainerToPre($elem);
189             });
190         });
191
192         editor.on('dblclick', event => {
193             let selectedNode = editor.selection.getNode();
194             if (!elemIsCodeBlock(selectedNode)) return;
195             showPopup(editor);
196         });
197
198         editor.on('SetContent', function () {
199
200             // Recover broken codemirror instances
201             $('.CodeMirrorContainer').filter((index ,elem) => {
202                 return typeof elem.querySelector('.CodeMirror').CodeMirror === 'undefined';
203             }).each((index, elem) => {
204                 codeMirrorContainerToPre($(elem));
205             });
206
207             let codeSamples = $('body > pre').filter((index, elem) => {
208                 return elem.contentEditable !== "false";
209             });
210
211             if (!codeSamples.length) return;
212             editor.undoManager.transact(function () {
213                 codeSamples.each((index, elem) => {
214                     Code.wysiwygView(elem);
215                 });
216             });
217         });
218
219     });
220 }
221
222 function drawIoPlugin() {
223
224     let pageEditor = null;
225     let currentNode = null;
226
227     function isDrawing(node) {
228         return node.hasAttribute('drawio-diagram');
229     }
230
231     function showDrawingManager(mceEditor, selectedNode = null) {
232         // TODO - Handle how image manager links in.
233         // Show image manager
234         window.ImageManager.show(function (image) {
235
236
237             // // Replace the actively selected content with the linked image
238             // let html = `<a href="${image.url}" target="_blank">`;
239             // html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
240             // html += '</a>';
241             // win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
242         }, 'drawio');
243     }
244
245     function showDrawingEditor(mceEditor, selectedNode = null) {
246         pageEditor = mceEditor;
247         currentNode = selectedNode;
248         DrawIO.show(drawingInit, updateContent);
249     }
250
251     function updateContent(pngData) {
252         let id = "image-" + Math.random().toString(16).slice(2);
253         let loadingImage = window.baseUrl('/loading.gif');
254         let data = {
255             image: pngData,
256             uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
257         };
258
259         // Handle updating an existing image
260         if (currentNode) {
261             DrawIO.close();
262             let imgElem = currentNode.querySelector('img');
263             let drawingId = currentNode.getAttribute('drawio-diagram');
264             window.$http.put(window.baseUrl(`/images/drawing/upload/${drawingId}`), data).then(resp => {
265                 pageEditor.dom.setAttrib(imgElem, 'src', `${resp.data.url}?updated=${Date.now()}`);
266             }).catch(err => {
267                 window.$events.emit('error', trans('errors.image_upload_error'));
268                 console.log(err);
269             });
270             return;
271         }
272
273         setTimeout(() => {
274             pageEditor.insertContent(`<div drawio-diagram contenteditable="false"><img src="${loadingImage}" id="${id}"></div>`);
275             DrawIO.close();
276             window.$http.post(window.baseUrl('/images/drawing/upload'), data).then(resp => {
277                 pageEditor.dom.setAttrib(id, 'src', resp.data.url);
278                 pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', resp.data.id);
279             }).catch(err => {
280                 pageEditor.dom.remove(id);
281                 window.$events.emit('error', trans('errors.image_upload_error'));
282                 console.log(err);
283             });
284         }, 5);
285     }
286
287
288     function drawingInit() {
289         if (!currentNode) {
290             return Promise.resolve('');
291         }
292
293         let drawingId = currentNode.getAttribute('drawio-diagram');
294         return window.$http.get(window.baseUrl(`/images/base64/${drawingId}`)).then(resp => {
295             return `data:image/png;base64,${resp.data.content}`;
296         });
297     }
298
299     window.tinymce.PluginManager.add('drawio', function(editor, url) {
300
301         editor.addCommand('drawio', () => {
302             let selectedNode = editor.selection.getNode();
303             if (isDrawing(selectedNode)) {
304                 showDrawingManager(editor, selectedNode);
305             } else {
306                 showDrawingEditor(editor);
307             }
308         });
309
310         editor.addButton('drawio', {
311             tooltip: 'Drawing',
312             image: window.baseUrl('/icon/drawing.svg?color=000000'),
313             cmd: 'drawio'
314         });
315
316         editor.on('dblclick', event => {
317             let selectedNode = editor.selection.getNode();
318             if (!isDrawing(selectedNode)) return;
319             showDrawingEditor(editor, selectedNode);
320         });
321
322         editor.on('SetContent', function () {
323             let drawings = editor.$('body > div[drawio-diagram]');
324             if (!drawings.length) return;
325
326             editor.undoManager.transact(function () {
327                 drawings.each((index, elem) => {
328                     elem.setAttribute('contenteditable', 'false');
329                 });
330             });
331         });
332
333     });
334 }
335
336 function customHrPlugin() {
337     window.tinymce.PluginManager.add('customhr', function (editor) {
338         editor.addCommand('InsertHorizontalRule', function () {
339             let hrElem = document.createElement('hr');
340             let cNode = editor.selection.getNode();
341             let parentNode = cNode.parentNode;
342             parentNode.insertBefore(hrElem, cNode);
343         });
344
345         editor.addButton('hr', {
346             icon: 'hr',
347             tooltip: 'Horizontal line',
348             cmd: 'InsertHorizontalRule'
349         });
350
351         editor.addMenuItem('hr', {
352             icon: 'hr',
353             text: 'Horizontal line',
354             cmd: 'InsertHorizontalRule',
355             context: 'insert'
356         });
357     });
358 }
359
360
361 class WysiwygEditor {
362
363     constructor(elem) {
364         this.elem = elem;
365
366         this.plugins = "image table textcolor paste link autolink fullscreen imagetools code customhr autosave lists codeeditor media";
367         this.loadPlugins();
368
369         this.tinyMceConfig = this.getTinyMceConfig();
370         window.tinymce.init(this.tinyMceConfig);
371     }
372
373     loadPlugins() {
374         codePlugin();
375         customHrPlugin();
376         if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') === 'true') {
377             drawIoPlugin();
378             this.plugins += ' drawio';
379         }
380     }
381
382     getTinyMceConfig() {
383         return {
384             selector: '#html-editor',
385             content_css: [
386                 window.baseUrl('/dist/styles.css'),
387             ],
388             branding: false,
389             body_class: 'page-content',
390             browser_spellcheck: true,
391             relative_urls: false,
392             remove_script_host: false,
393             document_base_url: window.baseUrl('/'),
394             statusbar: false,
395             menubar: false,
396             paste_data_images: false,
397             extended_valid_elements: 'pre[*],svg[*],div[drawio-diagram]',
398             automatic_uploads: false,
399             valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre],+div[img]",
400             plugins: this.plugins,
401             imagetools_toolbar: 'imageoptions',
402             toolbar: "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 fullscreen",
403             content_style: "body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}",
404             style_formats: [
405                 {title: "Header Large", format: "h2"},
406                 {title: "Header Medium", format: "h3"},
407                 {title: "Header Small", format: "h4"},
408                 {title: "Header Tiny", format: "h5"},
409                 {title: "Paragraph", format: "p", exact: true, classes: ''},
410                 {title: "Blockquote", format: "blockquote"},
411                 {title: "Code Block", icon: "code", cmd: 'codeeditor', format: 'codeeditor'},
412                 {title: "Inline Code", icon: "code", inline: "code"},
413                 {title: "Callouts", items: [
414                         {title: "Info", format: 'calloutinfo'},
415                         {title: "Success", format: 'calloutsuccess'},
416                         {title: "Warning", format: 'calloutwarning'},
417                         {title: "Danger", format: 'calloutdanger'}
418                     ]},
419             ],
420             style_formats_merge: false,
421             media_alt_source: false,
422             media_poster: false,
423             formats: {
424                 codeeditor: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div'},
425                 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
426                 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
427                 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
428                 calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
429                 calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
430                 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
431                 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
432             },
433             file_browser_callback: function (field_name, url, type, win) {
434
435                 if (type === 'file') {
436                     window.EntitySelectorPopup.show(function(entity) {
437                         let originalField = win.document.getElementById(field_name);
438                         originalField.value = entity.link;
439                         $(originalField).closest('.mce-form').find('input').eq(2).val(entity.name);
440                     });
441                 }
442
443                 if (type === 'image') {
444                     // Show image manager
445                     window.ImageManager.show(function (image) {
446
447                         // Set popover link input to image url then fire change event
448                         // to ensure the new value sticks
449                         win.document.getElementById(field_name).value = image.url;
450                         if ("createEvent" in document) {
451                             let evt = document.createEvent("HTMLEvents");
452                             evt.initEvent("change", false, true);
453                             win.document.getElementById(field_name).dispatchEvent(evt);
454                         } else {
455                             win.document.getElementById(field_name).fireEvent("onchange");
456                         }
457
458                         // Replace the actively selected content with the linked image
459                         let html = `<a href="${image.url}" target="_blank">`;
460                         html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
461                         html += '</a>';
462                         win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
463                     }, 'gallery');
464                 }
465
466             },
467             paste_preprocess: function (plugin, args) {
468                 let content = args.content;
469                 if (content.indexOf('<img src="file://') !== -1) {
470                     args.content = '';
471                 }
472             },
473             init_instance_callback: function(editor) {
474                 loadCustomHeadContent(editor);
475             },
476             setup: function (editor) {
477
478                 editor.on('init ExecCommand change input NodeChange ObjectResized', editorChange);
479
480                 function editorChange() {
481                     let content = editor.getContent();
482                     window.$events.emit('editor-html-change', content);
483                 }
484
485                 window.$events.listen('editor-html-update', html => {
486                     editor.setContent(html);
487                     editor.selection.select(editor.getBody(), true);
488                     editor.selection.collapse(false);
489                     editorChange(html);
490                 });
491
492                 registerEditorShortcuts(editor);
493
494                 let wrap;
495
496                 function hasTextContent(node) {
497                     return node && !!( node.textContent || node.innerText );
498                 }
499
500                 editor.on('dragstart', function () {
501                     let node = editor.selection.getNode();
502
503                     if (node.nodeName !== 'IMG') return;
504                     wrap = editor.dom.getParent(node, '.mceTemp');
505
506                     if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
507                         wrap = node.parentNode;
508                     }
509                 });
510
511                 editor.on('drop', function (event) {
512                     let dom = editor.dom,
513                         rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
514
515                     // Don't allow anything to be dropped in a captioned image.
516                     if (dom.getParent(rng.startContainer, '.mceTemp')) {
517                         event.preventDefault();
518                     } else if (wrap) {
519                         event.preventDefault();
520
521                         editor.undoManager.transact(function () {
522                             editor.selection.setRng(rng);
523                             editor.selection.setNode(wrap);
524                             dom.remove(wrap);
525                         });
526                     }
527
528                     wrap = null;
529                 });
530
531                 // Custom Image picker button
532                 editor.addButton('image-insert', {
533                     title: 'My title',
534                     icon: 'image',
535                     tooltip: 'Insert an image',
536                     onclick: function () {
537                         window.ImageManager.show(function (image) {
538                             let html = `<a href="${image.url}" target="_blank">`;
539                             html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
540                             html += '</a>';
541                             editor.execCommand('mceInsertContent', false, html);
542                         });
543                     }
544                 });
545
546                 // Paste image-uploads
547                 editor.on('paste', event => editorPaste(event, editor));
548             }
549         };
550     }
551
552 }
553
554 module.exports = WysiwygEditor;