import MarkdownIt from "markdown-it";
import mdTasksLists from 'markdown-it-task-lists';
-import code from '../services/code';
+import Clipboard from "../services/clipboard";
import {debounce} from "../services/util";
-
+import {patchDomFromHtmlString} from "../services/vdom";
import DrawIO from "../services/drawio";
+import {Component} from "./component";
-class MarkdownEditor {
+export class MarkdownEditor extends Component {
- 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.markdown = new MarkdownIt({html: true});
this.markdown.use(mdTasksLists, {label: true});
this.displayStylesLoaded = false;
this.input = this.elem.querySelector('textarea');
- this.htmlInput = this.elem.querySelector('input[name=html]');
- this.cm = code.markdownEditor(this.input);
+
+ this.cm = null;
+ this.Code = null;
+ const cmLoadPromise = window.importVersioned('code').then(Code => {
+ this.cm = Code.markdownEditor(this.input);
+ this.Code = Code;
+ return this.cm;
+ });
this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
- this.display.addEventListener('load', () => {
+ const displayLoad = () => {
this.displayDoc = this.display.contentDocument;
- this.init();
- });
+ this.init(cmLoadPromise);
+ };
+
+ if (this.display.contentDocument.readyState === 'complete') {
+ displayLoad();
+ } else {
+ this.display.addEventListener('load', displayLoad.bind(this));
+ }
- window.$events.emitPublic(elem, 'editor-markdown::setup', {
+ window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
markdownIt: this.markdown,
displayEl: this.display,
codeMirrorInstance: this.cm,
});
}
- init() {
+ init(cmLoadPromise) {
let lastClick = 0;
return;
}
if (action === 'insertDrawing') this.actionStartDrawing();
+ if (action === 'fullscreen') this.actionFullScreen();
});
// Mobile section toggling
toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
});
- window.$events.listen('editor-markdown-update', value => {
- this.cm.setValue(value);
- this.updateAndRender();
+ cmLoadPromise.then(cm => {
+ this.codeMirrorSetup(cm);
+
+ // Refresh CodeMirror on container resize
+ const resizeDebounced = debounce(() => this.Code.updateLayout(cm), 100, false);
+ const observer = new ResizeObserver(resizeDebounced);
+ observer.observe(this.elem);
});
- this.codeMirrorSetup();
this.listenForBookStackEditorEvents();
// Scroll to text if needed.
updateAndRender() {
const content = this.cm.getValue();
this.input.value = content;
+
const html = this.markdown.render(content);
window.$events.emit('editor-html-change', html);
window.$events.emit('editor-markdown-change', content);
// Set body content
+ const target = this.getDisplayTarget();
this.displayDoc.body.className = 'page-content';
- this.displayDoc.body.innerHTML = html;
- this.htmlInput.value = html;
+ patchDomFromHtmlString(target, html);
// Copy styles from page head and set custom styles for editor
this.loadStylesIntoDisplay();
}
+ getDisplayTarget() {
+ const body = this.displayDoc.body;
+
+ if (body.children.length === 0) {
+ const wrap = document.createElement('div');
+ this.displayDoc.body.append(wrap);
+ }
+
+ return body.children[0];
+ }
+
loadStylesIntoDisplay() {
if (this.displayStylesLoaded) return;
- this.displayDoc.documentElement.className = 'markdown-editor-display';
+ this.displayDoc.documentElement.classList.add('markdown-editor-display');
+ // Set display to be dark mode if parent is
+
+ if (document.documentElement.classList.contains('dark-mode')) {
+ this.displayDoc.documentElement.style.backgroundColor = '#222';
+ this.displayDoc.documentElement.classList.add('dark-mode');
+ }
this.displayDoc.head.innerHTML = '';
const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
}
- codeMirrorSetup() {
- const cm = this.cm;
+ codeMirrorSetup(cm) {
const context = this;
// Text direction
// cm.setOption('direction', this.textDirection);
cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
// Custom key commands
- let metaKey = code.getMetaKey();
+ let metaKey = this.Code.getMetaKey();
const extraKeys = {};
// Insert Image shortcut
extraKeys[`${metaKey}-Alt-I`] = function(cm) {
extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
- extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
+ extraKeys[`${metaKey}-D`] = cm => {replaceLineStart('');};
extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
- extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
+ extraKeys[`${metaKey}-Q`] = cm => {replaceLineStart('>');};
extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
+ extraKeys[`${metaKey}-P`] = cm => {replaceLineStart('-')}
+ extraKeys[`${metaKey}-O`] = cm => {replaceLineStartForOrderedList()}
cm.setOption('extraKeys', extraKeys);
// Update data on content change
// Handle image paste
cm.on('paste', (cm, event) => {
- 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")) {
- uploadImage(clipboardItem.getAsFile());
- }
+ const images = clipboard.getImages();
+ for (const image of images) {
+ uploadImage(image);
}
});
});
}
- if (event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files.length > 0) {
+ const clipboard = new Clipboard(event.dataTransfer);
+ if (clipboard.hasItems() && clipboard.getImages().length > 0) {
const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
cm.setCursor(cursorPos);
event.stopPropagation();
event.preventDefault();
- for (let i = 0; i < event.dataTransfer.files.length; i++) {
- uploadImage(event.dataTransfer.files[i]);
+ const images = clipboard.getImages();
+ for (const image of images) {
+ uploadImage(image);
}
}
cm.setSelections([selections]);
}
+ function replaceLineStartForOrderedList() {
+ const cursor = cm.getCursor();
+ const prevLineContent = cm.getLine(cursor.line - 1) || '';
+ const listMatch = prevLineContent.match(/^(\s*)(\d)([).])\s/) || [];
+
+ const number = (Number(listMatch[2]) || 0) + 1;
+ const whiteSpace = listMatch[1] || '';
+ const listMark = listMatch[3] || '.'
+
+ const prefix = `${whiteSpace}${number}${listMark}`;
+ return replaceLineStart(prefix);
+ }
+
// Handle image upload and add image into markdown content
function uploadImage(file) {
if (file === null || file.type.indexOf('image') !== 0) return;
const newContent = `[](${resp.data.url})`;
replaceContent(placeHolderText, newContent);
}).catch(err => {
- window.$events.emit('error', trans('errors.image_upload_error'));
+ window.$events.emit('error', context.imageUploadErrorText);
replaceContent(placeHolderText, selectedText);
console.log(err);
});
actionInsertImage() {
const cursorPos = this.cm.getCursor('from');
window.ImageManager.show(image => {
+ const imageUrl = image.thumbs.display || image.url;
let selectedText = this.cm.getSelection();
- let newText = "[](" + image.url + ")";
+ let newText = "[](" + image.url + ")";
this.cm.focus();
this.cm.replaceSelection(newText);
this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
});
}
+ getDrawioUrl() {
+ const drawioUrlElem = document.querySelector('[drawio-url]');
+ return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
+ }
+
// Show draw.io if enabled and handle save.
actionStartDrawing() {
- if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
- let cursorPos = this.cm.getCursor('from');
+ const url = this.getDrawioUrl();
+ if (!url) return;
+
+ const cursorPos = this.cm.getCursor('from');
- DrawIO.show(() => {
+ DrawIO.show(url,() => {
return Promise.resolve('');
}, (pngData) => {
- // let id = "image-" + Math.random().toString(16).slice(2);
- // let loadingImage = window.baseUrl('/loading.gif');
- let data = {
+
+ const data = {
image: pngData,
- uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
+ uploaded_to: Number(this.pageId),
};
- window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
+ window.$http.post("/images/drawio", data).then(resp => {
this.insertDrawing(resp.data, cursorPos);
DrawIO.close();
}).catch(err => {
- window.$events.emit('error', trans('errors.image_upload_error'));
- console.log(err);
+ this.handleDrawingUploadError(err);
});
});
}
// Show draw.io if enabled and handle save.
actionEditDrawing(imgContainer) {
- const drawingDisabled = document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true';
- if (drawingDisabled) {
+ const drawioUrl = this.getDrawioUrl();
+ if (!drawioUrl) {
return;
}
const cursorPos = this.cm.getCursor('from');
const drawingId = imgContainer.getAttribute('drawio-diagram');
- DrawIO.show(() => {
+ DrawIO.show(drawioUrl, () => {
return DrawIO.load(drawingId);
}, (pngData) => {
let data = {
image: pngData,
- uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
+ uploaded_to: Number(this.pageId),
};
- window.$http.post(window.baseUrl(`/images/drawio`), data).then(resp => {
+ window.$http.post("/images/drawio", data).then(resp => {
let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
let newContent = this.cm.getValue().split('\n').map(line => {
if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
this.cm.focus();
DrawIO.close();
}).catch(err => {
- window.$events.emit('error', trans('errors.image_upload_error'));
- console.log(err);
+ this.handleDrawingUploadError(err);
});
});
}
+ handleDrawingUploadError(error) {
+ if (error.status === 413) {
+ window.$events.emit('error', this.serverUploadLimitText);
+ } else {
+ window.$events.emit('error', this.imageUploadErrorText);
+ }
+ console.log(error);
+ }
+
+ // Make the editor full screen
+ actionFullScreen() {
+ const alreadyFullscreen = this.elem.classList.contains('fullscreen');
+ this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
+ document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
+ }
+
// Scroll to a specified text
scrollToText(searchText) {
if (!searchText) {
const prependLineCount = markdown.split('\n').length;
this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
});
+
+ // Insert editor content at the current location
+ window.$events.listen('editor::insert', (eventContent) => {
+ const markdown = getContentToInsert(eventContent);
+ this.cm.replaceSelection(markdown);
+ });
+
+ // Focus on editor
+ window.$events.listen('editor::focus', () => {
+ this.cm.focus();
+ });
}
}
-
-export default MarkdownEditor ;