1 import MarkdownIt from "markdown-it";
2 import mdTasksLists from 'markdown-it-task-lists';
3 import Clipboard from "../services/clipboard";
4 import {debounce} from "../services/util";
5 import {patchDomFromHtmlString} from "../services/vdom";
6 import DrawIO from "../services/drawio";
7 import {Component} from "./component";
9 export class MarkdownEditor extends Component {
14 this.pageId = this.$opts.pageId;
15 this.textDirection = this.$opts.textDirection;
16 this.imageUploadErrorText = this.$opts.imageUploadErrorText;
17 this.serverUploadLimitText = this.$opts.serverUploadLimitText;
19 this.markdown = new MarkdownIt({html: true});
20 this.markdown.use(mdTasksLists, {label: true});
22 this.display = this.elem.querySelector('.markdown-display');
24 this.displayStylesLoaded = false;
25 this.input = this.elem.querySelector('textarea');
29 const cmLoadPromise = window.importVersioned('code').then(Code => {
30 this.cm = Code.markdownEditor(this.input);
35 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
37 const displayLoad = () => {
38 this.displayDoc = this.display.contentDocument;
39 this.init(cmLoadPromise);
42 if (this.display.contentDocument.readyState === 'complete') {
45 this.display.addEventListener('load', displayLoad.bind(this));
48 window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
49 markdownIt: this.markdown,
50 displayEl: this.display,
51 codeMirrorInstance: this.cm,
59 // Prevent markdown display link click redirect
60 this.displayDoc.addEventListener('click', event => {
61 let isDblClick = Date.now() - lastClick < 300;
63 let link = event.target.closest('a');
65 event.preventDefault();
66 window.open(link.getAttribute('href'));
70 let drawing = event.target.closest('[drawio-diagram]');
71 if (drawing !== null && isDblClick) {
72 this.actionEditDrawing(drawing);
76 lastClick = Date.now();
80 this.elem.addEventListener('click', event => {
81 let button = event.target.closest('button[data-action]');
82 if (button === null) return;
84 let action = button.getAttribute('data-action');
85 if (action === 'insertImage') this.actionInsertImage();
86 if (action === 'insertLink') this.actionShowLinkSelector();
87 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
88 this.actionShowImageManager();
91 if (action === 'insertDrawing') this.actionStartDrawing();
92 if (action === 'fullscreen') this.actionFullScreen();
95 // Mobile section toggling
96 this.elem.addEventListener('click', event => {
97 const toolbarLabel = event.target.closest('.editor-toolbar-label');
98 if (!toolbarLabel) return;
100 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
101 for (let activeElem of currentActiveSections) {
102 activeElem.classList.remove('active');
105 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
108 cmLoadPromise.then(cm => {
109 this.codeMirrorSetup(cm);
111 // Refresh CodeMirror on container resize
112 const resizeDebounced = debounce(() => this.Code.updateLayout(cm), 100, false);
113 const observer = new ResizeObserver(resizeDebounced);
114 observer.observe(this.elem);
117 this.listenForBookStackEditorEvents();
119 // Scroll to text if needed.
120 const queryParams = (new URL(window.location)).searchParams;
121 const scrollText = queryParams.get('content-text');
123 this.scrollToText(scrollText);
127 // Update the input content and render the display.
129 const content = this.cm.getValue();
130 this.input.value = content;
132 const html = this.markdown.render(content);
133 window.$events.emit('editor-html-change', html);
134 window.$events.emit('editor-markdown-change', content);
137 const target = this.getDisplayTarget();
138 this.displayDoc.body.className = 'page-content';
139 patchDomFromHtmlString(target, html);
141 // Copy styles from page head and set custom styles for editor
142 this.loadStylesIntoDisplay();
146 const body = this.displayDoc.body;
148 if (body.children.length === 0) {
149 const wrap = document.createElement('div');
150 this.displayDoc.body.append(wrap);
153 return body.children[0];
156 loadStylesIntoDisplay() {
157 if (this.displayStylesLoaded) return;
158 this.displayDoc.documentElement.classList.add('markdown-editor-display');
159 // Set display to be dark mode if parent is
161 if (document.documentElement.classList.contains('dark-mode')) {
162 this.displayDoc.documentElement.style.backgroundColor = '#222';
163 this.displayDoc.documentElement.classList.add('dark-mode');
166 this.displayDoc.head.innerHTML = '';
167 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
168 for (let style of styles) {
169 const copy = style.cloneNode(true);
170 this.displayDoc.head.appendChild(copy);
173 this.displayStylesLoaded = true;
176 onMarkdownScroll(lineCount) {
177 const elems = this.displayDoc.body.children;
178 if (elems.length <= lineCount) return;
180 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
181 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
184 codeMirrorSetup(cm) {
185 const context = this;
188 // cm.setOption('direction', this.textDirection);
189 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
190 // Custom key commands
191 let metaKey = this.Code.getMetaKey();
192 const extraKeys = {};
193 // Insert Image shortcut
194 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
195 let selectedText = cm.getSelection();
196 let newText = ``;
197 let cursorPos = cm.getCursor('from');
198 cm.replaceSelection(newText);
199 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
202 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
204 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
205 // Show link selector
206 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
208 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
210 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
211 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
212 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
213 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
214 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
215 extraKeys[`${metaKey}-D`] = cm => {replaceLineStart('');};
216 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
217 extraKeys[`${metaKey}-Q`] = cm => {replaceLineStart('>');};
218 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
219 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
220 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
221 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
222 extraKeys[`${metaKey}-P`] = cm => {replaceLineStart('-')}
223 extraKeys[`${metaKey}-O`] = cm => {replaceLineStartForOrderedList()}
224 cm.setOption('extraKeys', extraKeys);
226 // Update data on content change
227 cm.on('change', (instance, changeObj) => {
228 this.updateAndRender();
231 const onScrollDebounced = debounce((instance) => {
232 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
233 let scroll = instance.getScrollInfo();
234 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
236 this.onMarkdownScroll(-1);
240 let lineNum = instance.lineAtHeight(scroll.top, 'local');
241 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
242 let parser = new DOMParser();
243 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
244 let totalLines = doc.documentElement.querySelectorAll('body > *');
245 this.onMarkdownScroll(totalLines.length);
248 // Handle scroll to sync display view
249 cm.on('scroll', instance => {
250 onScrollDebounced(instance);
253 // Handle image paste
254 cm.on('paste', (cm, event) => {
255 const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
257 // Don't handle the event ourselves if no items exist of contains table-looking data
258 if (!clipboard.hasItems() || clipboard.containsTabularData()) {
262 const images = clipboard.getImages();
263 for (const image of images) {
268 // Handle image & content drag n drop
269 cm.on('drop', (cm, event) => {
271 const templateId = event.dataTransfer.getData('bookstack/template');
273 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
274 cm.setCursor(cursorPos);
275 event.preventDefault();
276 window.$http.get(`/templates/${templateId}`).then(resp => {
277 const content = resp.data.markdown || resp.data.html;
278 cm.replaceSelection(content);
282 const clipboard = new Clipboard(event.dataTransfer);
283 if (clipboard.hasItems() && clipboard.getImages().length > 0) {
284 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
285 cm.setCursor(cursorPos);
286 event.stopPropagation();
287 event.preventDefault();
288 const images = clipboard.getImages();
289 for (const image of images) {
296 // Helper to replace editor content
297 function replaceContent(search, replace) {
298 let text = cm.getValue();
299 let cursor = cm.listSelections();
300 cm.setValue(text.replace(search, replace));
301 cm.setSelections(cursor);
304 // Helper to replace the start of the line
305 function replaceLineStart(newStart) {
306 let cursor = cm.getCursor();
307 let lineContent = cm.getLine(cursor.line);
308 let lineLen = lineContent.length;
309 let lineStart = lineContent.split(' ')[0];
311 // Remove symbol if already set
312 if (lineStart === newStart) {
313 lineContent = lineContent.replace(`${newStart} `, '');
314 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
315 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
319 let alreadySymbol = /^[#>`]/.test(lineStart);
322 posDif = newStart.length - lineStart.length;
323 lineContent = lineContent.replace(lineStart, newStart).trim();
324 } else if (newStart !== '') {
325 posDif = newStart.length + 1;
326 lineContent = newStart + ' ' + lineContent;
328 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
329 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
332 function wrapLine(start, end) {
333 let cursor = cm.getCursor();
334 let lineContent = cm.getLine(cursor.line);
335 let lineLen = lineContent.length;
336 let newLineContent = lineContent;
338 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
339 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
341 newLineContent = `${start}${lineContent}${end}`;
344 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
345 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
348 function wrapSelection(start, end) {
349 let selection = cm.getSelection();
350 if (selection === '') return wrapLine(start, end);
352 let newSelection = selection;
356 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
357 newSelection = selection.slice(start.length, selection.length - end.length);
358 endDiff = -(end.length + start.length);
360 newSelection = `${start}${selection}${end}`;
361 endDiff = start.length + end.length;
364 let selections = cm.listSelections()[0];
365 cm.replaceSelection(newSelection);
366 let headFirst = selections.head.ch <= selections.anchor.ch;
367 selections.head.ch += headFirst ? frontDiff : endDiff;
368 selections.anchor.ch += headFirst ? endDiff : frontDiff;
369 cm.setSelections([selections]);
372 function replaceLineStartForOrderedList() {
373 const cursor = cm.getCursor();
374 const prevLineContent = cm.getLine(cursor.line - 1) || '';
375 const listMatch = prevLineContent.match(/^(\s*)(\d)([).])\s/) || [];
377 const number = (Number(listMatch[2]) || 0) + 1;
378 const whiteSpace = listMatch[1] || '';
379 const listMark = listMatch[3] || '.'
381 const prefix = `${whiteSpace}${number}${listMark}`;
382 return replaceLineStart(prefix);
385 // Handle image upload and add image into markdown content
386 function uploadImage(file) {
387 if (file === null || file.type.indexOf('image') !== 0) return;
391 let fileNameMatches = file.name.match(/\.(.+)$/);
392 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
395 // Insert image into markdown
396 const id = "image-" + Math.random().toString(16).slice(2);
397 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
398 const selectedText = cm.getSelection();
399 const placeHolderText = ``;
400 const cursor = cm.getCursor();
401 cm.replaceSelection(placeHolderText);
402 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
404 const remoteFilename = "image-" + Date.now() + "." + ext;
405 const formData = new FormData();
406 formData.append('file', file, remoteFilename);
407 formData.append('uploaded_to', context.pageId);
409 window.$http.post('/images/gallery', formData).then(resp => {
410 const newContent = `[](${resp.data.url})`;
411 replaceContent(placeHolderText, newContent);
413 window.$events.emit('error', context.imageUploadErrorText);
414 replaceContent(placeHolderText, selectedText);
419 function insertLink() {
420 let cursorPos = cm.getCursor('from');
421 let selectedText = cm.getSelection() || '';
422 let newText = `[${selectedText}]()`;
424 cm.replaceSelection(newText);
425 let cursorPosDiff = (selectedText === '') ? -3 : -1;
426 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
429 this.updateAndRender();
432 actionInsertImage() {
433 const cursorPos = this.cm.getCursor('from');
434 window.ImageManager.show(image => {
435 const imageUrl = image.thumbs.display || image.url;
436 let selectedText = this.cm.getSelection();
437 let newText = "[](" + image.url + ")";
439 this.cm.replaceSelection(newText);
440 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
444 actionShowImageManager() {
445 const cursorPos = this.cm.getCursor('from');
446 window.ImageManager.show(image => {
447 this.insertDrawing(image, cursorPos);
451 // Show the popup link selector and insert a link when finished
452 actionShowLinkSelector() {
453 const cursorPos = this.cm.getCursor('from');
454 window.EntitySelectorPopup.show(entity => {
455 let selectedText = this.cm.getSelection() || entity.name;
456 let newText = `[${selectedText}](${entity.link})`;
458 this.cm.replaceSelection(newText);
459 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
464 const drawioUrlElem = document.querySelector('[drawio-url]');
465 return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
468 // Show draw.io if enabled and handle save.
469 actionStartDrawing() {
470 const url = this.getDrawioUrl();
473 const cursorPos = this.cm.getCursor('from');
475 DrawIO.show(url,() => {
476 return Promise.resolve('');
481 uploaded_to: Number(this.pageId),
484 window.$http.post("/images/drawio", data).then(resp => {
485 this.insertDrawing(resp.data, cursorPos);
488 this.handleDrawingUploadError(err);
493 insertDrawing(image, originalCursor) {
494 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
496 this.cm.replaceSelection(newText);
497 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
500 // Show draw.io if enabled and handle save.
501 actionEditDrawing(imgContainer) {
502 const drawioUrl = this.getDrawioUrl();
507 const cursorPos = this.cm.getCursor('from');
508 const drawingId = imgContainer.getAttribute('drawio-diagram');
510 DrawIO.show(drawioUrl, () => {
511 return DrawIO.load(drawingId);
516 uploaded_to: Number(this.pageId),
519 window.$http.post("/images/drawio", data).then(resp => {
520 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
521 let newContent = this.cm.getValue().split('\n').map(line => {
522 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
527 this.cm.setValue(newContent);
528 this.cm.setCursor(cursorPos);
532 this.handleDrawingUploadError(err);
537 handleDrawingUploadError(error) {
538 if (error.status === 413) {
539 window.$events.emit('error', this.serverUploadLimitText);
541 window.$events.emit('error', this.imageUploadErrorText);
546 // Make the editor full screen
548 const alreadyFullscreen = this.elem.classList.contains('fullscreen');
549 this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
550 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
553 // Scroll to a specified text
554 scrollToText(searchText) {
559 const content = this.cm.getValue();
560 const lines = content.split(/\r?\n/);
561 let lineNumber = lines.findIndex(line => {
562 return line && line.indexOf(searchText) !== -1;
565 if (lineNumber === -1) {
569 this.cm.scrollIntoView({
573 // set the cursor location.
576 char: lines[lineNumber].length
580 listenForBookStackEditorEvents() {
582 function getContentToInsert({html, markdown}) {
583 return markdown || html;
586 // Replace editor content
587 window.$events.listen('editor::replace', (eventContent) => {
588 const markdown = getContentToInsert(eventContent);
589 this.cm.setValue(markdown);
592 // Append editor content
593 window.$events.listen('editor::append', (eventContent) => {
594 const cursorPos = this.cm.getCursor('from');
595 const markdown = getContentToInsert(eventContent);
596 const content = this.cm.getValue() + '\n' + markdown;
597 this.cm.setValue(content);
598 this.cm.setCursor(cursorPos.line, cursorPos.ch);
601 // Prepend editor content
602 window.$events.listen('editor::prepend', (eventContent) => {
603 const cursorPos = this.cm.getCursor('from');
604 const markdown = getContentToInsert(eventContent);
605 const content = markdown + '\n' + this.cm.getValue();
606 this.cm.setValue(content);
607 const prependLineCount = markdown.split('\n').length;
608 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
611 // Insert editor content at the current location
612 window.$events.listen('editor::insert', (eventContent) => {
613 const markdown = getContentToInsert(eventContent);
614 this.cm.replaceSelection(markdown);
618 window.$events.listen('editor::focus', () => {