1 import Code from "../services/code";
2 import DrawIO from "../services/drawio";
5 * Handle pasting images from clipboard.
6 * @param {ClipboardEvent} event
7 * @param {WysiwygEditor} wysiwygComponent
10 function editorPaste(event, editor, wysiwygComponent) {
11 const clipboardItems = event.clipboardData.items;
12 if (!event.clipboardData || !clipboardItems) return;
14 // Don't handle if clipboard includes text content
15 for (let clipboardItem of clipboardItems) {
16 if (clipboardItem.type.includes('text/')) {
21 for (let clipboardItem of clipboardItems) {
22 if (!clipboardItem.type.includes("image")) {
26 const id = "image-" + Math.random().toString(16).slice(2);
27 const loadingImage = window.baseUrl('/loading.gif');
28 const file = clipboardItem.getAsFile();
31 editor.insertContent(`<p><img src="${loadingImage}" id="${id}"></p>`);
33 uploadImageFile(file, wysiwygComponent).then(resp => {
34 editor.dom.setAttrib(id, 'src', resp.thumbs.display);
36 editor.dom.remove(id);
37 window.$events.emit('error', trans('errors.image_upload_error'));
45 * Upload an image file to the server
47 * @param {WysiwygEditor} wysiwygComponent
49 async function uploadImageFile(file, wysiwygComponent) {
50 if (file === null || file.type.indexOf('image') !== 0) {
51 throw new Error(`Not an image file`);
56 let fileNameMatches = file.name.match(/\.(.+)$/);
57 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
60 const remoteFilename = "image-" + Date.now() + "." + ext;
61 const formData = new FormData();
62 formData.append('file', file, remoteFilename);
63 formData.append('uploaded_to', wysiwygComponent.pageId);
65 const resp = await window.$http.post(window.baseUrl('/images/gallery'), formData);
69 function registerEditorShortcuts(editor) {
71 for (let i = 1; i < 5; i++) {
72 editor.shortcuts.add('meta+' + i, '', ['FormatBlock', false, 'h' + (i+1)]);
75 // Other block shortcuts
76 editor.shortcuts.add('meta+5', '', ['FormatBlock', false, 'p']);
77 editor.shortcuts.add('meta+d', '', ['FormatBlock', false, 'p']);
78 editor.shortcuts.add('meta+6', '', ['FormatBlock', false, 'blockquote']);
79 editor.shortcuts.add('meta+q', '', ['FormatBlock', false, 'blockquote']);
80 editor.shortcuts.add('meta+7', '', ['codeeditor', false, 'pre']);
81 editor.shortcuts.add('meta+e', '', ['codeeditor', false, 'pre']);
82 editor.shortcuts.add('meta+8', '', ['FormatBlock', false, 'code']);
83 editor.shortcuts.add('meta+shift+E', '', ['FormatBlock', false, 'code']);
85 // Save draft shortcut
86 editor.shortcuts.add('meta+S', '', () => {
87 window.$events.emit('editor-save-draft');
91 editor.shortcuts.add('meta+13', '', () => {
92 window.$events.emit('editor-save-page');
95 // Loop through callout styles
96 editor.shortcuts.add('meta+9', '', function() {
97 let selectedNode = editor.selection.getNode();
98 let formats = ['info', 'success', 'warning', 'danger'];
100 if (!selectedNode || selectedNode.className.indexOf('callout') === -1) {
101 editor.formatter.apply('calloutinfo');
105 for (let i = 0; i < formats.length; i++) {
106 if (selectedNode.className.indexOf(formats[i]) === -1) continue;
107 let newFormat = (i === formats.length -1) ? formats[0] : formats[i+1];
108 editor.formatter.apply('callout' + newFormat);
111 editor.formatter.apply('p');
117 * Load custom HTML head content from the settings into the editor.
120 function loadCustomHeadContent(editor) {
121 window.$http.get(window.baseUrl('/custom-head-content')).then(resp => {
122 if (!resp.data) return;
123 let head = editor.getDoc().querySelector('head');
124 head.innerHTML += resp.data;
129 * Create and enable our custom code plugin
131 function codePlugin() {
133 function elemIsCodeBlock(elem) {
134 return elem.className === 'CodeMirrorContainer';
137 function showPopup(editor) {
138 let selectedNode = editor.selection.getNode();
140 if (!elemIsCodeBlock(selectedNode)) {
141 let providedCode = editor.selection.getNode().textContent;
142 window.vues['code-editor'].open(providedCode, '', (code, lang) => {
143 let wrap = document.createElement('div');
144 wrap.innerHTML = `<pre><code class="language-${lang}"></code></pre>`;
145 wrap.querySelector('code').innerText = code;
147 editor.formatter.toggle('pre');
148 let node = editor.selection.getNode();
149 editor.dom.setHTML(node, wrap.querySelector('pre').innerHTML);
150 editor.fire('SetContent');
155 let lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
156 let currentCode = selectedNode.querySelector('textarea').textContent;
158 window.vues['code-editor'].open(currentCode, lang, (code, lang) => {
159 let editorElem = selectedNode.querySelector('.CodeMirror');
160 let cmInstance = editorElem.CodeMirror;
162 Code.setContent(cmInstance, code);
163 Code.setMode(cmInstance, lang);
165 let textArea = selectedNode.querySelector('textarea');
166 if (textArea) textArea.textContent = code;
167 selectedNode.setAttribute('data-lang', lang);
171 function codeMirrorContainerToPre(codeMirrorContainer) {
172 const textArea = codeMirrorContainer.querySelector('textarea');
173 const code = textArea.textContent;
174 const lang = codeMirrorContainer.getAttribute('data-lang');
176 codeMirrorContainer.removeAttribute('contentEditable');
177 const pre = document.createElement('pre');
178 const codeElem = document.createElement('code');
179 codeElem.classList.add(`language-${lang}`);
180 codeElem.textContent = code;
181 pre.appendChild(codeElem);
183 codeMirrorContainer.parentElement.replaceChild(pre, codeMirrorContainer);
186 window.tinymce.PluginManager.add('codeeditor', function(editor, url) {
190 editor.addButton('codeeditor', {
196 editor.addCommand('codeeditor', () => {
201 editor.on('PreProcess', function (e) {
202 $('div.CodeMirrorContainer', e.node).each((index, elem) => {
203 codeMirrorContainerToPre(elem);
207 editor.on('dblclick', event => {
208 let selectedNode = editor.selection.getNode();
209 if (!elemIsCodeBlock(selectedNode)) return;
213 editor.on('SetContent', function () {
215 // Recover broken codemirror instances
216 $('.CodeMirrorContainer').filter((index ,elem) => {
217 return typeof elem.querySelector('.CodeMirror').CodeMirror === 'undefined';
218 }).each((index, elem) => {
219 codeMirrorContainerToPre(elem);
222 const codeSamples = $('body > pre').filter((index, elem) => {
223 return elem.contentEditable !== "false";
226 if (!codeSamples.length) return;
227 editor.undoManager.transact(function () {
228 codeSamples.each((index, elem) => {
229 Code.wysiwygView(elem);
237 function drawIoPlugin() {
239 let pageEditor = null;
240 let currentNode = null;
242 function isDrawing(node) {
243 return node.hasAttribute('drawio-diagram');
246 function showDrawingManager(mceEditor, selectedNode = null) {
247 pageEditor = mceEditor;
248 currentNode = selectedNode;
249 // Show image manager
250 window.ImageManager.show(function (image) {
252 let imgElem = selectedNode.querySelector('img');
253 pageEditor.dom.setAttrib(imgElem, 'src', image.url);
254 pageEditor.dom.setAttrib(selectedNode, 'drawio-diagram', image.id);
256 let imgHTML = `<div drawio-diagram="${image.id}" contenteditable="false"><img src="${image.url}"></div>`;
257 pageEditor.insertContent(imgHTML);
262 function showDrawingEditor(mceEditor, selectedNode = null) {
263 pageEditor = mceEditor;
264 currentNode = selectedNode;
265 DrawIO.show(drawingInit, updateContent);
268 async function updateContent(pngData) {
269 const id = "image-" + Math.random().toString(16).slice(2);
270 const loadingImage = window.baseUrl('/loading.gif');
271 const pageId = Number(document.getElementById('page-editor').getAttribute('page-id'));
273 // Handle updating an existing image
276 let imgElem = currentNode.querySelector('img');
278 const img = await DrawIO.upload(pngData, pageId);
279 pageEditor.dom.setAttrib(imgElem, 'src', img.url);
280 pageEditor.dom.setAttrib(currentNode, 'drawio-diagram', img.id);
282 window.$events.emit('error', trans('errors.image_upload_error'));
288 setTimeout(async () => {
289 pageEditor.insertContent(`<div drawio-diagram contenteditable="false"><img src="${loadingImage}" id="${id}"></div>`);
292 const img = await DrawIO.upload(pngData, pageId);
293 pageEditor.dom.setAttrib(id, 'src', img.url);
294 pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', img.id);
296 pageEditor.dom.remove(id);
297 window.$events.emit('error', trans('errors.image_upload_error'));
304 function drawingInit() {
306 return Promise.resolve('');
309 let drawingId = currentNode.getAttribute('drawio-diagram');
310 return DrawIO.load(drawingId);
313 window.tinymce.PluginManager.add('drawio', function(editor, url) {
315 editor.addCommand('drawio', () => {
316 let selectedNode = editor.selection.getNode();
317 showDrawingEditor(editor, isDrawing(selectedNode) ? selectedNode : null);
320 editor.addButton('drawio', {
323 image: `data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9IiMwMDAwMDAiICB4bWxucz0iaHR0cDovL3d3 dy53My5vcmcvMjAwMC9zdmciPgogICAgPHBhdGggZD0iTTIzIDdWMWgtNnYySDdWMUgxdjZoMnYx MEgxdjZoNnYtMmgxMHYyaDZ2LTZoLTJWN2gyek0zIDNoMnYySDNWM3ptMiAxOEgzdi0yaDJ2Mnpt MTItMkg3di0ySDVWN2gyVjVoMTB2MmgydjEwaC0ydjJ6bTQgMmgtMnYtMmgydjJ6TTE5IDVWM2gy djJoLTJ6bS01LjI3IDloLTMuNDlsLS43MyAySDcuODlsMy40LTloMS40bDMuNDEgOWgtMS42M2wt Ljc0LTJ6bS0zLjA0LTEuMjZoMi42MUwxMiA4LjkxbC0xLjMxIDMuODN6Ii8+CiAgICA8cGF0aCBk PSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIi8+Cjwvc3ZnPg==`,
327 text: 'Drawing Manager',
329 let selectedNode = editor.selection.getNode();
330 showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
336 editor.on('dblclick', event => {
337 let selectedNode = editor.selection.getNode();
338 if (!isDrawing(selectedNode)) return;
339 showDrawingEditor(editor, selectedNode);
342 editor.on('SetContent', function () {
343 const drawings = editor.$('body > div[drawio-diagram]');
344 if (!drawings.length) return;
346 editor.undoManager.transact(function () {
347 drawings.each((index, elem) => {
348 elem.setAttribute('contenteditable', 'false');
356 function customHrPlugin() {
357 window.tinymce.PluginManager.add('customhr', function (editor) {
358 editor.addCommand('InsertHorizontalRule', function () {
359 let hrElem = document.createElement('hr');
360 let cNode = editor.selection.getNode();
361 let parentNode = cNode.parentNode;
362 parentNode.insertBefore(hrElem, cNode);
365 editor.addButton('hr', {
367 tooltip: 'Horizontal line',
368 cmd: 'InsertHorizontalRule'
371 editor.addMenuItem('hr', {
373 text: 'Horizontal line',
374 cmd: 'InsertHorizontalRule',
381 function listenForBookStackEditorEvents(editor) {
383 // Replace editor content
384 window.$events.listen('editor::replace', ({html}) => {
385 editor.setContent(html);
388 // Append editor content
389 window.$events.listen('editor::append', ({html}) => {
390 const content = editor.getContent() + html;
391 editor.setContent(content);
394 // Prepend editor content
395 window.$events.listen('editor::prepend', ({html}) => {
396 const content = html + editor.getContent();
397 editor.setContent(content);
402 class WysiwygEditor {
407 const pageEditor = document.getElementById('page-editor');
408 this.pageId = pageEditor.getAttribute('page-id');
409 this.textDirection = pageEditor.getAttribute('text-direction');
411 this.plugins = "image table textcolor paste link autolink fullscreen imagetools code customhr autosave lists codeeditor media";
414 this.tinyMceConfig = this.getTinyMceConfig();
415 window.tinymce.init(this.tinyMceConfig);
421 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') === 'true') {
423 this.plugins += ' drawio';
425 if (this.textDirection === 'rtl') {
426 this.plugins += ' directionality'
431 const textDirPlugins = this.textDirection === 'rtl' ? 'ltr rtl' : '';
432 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`
437 const context = this;
440 selector: '#html-editor',
442 window.baseUrl('/dist/styles.css'),
445 body_class: 'page-content',
446 browser_spellcheck: true,
447 relative_urls: false,
448 directionality : this.textDirection,
449 remove_script_host: false,
450 document_base_url: window.baseUrl('/'),
451 end_container_on_empty_block: true,
454 paste_data_images: false,
455 extended_valid_elements: 'pre[*],svg[*],div[drawio-diagram]',
456 automatic_uploads: false,
457 valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre],+div[img]",
458 plugins: this.plugins,
459 imagetools_toolbar: 'imageoptions',
460 toolbar: this.getToolBar(),
461 content_style: "html, body {background: #FFF;} body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}",
463 {title: "Header Large", format: "h2"},
464 {title: "Header Medium", format: "h3"},
465 {title: "Header Small", format: "h4"},
466 {title: "Header Tiny", format: "h5"},
467 {title: "Paragraph", format: "p", exact: true, classes: ''},
468 {title: "Blockquote", format: "blockquote"},
469 {title: "Code Block", icon: "code", cmd: 'codeeditor', format: 'codeeditor'},
470 {title: "Inline Code", icon: "code", inline: "code"},
471 {title: "Callouts", items: [
472 {title: "Info", format: 'calloutinfo'},
473 {title: "Success", format: 'calloutsuccess'},
474 {title: "Warning", format: 'calloutwarning'},
475 {title: "Danger", format: 'calloutdanger'}
478 style_formats_merge: false,
479 media_alt_source: false,
482 codeeditor: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div'},
483 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
484 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
485 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
486 calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
487 calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
488 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
489 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
491 file_browser_callback: function (field_name, url, type, win) {
493 if (type === 'file') {
494 window.EntitySelectorPopup.show(function(entity) {
495 const originalField = win.document.getElementById(field_name);
496 originalField.value = entity.link;
497 const mceForm = originalField.closest('.mce-form');
498 mceForm.querySelectorAll('input')[2].value = entity.name;
502 if (type === 'image') {
503 // Show image manager
504 window.ImageManager.show(function (image) {
506 // Set popover link input to image url then fire change event
507 // to ensure the new value sticks
508 win.document.getElementById(field_name).value = image.url;
509 if ("createEvent" in document) {
510 let evt = document.createEvent("HTMLEvents");
511 evt.initEvent("change", false, true);
512 win.document.getElementById(field_name).dispatchEvent(evt);
514 win.document.getElementById(field_name).fireEvent("onchange");
517 // Replace the actively selected content with the linked image
518 let html = `<a href="${image.url}" target="_blank">`;
519 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
521 win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
526 paste_preprocess: function (plugin, args) {
527 let content = args.content;
528 if (content.indexOf('<img src="file://') !== -1) {
532 init_instance_callback: function(editor) {
533 loadCustomHeadContent(editor);
535 setup: function (editor) {
537 editor.on('ExecCommand change input NodeChange ObjectResized', editorChange);
539 editor.on('init', () => {
541 // Scroll to the content if needed.
542 const queryParams = (new URL(window.location)).searchParams;
543 const scrollId = queryParams.get('content-id');
545 scrollToText(scrollId);
548 // Override for touch events to allow scroll on mobile
549 const container = editor.getContainer();
550 const toolbarButtons = container.querySelectorAll('.mce-btn');
551 for (let button of toolbarButtons) {
552 button.addEventListener('touchstart', event => {
553 event.stopPropagation();
556 window.editor = editor;
559 function editorChange() {
560 let content = editor.getContent();
561 window.$events.emit('editor-html-change', content);
564 function scrollToText(scrollId) {
565 const element = editor.dom.get(encodeURIComponent(scrollId).replace(/!/g, '%21'));
570 // scroll the element into the view and put the cursor at the end.
571 element.scrollIntoView();
572 editor.selection.select(element, true);
573 editor.selection.collapse(false);
577 listenForBookStackEditorEvents(editor);
579 // TODO - Update to standardise across both editors
580 // Use events within listenForBookStackEditorEvents instead (Different event signature)
581 window.$events.listen('editor-html-update', html => {
582 editor.setContent(html);
583 editor.selection.select(editor.getBody(), true);
584 editor.selection.collapse(false);
588 registerEditorShortcuts(editor);
592 function hasTextContent(node) {
593 return node && !!( node.textContent || node.innerText );
596 editor.on('dragstart', function () {
597 let node = editor.selection.getNode();
599 if (node.nodeName !== 'IMG') return;
600 wrap = editor.dom.getParent(node, '.mceTemp');
602 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
603 wrap = node.parentNode;
607 editor.on('drop', function (event) {
608 let dom = editor.dom,
609 rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
611 // Template insertion
612 const templateId = event.dataTransfer.getData('bookstack/template');
614 event.preventDefault();
615 window.$http.get(`/templates/${templateId}`).then(resp => {
616 editor.selection.setRng(rng);
617 editor.undoManager.transact(function () {
618 editor.execCommand('mceInsertContent', false, resp.data.html);
623 // Don't allow anything to be dropped in a captioned image.
624 if (dom.getParent(rng.startContainer, '.mceTemp')) {
625 event.preventDefault();
627 event.preventDefault();
629 editor.undoManager.transact(function () {
630 editor.selection.setRng(rng);
631 editor.selection.setNode(wrap);
639 // Custom Image picker button
640 editor.addButton('image-insert', {
643 tooltip: 'Insert an image',
644 onclick: function () {
645 window.ImageManager.show(function (image) {
646 let html = `<a href="${image.url}" target="_blank">`;
647 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
649 editor.execCommand('mceInsertContent', false, html);
654 // Paste image-uploads
655 editor.on('paste', event => editorPaste(event, editor, context));
663 export default WysiwygEditor;