]> BookStack Code Mirror - bookstack/blobdiff - resources/js/components/wysiwyg-editor.js
Made further tweaks to align with current editor
[bookstack] / resources / js / components / wysiwyg-editor.js
index 41b2273e2a0ad48918e5e50c334f5c1e29ef319f..100a70ff4dd9436dc717275bcb647fabea0cc362 100644 (file)
@@ -152,8 +152,8 @@ function codePlugin() {
             return;
         }
 
-        let lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
-        let currentCode = selectedNode.querySelector('textarea').textContent;
+        const lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
+        const currentCode = selectedNode.querySelector('textarea').textContent;
 
         window.components.first('code-editor').open(currentCode, lang, (code, lang) => {
             const editorElem = selectedNode.querySelector('.CodeMirror');
@@ -189,10 +189,14 @@ function codePlugin() {
 
         const $ = editor.$;
 
-        editor.addButton('codeeditor', {
-            text: 'Code block',
-            icon: false,
-            cmd: 'codeeditor'
+        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>')
+
+        editor.ui.registry.addButton('codeeditor', {
+            title: 'Insert code block',
+            icon: 'codeblock',
+            onAction() {
+                editor.execCommand('codeeditor');
+            }
         });
 
         editor.addCommand('codeeditor', () => {
@@ -212,7 +216,7 @@ function codePlugin() {
             showPopup(editor);
         });
 
-        editor.on('SetContent', function () {
+        function parseCodeMirrorInstances() {
 
             // Recover broken codemirror instances
             $('.CodeMirrorContainer').filter((index ,elem) => {
@@ -225,12 +229,24 @@ function codePlugin() {
                 return elem.contentEditable !== "false";
             });
 
-            if (!codeSamples.length) return;
+            codeSamples.each((index, elem) => {
+                Code.wysiwygView(elem);
+            });
+        }
+
+        editor.on('init', function() {
+            // Parse code mirror instances on init, but delay a little so this runs after
+            // initial styles are fetched into the editor.
             editor.undoManager.transact(function () {
-                codeSamples.each((index, elem) => {
-                    Code.wysiwygView(elem);
-                });
+                parseCodeMirrorInstances();
             });
+            // Parsed code mirror blocks when content is set but wait before setting this handler
+            // to avoid any init 'SetContent' events.
+            setTimeout(() => {
+                editor.on('SetContent', () => {
+                    setTimeout(parseCodeMirrorInstances, 100);
+                });
+            }, 200);
         });
 
     });
@@ -271,6 +287,15 @@ function drawIoPlugin(drawioUrl, isDarkMode, pageId, wysiwygComponent) {
         const id = "image-" + Math.random().toString(16).slice(2);
         const loadingImage = window.baseUrl('/loading.gif');
 
+        const handleUploadError = (error) => {
+            if (error.status === 413) {
+                window.$events.emit('error', wysiwygComponent.serverUploadLimitText);
+            } else {
+                window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
+            }
+            console.log(error);
+        };
+
         // Handle updating an existing image
         if (currentNode) {
             DrawIO.close();
@@ -280,8 +305,7 @@ function drawIoPlugin(drawioUrl, isDarkMode, pageId, wysiwygComponent) {
                 pageEditor.dom.setAttrib(imgElem, 'src', img.url);
                 pageEditor.dom.setAttrib(currentNode, 'drawio-diagram', img.id);
             } catch (err) {
-                window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
-                console.log(err);
+                handleUploadError(err);
             }
             return;
         }
@@ -295,8 +319,7 @@ function drawIoPlugin(drawioUrl, isDarkMode, pageId, wysiwygComponent) {
                 pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', img.id);
             } catch (err) {
                 pageEditor.dom.remove(id);
-                window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
-                console.log(err);
+                handleUploadError(err);
             }
         }, 5);
     }
@@ -318,23 +341,30 @@ function drawIoPlugin(drawioUrl, isDarkMode, pageId, wysiwygComponent) {
             showDrawingEditor(editor, isDrawing(selectedNode) ? selectedNode : null);
         });
 
-        editor.addButton('drawio', {
-            type: 'splitbutton',
+        // 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>`)
+        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>`)
+
+        editor.ui.registry.addSplitButton('drawio', {
             tooltip: 'Drawing',
-            image: `data:image/svg+xml;base64,${btoa(`<svg viewBox="0 0 24 24" fill="${isDarkMode ? '#BBB' : '#000000'}"  xmlns="http://www.w3.org/2000/svg">
-    <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"/>
-    <path d="M0 0h24v24H0z" fill="none"/>
-</svg>`)}`,
-            cmd: 'drawio',
-            menu: [
-                {
-                    text: 'Drawing Manager',
-                    onclick() {
-                        let selectedNode = editor.selection.getNode();
-                        showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
+            icon: 'diagram',
+            onAction() {
+                editor.execCommand('drawio');
+            },
+            fetch(callback) {
+                callback([
+                    {
+                        type: 'choiceitem',
+                        text: 'Drawing Manager',
+                        value: 'drawing-manager',
                     }
+                ]);
+            },
+            onItemAction(api, value) {
+                if (value === 'drawing-manager') {
+                    const selectedNode = editor.selection.getNode();
+                    showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
                 }
-            ]
+            }
         });
 
         editor.on('dblclick', event => {
@@ -366,17 +396,21 @@ function customHrPlugin() {
             parentNode.insertBefore(hrElem, cNode);
         });
 
-        editor.addButton('hr', {
-            icon: 'hr',
+        editor.ui.registry.addButton('hr', {
+            icon: 'horizontal-rule',
             tooltip: 'Horizontal line',
-            cmd: 'InsertHorizontalRule'
+            onAction() {
+                editor.execCommand('InsertHorizontalRule');
+            }
         });
 
-        editor.addMenuItem('hr', {
-            icon: 'hr',
+        editor.ui.registry.addMenuItem('hr', {
+            icon: 'horizontal-rule',
             text: 'Horizontal line',
-            cmd: 'InsertHorizontalRule',
-            context: 'insert'
+            context: 'insert',
+            onAction() {
+                editor.execCommand('InsertHorizontalRule');
+            }
         });
     });
 }
@@ -420,9 +454,10 @@ class WysiwygEditor {
         this.pageId = this.$opts.pageId;
         this.textDirection = this.$opts.textDirection;
         this.imageUploadErrorText = this.$opts.imageUploadErrorText;
+        this.serverUploadLimitText = this.$opts.serverUploadLimitText;
         this.isDarkMode = document.documentElement.classList.contains('dark-mode');
 
-        this.plugins = "image imagetools table textcolor paste link autolink fullscreen code customhr autosave lists codeeditor media";
+        this.plugins = "image imagetools table paste link autolink fullscreen code customhr autosave lists codeeditor media";
         this.loadPlugins();
 
         this.tinyMceConfig = this.getTinyMceConfig();
@@ -448,7 +483,7 @@ class WysiwygEditor {
 
     getToolBar() {
         const textDirPlugins = this.textDirection === 'rtl' ? 'ltr rtl' : '';
-        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`
+        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`
     }
 
     getTinyMceConfig() {
@@ -456,12 +491,14 @@ class WysiwygEditor {
         const context = this;
 
         return {
+            width: '100%',
+            height: '100%',
             selector: '#html-editor',
             content_css: [
                 window.baseUrl('/dist/styles.css'),
             ],
             branding: false,
-            skin: this.isDarkMode ? 'dark' : 'lightgray',
+            skin: this.isDarkMode ? 'oxide-dark' : 'oxide',
             body_class: 'page-content',
             browser_spellcheck: true,
             relative_urls: false,
@@ -477,17 +514,17 @@ class WysiwygEditor {
             valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre],+div[img]",
             plugins: this.plugins,
             imagetools_toolbar: 'imageoptions',
+            contextmenu: false,
             toolbar: this.getToolBar(),
             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;}`,
             style_formats: [
-                {title: "Header Large", format: "h2"},
+                {title: "Header Large", format: "h2", preview: 'color: blue;'},
                 {title: "Header Medium", format: "h3"},
                 {title: "Header Small", format: "h4"},
                 {title: "Header Tiny", format: "h5"},
                 {title: "Paragraph", format: "p", exact: true, classes: ''},
                 {title: "Blockquote", format: "blockquote"},
-                {title: "Code Block", icon: "code", cmd: 'codeeditor', format: 'codeeditor'},
-                {title: "Inline Code", icon: "code", inline: "code"},
+                {title: "Inline Code", inline: "code"},
                 {title: "Callouts", items: [
                         {title: "Info", format: 'calloutinfo'},
                         {title: "Success", format: 'calloutsuccess'},
@@ -508,59 +545,37 @@ class WysiwygEditor {
                 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
                 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
             },
-            file_browser_callback: function (field_name, url, type, win) {
-
-                if (type === 'file') {
-                    window.EntitySelectorPopup.show(function(entity) {
-                        const originalField = win.document.getElementById(field_name);
-                        originalField.value = entity.link;
-                        const mceForm = originalField.closest('.mce-form');
-                        const inputs = mceForm.querySelectorAll('input');
-
-                        // Set text to display if not empty
-                        if (!inputs[1].value) {
-                            inputs[1].value = entity.name;
-                        }
-
-                        // Set title field
-                        inputs[2].value = entity.name;
+            file_picker_types: 'file image',
+            file_picker_callback(callback, value, meta) {
+
+                // field_name, url, type, win
+                if (meta.filetype === 'file') {
+                    window.EntitySelectorPopup.show(entity => {
+                        callback(entity.link, {
+                            text: entity.name,
+                            title: entity.name,
+                        });
                     });
                 }
 
-                if (type === 'image') {
+                if (meta.filetype === 'image') {
                     // Show image manager
                     window.ImageManager.show(function (image) {
-
-                        // Set popover link input to image url then fire change event
-                        // to ensure the new value sticks
-                        win.document.getElementById(field_name).value = image.url;
-                        if ("createEvent" in document) {
-                            let evt = document.createEvent("HTMLEvents");
-                            evt.initEvent("change", false, true);
-                            win.document.getElementById(field_name).dispatchEvent(evt);
-                        } else {
-                            win.document.getElementById(field_name).fireEvent("onchange");
-                        }
-
-                        // Replace the actively selected content with the linked image
-                        let html = `<a href="${image.url}" target="_blank">`;
-                        html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
-                        html += '</a>';
-                        win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
+                        callback(image.url, {alt: image.name});
                     }, 'gallery');
                 }
 
             },
-            paste_preprocess: function (plugin, args) {
+            paste_preprocess(plugin, args) {
                 let content = args.content;
                 if (content.indexOf('<img src="file://') !== -1) {
                     args.content = '';
                 }
             },
-            init_instance_callback: function(editor) {
+            init_instance_callback(editor) {
                 loadCustomHeadContent(editor);
             },
-            setup: function (editor) {
+            setup(editor) {
 
                 editor.on('ExecCommand change input NodeChange ObjectResized', editorChange);
 
@@ -697,14 +712,15 @@ class WysiwygEditor {
                 });
 
                 // Custom Image picker button
-                editor.addButton('image-insert', {
-                    title: 'My title',
+                editor.ui.registry.addButton('image-insert', {
+                    title: 'Insert an image',
                     icon: 'image',
                     tooltip: 'Insert an image',
-                    onclick: function () {
+                    onAction() {
                         window.ImageManager.show(function (image) {
+                            const imageUrl = image.thumbs.display || image.url;
                             let html = `<a href="${image.url}" target="_blank">`;
-                            html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
+                            html += `<img src="${imageUrl}" alt="${image.name}">`;
                             html += '</a>';
                             editor.execCommand('mceInsertContent', false, html);
                         }, 'gallery');