1 import Code from "../services/code";
2 import DrawIO from "../services/drawio";
3 import Clipboard from "../services/clipboard";
6 * Handle pasting images from clipboard.
7 * @param {ClipboardEvent} event
8 * @param {WysiwygEditor} wysiwygComponent
11 function editorPaste(event, editor, wysiwygComponent) {
12 const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
14 // Don't handle the event ourselves if no items exist of contains table-looking data
15 if (!clipboard.hasItems() || clipboard.containsTabularData()) {
19 const images = clipboard.getImages();
20 for (const imageFile of images) {
22 const id = "image-" + Math.random().toString(16).slice(2);
23 const loadingImage = window.baseUrl('/loading.gif');
24 event.preventDefault();
27 editor.insertContent(`<p><img src="${loadingImage}" id="${id}"></p>`);
29 uploadImageFile(imageFile, wysiwygComponent).then(resp => {
30 const safeName = resp.name.replace(/"/g, '');
31 const newImageHtml = `<img src="${resp.thumbs.display}" alt="${safeName}" />`;
33 const newEl = editor.dom.create('a', {
38 editor.dom.replace(newEl, id);
40 editor.dom.remove(id);
41 window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
49 * Upload an image file to the server
51 * @param {WysiwygEditor} wysiwygComponent
53 async function uploadImageFile(file, wysiwygComponent) {
54 if (file === null || file.type.indexOf('image') !== 0) {
55 throw new Error(`Not an image file`);
60 let fileNameMatches = file.name.match(/\.(.+)$/);
61 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
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);
69 const resp = await window.$http.post(window.baseUrl('/images/gallery'), formData);
73 function registerEditorShortcuts(editor) {
75 for (let i = 1; i < 5; i++) {
76 editor.shortcuts.add('meta+' + i, '', ['FormatBlock', false, 'h' + (i+1)]);
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']);
89 // Save draft shortcut
90 editor.shortcuts.add('meta+S', '', () => {
91 window.$events.emit('editor-save-draft');
95 editor.shortcuts.add('meta+13', '', () => {
96 window.$events.emit('editor-save-page');
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;
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];
109 editor.formatter.apply('callout' + newFormat);
115 * Load custom HTML head content from the settings into the editor.
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;
127 * Create and enable our custom code plugin
129 function codePlugin() {
131 function elemIsCodeBlock(elem) {
132 return elem.className === 'CodeMirrorContainer';
135 function showPopup(editor) {
136 const selectedNode = editor.selection.getNode();
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;
145 editor.formatter.toggle('pre');
146 const node = editor.selection.getNode();
147 editor.dom.setHTML(node, wrap.querySelector('pre').innerHTML);
148 editor.fire('SetContent');
155 const lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
156 const currentCode = selectedNode.querySelector('textarea').textContent;
158 window.components.first('code-editor').open(currentCode, lang, (code, lang) => {
159 const editorElem = selectedNode.querySelector('.CodeMirror');
160 const cmInstance = editorElem.CodeMirror;
162 Code.setContent(cmInstance, code);
163 Code.setMode(cmInstance, lang, code);
165 const textArea = selectedNode.querySelector('textarea');
166 if (textArea) textArea.textContent = code;
167 selectedNode.setAttribute('data-lang', lang);
173 function codeMirrorContainerToPre(codeMirrorContainer) {
174 const textArea = codeMirrorContainer.querySelector('textarea');
175 const code = textArea.textContent;
176 const lang = codeMirrorContainer.getAttribute('data-lang');
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);
185 codeMirrorContainer.parentElement.replaceChild(pre, codeMirrorContainer);
188 window.tinymce.PluginManager.add('codeeditor', function(editor, url) {
192 editor.ui.registry.addButton('codeeditor', {
196 editor.execCommand('codeeditor');
200 editor.addCommand('codeeditor', () => {
205 editor.on('PreProcess', function (e) {
206 $('div.CodeMirrorContainer', e.node).each((index, elem) => {
207 codeMirrorContainerToPre(elem);
211 editor.on('dblclick', event => {
212 let selectedNode = editor.selection.getNode();
213 if (!elemIsCodeBlock(selectedNode)) return;
217 function parseCodeMirrorInstances() {
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);
226 const codeSamples = $('body > pre').filter((index, elem) => {
227 return elem.contentEditable !== "false";
230 codeSamples.each((index, elem) => {
231 Code.wysiwygView(elem);
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();
241 // Parsed code mirror blocks when content is set but wait before setting this handler
242 // to avoid any init 'SetContent' events.
244 editor.on('SetContent', () => {
245 setTimeout(parseCodeMirrorInstances, 100);
253 function drawIoPlugin(drawioUrl, isDarkMode, pageId, wysiwygComponent) {
255 let pageEditor = null;
256 let currentNode = null;
258 function isDrawing(node) {
259 return node.hasAttribute('drawio-diagram');
262 function showDrawingManager(mceEditor, selectedNode = null) {
263 pageEditor = mceEditor;
264 currentNode = selectedNode;
265 // Show image manager
266 window.ImageManager.show(function (image) {
268 let imgElem = selectedNode.querySelector('img');
269 pageEditor.dom.setAttrib(imgElem, 'src', image.url);
270 pageEditor.dom.setAttrib(selectedNode, 'drawio-diagram', image.id);
272 let imgHTML = `<div drawio-diagram="${image.id}" contenteditable="false"><img src="${image.url}"></div>`;
273 pageEditor.insertContent(imgHTML);
278 function showDrawingEditor(mceEditor, selectedNode = null) {
279 pageEditor = mceEditor;
280 currentNode = selectedNode;
281 DrawIO.show(drawioUrl, drawingInit, updateContent);
284 async function updateContent(pngData) {
285 const id = "image-" + Math.random().toString(16).slice(2);
286 const loadingImage = window.baseUrl('/loading.gif');
288 const handleUploadError = (error) => {
289 if (error.status === 413) {
290 window.$events.emit('error', wysiwygComponent.serverUploadLimitText);
292 window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
297 // Handle updating an existing image
300 let imgElem = currentNode.querySelector('img');
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);
306 handleUploadError(err);
311 setTimeout(async () => {
312 pageEditor.insertContent(`<div drawio-diagram contenteditable="false"><img src="${loadingImage}" id="${id}"></div>`);
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);
319 pageEditor.dom.remove(id);
320 handleUploadError(err);
326 function drawingInit() {
328 return Promise.resolve('');
331 let drawingId = currentNode.getAttribute('drawio-diagram');
332 return DrawIO.load(drawingId);
335 window.tinymce.PluginManager.add('drawio', function(editor, url) {
337 editor.addCommand('drawio', () => {
338 const selectedNode = editor.selection.getNode();
339 showDrawingEditor(editor, isDrawing(selectedNode) ? selectedNode : null);
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>`)
345 editor.ui.registry.addSplitButton('drawio', {
349 editor.execCommand('drawio');
355 text: 'Drawing Manager',
356 value: 'drawing-manager',
360 onItemAction(api, value) {
361 if (value === 'drawing-manager') {
362 const selectedNode = editor.selection.getNode();
363 showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
368 editor.on('dblclick', event => {
369 let selectedNode = editor.selection.getNode();
370 if (!isDrawing(selectedNode)) return;
371 showDrawingEditor(editor, selectedNode);
374 editor.on('SetContent', function () {
375 const drawings = editor.$('body > div[drawio-diagram]');
376 if (!drawings.length) return;
378 editor.undoManager.transact(function () {
379 drawings.each((index, elem) => {
380 elem.setAttribute('contenteditable', 'false');
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);
397 editor.ui.registry.addButton('hr', {
398 icon: 'horizontal-rule',
399 tooltip: 'Horizontal line',
401 editor.execCommand('InsertHorizontalRule');
405 editor.ui.registry.addMenuItem('hr', {
406 icon: 'horizontal-rule',
407 text: 'Horizontal line',
410 editor.execCommand('InsertHorizontalRule');
417 function listenForBookStackEditorEvents(editor) {
419 // Replace editor content
420 window.$events.listen('editor::replace', ({html}) => {
421 editor.setContent(html);
424 // Append editor content
425 window.$events.listen('editor::append', ({html}) => {
426 const content = editor.getContent() + html;
427 editor.setContent(content);
430 // Prepend editor content
431 window.$events.listen('editor::prepend', ({html}) => {
432 const content = html + editor.getContent();
433 editor.setContent(content);
436 // Insert editor content at the current location
437 window.$events.listen('editor::insert', ({html}) => {
438 editor.insertContent(html);
441 // Focus on the editor
442 window.$events.listen('editor::focus', () => {
447 class WysiwygEditor {
450 this.elem = this.$el;
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');
458 this.plugins = "image imagetools table textcolor paste link autolink fullscreen code customhr autosave lists codeeditor media";
461 this.tinyMceConfig = this.getTinyMceConfig();
462 window.$events.emitPublic(this.elem, 'editor-tinymce::pre-init', {config: this.tinyMceConfig});
463 window.tinymce.init(this.tinyMceConfig);
470 const drawioUrlElem = document.querySelector('[drawio-url]');
472 const url = drawioUrlElem.getAttribute('drawio-url');
473 drawIoPlugin(url, this.isDarkMode, this.pageId, this);
474 this.plugins += ' drawio';
477 if (this.textDirection === 'rtl') {
478 this.plugins += ' directionality'
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`
489 const context = this;
494 selector: '#html-editor',
496 window.baseUrl('/dist/styles.css'),
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,
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;}`,
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'}
533 style_formats_merge: false,
534 media_alt_source: false,
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'}}
546 file_browser_callback: function (field_name, url, type, win) {
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');
555 // Set text to display if not empty
556 if (!inputs[1].value) {
557 inputs[1].value = entity.name;
561 inputs[2].value = entity.name;
565 if (type === 'image') {
566 // Show image manager
567 window.ImageManager.show(function (image) {
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);
577 win.document.getElementById(field_name).fireEvent("onchange");
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}">`;
585 win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
590 paste_preprocess: function (plugin, args) {
591 let content = args.content;
592 if (content.indexOf('<img src="file://') !== -1) {
596 init_instance_callback: function(editor) {
597 loadCustomHeadContent(editor);
599 setup: function (editor) {
601 editor.on('ExecCommand change input NodeChange ObjectResized', editorChange);
603 editor.on('init', () => {
605 // Scroll to the content if needed.
606 const queryParams = (new URL(window.location)).searchParams;
607 const scrollId = queryParams.get('content-id');
609 scrollToText(scrollId);
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();
620 window.editor = editor;
623 function editorChange() {
624 const content = editor.getContent();
625 if (context.isDarkMode) {
626 editor.contentDocument.documentElement.classList.add('dark-mode');
628 window.$events.emit('editor-html-change', content);
631 function scrollToText(scrollId) {
632 const element = editor.dom.get(encodeURIComponent(scrollId).replace(/!/g, '%21'));
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);
644 listenForBookStackEditorEvents(editor);
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);
655 registerEditorShortcuts(editor);
658 let draggedContentEditable;
660 function hasTextContent(node) {
661 return node && !!( node.textContent || node.innerText );
664 editor.on('dragstart', function () {
665 let node = editor.selection.getNode();
667 if (node.nodeName === 'IMG') {
668 wrap = editor.dom.getParent(node, '.mceTemp');
670 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
671 wrap = node.parentNode;
675 // Track dragged contenteditable blocks
676 if (node.hasAttribute('contenteditable') && node.getAttribute('contenteditable') === 'false') {
677 draggedContentEditable = node;
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());
687 // Template insertion
688 const templateId = event.dataTransfer && event.dataTransfer.getData('bookstack/template');
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);
699 // Don't allow anything to be dropped in a captioned image.
700 if (dom.getParent(rng.startContainer, '.mceTemp')) {
701 event.preventDefault();
703 event.preventDefault();
705 editor.undoManager.transact(function () {
706 editor.selection.setRng(rng);
707 editor.selection.setNode(wrap);
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);
722 editor.$(selectedNodeRoot).before(draggedContentEditable);
727 // Handle image insert
728 if (!event.isDefaultPrevented()) {
729 editorPaste(event, editor, context);
735 // Custom Image picker button
736 editor.ui.registry.addButton('image-insert', {
739 tooltip: 'Insert an image',
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}">`;
746 editor.execCommand('mceInsertContent', false, html);
751 // Paste image-uploads
752 editor.on('paste', event => editorPaste(event, editor, context));
754 // Custom handler hook
755 window.$events.emitPublic(context.elem, 'editor-tinymce::setup', {editor});
762 export default WysiwygEditor;