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.getContent({format: 'text'});
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.insertContent(wrap.innerHTML);
151 const lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
152 const currentCode = selectedNode.querySelector('textarea').textContent;
154 window.components.first('code-editor').open(currentCode, lang, (code, lang) => {
155 const editorElem = selectedNode.querySelector('.CodeMirror');
156 const cmInstance = editorElem.CodeMirror;
158 Code.setContent(cmInstance, code);
159 Code.setMode(cmInstance, lang, code);
161 const textArea = selectedNode.querySelector('textarea');
162 if (textArea) textArea.textContent = code;
163 selectedNode.setAttribute('data-lang', lang);
169 function codeMirrorContainerToPre(codeMirrorContainer) {
170 const textArea = codeMirrorContainer.querySelector('textarea');
171 const code = textArea.textContent;
172 const lang = codeMirrorContainer.getAttribute('data-lang');
174 codeMirrorContainer.removeAttribute('contentEditable');
175 const pre = document.createElement('pre');
176 const codeElem = document.createElement('code');
177 codeElem.classList.add(`language-${lang}`);
178 codeElem.textContent = code;
179 pre.appendChild(codeElem);
181 codeMirrorContainer.parentElement.replaceChild(pre, codeMirrorContainer);
184 window.tinymce.PluginManager.add('codeeditor', function(editor, url) {
188 editor.addButton('codeeditor', {
194 editor.addCommand('codeeditor', () => {
199 editor.on('PreProcess', function (e) {
200 $('div.CodeMirrorContainer', e.node).each((index, elem) => {
201 codeMirrorContainerToPre(elem);
205 editor.on('dblclick', event => {
206 let selectedNode = editor.selection.getNode();
207 if (!elemIsCodeBlock(selectedNode)) return;
211 function parseCodeMirrorInstances() {
213 // Recover broken codemirror instances
214 $('.CodeMirrorContainer').filter((index ,elem) => {
215 return typeof elem.querySelector('.CodeMirror').CodeMirror === 'undefined';
216 }).each((index, elem) => {
217 codeMirrorContainerToPre(elem);
220 const codeSamples = $('body > pre').filter((index, elem) => {
221 return elem.contentEditable !== "false";
224 codeSamples.each((index, elem) => {
225 Code.wysiwygView(elem);
229 editor.on('init', function() {
230 // Parse code mirror instances on init, but delay a little so this runs after
231 // initial styles are fetched into the editor.
232 editor.undoManager.transact(function () {
233 parseCodeMirrorInstances();
235 // Parsed code mirror blocks when content is set but wait before setting this handler
236 // to avoid any init 'SetContent' events.
238 editor.on('SetContent', () => {
239 setTimeout(parseCodeMirrorInstances, 100);
247 function drawIoPlugin(drawioUrl, isDarkMode, pageId, wysiwygComponent) {
249 let pageEditor = null;
250 let currentNode = null;
252 function isDrawing(node) {
253 return node.hasAttribute('drawio-diagram');
256 function showDrawingManager(mceEditor, selectedNode = null) {
257 pageEditor = mceEditor;
258 currentNode = selectedNode;
259 // Show image manager
260 window.ImageManager.show(function (image) {
262 let imgElem = selectedNode.querySelector('img');
263 pageEditor.dom.setAttrib(imgElem, 'src', image.url);
264 pageEditor.dom.setAttrib(selectedNode, 'drawio-diagram', image.id);
266 let imgHTML = `<div drawio-diagram="${image.id}" contenteditable="false"><img src="${image.url}"></div>`;
267 pageEditor.insertContent(imgHTML);
272 function showDrawingEditor(mceEditor, selectedNode = null) {
273 pageEditor = mceEditor;
274 currentNode = selectedNode;
275 DrawIO.show(drawioUrl, drawingInit, updateContent);
278 async function updateContent(pngData) {
279 const id = "image-" + Math.random().toString(16).slice(2);
280 const loadingImage = window.baseUrl('/loading.gif');
282 const handleUploadError = (error) => {
283 if (error.status === 413) {
284 window.$events.emit('error', wysiwygComponent.serverUploadLimitText);
286 window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
291 // Handle updating an existing image
294 let imgElem = currentNode.querySelector('img');
296 const img = await DrawIO.upload(pngData, pageId);
297 pageEditor.dom.setAttrib(imgElem, 'src', img.url);
298 pageEditor.dom.setAttrib(currentNode, 'drawio-diagram', img.id);
300 handleUploadError(err);
305 setTimeout(async () => {
306 pageEditor.insertContent(`<div drawio-diagram contenteditable="false"><img src="${loadingImage}" id="${id}"></div>`);
309 const img = await DrawIO.upload(pngData, pageId);
310 pageEditor.dom.setAttrib(id, 'src', img.url);
311 pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', img.id);
313 pageEditor.dom.remove(id);
314 handleUploadError(err);
320 function drawingInit() {
322 return Promise.resolve('');
325 let drawingId = currentNode.getAttribute('drawio-diagram');
326 return DrawIO.load(drawingId);
329 window.tinymce.PluginManager.add('drawio', function(editor, url) {
331 editor.addCommand('drawio', () => {
332 const selectedNode = editor.selection.getNode();
333 showDrawingEditor(editor, isDrawing(selectedNode) ? selectedNode : null);
336 editor.addButton('drawio', {
339 image: `data:image/svg+xml;base64,${btoa(`<svg viewBox="0 0 24 24" fill="${isDarkMode ? '#BBB' : '#000000'}" xmlns="http://www.w3.org/2000/svg">
340 <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"/>
341 <path d="M0 0h24v24H0z" fill="none"/>
346 text: 'Drawing Manager',
348 let selectedNode = editor.selection.getNode();
349 showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
355 editor.on('dblclick', event => {
356 let selectedNode = editor.selection.getNode();
357 if (!isDrawing(selectedNode)) return;
358 showDrawingEditor(editor, selectedNode);
361 editor.on('SetContent', function () {
362 const drawings = editor.$('body > div[drawio-diagram]');
363 if (!drawings.length) return;
365 editor.undoManager.transact(function () {
366 drawings.each((index, elem) => {
367 elem.setAttribute('contenteditable', 'false');
375 function customHrPlugin() {
376 window.tinymce.PluginManager.add('customhr', function (editor) {
377 editor.addCommand('InsertHorizontalRule', function () {
378 let hrElem = document.createElement('hr');
379 let cNode = editor.selection.getNode();
380 let parentNode = cNode.parentNode;
381 parentNode.insertBefore(hrElem, cNode);
384 editor.addButton('hr', {
386 tooltip: 'Horizontal line',
387 cmd: 'InsertHorizontalRule'
390 editor.addMenuItem('hr', {
392 text: 'Horizontal line',
393 cmd: 'InsertHorizontalRule',
400 function listenForBookStackEditorEvents(editor) {
402 // Replace editor content
403 window.$events.listen('editor::replace', ({html}) => {
404 editor.setContent(html);
407 // Append editor content
408 window.$events.listen('editor::append', ({html}) => {
409 const content = editor.getContent() + html;
410 editor.setContent(content);
413 // Prepend editor content
414 window.$events.listen('editor::prepend', ({html}) => {
415 const content = html + editor.getContent();
416 editor.setContent(content);
419 // Insert editor content at the current location
420 window.$events.listen('editor::insert', ({html}) => {
421 editor.insertContent(html);
424 // Focus on the editor
425 window.$events.listen('editor::focus', () => {
430 class WysiwygEditor {
433 this.elem = this.$el;
435 this.pageId = this.$opts.pageId;
436 this.textDirection = this.$opts.textDirection;
437 this.imageUploadErrorText = this.$opts.imageUploadErrorText;
438 this.serverUploadLimitText = this.$opts.serverUploadLimitText;
439 this.isDarkMode = document.documentElement.classList.contains('dark-mode');
441 this.plugins = "image imagetools table textcolor paste link autolink fullscreen code customhr autosave lists codeeditor media";
444 this.tinyMceConfig = this.getTinyMceConfig();
445 window.$events.emitPublic(this.elem, 'editor-tinymce::pre-init', {config: this.tinyMceConfig});
446 window.tinymce.init(this.tinyMceConfig);
453 const drawioUrlElem = document.querySelector('[drawio-url]');
455 const url = drawioUrlElem.getAttribute('drawio-url');
456 drawIoPlugin(url, this.isDarkMode, this.pageId, this);
457 this.plugins += ' drawio';
460 if (this.textDirection === 'rtl') {
461 this.plugins += ' directionality'
466 const textDirPlugins = this.textDirection === 'rtl' ? 'ltr rtl' : '';
467 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`
472 const context = this;
475 selector: '#html-editor',
477 window.baseUrl('/dist/styles.css'),
480 skin: this.isDarkMode ? 'dark' : 'lightgray',
481 body_class: 'page-content',
482 browser_spellcheck: true,
483 relative_urls: false,
484 directionality : this.textDirection,
485 remove_script_host: false,
486 document_base_url: window.baseUrl('/'),
487 end_container_on_empty_block: true,
490 paste_data_images: false,
491 extended_valid_elements: 'pre[*],svg[*],div[drawio-diagram]',
492 automatic_uploads: false,
493 valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre],+div[img]",
494 plugins: this.plugins,
495 imagetools_toolbar: 'imageoptions',
496 toolbar: this.getToolBar(),
497 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;}`,
499 {title: "Header Large", format: "h2"},
500 {title: "Header Medium", format: "h3"},
501 {title: "Header Small", format: "h4"},
502 {title: "Header Tiny", format: "h5"},
503 {title: "Paragraph", format: "p", exact: true, classes: ''},
504 {title: "Blockquote", format: "blockquote"},
505 {title: "Code Block", icon: "code", cmd: 'codeeditor', format: 'codeeditor'},
506 {title: "Inline Code", icon: "code", inline: "code"},
507 {title: "Callouts", items: [
508 {title: "Info", format: 'calloutinfo'},
509 {title: "Success", format: 'calloutsuccess'},
510 {title: "Warning", format: 'calloutwarning'},
511 {title: "Danger", format: 'calloutdanger'}
514 style_formats_merge: false,
515 media_alt_source: false,
518 codeeditor: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div'},
519 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
520 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
521 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
522 calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
523 calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
524 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
525 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
527 file_browser_callback: function (field_name, url, type, win) {
529 if (type === 'file') {
530 window.EntitySelectorPopup.show(function(entity) {
531 const originalField = win.document.getElementById(field_name);
532 originalField.value = entity.link;
533 const mceForm = originalField.closest('.mce-form');
534 const inputs = mceForm.querySelectorAll('input');
536 // Set text to display if not empty
537 if (!inputs[1].value) {
538 inputs[1].value = entity.name;
542 inputs[2].value = entity.name;
546 if (type === 'image') {
547 // Show image manager
548 window.ImageManager.show(function (image) {
550 // Set popover link input to image url then fire change event
551 // to ensure the new value sticks
552 win.document.getElementById(field_name).value = image.url;
553 if ("createEvent" in document) {
554 let evt = document.createEvent("HTMLEvents");
555 evt.initEvent("change", false, true);
556 win.document.getElementById(field_name).dispatchEvent(evt);
558 win.document.getElementById(field_name).fireEvent("onchange");
561 // Replace the actively selected content with the linked image
562 const imageUrl = image.thumbs.display || image.url;
563 let html = `<a href="${image.url}" target="_blank">`;
564 html += `<img src="${imageUrl}" alt="${image.name}">`;
566 win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
571 paste_preprocess: function (plugin, args) {
572 let content = args.content;
573 if (content.indexOf('<img src="file://') !== -1) {
577 init_instance_callback: function(editor) {
578 loadCustomHeadContent(editor);
580 setup: function (editor) {
582 editor.on('ExecCommand change input NodeChange ObjectResized', editorChange);
584 editor.on('init', () => {
586 // Scroll to the content if needed.
587 const queryParams = (new URL(window.location)).searchParams;
588 const scrollId = queryParams.get('content-id');
590 scrollToText(scrollId);
593 // Override for touch events to allow scroll on mobile
594 const container = editor.getContainer();
595 const toolbarButtons = container.querySelectorAll('.mce-btn');
596 for (let button of toolbarButtons) {
597 button.addEventListener('touchstart', event => {
598 event.stopPropagation();
601 window.editor = editor;
604 function editorChange() {
605 const content = editor.getContent();
606 if (context.isDarkMode) {
607 editor.contentDocument.documentElement.classList.add('dark-mode');
609 window.$events.emit('editor-html-change', content);
612 function scrollToText(scrollId) {
613 const element = editor.dom.get(encodeURIComponent(scrollId).replace(/!/g, '%21'));
618 // scroll the element into the view and put the cursor at the end.
619 element.scrollIntoView();
620 editor.selection.select(element, true);
621 editor.selection.collapse(false);
625 listenForBookStackEditorEvents(editor);
627 // TODO - Update to standardise across both editors
628 // Use events within listenForBookStackEditorEvents instead (Different event signature)
629 window.$events.listen('editor-html-update', html => {
630 editor.setContent(html);
631 editor.selection.select(editor.getBody(), true);
632 editor.selection.collapse(false);
636 registerEditorShortcuts(editor);
639 let draggedContentEditable;
641 function hasTextContent(node) {
642 return node && !!( node.textContent || node.innerText );
645 editor.on('dragstart', function () {
646 let node = editor.selection.getNode();
648 if (node.nodeName === 'IMG') {
649 wrap = editor.dom.getParent(node, '.mceTemp');
651 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
652 wrap = node.parentNode;
656 // Track dragged contenteditable blocks
657 if (node.hasAttribute('contenteditable') && node.getAttribute('contenteditable') === 'false') {
658 draggedContentEditable = node;
663 // Custom drop event handling
664 editor.on('drop', function (event) {
665 let dom = editor.dom,
666 rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
668 // Template insertion
669 const templateId = event.dataTransfer && event.dataTransfer.getData('bookstack/template');
671 event.preventDefault();
672 window.$http.get(`/templates/${templateId}`).then(resp => {
673 editor.selection.setRng(rng);
674 editor.undoManager.transact(function () {
675 editor.execCommand('mceInsertContent', false, resp.data.html);
680 // Don't allow anything to be dropped in a captioned image.
681 if (dom.getParent(rng.startContainer, '.mceTemp')) {
682 event.preventDefault();
684 event.preventDefault();
686 editor.undoManager.transact(function () {
687 editor.selection.setRng(rng);
688 editor.selection.setNode(wrap);
693 // Handle contenteditable section drop
694 if (!event.isDefaultPrevented() && draggedContentEditable) {
695 event.preventDefault();
696 editor.undoManager.transact(function () {
697 const selectedNode = editor.selection.getNode();
698 const range = editor.selection.getRng();
699 const selectedNodeRoot = selectedNode.closest('body > *');
700 if (range.startOffset > (range.startContainer.length / 2)) {
701 editor.$(selectedNodeRoot).after(draggedContentEditable);
703 editor.$(selectedNodeRoot).before(draggedContentEditable);
708 // Handle image insert
709 if (!event.isDefaultPrevented()) {
710 editorPaste(event, editor, context);
716 // Custom Image picker button
717 editor.addButton('image-insert', {
720 tooltip: 'Insert an image',
721 onclick: function () {
722 window.ImageManager.show(function (image) {
723 const imageUrl = image.thumbs.display || image.url;
724 let html = `<a href="${image.url}" target="_blank">`;
725 html += `<img src="${imageUrl}" alt="${image.name}">`;
727 editor.execCommand('mceInsertContent', false, html);
732 // Paste image-uploads
733 editor.on('paste', event => editorPaste(event, editor, context));
735 // Custom handler hook
736 window.$events.emitPublic(context.elem, 'editor-tinymce::setup', {editor});
743 export default WysiwygEditor;