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";
13 this.pageId = this.$opts.pageId;
14 this.textDirection = this.$opts.textDirection;
15 this.imageUploadErrorText = this.$opts.imageUploadErrorText;
16 this.serverUploadLimitText = this.$opts.serverUploadLimitText;
18 this.markdown = new MarkdownIt({html: true});
19 this.markdown.use(mdTasksLists, {label: true});
21 this.display = this.elem.querySelector('.markdown-display');
23 this.displayStylesLoaded = false;
24 this.input = this.elem.querySelector('textarea');
28 const cmLoadPromise = window.importVersioned('code').then(Code => {
29 this.cm = Code.markdownEditor(this.input);
34 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
36 const displayLoad = () => {
37 this.displayDoc = this.display.contentDocument;
38 this.init(cmLoadPromise);
41 if (this.display.contentDocument.readyState === 'complete') {
44 this.display.addEventListener('load', displayLoad.bind(this));
47 window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
48 markdownIt: this.markdown,
49 displayEl: this.display,
50 codeMirrorInstance: this.cm,
58 // Prevent markdown display link click redirect
59 this.displayDoc.addEventListener('click', event => {
60 let isDblClick = Date.now() - lastClick < 300;
62 let link = event.target.closest('a');
64 event.preventDefault();
65 window.open(link.getAttribute('href'));
69 let drawing = event.target.closest('[drawio-diagram]');
70 if (drawing !== null && isDblClick) {
71 this.actionEditDrawing(drawing);
75 lastClick = Date.now();
79 this.elem.addEventListener('click', event => {
80 let button = event.target.closest('button[data-action]');
81 if (button === null) return;
83 let action = button.getAttribute('data-action');
84 if (action === 'insertImage') this.actionInsertImage();
85 if (action === 'insertLink') this.actionShowLinkSelector();
86 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
87 this.actionShowImageManager();
90 if (action === 'insertDrawing') this.actionStartDrawing();
91 if (action === 'fullscreen') this.actionFullScreen();
94 // Mobile section toggling
95 this.elem.addEventListener('click', event => {
96 const toolbarLabel = event.target.closest('.editor-toolbar-label');
97 if (!toolbarLabel) return;
99 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
100 for (let activeElem of currentActiveSections) {
101 activeElem.classList.remove('active');
104 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
107 cmLoadPromise.then(cm => {
108 this.codeMirrorSetup(cm);
110 // Refresh CodeMirror on container resize
111 const resizeDebounced = debounce(() => this.Code.updateLayout(cm), 100, false);
112 const observer = new ResizeObserver(resizeDebounced);
113 observer.observe(this.elem);
116 this.listenForBookStackEditorEvents();
118 // Scroll to text if needed.
119 const queryParams = (new URL(window.location)).searchParams;
120 const scrollText = queryParams.get('content-text');
122 this.scrollToText(scrollText);
126 // Update the input content and render the display.
128 const content = this.cm.getValue();
129 this.input.value = content;
131 const html = this.markdown.render(content);
132 window.$events.emit('editor-html-change', html);
133 window.$events.emit('editor-markdown-change', content);
136 const target = this.getDisplayTarget();
137 this.displayDoc.body.className = 'page-content';
138 patchDomFromHtmlString(target, html);
140 // Copy styles from page head and set custom styles for editor
141 this.loadStylesIntoDisplay();
145 const body = this.displayDoc.body;
147 if (body.children.length === 0) {
148 const wrap = document.createElement('div');
149 this.displayDoc.body.append(wrap);
152 return body.children[0];
155 loadStylesIntoDisplay() {
156 if (this.displayStylesLoaded) return;
157 this.displayDoc.documentElement.classList.add('markdown-editor-display');
158 // Set display to be dark mode if parent is
160 if (document.documentElement.classList.contains('dark-mode')) {
161 this.displayDoc.documentElement.style.backgroundColor = '#222';
162 this.displayDoc.documentElement.classList.add('dark-mode');
165 this.displayDoc.head.innerHTML = '';
166 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
167 for (let style of styles) {
168 const copy = style.cloneNode(true);
169 this.displayDoc.head.appendChild(copy);
172 this.displayStylesLoaded = true;
175 onMarkdownScroll(lineCount) {
176 const elems = this.displayDoc.body.children;
177 if (elems.length <= lineCount) return;
179 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
180 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
183 codeMirrorSetup(cm) {
184 const context = this;
187 // cm.setOption('direction', this.textDirection);
188 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
189 // Custom key commands
190 let metaKey = this.Code.getMetaKey();
191 const extraKeys = {};
192 // Insert Image shortcut
193 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
194 let selectedText = cm.getSelection();
195 let newText = ``;
196 let cursorPos = cm.getCursor('from');
197 cm.replaceSelection(newText);
198 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
201 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
203 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
204 // Show link selector
205 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
207 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
209 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
210 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
211 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
212 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
213 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
214 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
215 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
216 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
217 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
218 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
219 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
220 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
221 cm.setOption('extraKeys', extraKeys);
223 // Update data on content change
224 cm.on('change', (instance, changeObj) => {
225 this.updateAndRender();
228 const onScrollDebounced = debounce((instance) => {
229 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
230 let scroll = instance.getScrollInfo();
231 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
233 this.onMarkdownScroll(-1);
237 let lineNum = instance.lineAtHeight(scroll.top, 'local');
238 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
239 let parser = new DOMParser();
240 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
241 let totalLines = doc.documentElement.querySelectorAll('body > *');
242 this.onMarkdownScroll(totalLines.length);
245 // Handle scroll to sync display view
246 cm.on('scroll', instance => {
247 onScrollDebounced(instance);
250 // Handle image paste
251 cm.on('paste', (cm, event) => {
252 const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
254 // Don't handle the event ourselves if no items exist of contains table-looking data
255 if (!clipboard.hasItems() || clipboard.containsTabularData()) {
259 const images = clipboard.getImages();
260 for (const image of images) {
265 // Handle image & content drag n drop
266 cm.on('drop', (cm, event) => {
268 const templateId = event.dataTransfer.getData('bookstack/template');
270 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
271 cm.setCursor(cursorPos);
272 event.preventDefault();
273 window.$http.get(`/templates/${templateId}`).then(resp => {
274 const content = resp.data.markdown || resp.data.html;
275 cm.replaceSelection(content);
279 const clipboard = new Clipboard(event.dataTransfer);
280 if (clipboard.hasItems() && clipboard.getImages().length > 0) {
281 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
282 cm.setCursor(cursorPos);
283 event.stopPropagation();
284 event.preventDefault();
285 const images = clipboard.getImages();
286 for (const image of images) {
293 // Helper to replace editor content
294 function replaceContent(search, replace) {
295 let text = cm.getValue();
296 let cursor = cm.listSelections();
297 cm.setValue(text.replace(search, replace));
298 cm.setSelections(cursor);
301 // Helper to replace the start of the line
302 function replaceLineStart(newStart) {
303 let cursor = cm.getCursor();
304 let lineContent = cm.getLine(cursor.line);
305 let lineLen = lineContent.length;
306 let lineStart = lineContent.split(' ')[0];
308 // Remove symbol if already set
309 if (lineStart === newStart) {
310 lineContent = lineContent.replace(`${newStart} `, '');
311 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
312 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
316 let alreadySymbol = /^[#>`]/.test(lineStart);
319 posDif = newStart.length - lineStart.length;
320 lineContent = lineContent.replace(lineStart, newStart).trim();
321 } else if (newStart !== '') {
322 posDif = newStart.length + 1;
323 lineContent = newStart + ' ' + lineContent;
325 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
326 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
329 function wrapLine(start, end) {
330 let cursor = cm.getCursor();
331 let lineContent = cm.getLine(cursor.line);
332 let lineLen = lineContent.length;
333 let newLineContent = lineContent;
335 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
336 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
338 newLineContent = `${start}${lineContent}${end}`;
341 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
342 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
345 function wrapSelection(start, end) {
346 let selection = cm.getSelection();
347 if (selection === '') return wrapLine(start, end);
349 let newSelection = selection;
353 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
354 newSelection = selection.slice(start.length, selection.length - end.length);
355 endDiff = -(end.length + start.length);
357 newSelection = `${start}${selection}${end}`;
358 endDiff = start.length + end.length;
361 let selections = cm.listSelections()[0];
362 cm.replaceSelection(newSelection);
363 let headFirst = selections.head.ch <= selections.anchor.ch;
364 selections.head.ch += headFirst ? frontDiff : endDiff;
365 selections.anchor.ch += headFirst ? endDiff : frontDiff;
366 cm.setSelections([selections]);
369 // Handle image upload and add image into markdown content
370 function uploadImage(file) {
371 if (file === null || file.type.indexOf('image') !== 0) return;
375 let fileNameMatches = file.name.match(/\.(.+)$/);
376 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
379 // Insert image into markdown
380 const id = "image-" + Math.random().toString(16).slice(2);
381 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
382 const selectedText = cm.getSelection();
383 const placeHolderText = ``;
384 const cursor = cm.getCursor();
385 cm.replaceSelection(placeHolderText);
386 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
388 const remoteFilename = "image-" + Date.now() + "." + ext;
389 const formData = new FormData();
390 formData.append('file', file, remoteFilename);
391 formData.append('uploaded_to', context.pageId);
393 window.$http.post('/images/gallery', formData).then(resp => {
394 const newContent = `[](${resp.data.url})`;
395 replaceContent(placeHolderText, newContent);
397 window.$events.emit('error', context.imageUploadErrorText);
398 replaceContent(placeHolderText, selectedText);
403 function insertLink() {
404 let cursorPos = cm.getCursor('from');
405 let selectedText = cm.getSelection() || '';
406 let newText = `[${selectedText}]()`;
408 cm.replaceSelection(newText);
409 let cursorPosDiff = (selectedText === '') ? -3 : -1;
410 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
413 this.updateAndRender();
416 actionInsertImage() {
417 const cursorPos = this.cm.getCursor('from');
418 window.ImageManager.show(image => {
419 const imageUrl = image.thumbs.display || image.url;
420 let selectedText = this.cm.getSelection();
421 let newText = "[](" + image.url + ")";
423 this.cm.replaceSelection(newText);
424 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
428 actionShowImageManager() {
429 const cursorPos = this.cm.getCursor('from');
430 window.ImageManager.show(image => {
431 this.insertDrawing(image, cursorPos);
435 // Show the popup link selector and insert a link when finished
436 actionShowLinkSelector() {
437 const cursorPos = this.cm.getCursor('from');
438 window.EntitySelectorPopup.show(entity => {
439 let selectedText = this.cm.getSelection() || entity.name;
440 let newText = `[${selectedText}](${entity.link})`;
442 this.cm.replaceSelection(newText);
443 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
448 const drawioUrlElem = document.querySelector('[drawio-url]');
449 return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
452 // Show draw.io if enabled and handle save.
453 actionStartDrawing() {
454 const url = this.getDrawioUrl();
457 const cursorPos = this.cm.getCursor('from');
459 DrawIO.show(url,() => {
460 return Promise.resolve('');
465 uploaded_to: Number(this.pageId),
468 window.$http.post("/images/drawio", data).then(resp => {
469 this.insertDrawing(resp.data, cursorPos);
472 this.handleDrawingUploadError(err);
477 insertDrawing(image, originalCursor) {
478 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
480 this.cm.replaceSelection(newText);
481 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
484 // Show draw.io if enabled and handle save.
485 actionEditDrawing(imgContainer) {
486 const drawioUrl = this.getDrawioUrl();
491 const cursorPos = this.cm.getCursor('from');
492 const drawingId = imgContainer.getAttribute('drawio-diagram');
494 DrawIO.show(drawioUrl, () => {
495 return DrawIO.load(drawingId);
500 uploaded_to: Number(this.pageId),
503 window.$http.post("/images/drawio", data).then(resp => {
504 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
505 let newContent = this.cm.getValue().split('\n').map(line => {
506 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
511 this.cm.setValue(newContent);
512 this.cm.setCursor(cursorPos);
516 this.handleDrawingUploadError(err);
521 handleDrawingUploadError(error) {
522 if (error.status === 413) {
523 window.$events.emit('error', this.serverUploadLimitText);
525 window.$events.emit('error', this.imageUploadErrorText);
530 // Make the editor full screen
532 const alreadyFullscreen = this.elem.classList.contains('fullscreen');
533 this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
534 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
537 // Scroll to a specified text
538 scrollToText(searchText) {
543 const content = this.cm.getValue();
544 const lines = content.split(/\r?\n/);
545 let lineNumber = lines.findIndex(line => {
546 return line && line.indexOf(searchText) !== -1;
549 if (lineNumber === -1) {
553 this.cm.scrollIntoView({
557 // set the cursor location.
560 char: lines[lineNumber].length
564 listenForBookStackEditorEvents() {
566 function getContentToInsert({html, markdown}) {
567 return markdown || html;
570 // Replace editor content
571 window.$events.listen('editor::replace', (eventContent) => {
572 const markdown = getContentToInsert(eventContent);
573 this.cm.setValue(markdown);
576 // Append editor content
577 window.$events.listen('editor::append', (eventContent) => {
578 const cursorPos = this.cm.getCursor('from');
579 const markdown = getContentToInsert(eventContent);
580 const content = this.cm.getValue() + '\n' + markdown;
581 this.cm.setValue(content);
582 this.cm.setCursor(cursorPos.line, cursorPos.ch);
585 // Prepend editor content
586 window.$events.listen('editor::prepend', (eventContent) => {
587 const cursorPos = this.cm.getCursor('from');
588 const markdown = getContentToInsert(eventContent);
589 const content = markdown + '\n' + this.cm.getValue();
590 this.cm.setValue(content);
591 const prependLineCount = markdown.split('\n').length;
592 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
595 // Insert editor content at the current location
596 window.$events.listen('editor::insert', (eventContent) => {
597 const markdown = getContentToInsert(eventContent);
598 this.cm.replaceSelection(markdown);
602 window.$events.listen('editor::focus', () => {
608 export default MarkdownEditor ;