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', trans('errors.image_upload_error'));
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.vues['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 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 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 editor.on('SetContent', function () {
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 if (!codeSamples.length) return;
229 editor.undoManager.transact(function () {
230 codeSamples.each((index, elem) => {
231 Code.wysiwygView(elem);
239 function drawIoPlugin(drawioUrl, isDarkMode) {
241 let pageEditor = null;
242 let currentNode = null;
244 function isDrawing(node) {
245 return node.hasAttribute('drawio-diagram');
248 function showDrawingManager(mceEditor, selectedNode = null) {
249 pageEditor = mceEditor;
250 currentNode = selectedNode;
251 // Show image manager
252 window.ImageManager.show(function (image) {
254 let imgElem = selectedNode.querySelector('img');
255 pageEditor.dom.setAttrib(imgElem, 'src', image.url);
256 pageEditor.dom.setAttrib(selectedNode, 'drawio-diagram', image.id);
258 let imgHTML = `<div drawio-diagram="${image.id}" contenteditable="false"><img src="${image.url}"></div>`;
259 pageEditor.insertContent(imgHTML);
264 function showDrawingEditor(mceEditor, selectedNode = null) {
265 pageEditor = mceEditor;
266 currentNode = selectedNode;
267 DrawIO.show(drawioUrl, drawingInit, updateContent);
270 async function updateContent(pngData) {
271 const id = "image-" + Math.random().toString(16).slice(2);
272 const loadingImage = window.baseUrl('/loading.gif');
273 const pageId = Number(document.getElementById('page-editor').getAttribute('page-id'));
275 // Handle updating an existing image
278 let imgElem = currentNode.querySelector('img');
280 const img = await DrawIO.upload(pngData, pageId);
281 pageEditor.dom.setAttrib(imgElem, 'src', img.url);
282 pageEditor.dom.setAttrib(currentNode, 'drawio-diagram', img.id);
284 window.$events.emit('error', trans('errors.image_upload_error'));
290 setTimeout(async () => {
291 pageEditor.insertContent(`<div drawio-diagram contenteditable="false"><img src="${loadingImage}" id="${id}"></div>`);
294 const img = await DrawIO.upload(pngData, pageId);
295 pageEditor.dom.setAttrib(id, 'src', img.url);
296 pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', img.id);
298 pageEditor.dom.remove(id);
299 window.$events.emit('error', trans('errors.image_upload_error'));
306 function drawingInit() {
308 return Promise.resolve('');
311 let drawingId = currentNode.getAttribute('drawio-diagram');
312 return DrawIO.load(drawingId);
315 window.tinymce.PluginManager.add('drawio', function(editor, url) {
317 editor.addCommand('drawio', () => {
318 const selectedNode = editor.selection.getNode();
319 showDrawingEditor(editor, isDrawing(selectedNode) ? selectedNode : null);
322 editor.addButton('drawio', {
325 image: `data:image/svg+xml;base64,${btoa(`<svg viewBox="0 0 24 24" fill="${isDarkMode ? '#BBB' : '#000000'}" xmlns="http://www.w3.org/2000/svg">
326 <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"/>
327 <path d="M0 0h24v24H0z" fill="none"/>
332 text: 'Drawing Manager',
334 let selectedNode = editor.selection.getNode();
335 showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
341 editor.on('dblclick', event => {
342 let selectedNode = editor.selection.getNode();
343 if (!isDrawing(selectedNode)) return;
344 showDrawingEditor(editor, selectedNode);
347 editor.on('SetContent', function () {
348 const drawings = editor.$('body > div[drawio-diagram]');
349 if (!drawings.length) return;
351 editor.undoManager.transact(function () {
352 drawings.each((index, elem) => {
353 elem.setAttribute('contenteditable', 'false');
361 function customHrPlugin() {
362 window.tinymce.PluginManager.add('customhr', function (editor) {
363 editor.addCommand('InsertHorizontalRule', function () {
364 let hrElem = document.createElement('hr');
365 let cNode = editor.selection.getNode();
366 let parentNode = cNode.parentNode;
367 parentNode.insertBefore(hrElem, cNode);
370 editor.addButton('hr', {
372 tooltip: 'Horizontal line',
373 cmd: 'InsertHorizontalRule'
376 editor.addMenuItem('hr', {
378 text: 'Horizontal line',
379 cmd: 'InsertHorizontalRule',
386 function listenForBookStackEditorEvents(editor) {
388 // Replace editor content
389 window.$events.listen('editor::replace', ({html}) => {
390 editor.setContent(html);
393 // Append editor content
394 window.$events.listen('editor::append', ({html}) => {
395 const content = editor.getContent() + html;
396 editor.setContent(content);
399 // Prepend editor content
400 window.$events.listen('editor::prepend', ({html}) => {
401 const content = html + editor.getContent();
402 editor.setContent(content);
407 class WysiwygEditor {
412 const pageEditor = document.getElementById('page-editor');
413 this.pageId = pageEditor.getAttribute('page-id');
414 this.textDirection = pageEditor.getAttribute('text-direction');
415 this.isDarkMode = document.documentElement.classList.contains('dark-mode');
417 this.plugins = "image table textcolor paste link autolink fullscreen imagetools code customhr autosave lists codeeditor media";
420 this.tinyMceConfig = this.getTinyMceConfig();
421 window.$events.emitPublic(elem, 'editor-tinymce::pre-init', {config: this.tinyMceConfig});
422 window.tinymce.init(this.tinyMceConfig);
429 const drawioUrlElem = document.querySelector('[drawio-url]');
431 const url = drawioUrlElem.getAttribute('drawio-url');
432 drawIoPlugin(url, this.isDarkMode);
433 this.plugins += ' drawio';
436 if (this.textDirection === 'rtl') {
437 this.plugins += ' directionality'
442 const textDirPlugins = this.textDirection === 'rtl' ? 'ltr rtl' : '';
443 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`
448 const context = this;
451 selector: '#html-editor',
453 window.baseUrl('/dist/styles.css'),
456 skin: this.isDarkMode ? 'dark' : 'lightgray',
457 body_class: 'page-content',
458 browser_spellcheck: true,
459 relative_urls: false,
460 directionality : this.textDirection,
461 remove_script_host: false,
462 document_base_url: window.baseUrl('/'),
463 end_container_on_empty_block: true,
466 paste_data_images: false,
467 extended_valid_elements: 'pre[*],svg[*],div[drawio-diagram]',
468 automatic_uploads: false,
469 valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre],+div[img]",
470 plugins: this.plugins,
471 imagetools_toolbar: 'imageoptions',
472 toolbar: this.getToolBar(),
473 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;}`,
475 {title: "Header Large", format: "h2"},
476 {title: "Header Medium", format: "h3"},
477 {title: "Header Small", format: "h4"},
478 {title: "Header Tiny", format: "h5"},
479 {title: "Paragraph", format: "p", exact: true, classes: ''},
480 {title: "Blockquote", format: "blockquote"},
481 {title: "Code Block", icon: "code", cmd: 'codeeditor', format: 'codeeditor'},
482 {title: "Inline Code", icon: "code", inline: "code"},
483 {title: "Callouts", items: [
484 {title: "Info", format: 'calloutinfo'},
485 {title: "Success", format: 'calloutsuccess'},
486 {title: "Warning", format: 'calloutwarning'},
487 {title: "Danger", format: 'calloutdanger'}
490 style_formats_merge: false,
491 media_alt_source: false,
494 codeeditor: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div'},
495 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
496 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
497 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
498 calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
499 calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
500 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
501 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
503 file_browser_callback: function (field_name, url, type, win) {
505 if (type === 'file') {
506 window.EntitySelectorPopup.show(function(entity) {
507 const originalField = win.document.getElementById(field_name);
508 originalField.value = entity.link;
509 const mceForm = originalField.closest('.mce-form');
510 const inputs = mceForm.querySelectorAll('input');
512 // Set text to display if not empty
513 if (!inputs[1].value) {
514 inputs[1].value = entity.name;
518 inputs[2].value = entity.name;
522 if (type === 'image') {
523 // Show image manager
524 window.ImageManager.show(function (image) {
526 // Set popover link input to image url then fire change event
527 // to ensure the new value sticks
528 win.document.getElementById(field_name).value = image.url;
529 if ("createEvent" in document) {
530 let evt = document.createEvent("HTMLEvents");
531 evt.initEvent("change", false, true);
532 win.document.getElementById(field_name).dispatchEvent(evt);
534 win.document.getElementById(field_name).fireEvent("onchange");
537 // Replace the actively selected content with the linked image
538 let html = `<a href="${image.url}" target="_blank">`;
539 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
541 win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
546 paste_preprocess: function (plugin, args) {
547 let content = args.content;
548 if (content.indexOf('<img src="file://') !== -1) {
552 init_instance_callback: function(editor) {
553 loadCustomHeadContent(editor);
555 setup: function (editor) {
557 editor.on('ExecCommand change input NodeChange ObjectResized', editorChange);
559 editor.on('init', () => {
561 // Scroll to the content if needed.
562 const queryParams = (new URL(window.location)).searchParams;
563 const scrollId = queryParams.get('content-id');
565 scrollToText(scrollId);
568 // Override for touch events to allow scroll on mobile
569 const container = editor.getContainer();
570 const toolbarButtons = container.querySelectorAll('.mce-btn');
571 for (let button of toolbarButtons) {
572 button.addEventListener('touchstart', event => {
573 event.stopPropagation();
576 window.editor = editor;
579 function editorChange() {
580 const content = editor.getContent();
581 if (context.isDarkMode) {
582 editor.contentDocument.documentElement.classList.add('dark-mode');
584 window.$events.emit('editor-html-change', content);
587 function scrollToText(scrollId) {
588 const element = editor.dom.get(encodeURIComponent(scrollId).replace(/!/g, '%21'));
593 // scroll the element into the view and put the cursor at the end.
594 element.scrollIntoView();
595 editor.selection.select(element, true);
596 editor.selection.collapse(false);
600 listenForBookStackEditorEvents(editor);
602 // TODO - Update to standardise across both editors
603 // Use events within listenForBookStackEditorEvents instead (Different event signature)
604 window.$events.listen('editor-html-update', html => {
605 editor.setContent(html);
606 editor.selection.select(editor.getBody(), true);
607 editor.selection.collapse(false);
611 registerEditorShortcuts(editor);
614 let draggedContentEditable;
616 function hasTextContent(node) {
617 return node && !!( node.textContent || node.innerText );
620 editor.on('dragstart', function () {
621 let node = editor.selection.getNode();
623 if (node.nodeName === 'IMG') {
624 wrap = editor.dom.getParent(node, '.mceTemp');
626 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
627 wrap = node.parentNode;
631 // Track dragged contenteditable blocks
632 if (node.hasAttribute('contenteditable') && node.getAttribute('contenteditable') === 'false') {
633 draggedContentEditable = node;
638 editor.on('drop', function (event) {
639 let dom = editor.dom,
640 rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
642 // Template insertion
643 const templateId = event.dataTransfer && event.dataTransfer.getData('bookstack/template');
645 event.preventDefault();
646 window.$http.get(`/templates/${templateId}`).then(resp => {
647 editor.selection.setRng(rng);
648 editor.undoManager.transact(function () {
649 editor.execCommand('mceInsertContent', false, resp.data.html);
654 // Don't allow anything to be dropped in a captioned image.
655 if (dom.getParent(rng.startContainer, '.mceTemp')) {
656 event.preventDefault();
658 event.preventDefault();
660 editor.undoManager.transact(function () {
661 editor.selection.setRng(rng);
662 editor.selection.setNode(wrap);
667 // Handle contenteditable section drop
668 if (!event.isDefaultPrevented() && draggedContentEditable) {
669 event.preventDefault();
670 editor.undoManager.transact(function () {
671 const selectedNode = editor.selection.getNode();
672 const range = editor.selection.getRng();
673 const selectedNodeRoot = selectedNode.closest('body > *');
674 if (range.startOffset > (range.startContainer.length / 2)) {
675 editor.$(selectedNodeRoot).after(draggedContentEditable);
677 editor.$(selectedNodeRoot).before(draggedContentEditable);
682 // Handle image insert
683 if (!event.isDefaultPrevented()) {
684 editorPaste(event, editor, context);
690 // Custom Image picker button
691 editor.addButton('image-insert', {
694 tooltip: 'Insert an image',
695 onclick: function () {
696 window.ImageManager.show(function (image) {
697 let html = `<a href="${image.url}" target="_blank">`;
698 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
700 editor.execCommand('mceInsertContent', false, html);
705 // Paste image-uploads
706 editor.on('paste', event => editorPaste(event, editor, context));
708 // Custom handler hook
709 window.$events.emitPublic(context.elem, 'editor-tinymce::setup', {editor});
716 export default WysiwygEditor;