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.addButton('codeeditor', {
198 editor.addCommand('codeeditor', () => {
203 editor.on('PreProcess', function (e) {
204 $('div.CodeMirrorContainer', e.node).each((index, elem) => {
205 codeMirrorContainerToPre(elem);
209 editor.on('dblclick', event => {
210 let selectedNode = editor.selection.getNode();
211 if (!elemIsCodeBlock(selectedNode)) return;
215 function parseCodeMirrorInstances() {
217 // Recover broken codemirror instances
218 $('.CodeMirrorContainer').filter((index ,elem) => {
219 return typeof elem.querySelector('.CodeMirror').CodeMirror === 'undefined';
220 }).each((index, elem) => {
221 codeMirrorContainerToPre(elem);
224 const codeSamples = $('body > pre').filter((index, elem) => {
225 return elem.contentEditable !== "false";
228 codeSamples.each((index, elem) => {
229 Code.wysiwygView(elem);
233 editor.on('init', function() {
234 // Parse code mirror instances on init, but delay a little so this runs after
235 // initial styles are fetched into the editor.
236 editor.undoManager.transact(function () {
237 parseCodeMirrorInstances();
239 // Parsed code mirror blocks when content is set but wait before setting this handler
240 // to avoid any init 'SetContent' events.
242 editor.on('SetContent', () => {
243 setTimeout(parseCodeMirrorInstances, 100);
251 function drawIoPlugin(drawioUrl, isDarkMode, pageId, wysiwygComponent) {
253 let pageEditor = null;
254 let currentNode = null;
256 function isDrawing(node) {
257 return node.hasAttribute('drawio-diagram');
260 function showDrawingManager(mceEditor, selectedNode = null) {
261 pageEditor = mceEditor;
262 currentNode = selectedNode;
263 // Show image manager
264 window.ImageManager.show(function (image) {
266 let imgElem = selectedNode.querySelector('img');
267 pageEditor.dom.setAttrib(imgElem, 'src', image.url);
268 pageEditor.dom.setAttrib(selectedNode, 'drawio-diagram', image.id);
270 let imgHTML = `<div drawio-diagram="${image.id}" contenteditable="false"><img src="${image.url}"></div>`;
271 pageEditor.insertContent(imgHTML);
276 function showDrawingEditor(mceEditor, selectedNode = null) {
277 pageEditor = mceEditor;
278 currentNode = selectedNode;
279 DrawIO.show(drawioUrl, drawingInit, updateContent);
282 async function updateContent(pngData) {
283 const id = "image-" + Math.random().toString(16).slice(2);
284 const loadingImage = window.baseUrl('/loading.gif');
286 // Handle updating an existing image
289 let imgElem = currentNode.querySelector('img');
291 const img = await DrawIO.upload(pngData, pageId);
292 pageEditor.dom.setAttrib(imgElem, 'src', img.url);
293 pageEditor.dom.setAttrib(currentNode, 'drawio-diagram', img.id);
295 window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
301 setTimeout(async () => {
302 pageEditor.insertContent(`<div drawio-diagram contenteditable="false"><img src="${loadingImage}" id="${id}"></div>`);
305 const img = await DrawIO.upload(pngData, pageId);
306 pageEditor.dom.setAttrib(id, 'src', img.url);
307 pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', img.id);
309 pageEditor.dom.remove(id);
310 window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
317 function drawingInit() {
319 return Promise.resolve('');
322 let drawingId = currentNode.getAttribute('drawio-diagram');
323 return DrawIO.load(drawingId);
326 window.tinymce.PluginManager.add('drawio', function(editor, url) {
328 editor.addCommand('drawio', () => {
329 const selectedNode = editor.selection.getNode();
330 showDrawingEditor(editor, isDrawing(selectedNode) ? selectedNode : null);
333 editor.addButton('drawio', {
336 image: `data:image/svg+xml;base64,${btoa(`<svg viewBox="0 0 24 24" fill="${isDarkMode ? '#BBB' : '#000000'}" xmlns="http://www.w3.org/2000/svg">
337 <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"/>
338 <path d="M0 0h24v24H0z" fill="none"/>
343 text: 'Drawing Manager',
345 let selectedNode = editor.selection.getNode();
346 showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
352 editor.on('dblclick', event => {
353 let selectedNode = editor.selection.getNode();
354 if (!isDrawing(selectedNode)) return;
355 showDrawingEditor(editor, selectedNode);
358 editor.on('SetContent', function () {
359 const drawings = editor.$('body > div[drawio-diagram]');
360 if (!drawings.length) return;
362 editor.undoManager.transact(function () {
363 drawings.each((index, elem) => {
364 elem.setAttribute('contenteditable', 'false');
372 function customHrPlugin() {
373 window.tinymce.PluginManager.add('customhr', function (editor) {
374 editor.addCommand('InsertHorizontalRule', function () {
375 let hrElem = document.createElement('hr');
376 let cNode = editor.selection.getNode();
377 let parentNode = cNode.parentNode;
378 parentNode.insertBefore(hrElem, cNode);
381 editor.addButton('hr', {
383 tooltip: 'Horizontal line',
384 cmd: 'InsertHorizontalRule'
387 editor.addMenuItem('hr', {
389 text: 'Horizontal line',
390 cmd: 'InsertHorizontalRule',
397 function listenForBookStackEditorEvents(editor) {
399 // Replace editor content
400 window.$events.listen('editor::replace', ({html}) => {
401 editor.setContent(html);
404 // Append editor content
405 window.$events.listen('editor::append', ({html}) => {
406 const content = editor.getContent() + html;
407 editor.setContent(content);
410 // Prepend editor content
411 window.$events.listen('editor::prepend', ({html}) => {
412 const content = html + editor.getContent();
413 editor.setContent(content);
416 // Insert editor content at the current location
417 window.$events.listen('editor::insert', ({html}) => {
418 editor.insertContent(html);
421 // Focus on the editor
422 window.$events.listen('editor::focus', () => {
427 class WysiwygEditor {
430 this.elem = this.$el;
432 this.pageId = this.$opts.pageId;
433 this.textDirection = this.$opts.textDirection;
434 this.imageUploadErrorText = this.$opts.imageUploadErrorText;
435 this.isDarkMode = document.documentElement.classList.contains('dark-mode');
437 this.plugins = "image imagetools table textcolor paste link autolink fullscreen code customhr autosave lists codeeditor media";
440 this.tinyMceConfig = this.getTinyMceConfig();
441 window.$events.emitPublic(this.elem, 'editor-tinymce::pre-init', {config: this.tinyMceConfig});
442 window.tinymce.init(this.tinyMceConfig);
449 const drawioUrlElem = document.querySelector('[drawio-url]');
451 const url = drawioUrlElem.getAttribute('drawio-url');
452 drawIoPlugin(url, this.isDarkMode, this.pageId, this);
453 this.plugins += ' drawio';
456 if (this.textDirection === 'rtl') {
457 this.plugins += ' directionality'
462 const textDirPlugins = this.textDirection === 'rtl' ? 'ltr rtl' : '';
463 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`
468 const context = this;
471 selector: '#html-editor',
473 window.baseUrl('/dist/styles.css'),
476 skin: this.isDarkMode ? 'dark' : 'lightgray',
477 body_class: 'page-content',
478 browser_spellcheck: true,
479 relative_urls: false,
480 directionality : this.textDirection,
481 remove_script_host: false,
482 document_base_url: window.baseUrl('/'),
483 end_container_on_empty_block: true,
486 paste_data_images: false,
487 extended_valid_elements: 'pre[*],svg[*],div[drawio-diagram]',
488 automatic_uploads: false,
489 valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre],+div[img]",
490 plugins: this.plugins,
491 imagetools_toolbar: 'imageoptions',
492 toolbar: this.getToolBar(),
493 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;}`,
495 {title: "Header Large", format: "h2"},
496 {title: "Header Medium", format: "h3"},
497 {title: "Header Small", format: "h4"},
498 {title: "Header Tiny", format: "h5"},
499 {title: "Paragraph", format: "p", exact: true, classes: ''},
500 {title: "Blockquote", format: "blockquote"},
501 {title: "Code Block", icon: "code", cmd: 'codeeditor', format: 'codeeditor'},
502 {title: "Inline Code", icon: "code", inline: "code"},
503 {title: "Callouts", items: [
504 {title: "Info", format: 'calloutinfo'},
505 {title: "Success", format: 'calloutsuccess'},
506 {title: "Warning", format: 'calloutwarning'},
507 {title: "Danger", format: 'calloutdanger'}
510 style_formats_merge: false,
511 media_alt_source: false,
514 codeeditor: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div'},
515 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
516 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
517 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
518 calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
519 calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
520 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
521 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
523 file_browser_callback: function (field_name, url, type, win) {
525 if (type === 'file') {
526 window.EntitySelectorPopup.show(function(entity) {
527 const originalField = win.document.getElementById(field_name);
528 originalField.value = entity.link;
529 const mceForm = originalField.closest('.mce-form');
530 const inputs = mceForm.querySelectorAll('input');
532 // Set text to display if not empty
533 if (!inputs[1].value) {
534 inputs[1].value = entity.name;
538 inputs[2].value = entity.name;
542 if (type === 'image') {
543 // Show image manager
544 window.ImageManager.show(function (image) {
546 // Set popover link input to image url then fire change event
547 // to ensure the new value sticks
548 win.document.getElementById(field_name).value = image.url;
549 if ("createEvent" in document) {
550 let evt = document.createEvent("HTMLEvents");
551 evt.initEvent("change", false, true);
552 win.document.getElementById(field_name).dispatchEvent(evt);
554 win.document.getElementById(field_name).fireEvent("onchange");
557 // Replace the actively selected content with the linked image
558 let html = `<a href="${image.url}" target="_blank">`;
559 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
561 win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
566 paste_preprocess: function (plugin, args) {
567 let content = args.content;
568 if (content.indexOf('<img src="file://') !== -1) {
572 init_instance_callback: function(editor) {
573 loadCustomHeadContent(editor);
575 setup: function (editor) {
577 editor.on('ExecCommand change input NodeChange ObjectResized', editorChange);
579 editor.on('init', () => {
581 // Scroll to the content if needed.
582 const queryParams = (new URL(window.location)).searchParams;
583 const scrollId = queryParams.get('content-id');
585 scrollToText(scrollId);
588 // Override for touch events to allow scroll on mobile
589 const container = editor.getContainer();
590 const toolbarButtons = container.querySelectorAll('.mce-btn');
591 for (let button of toolbarButtons) {
592 button.addEventListener('touchstart', event => {
593 event.stopPropagation();
596 window.editor = editor;
599 function editorChange() {
600 const content = editor.getContent();
601 if (context.isDarkMode) {
602 editor.contentDocument.documentElement.classList.add('dark-mode');
604 window.$events.emit('editor-html-change', content);
607 function scrollToText(scrollId) {
608 const element = editor.dom.get(encodeURIComponent(scrollId).replace(/!/g, '%21'));
613 // scroll the element into the view and put the cursor at the end.
614 element.scrollIntoView();
615 editor.selection.select(element, true);
616 editor.selection.collapse(false);
620 listenForBookStackEditorEvents(editor);
622 // TODO - Update to standardise across both editors
623 // Use events within listenForBookStackEditorEvents instead (Different event signature)
624 window.$events.listen('editor-html-update', html => {
625 editor.setContent(html);
626 editor.selection.select(editor.getBody(), true);
627 editor.selection.collapse(false);
631 registerEditorShortcuts(editor);
634 let draggedContentEditable;
636 function hasTextContent(node) {
637 return node && !!( node.textContent || node.innerText );
640 editor.on('dragstart', function () {
641 let node = editor.selection.getNode();
643 if (node.nodeName === 'IMG') {
644 wrap = editor.dom.getParent(node, '.mceTemp');
646 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
647 wrap = node.parentNode;
651 // Track dragged contenteditable blocks
652 if (node.hasAttribute('contenteditable') && node.getAttribute('contenteditable') === 'false') {
653 draggedContentEditable = node;
658 // Custom drop event handling
659 editor.on('drop', function (event) {
660 let dom = editor.dom,
661 rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
663 // Template insertion
664 const templateId = event.dataTransfer && event.dataTransfer.getData('bookstack/template');
666 event.preventDefault();
667 window.$http.get(`/templates/${templateId}`).then(resp => {
668 editor.selection.setRng(rng);
669 editor.undoManager.transact(function () {
670 editor.execCommand('mceInsertContent', false, resp.data.html);
675 // Don't allow anything to be dropped in a captioned image.
676 if (dom.getParent(rng.startContainer, '.mceTemp')) {
677 event.preventDefault();
679 event.preventDefault();
681 editor.undoManager.transact(function () {
682 editor.selection.setRng(rng);
683 editor.selection.setNode(wrap);
688 // Handle contenteditable section drop
689 if (!event.isDefaultPrevented() && draggedContentEditable) {
690 event.preventDefault();
691 editor.undoManager.transact(function () {
692 const selectedNode = editor.selection.getNode();
693 const range = editor.selection.getRng();
694 const selectedNodeRoot = selectedNode.closest('body > *');
695 if (range.startOffset > (range.startContainer.length / 2)) {
696 editor.$(selectedNodeRoot).after(draggedContentEditable);
698 editor.$(selectedNodeRoot).before(draggedContentEditable);
703 // Handle image insert
704 if (!event.isDefaultPrevented()) {
705 editorPaste(event, editor, context);
711 // Custom Image picker button
712 editor.addButton('image-insert', {
715 tooltip: 'Insert an image',
716 onclick: function () {
717 window.ImageManager.show(function (image) {
718 let html = `<a href="${image.url}" target="_blank">`;
719 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
721 editor.execCommand('mceInsertContent', false, html);
726 // Paste image-uploads
727 editor.on('paste', event => editorPaste(event, editor, context));
729 // Custom handler hook
730 window.$events.emitPublic(context.elem, 'editor-tinymce::setup', {editor});
737 export default WysiwygEditor;