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.addIcon('codeblock', '<svg width="24" height="24"><path d="M4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 0 1-1-1V4c0-.6.4-1 1-1Zm1 2v14h14V5Z"/><path d="M11.103 15.423c.277.277.277.738 0 .922a.692.692 0 0 1-1.106 0l-4.057-3.78a.738.738 0 0 1 0-1.107l4.057-3.872c.276-.277.83-.277 1.106 0a.724.724 0 0 1 0 1.014L7.6 12.012ZM12.897 8.577c-.245-.312-.2-.675.08-.955.28-.281.727-.27 1.027.033l4.057 3.78a.738.738 0 0 1 0 1.107l-4.057 3.872c-.277.277-.83.277-1.107 0a.724.724 0 0 1 0-1.014l3.504-3.412z"/></svg>')
194 editor.ui.registry.addButton('codeeditor', {
195 title: 'Insert code block',
198 editor.execCommand('codeeditor');
202 editor.addCommand('codeeditor', () => {
207 editor.on('PreProcess', function (e) {
208 $('div.CodeMirrorContainer', e.node).each((index, elem) => {
209 codeMirrorContainerToPre(elem);
213 editor.on('dblclick', event => {
214 let selectedNode = editor.selection.getNode();
215 if (!elemIsCodeBlock(selectedNode)) return;
219 function parseCodeMirrorInstances() {
221 // Recover broken codemirror instances
222 $('.CodeMirrorContainer').filter((index ,elem) => {
223 return typeof elem.querySelector('.CodeMirror').CodeMirror === 'undefined';
224 }).each((index, elem) => {
225 codeMirrorContainerToPre(elem);
228 const codeSamples = $('body > pre').filter((index, elem) => {
229 return elem.contentEditable !== "false";
232 codeSamples.each((index, elem) => {
233 Code.wysiwygView(elem);
237 editor.on('init', function() {
238 // Parse code mirror instances on init, but delay a little so this runs after
239 // initial styles are fetched into the editor.
240 editor.undoManager.transact(function () {
241 parseCodeMirrorInstances();
243 // Parsed code mirror blocks when content is set but wait before setting this handler
244 // to avoid any init 'SetContent' events.
246 editor.on('SetContent', () => {
247 setTimeout(parseCodeMirrorInstances, 100);
255 function drawIoPlugin(drawioUrl, isDarkMode, pageId, wysiwygComponent) {
257 let pageEditor = null;
258 let currentNode = null;
260 function isDrawing(node) {
261 return node.hasAttribute('drawio-diagram');
264 function showDrawingManager(mceEditor, selectedNode = null) {
265 pageEditor = mceEditor;
266 currentNode = selectedNode;
267 // Show image manager
268 window.ImageManager.show(function (image) {
270 let imgElem = selectedNode.querySelector('img');
271 pageEditor.dom.setAttrib(imgElem, 'src', image.url);
272 pageEditor.dom.setAttrib(selectedNode, 'drawio-diagram', image.id);
274 let imgHTML = `<div drawio-diagram="${image.id}" contenteditable="false"><img src="${image.url}"></div>`;
275 pageEditor.insertContent(imgHTML);
280 function showDrawingEditor(mceEditor, selectedNode = null) {
281 pageEditor = mceEditor;
282 currentNode = selectedNode;
283 DrawIO.show(drawioUrl, drawingInit, updateContent);
286 async function updateContent(pngData) {
287 const id = "image-" + Math.random().toString(16).slice(2);
288 const loadingImage = window.baseUrl('/loading.gif');
290 const handleUploadError = (error) => {
291 if (error.status === 413) {
292 window.$events.emit('error', wysiwygComponent.serverUploadLimitText);
294 window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
299 // Handle updating an existing image
302 let imgElem = currentNode.querySelector('img');
304 const img = await DrawIO.upload(pngData, pageId);
305 pageEditor.dom.setAttrib(imgElem, 'src', img.url);
306 pageEditor.dom.setAttrib(currentNode, 'drawio-diagram', img.id);
308 handleUploadError(err);
313 setTimeout(async () => {
314 pageEditor.insertContent(`<div drawio-diagram contenteditable="false"><img src="${loadingImage}" id="${id}"></div>`);
317 const img = await DrawIO.upload(pngData, pageId);
318 pageEditor.dom.setAttrib(id, 'src', img.url);
319 pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', img.id);
321 pageEditor.dom.remove(id);
322 handleUploadError(err);
328 function drawingInit() {
330 return Promise.resolve('');
333 let drawingId = currentNode.getAttribute('drawio-diagram');
334 return DrawIO.load(drawingId);
337 window.tinymce.PluginManager.add('drawio', function(editor, url) {
339 editor.addCommand('drawio', () => {
340 const selectedNode = editor.selection.getNode();
341 showDrawingEditor(editor, isDrawing(selectedNode) ? selectedNode : null);
344 // 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>`)
345 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>`)
347 editor.ui.registry.addSplitButton('drawio', {
351 editor.execCommand('drawio');
357 text: 'Drawing Manager',
358 value: 'drawing-manager',
362 onItemAction(api, value) {
363 if (value === 'drawing-manager') {
364 const selectedNode = editor.selection.getNode();
365 showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
370 editor.on('dblclick', event => {
371 let selectedNode = editor.selection.getNode();
372 if (!isDrawing(selectedNode)) return;
373 showDrawingEditor(editor, selectedNode);
376 editor.on('SetContent', function () {
377 const drawings = editor.$('body > div[drawio-diagram]');
378 if (!drawings.length) return;
380 editor.undoManager.transact(function () {
381 drawings.each((index, elem) => {
382 elem.setAttribute('contenteditable', 'false');
390 function customHrPlugin() {
391 window.tinymce.PluginManager.add('customhr', function (editor) {
392 editor.addCommand('InsertHorizontalRule', function () {
393 let hrElem = document.createElement('hr');
394 let cNode = editor.selection.getNode();
395 let parentNode = cNode.parentNode;
396 parentNode.insertBefore(hrElem, cNode);
399 editor.ui.registry.addButton('hr', {
400 icon: 'horizontal-rule',
401 tooltip: 'Horizontal line',
403 editor.execCommand('InsertHorizontalRule');
407 editor.ui.registry.addMenuItem('hr', {
408 icon: 'horizontal-rule',
409 text: 'Horizontal line',
412 editor.execCommand('InsertHorizontalRule');
419 function listenForBookStackEditorEvents(editor) {
421 // Replace editor content
422 window.$events.listen('editor::replace', ({html}) => {
423 editor.setContent(html);
426 // Append editor content
427 window.$events.listen('editor::append', ({html}) => {
428 const content = editor.getContent() + html;
429 editor.setContent(content);
432 // Prepend editor content
433 window.$events.listen('editor::prepend', ({html}) => {
434 const content = html + editor.getContent();
435 editor.setContent(content);
438 // Insert editor content at the current location
439 window.$events.listen('editor::insert', ({html}) => {
440 editor.insertContent(html);
443 // Focus on the editor
444 window.$events.listen('editor::focus', () => {
449 class WysiwygEditor {
452 this.elem = this.$el;
454 this.pageId = this.$opts.pageId;
455 this.textDirection = this.$opts.textDirection;
456 this.imageUploadErrorText = this.$opts.imageUploadErrorText;
457 this.serverUploadLimitText = this.$opts.serverUploadLimitText;
458 this.isDarkMode = document.documentElement.classList.contains('dark-mode');
460 this.plugins = "image imagetools table paste link autolink fullscreen code customhr autosave lists codeeditor media";
463 this.tinyMceConfig = this.getTinyMceConfig();
464 window.$events.emitPublic(this.elem, 'editor-tinymce::pre-init', {config: this.tinyMceConfig});
465 window.tinymce.init(this.tinyMceConfig);
472 const drawioUrlElem = document.querySelector('[drawio-url]');
474 const url = drawioUrlElem.getAttribute('drawio-url');
475 drawIoPlugin(url, this.isDarkMode, this.pageId, this);
476 this.plugins += ' drawio';
479 if (this.textDirection === 'rtl') {
480 this.plugins += ' directionality'
485 const textDirPlugins = this.textDirection === 'rtl' ? 'ltr rtl' : '';
486 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 codeeditor drawio media | removeformat code ${textDirPlugins} fullscreen`
491 const context = this;
496 selector: '#html-editor',
498 window.baseUrl('/dist/styles.css'),
501 skin: this.isDarkMode ? 'oxide-dark' : 'oxide',
502 body_class: 'page-content',
503 browser_spellcheck: true,
504 relative_urls: false,
505 directionality : this.textDirection,
506 remove_script_host: false,
507 document_base_url: window.baseUrl('/'),
508 end_container_on_empty_block: true,
511 paste_data_images: false,
512 extended_valid_elements: 'pre[*],svg[*],div[drawio-diagram]',
513 automatic_uploads: false,
514 valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre],+div[img]",
515 plugins: this.plugins,
516 imagetools_toolbar: 'imageoptions',
518 toolbar: this.getToolBar(),
519 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;}`,
521 {title: "Header Large", format: "h2", preview: 'color: blue;'},
522 {title: "Header Medium", format: "h3"},
523 {title: "Header Small", format: "h4"},
524 {title: "Header Tiny", format: "h5"},
525 {title: "Paragraph", format: "p", exact: true, classes: ''},
526 {title: "Blockquote", format: "blockquote"},
527 {title: "Inline Code", inline: "code"},
528 {title: "Callouts", items: [
529 {title: "Info", format: 'calloutinfo'},
530 {title: "Success", format: 'calloutsuccess'},
531 {title: "Warning", format: 'calloutwarning'},
532 {title: "Danger", format: 'calloutdanger'}
535 style_formats_merge: false,
536 media_alt_source: false,
539 codeeditor: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div'},
540 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
541 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
542 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
543 calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
544 calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
545 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
546 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
548 file_picker_types: 'file image',
549 file_picker_callback(callback, value, meta) {
551 // field_name, url, type, win
552 if (meta.filetype === 'file') {
553 window.EntitySelectorPopup.show(entity => {
554 callback(entity.link, {
561 if (meta.filetype === 'image') {
562 // Show image manager
563 window.ImageManager.show(function (image) {
564 callback(image.url, {alt: image.name});
569 paste_preprocess(plugin, args) {
570 let content = args.content;
571 if (content.indexOf('<img src="file://') !== -1) {
575 init_instance_callback(editor) {
576 loadCustomHeadContent(editor);
580 editor.on('ExecCommand change input NodeChange ObjectResized', editorChange);
582 editor.on('init', () => {
584 // Scroll to the content if needed.
585 const queryParams = (new URL(window.location)).searchParams;
586 const scrollId = queryParams.get('content-id');
588 scrollToText(scrollId);
591 // Override for touch events to allow scroll on mobile
592 const container = editor.getContainer();
593 const toolbarButtons = container.querySelectorAll('.mce-btn');
594 for (let button of toolbarButtons) {
595 button.addEventListener('touchstart', event => {
596 event.stopPropagation();
599 window.editor = editor;
602 function editorChange() {
603 const content = editor.getContent();
604 if (context.isDarkMode) {
605 editor.contentDocument.documentElement.classList.add('dark-mode');
607 window.$events.emit('editor-html-change', content);
610 function scrollToText(scrollId) {
611 const element = editor.dom.get(encodeURIComponent(scrollId).replace(/!/g, '%21'));
616 // scroll the element into the view and put the cursor at the end.
617 element.scrollIntoView();
618 editor.selection.select(element, true);
619 editor.selection.collapse(false);
623 listenForBookStackEditorEvents(editor);
625 // TODO - Update to standardise across both editors
626 // Use events within listenForBookStackEditorEvents instead (Different event signature)
627 window.$events.listen('editor-html-update', html => {
628 editor.setContent(html);
629 editor.selection.select(editor.getBody(), true);
630 editor.selection.collapse(false);
634 registerEditorShortcuts(editor);
637 let draggedContentEditable;
639 function hasTextContent(node) {
640 return node && !!( node.textContent || node.innerText );
643 editor.on('dragstart', function () {
644 let node = editor.selection.getNode();
646 if (node.nodeName === 'IMG') {
647 wrap = editor.dom.getParent(node, '.mceTemp');
649 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
650 wrap = node.parentNode;
654 // Track dragged contenteditable blocks
655 if (node.hasAttribute('contenteditable') && node.getAttribute('contenteditable') === 'false') {
656 draggedContentEditable = node;
661 // Custom drop event handling
662 editor.on('drop', function (event) {
663 let dom = editor.dom,
664 rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
666 // Template insertion
667 const templateId = event.dataTransfer && event.dataTransfer.getData('bookstack/template');
669 event.preventDefault();
670 window.$http.get(`/templates/${templateId}`).then(resp => {
671 editor.selection.setRng(rng);
672 editor.undoManager.transact(function () {
673 editor.execCommand('mceInsertContent', false, resp.data.html);
678 // Don't allow anything to be dropped in a captioned image.
679 if (dom.getParent(rng.startContainer, '.mceTemp')) {
680 event.preventDefault();
682 event.preventDefault();
684 editor.undoManager.transact(function () {
685 editor.selection.setRng(rng);
686 editor.selection.setNode(wrap);
691 // Handle contenteditable section drop
692 if (!event.isDefaultPrevented() && draggedContentEditable) {
693 event.preventDefault();
694 editor.undoManager.transact(function () {
695 const selectedNode = editor.selection.getNode();
696 const range = editor.selection.getRng();
697 const selectedNodeRoot = selectedNode.closest('body > *');
698 if (range.startOffset > (range.startContainer.length / 2)) {
699 editor.$(selectedNodeRoot).after(draggedContentEditable);
701 editor.$(selectedNodeRoot).before(draggedContentEditable);
706 // Handle image insert
707 if (!event.isDefaultPrevented()) {
708 editorPaste(event, editor, context);
714 // Custom Image picker button
715 editor.ui.registry.addButton('image-insert', {
716 title: 'Insert an image',
718 tooltip: 'Insert an image',
720 window.ImageManager.show(function (image) {
721 const imageUrl = image.thumbs.display || image.url;
722 let html = `<a href="${image.url}" target="_blank">`;
723 html += `<img src="${imageUrl}" alt="${image.name}">`;
725 editor.execCommand('mceInsertContent', false, html);
730 // Paste image-uploads
731 editor.on('paste', event => editorPaste(event, editor, context));
733 // Custom handler hook
734 window.$events.emitPublic(context.elem, 'editor-tinymce::setup', {editor});
741 export default WysiwygEditor;