import Code from "../services/code";
import DrawIO from "../services/drawio";
+import Clipboard from "../services/clipboard";
/**
* Handle pasting images from clipboard.
* @param editor
*/
function editorPaste(event, editor, wysiwygComponent) {
- const clipboardItems = event.clipboardData.items;
- if (!event.clipboardData || !clipboardItems) return;
+ const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
- // Don't handle if clipboard includes text content
- for (let clipboardItem of clipboardItems) {
- if (clipboardItem.type.includes('text/')) {
- return;
- }
+ // Don't handle the event ourselves if no items exist of contains table-looking data
+ if (!clipboard.hasItems() || clipboard.containsTabularData()) {
+ return;
}
- for (let clipboardItem of clipboardItems) {
- if (!clipboardItem.type.includes("image")) {
- continue;
- }
+ const images = clipboard.getImages();
+ for (const imageFile of images) {
const id = "image-" + Math.random().toString(16).slice(2);
const loadingImage = window.baseUrl('/loading.gif');
- const file = clipboardItem.getAsFile();
+ event.preventDefault();
setTimeout(() => {
editor.insertContent(`<p><img src="${loadingImage}" id="${id}"></p>`);
- uploadImageFile(file, wysiwygComponent).then(resp => {
- editor.dom.setAttrib(id, 'src', resp.thumbs.display);
+ uploadImageFile(imageFile, wysiwygComponent).then(resp => {
+ const safeName = resp.name.replace(/"/g, '');
+ const newImageHtml = `<img src="${resp.thumbs.display}" alt="${safeName}" />`;
+
+ const newEl = editor.dom.create('a', {
+ target: '_blank',
+ href: resp.url,
+ }, newImageHtml);
+
+ editor.dom.replace(newEl, id);
}).catch(err => {
editor.dom.remove(id);
- window.$events.emit('error', trans('errors.image_upload_error'));
+ window.$events.emit('error', wysiwygComponent.imageUploadErrorText);
console.log(err);
});
}, 10);
// Loop through callout styles
editor.shortcuts.add('meta+9', '', function() {
- let selectedNode = editor.selection.getNode();
- let formats = ['info', 'success', 'warning', 'danger'];
+ const selectedNode = editor.selection.getNode();
+ const callout = selectedNode ? selectedNode.closest('.callout') : null;
- if (!selectedNode || selectedNode.className.indexOf('callout') === -1) {
- editor.formatter.apply('calloutinfo');
- return;
- }
+ const formats = ['info', 'success', 'warning', 'danger'];
+ const currentFormatIndex = formats.findIndex(format => callout && callout.classList.contains(format));
+ const newFormatIndex = (currentFormatIndex + 1) % formats.length;
+ const newFormat = formats[newFormatIndex];
- for (let i = 0; i < formats.length; i++) {
- if (selectedNode.className.indexOf(formats[i]) === -1) continue;
- let newFormat = (i === formats.length -1) ? formats[0] : formats[i+1];
- editor.formatter.apply('callout' + newFormat);
- return;
- }
- editor.formatter.apply('p');
+ editor.formatter.apply('callout' + newFormat);
});
}
}
function showPopup(editor) {
- let selectedNode = editor.selection.getNode();
+ const selectedNode = editor.selection.getNode();
if (!elemIsCodeBlock(selectedNode)) {
- let providedCode = editor.selection.getNode().textContent;
- window.vues['code-editor'].open(providedCode, '', (code, lang) => {
- let wrap = document.createElement('div');
+ const providedCode = editor.selection.getNode().textContent;
+ window.components.first('code-editor').open(providedCode, '', (code, lang) => {
+ const wrap = document.createElement('div');
wrap.innerHTML = `<pre><code class="language-${lang}"></code></pre>`;
wrap.querySelector('code').innerText = code;
editor.formatter.toggle('pre');
- let node = editor.selection.getNode();
+ const node = editor.selection.getNode();
editor.dom.setHTML(node, wrap.querySelector('pre').innerHTML);
editor.fire('SetContent');
+
+ editor.focus()
});
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.vues['code-editor'].open(currentCode, lang, (code, lang) => {
- let editorElem = selectedNode.querySelector('.CodeMirror');
- let cmInstance = editorElem.CodeMirror;
+ window.components.first('code-editor').open(currentCode, lang, (code, lang) => {
+ const editorElem = selectedNode.querySelector('.CodeMirror');
+ const cmInstance = editorElem.CodeMirror;
if (cmInstance) {
Code.setContent(cmInstance, code);
- Code.setMode(cmInstance, lang);
+ Code.setMode(cmInstance, lang, code);
}
- let textArea = selectedNode.querySelector('textarea');
+ const textArea = selectedNode.querySelector('textarea');
if (textArea) textArea.textContent = code;
selectedNode.setAttribute('data-lang', lang);
+
+ editor.focus()
});
}
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', () => {
showPopup(editor);
});
- editor.on('SetContent', function () {
+ function parseCodeMirrorInstances() {
// Recover broken codemirror instances
$('.CodeMirrorContainer').filter((index ,elem) => {
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);
});
});
}
-function drawIoPlugin() {
+function drawIoPlugin(drawioUrl, isDarkMode, pageId, wysiwygComponent) {
let pageEditor = null;
let currentNode = null;
function showDrawingEditor(mceEditor, selectedNode = null) {
pageEditor = mceEditor;
currentNode = selectedNode;
- DrawIO.show(drawingInit, updateContent);
+ DrawIO.show(drawioUrl, drawingInit, updateContent);
}
async function updateContent(pngData) {
const id = "image-" + Math.random().toString(16).slice(2);
const loadingImage = window.baseUrl('/loading.gif');
- const pageId = Number(document.getElementById('page-editor').getAttribute('page-id'));
+
+ 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) {
pageEditor.dom.setAttrib(imgElem, 'src', img.url);
pageEditor.dom.setAttrib(currentNode, 'drawio-diagram', img.id);
} catch (err) {
- window.$events.emit('error', trans('errors.image_upload_error'));
- console.log(err);
+ handleUploadError(err);
}
return;
}
pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', img.id);
} catch (err) {
pageEditor.dom.remove(id);
- window.$events.emit('error', trans('errors.image_upload_error'));
- console.log(err);
+ handleUploadError(err);
}
}, 5);
}
window.tinymce.PluginManager.add('drawio', function(editor, url) {
editor.addCommand('drawio', () => {
- let selectedNode = editor.selection.getNode();
+ const selectedNode = editor.selection.getNode();
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,PHN2ZyB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9IiMwMDAwMDAiICB4bWxucz0iaHR0cDovL3d3 dy53My5vcmcvMjAwMC9zdmciPgogICAgPHBhdGggZD0iTTIzIDdWMWgtNnYySDdWMUgxdjZoMnYx MEgxdjZoNnYtMmgxMHYyaDZ2LTZoLTJWN2gyek0zIDNoMnYySDNWM3ptMiAxOEgzdi0yaDJ2Mnpt MTItMkg3di0ySDVWN2gyVjVoMTB2MmgydjEwaC0ydjJ6bTQgMmgtMnYtMmgydjJ6TTE5IDVWM2gy djJoLTJ6bS01LjI3IDloLTMuNDlsLS43MyAySDcuODlsMy40LTloMS40bDMuNDEgOWgtMS42M2wt Ljc0LTJ6bS0zLjA0LTEuMjZoMi42MUwxMiA4LjkxbC0xLjMxIDMuODN6Ii8+CiAgICA8cGF0aCBk PSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIi8+Cjwvc3ZnPg==`,
- 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 => {
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');
+ }
});
});
}
editor.setContent(content);
});
+ // Insert editor content at the current location
+ window.$events.listen('editor::insert', ({html}) => {
+ editor.insertContent(html);
+ });
+
+ // Focus on the editor
+ window.$events.listen('editor::focus', () => {
+ editor.focus();
+ });
}
class WysiwygEditor {
- constructor(elem) {
- this.elem = elem;
+ setup() {
+ this.elem = this.$el;
- const pageEditor = document.getElementById('page-editor');
- this.pageId = pageEditor.getAttribute('page-id');
- this.textDirection = pageEditor.getAttribute('text-direction');
+ 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 table textcolor paste link autolink fullscreen imagetools 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();
+ window.$events.emitPublic(this.elem, 'editor-tinymce::pre-init', {config: this.tinyMceConfig});
window.tinymce.init(this.tinyMceConfig);
}
loadPlugins() {
codePlugin();
customHrPlugin();
- if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') === 'true') {
- drawIoPlugin();
+
+ const drawioUrlElem = document.querySelector('[drawio-url]');
+ if (drawioUrlElem) {
+ const url = drawioUrlElem.getAttribute('drawio-url');
+ drawIoPlugin(url, this.isDarkMode, this.pageId, this);
this.plugins += ' drawio';
}
+
if (this.textDirection === 'rtl') {
this.plugins += ' directionality'
}
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() {
const context = this;
return {
+ width: '100%',
+ height: '100%',
selector: '#html-editor',
content_css: [
window.baseUrl('/dist/styles.css'),
],
branding: false,
+ skin: this.isDarkMode ? 'oxide-dark' : 'oxide',
body_class: 'page-content',
browser_spellcheck: true,
relative_urls: false,
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 {background: #FFF;} body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}",
+ 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'},
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');
- mceForm.querySelectorAll('input')[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);
});
function editorChange() {
- let content = editor.getContent();
+ const content = editor.getContent();
+ if (context.isDarkMode) {
+ editor.contentDocument.documentElement.classList.add('dark-mode');
+ }
window.$events.emit('editor-html-change', content);
}
registerEditorShortcuts(editor);
let wrap;
+ let draggedContentEditable;
function hasTextContent(node) {
return node && !!( node.textContent || node.innerText );
editor.on('dragstart', function () {
let node = editor.selection.getNode();
- if (node.nodeName !== 'IMG') return;
- wrap = editor.dom.getParent(node, '.mceTemp');
+ if (node.nodeName === 'IMG') {
+ wrap = editor.dom.getParent(node, '.mceTemp');
- if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
- wrap = node.parentNode;
+ if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
+ wrap = node.parentNode;
+ }
}
+
+ // Track dragged contenteditable blocks
+ if (node.hasAttribute('contenteditable') && node.getAttribute('contenteditable') === 'false') {
+ draggedContentEditable = node;
+ }
+
});
+ // Custom drop event handling
editor.on('drop', function (event) {
let dom = editor.dom,
rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
// Template insertion
- const templateId = event.dataTransfer.getData('bookstack/template');
+ const templateId = event.dataTransfer && event.dataTransfer.getData('bookstack/template');
if (templateId) {
event.preventDefault();
window.$http.get(`/templates/${templateId}`).then(resp => {
});
}
+ // Handle contenteditable section drop
+ if (!event.isDefaultPrevented() && draggedContentEditable) {
+ event.preventDefault();
+ editor.undoManager.transact(function () {
+ const selectedNode = editor.selection.getNode();
+ const range = editor.selection.getRng();
+ const selectedNodeRoot = selectedNode.closest('body > *');
+ if (range.startOffset > (range.startContainer.length / 2)) {
+ editor.$(selectedNodeRoot).after(draggedContentEditable);
+ } else {
+ editor.$(selectedNodeRoot).before(draggedContentEditable);
+ }
+ });
+ }
+
+ // Handle image insert
+ if (!event.isDefaultPrevented()) {
+ editorPaste(event, editor, context);
+ }
+
wrap = null;
});
// 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');
// Paste image-uploads
editor.on('paste', event => editorPaste(event, editor, context));
+ // Custom handler hook
+ window.$events.emitPublic(context.elem, 'editor-tinymce::setup', {editor});
}
};
}