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 let selectedNode = editor.selection.getNode();
102 let formats = ['info', 'success', 'warning', 'danger'];
104 if (!selectedNode || selectedNode.className.indexOf('callout') === -1) {
105 editor.formatter.apply('calloutinfo');
109 for (let i = 0; i < formats.length; i++) {
110 if (selectedNode.className.indexOf(formats[i]) === -1) continue;
111 let newFormat = (i === formats.length -1) ? formats[0] : formats[i+1];
112 editor.formatter.apply('callout' + newFormat);
115 editor.formatter.apply('p');
121 * Load custom HTML head content from the settings into the editor.
124 function loadCustomHeadContent(editor) {
125 window.$http.get(window.baseUrl('/custom-head-content')).then(resp => {
126 if (!resp.data) return;
127 let head = editor.getDoc().querySelector('head');
128 head.innerHTML += resp.data;
133 * Create and enable our custom code plugin
135 function codePlugin() {
137 function elemIsCodeBlock(elem) {
138 return elem.className === 'CodeMirrorContainer';
141 function showPopup(editor) {
142 const selectedNode = editor.selection.getNode();
144 if (!elemIsCodeBlock(selectedNode)) {
145 const providedCode = editor.selection.getNode().textContent;
146 window.vues['code-editor'].open(providedCode, '', (code, lang) => {
147 const wrap = document.createElement('div');
148 wrap.innerHTML = `<pre><code class="language-${lang}"></code></pre>`;
149 wrap.querySelector('code').innerText = code;
151 editor.formatter.toggle('pre');
152 const node = editor.selection.getNode();
153 editor.dom.setHTML(node, wrap.querySelector('pre').innerHTML);
154 editor.fire('SetContent');
161 let lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
162 let currentCode = selectedNode.querySelector('textarea').textContent;
164 window.vues['code-editor'].open(currentCode, lang, (code, lang) => {
165 const editorElem = selectedNode.querySelector('.CodeMirror');
166 const cmInstance = editorElem.CodeMirror;
168 Code.setContent(cmInstance, code);
169 Code.setMode(cmInstance, lang, code);
171 const textArea = selectedNode.querySelector('textarea');
172 if (textArea) textArea.textContent = code;
173 selectedNode.setAttribute('data-lang', lang);
179 function codeMirrorContainerToPre(codeMirrorContainer) {
180 const textArea = codeMirrorContainer.querySelector('textarea');
181 const code = textArea.textContent;
182 const lang = codeMirrorContainer.getAttribute('data-lang');
184 codeMirrorContainer.removeAttribute('contentEditable');
185 const pre = document.createElement('pre');
186 const codeElem = document.createElement('code');
187 codeElem.classList.add(`language-${lang}`);
188 codeElem.textContent = code;
189 pre.appendChild(codeElem);
191 codeMirrorContainer.parentElement.replaceChild(pre, codeMirrorContainer);
194 window.tinymce.PluginManager.add('codeeditor', function(editor, url) {
198 editor.addButton('codeeditor', {
204 editor.addCommand('codeeditor', () => {
209 editor.on('PreProcess', function (e) {
210 $('div.CodeMirrorContainer', e.node).each((index, elem) => {
211 codeMirrorContainerToPre(elem);
215 editor.on('dblclick', event => {
216 let selectedNode = editor.selection.getNode();
217 if (!elemIsCodeBlock(selectedNode)) return;
221 editor.on('SetContent', function () {
223 // Recover broken codemirror instances
224 $('.CodeMirrorContainer').filter((index ,elem) => {
225 return typeof elem.querySelector('.CodeMirror').CodeMirror === 'undefined';
226 }).each((index, elem) => {
227 codeMirrorContainerToPre(elem);
230 const codeSamples = $('body > pre').filter((index, elem) => {
231 return elem.contentEditable !== "false";
234 if (!codeSamples.length) return;
235 editor.undoManager.transact(function () {
236 codeSamples.each((index, elem) => {
237 Code.wysiwygView(elem);
245 function drawIoPlugin(drawioUrl, isDarkMode) {
247 let pageEditor = null;
248 let currentNode = null;
250 function isDrawing(node) {
251 return node.hasAttribute('drawio-diagram');
254 function showDrawingManager(mceEditor, selectedNode = null) {
255 pageEditor = mceEditor;
256 currentNode = selectedNode;
257 // Show image manager
258 window.ImageManager.show(function (image) {
260 let imgElem = selectedNode.querySelector('img');
261 pageEditor.dom.setAttrib(imgElem, 'src', image.url);
262 pageEditor.dom.setAttrib(selectedNode, 'drawio-diagram', image.id);
264 let imgHTML = `<div drawio-diagram="${image.id}" contenteditable="false"><img src="${image.url}"></div>`;
265 pageEditor.insertContent(imgHTML);
270 function showDrawingEditor(mceEditor, selectedNode = null) {
271 pageEditor = mceEditor;
272 currentNode = selectedNode;
273 DrawIO.show(drawioUrl, drawingInit, updateContent);
276 async function updateContent(pngData) {
277 const id = "image-" + Math.random().toString(16).slice(2);
278 const loadingImage = window.baseUrl('/loading.gif');
279 const pageId = Number(document.getElementById('page-editor').getAttribute('page-id'));
281 // Handle updating an existing image
284 let imgElem = currentNode.querySelector('img');
286 const img = await DrawIO.upload(pngData, pageId);
287 pageEditor.dom.setAttrib(imgElem, 'src', img.url);
288 pageEditor.dom.setAttrib(currentNode, 'drawio-diagram', img.id);
290 window.$events.emit('error', trans('errors.image_upload_error'));
296 setTimeout(async () => {
297 pageEditor.insertContent(`<div drawio-diagram contenteditable="false"><img src="${loadingImage}" id="${id}"></div>`);
300 const img = await DrawIO.upload(pngData, pageId);
301 pageEditor.dom.setAttrib(id, 'src', img.url);
302 pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', img.id);
304 pageEditor.dom.remove(id);
305 window.$events.emit('error', trans('errors.image_upload_error'));
312 function drawingInit() {
314 return Promise.resolve('');
317 let drawingId = currentNode.getAttribute('drawio-diagram');
318 return DrawIO.load(drawingId);
321 window.tinymce.PluginManager.add('drawio', function(editor, url) {
323 editor.addCommand('drawio', () => {
324 const selectedNode = editor.selection.getNode();
325 showDrawingEditor(editor, isDrawing(selectedNode) ? selectedNode : null);
328 editor.addButton('drawio', {
331 image: `data:image/svg+xml;base64,${btoa(`<svg viewBox="0 0 24 24" fill="${isDarkMode ? '#BBB' : '#000000'}" xmlns="http://www.w3.org/2000/svg">
332 <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"/>
333 <path d="M0 0h24v24H0z" fill="none"/>
338 text: 'Drawing Manager',
340 let selectedNode = editor.selection.getNode();
341 showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
347 editor.on('dblclick', event => {
348 let selectedNode = editor.selection.getNode();
349 if (!isDrawing(selectedNode)) return;
350 showDrawingEditor(editor, selectedNode);
353 editor.on('SetContent', function () {
354 const drawings = editor.$('body > div[drawio-diagram]');
355 if (!drawings.length) return;
357 editor.undoManager.transact(function () {
358 drawings.each((index, elem) => {
359 elem.setAttribute('contenteditable', 'false');
367 function customHrPlugin() {
368 window.tinymce.PluginManager.add('customhr', function (editor) {
369 editor.addCommand('InsertHorizontalRule', function () {
370 let hrElem = document.createElement('hr');
371 let cNode = editor.selection.getNode();
372 let parentNode = cNode.parentNode;
373 parentNode.insertBefore(hrElem, cNode);
376 editor.addButton('hr', {
378 tooltip: 'Horizontal line',
379 cmd: 'InsertHorizontalRule'
382 editor.addMenuItem('hr', {
384 text: 'Horizontal line',
385 cmd: 'InsertHorizontalRule',
392 function listenForBookStackEditorEvents(editor) {
394 // Replace editor content
395 window.$events.listen('editor::replace', ({html}) => {
396 editor.setContent(html);
399 // Append editor content
400 window.$events.listen('editor::append', ({html}) => {
401 const content = editor.getContent() + html;
402 editor.setContent(content);
405 // Prepend editor content
406 window.$events.listen('editor::prepend', ({html}) => {
407 const content = html + editor.getContent();
408 editor.setContent(content);
413 class WysiwygEditor {
418 const pageEditor = document.getElementById('page-editor');
419 this.pageId = pageEditor.getAttribute('page-id');
420 this.textDirection = pageEditor.getAttribute('text-direction');
421 this.isDarkMode = document.documentElement.classList.contains('dark-mode');
423 this.plugins = "image table textcolor paste link autolink fullscreen imagetools code customhr autosave lists codeeditor media";
426 this.tinyMceConfig = this.getTinyMceConfig();
427 window.$events.emitPublic(elem, 'editor-tinymce::pre-init', {config: this.tinyMceConfig});
428 window.tinymce.init(this.tinyMceConfig);
435 const drawioUrlElem = document.querySelector('[drawio-url]');
437 const url = drawioUrlElem.getAttribute('drawio-url');
438 drawIoPlugin(url, this.isDarkMode);
439 this.plugins += ' drawio';
442 if (this.textDirection === 'rtl') {
443 this.plugins += ' directionality'
448 const textDirPlugins = this.textDirection === 'rtl' ? 'ltr rtl' : '';
449 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`
454 const context = this;
457 selector: '#html-editor',
459 window.baseUrl('/dist/styles.css'),
462 skin: this.isDarkMode ? 'dark' : 'lightgray',
463 body_class: 'page-content',
464 browser_spellcheck: true,
465 relative_urls: false,
466 directionality : this.textDirection,
467 remove_script_host: false,
468 document_base_url: window.baseUrl('/'),
469 end_container_on_empty_block: true,
472 paste_data_images: false,
473 extended_valid_elements: 'pre[*],svg[*],div[drawio-diagram]',
474 automatic_uploads: false,
475 valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre],+div[img]",
476 plugins: this.plugins,
477 imagetools_toolbar: 'imageoptions',
478 toolbar: this.getToolBar(),
479 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;}`,
481 {title: "Header Large", format: "h2"},
482 {title: "Header Medium", format: "h3"},
483 {title: "Header Small", format: "h4"},
484 {title: "Header Tiny", format: "h5"},
485 {title: "Paragraph", format: "p", exact: true, classes: ''},
486 {title: "Blockquote", format: "blockquote"},
487 {title: "Code Block", icon: "code", cmd: 'codeeditor', format: 'codeeditor'},
488 {title: "Inline Code", icon: "code", inline: "code"},
489 {title: "Callouts", items: [
490 {title: "Info", format: 'calloutinfo'},
491 {title: "Success", format: 'calloutsuccess'},
492 {title: "Warning", format: 'calloutwarning'},
493 {title: "Danger", format: 'calloutdanger'}
496 style_formats_merge: false,
497 media_alt_source: false,
500 codeeditor: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div'},
501 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
502 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
503 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
504 calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
505 calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
506 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
507 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
509 file_browser_callback: function (field_name, url, type, win) {
511 if (type === 'file') {
512 window.EntitySelectorPopup.show(function(entity) {
513 const originalField = win.document.getElementById(field_name);
514 originalField.value = entity.link;
515 const mceForm = originalField.closest('.mce-form');
516 const inputs = mceForm.querySelectorAll('input');
518 // Set text to display if not empty
519 if (!inputs[1].value) {
520 inputs[1].value = entity.name;
524 inputs[2].value = entity.name;
528 if (type === 'image') {
529 // Show image manager
530 window.ImageManager.show(function (image) {
532 // Set popover link input to image url then fire change event
533 // to ensure the new value sticks
534 win.document.getElementById(field_name).value = image.url;
535 if ("createEvent" in document) {
536 let evt = document.createEvent("HTMLEvents");
537 evt.initEvent("change", false, true);
538 win.document.getElementById(field_name).dispatchEvent(evt);
540 win.document.getElementById(field_name).fireEvent("onchange");
543 // Replace the actively selected content with the linked image
544 let html = `<a href="${image.url}" target="_blank">`;
545 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
547 win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
552 paste_preprocess: function (plugin, args) {
553 let content = args.content;
554 if (content.indexOf('<img src="file://') !== -1) {
558 init_instance_callback: function(editor) {
559 loadCustomHeadContent(editor);
561 setup: function (editor) {
563 editor.on('ExecCommand change input NodeChange ObjectResized', editorChange);
565 editor.on('init', () => {
567 // Scroll to the content if needed.
568 const queryParams = (new URL(window.location)).searchParams;
569 const scrollId = queryParams.get('content-id');
571 scrollToText(scrollId);
574 // Override for touch events to allow scroll on mobile
575 const container = editor.getContainer();
576 const toolbarButtons = container.querySelectorAll('.mce-btn');
577 for (let button of toolbarButtons) {
578 button.addEventListener('touchstart', event => {
579 event.stopPropagation();
582 window.editor = editor;
585 function editorChange() {
586 const content = editor.getContent();
587 if (context.isDarkMode) {
588 editor.contentDocument.documentElement.classList.add('dark-mode');
590 window.$events.emit('editor-html-change', content);
593 function scrollToText(scrollId) {
594 const element = editor.dom.get(encodeURIComponent(scrollId).replace(/!/g, '%21'));
599 // scroll the element into the view and put the cursor at the end.
600 element.scrollIntoView();
601 editor.selection.select(element, true);
602 editor.selection.collapse(false);
606 listenForBookStackEditorEvents(editor);
608 // TODO - Update to standardise across both editors
609 // Use events within listenForBookStackEditorEvents instead (Different event signature)
610 window.$events.listen('editor-html-update', html => {
611 editor.setContent(html);
612 editor.selection.select(editor.getBody(), true);
613 editor.selection.collapse(false);
617 registerEditorShortcuts(editor);
620 let draggedContentEditable;
622 function hasTextContent(node) {
623 return node && !!( node.textContent || node.innerText );
626 editor.on('dragstart', function () {
627 let node = editor.selection.getNode();
629 if (node.nodeName === 'IMG') {
630 wrap = editor.dom.getParent(node, '.mceTemp');
632 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
633 wrap = node.parentNode;
637 // Track dragged contenteditable blocks
638 if (node.hasAttribute('contenteditable') && node.getAttribute('contenteditable') === 'false') {
639 draggedContentEditable = node;
644 editor.on('drop', function (event) {
645 let dom = editor.dom,
646 rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
648 // Template insertion
649 const templateId = event.dataTransfer && event.dataTransfer.getData('bookstack/template');
651 event.preventDefault();
652 window.$http.get(`/templates/${templateId}`).then(resp => {
653 editor.selection.setRng(rng);
654 editor.undoManager.transact(function () {
655 editor.execCommand('mceInsertContent', false, resp.data.html);
660 // Don't allow anything to be dropped in a captioned image.
661 if (dom.getParent(rng.startContainer, '.mceTemp')) {
662 event.preventDefault();
664 event.preventDefault();
666 editor.undoManager.transact(function () {
667 editor.selection.setRng(rng);
668 editor.selection.setNode(wrap);
673 // Handle contenteditable section drop
674 if (!event.isDefaultPrevented() && draggedContentEditable) {
675 event.preventDefault();
676 editor.undoManager.transact(function () {
677 const selectedNode = editor.selection.getNode();
678 const range = editor.selection.getRng();
679 const selectedNodeRoot = selectedNode.closest('body > *');
680 if (range.startOffset > (range.startContainer.length / 2)) {
681 editor.$(selectedNodeRoot).after(draggedContentEditable);
683 editor.$(selectedNodeRoot).before(draggedContentEditable);
688 // Handle image insert
689 if (!event.isDefaultPrevented()) {
690 editorPaste(event, editor, context);
696 // Custom Image picker button
697 editor.addButton('image-insert', {
700 tooltip: 'Insert an image',
701 onclick: function () {
702 window.ImageManager.show(function (image) {
703 let html = `<a href="${image.url}" target="_blank">`;
704 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
706 editor.execCommand('mceInsertContent', false, html);
711 // Paste image-uploads
712 editor.on('paste', event => editorPaste(event, editor, context));
714 // Custom handler hook
715 window.$events.emitPublic(context.elem, 'editor-tinymce::setup', {editor});
722 export default WysiwygEditor;