1 import MarkdownIt from "markdown-it";
2 import mdTasksLists from 'markdown-it-task-lists';
3 import code from '../services/code';
4 import Clipboard from "../services/clipboard";
5 import {debounce} from "../services/util";
7 import DrawIO from "../services/drawio";
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');
26 this.cm = code.markdownEditor(this.input);
28 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
30 const displayLoad = () => {
31 this.displayDoc = this.display.contentDocument;
35 if (this.display.contentDocument.readyState === 'complete') {
38 this.display.addEventListener('load', displayLoad.bind(this));
41 window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
42 markdownIt: this.markdown,
43 displayEl: this.display,
44 codeMirrorInstance: this.cm,
52 // Prevent markdown display link click redirect
53 this.displayDoc.addEventListener('click', event => {
54 let isDblClick = Date.now() - lastClick < 300;
56 let link = event.target.closest('a');
58 event.preventDefault();
59 window.open(link.getAttribute('href'));
63 let drawing = event.target.closest('[drawio-diagram]');
64 if (drawing !== null && isDblClick) {
65 this.actionEditDrawing(drawing);
69 lastClick = Date.now();
73 this.elem.addEventListener('click', event => {
74 let button = event.target.closest('button[data-action]');
75 if (button === null) return;
77 let action = button.getAttribute('data-action');
78 if (action === 'insertImage') this.actionInsertImage();
79 if (action === 'insertLink') this.actionShowLinkSelector();
80 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
81 this.actionShowImageManager();
84 if (action === 'insertDrawing') this.actionStartDrawing();
85 if (action === 'fullscreen') this.actionFullScreen();
88 // Mobile section toggling
89 this.elem.addEventListener('click', event => {
90 const toolbarLabel = event.target.closest('.editor-toolbar-label');
91 if (!toolbarLabel) return;
93 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
94 for (let activeElem of currentActiveSections) {
95 activeElem.classList.remove('active');
98 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
101 window.$events.listen('editor-markdown-update', value => {
102 this.cm.setValue(value);
103 this.updateAndRender();
106 this.codeMirrorSetup();
107 this.listenForBookStackEditorEvents();
109 // Scroll to text if needed.
110 const queryParams = (new URL(window.location)).searchParams;
111 const scrollText = queryParams.get('content-text');
113 this.scrollToText(scrollText);
117 // Update the input content and render the display.
119 const content = this.cm.getValue();
120 this.input.value = content;
121 const html = this.markdown.render(content);
122 window.$events.emit('editor-html-change', html);
123 window.$events.emit('editor-markdown-change', content);
126 this.displayDoc.body.className = 'page-content';
127 this.displayDoc.body.innerHTML = html;
129 // Copy styles from page head and set custom styles for editor
130 this.loadStylesIntoDisplay();
133 loadStylesIntoDisplay() {
134 if (this.displayStylesLoaded) return;
135 this.displayDoc.documentElement.classList.add('markdown-editor-display');
136 // Set display to be dark mode if parent is
138 if (document.documentElement.classList.contains('dark-mode')) {
139 this.displayDoc.documentElement.style.backgroundColor = '#222';
140 this.displayDoc.documentElement.classList.add('dark-mode');
143 this.displayDoc.head.innerHTML = '';
144 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
145 for (let style of styles) {
146 const copy = style.cloneNode(true);
147 this.displayDoc.head.appendChild(copy);
150 this.displayStylesLoaded = true;
153 onMarkdownScroll(lineCount) {
154 const elems = this.displayDoc.body.children;
155 if (elems.length <= lineCount) return;
157 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
158 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
163 const context = this;
166 // cm.setOption('direction', this.textDirection);
167 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
168 // Custom key commands
169 let metaKey = code.getMetaKey();
170 const extraKeys = {};
171 // Insert Image shortcut
172 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
173 let selectedText = cm.getSelection();
174 let newText = ``;
175 let cursorPos = cm.getCursor('from');
176 cm.replaceSelection(newText);
177 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
180 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
182 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
183 // Show link selector
184 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
186 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
188 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
189 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
190 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
191 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
192 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
193 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
194 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
195 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
196 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
197 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
198 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
199 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
200 cm.setOption('extraKeys', extraKeys);
202 // Update data on content change
203 cm.on('change', (instance, changeObj) => {
204 this.updateAndRender();
207 const onScrollDebounced = debounce((instance) => {
208 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
209 let scroll = instance.getScrollInfo();
210 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
212 this.onMarkdownScroll(-1);
216 let lineNum = instance.lineAtHeight(scroll.top, 'local');
217 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
218 let parser = new DOMParser();
219 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
220 let totalLines = doc.documentElement.querySelectorAll('body > *');
221 this.onMarkdownScroll(totalLines.length);
224 // Handle scroll to sync display view
225 cm.on('scroll', instance => {
226 onScrollDebounced(instance);
229 // Handle image paste
230 cm.on('paste', (cm, event) => {
231 const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
233 // Don't handle the event ourselves if no items exist of contains table-looking data
234 if (!clipboard.hasItems() || clipboard.containsTabularData()) {
238 const images = clipboard.getImages();
239 for (const image of images) {
244 // Handle image & content drag n drop
245 cm.on('drop', (cm, event) => {
247 const templateId = event.dataTransfer.getData('bookstack/template');
249 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
250 cm.setCursor(cursorPos);
251 event.preventDefault();
252 window.$http.get(`/templates/${templateId}`).then(resp => {
253 const content = resp.data.markdown || resp.data.html;
254 cm.replaceSelection(content);
258 const clipboard = new Clipboard(event.dataTransfer);
259 if (clipboard.hasItems() && clipboard.getImages().length > 0) {
260 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
261 cm.setCursor(cursorPos);
262 event.stopPropagation();
263 event.preventDefault();
264 const images = clipboard.getImages();
265 for (const image of images) {
272 // Helper to replace editor content
273 function replaceContent(search, replace) {
274 let text = cm.getValue();
275 let cursor = cm.listSelections();
276 cm.setValue(text.replace(search, replace));
277 cm.setSelections(cursor);
280 // Helper to replace the start of the line
281 function replaceLineStart(newStart) {
282 let cursor = cm.getCursor();
283 let lineContent = cm.getLine(cursor.line);
284 let lineLen = lineContent.length;
285 let lineStart = lineContent.split(' ')[0];
287 // Remove symbol if already set
288 if (lineStart === newStart) {
289 lineContent = lineContent.replace(`${newStart} `, '');
290 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
291 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
295 let alreadySymbol = /^[#>`]/.test(lineStart);
298 posDif = newStart.length - lineStart.length;
299 lineContent = lineContent.replace(lineStart, newStart).trim();
300 } else if (newStart !== '') {
301 posDif = newStart.length + 1;
302 lineContent = newStart + ' ' + lineContent;
304 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
305 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
308 function wrapLine(start, end) {
309 let cursor = cm.getCursor();
310 let lineContent = cm.getLine(cursor.line);
311 let lineLen = lineContent.length;
312 let newLineContent = lineContent;
314 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
315 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
317 newLineContent = `${start}${lineContent}${end}`;
320 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
321 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
324 function wrapSelection(start, end) {
325 let selection = cm.getSelection();
326 if (selection === '') return wrapLine(start, end);
328 let newSelection = selection;
332 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
333 newSelection = selection.slice(start.length, selection.length - end.length);
334 endDiff = -(end.length + start.length);
336 newSelection = `${start}${selection}${end}`;
337 endDiff = start.length + end.length;
340 let selections = cm.listSelections()[0];
341 cm.replaceSelection(newSelection);
342 let headFirst = selections.head.ch <= selections.anchor.ch;
343 selections.head.ch += headFirst ? frontDiff : endDiff;
344 selections.anchor.ch += headFirst ? endDiff : frontDiff;
345 cm.setSelections([selections]);
348 // Handle image upload and add image into markdown content
349 function uploadImage(file) {
350 if (file === null || file.type.indexOf('image') !== 0) return;
354 let fileNameMatches = file.name.match(/\.(.+)$/);
355 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
358 // Insert image into markdown
359 const id = "image-" + Math.random().toString(16).slice(2);
360 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
361 const selectedText = cm.getSelection();
362 const placeHolderText = ``;
363 const cursor = cm.getCursor();
364 cm.replaceSelection(placeHolderText);
365 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
367 const remoteFilename = "image-" + Date.now() + "." + ext;
368 const formData = new FormData();
369 formData.append('file', file, remoteFilename);
370 formData.append('uploaded_to', context.pageId);
372 window.$http.post('/images/gallery', formData).then(resp => {
373 const newContent = `[](${resp.data.url})`;
374 replaceContent(placeHolderText, newContent);
376 window.$events.emit('error', context.imageUploadErrorText);
377 replaceContent(placeHolderText, selectedText);
382 function insertLink() {
383 let cursorPos = cm.getCursor('from');
384 let selectedText = cm.getSelection() || '';
385 let newText = `[${selectedText}]()`;
387 cm.replaceSelection(newText);
388 let cursorPosDiff = (selectedText === '') ? -3 : -1;
389 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
392 this.updateAndRender();
395 actionInsertImage() {
396 const cursorPos = this.cm.getCursor('from');
397 window.ImageManager.show(image => {
398 const imageUrl = image.thumbs.display || image.url;
399 let selectedText = this.cm.getSelection();
400 let newText = "[](" + image.url + ")";
402 this.cm.replaceSelection(newText);
403 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
407 actionShowImageManager() {
408 const cursorPos = this.cm.getCursor('from');
409 window.ImageManager.show(image => {
410 this.insertDrawing(image, cursorPos);
414 // Show the popup link selector and insert a link when finished
415 actionShowLinkSelector() {
416 const cursorPos = this.cm.getCursor('from');
417 window.EntitySelectorPopup.show(entity => {
418 let selectedText = this.cm.getSelection() || entity.name;
419 let newText = `[${selectedText}](${entity.link})`;
421 this.cm.replaceSelection(newText);
422 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
427 const drawioUrlElem = document.querySelector('[drawio-url]');
428 return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
431 // Show draw.io if enabled and handle save.
432 actionStartDrawing() {
433 const url = this.getDrawioUrl();
436 const cursorPos = this.cm.getCursor('from');
438 DrawIO.show(url,() => {
439 return Promise.resolve('');
444 uploaded_to: Number(this.pageId),
447 window.$http.post("/images/drawio", data).then(resp => {
448 this.insertDrawing(resp.data, cursorPos);
451 this.handleDrawingUploadError(err);
456 insertDrawing(image, originalCursor) {
457 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
459 this.cm.replaceSelection(newText);
460 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
463 // Show draw.io if enabled and handle save.
464 actionEditDrawing(imgContainer) {
465 const drawioUrl = this.getDrawioUrl();
470 const cursorPos = this.cm.getCursor('from');
471 const drawingId = imgContainer.getAttribute('drawio-diagram');
473 DrawIO.show(drawioUrl, () => {
474 return DrawIO.load(drawingId);
479 uploaded_to: Number(this.pageId),
482 window.$http.post("/images/drawio", data).then(resp => {
483 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
484 let newContent = this.cm.getValue().split('\n').map(line => {
485 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
490 this.cm.setValue(newContent);
491 this.cm.setCursor(cursorPos);
495 this.handleDrawingUploadError(err);
500 handleDrawingUploadError(error) {
501 if (error.status === 413) {
502 window.$events.emit('error', this.serverUploadLimitText);
504 window.$events.emit('error', this.imageUploadErrorText);
509 // Make the editor full screen
511 const alreadyFullscreen = this.elem.classList.contains('fullscreen');
512 this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
513 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
516 // Scroll to a specified text
517 scrollToText(searchText) {
522 const content = this.cm.getValue();
523 const lines = content.split(/\r?\n/);
524 let lineNumber = lines.findIndex(line => {
525 return line && line.indexOf(searchText) !== -1;
528 if (lineNumber === -1) {
532 this.cm.scrollIntoView({
536 // set the cursor location.
539 char: lines[lineNumber].length
543 listenForBookStackEditorEvents() {
545 function getContentToInsert({html, markdown}) {
546 return markdown || html;
549 // Replace editor content
550 window.$events.listen('editor::replace', (eventContent) => {
551 const markdown = getContentToInsert(eventContent);
552 this.cm.setValue(markdown);
555 // Append editor content
556 window.$events.listen('editor::append', (eventContent) => {
557 const cursorPos = this.cm.getCursor('from');
558 const markdown = getContentToInsert(eventContent);
559 const content = this.cm.getValue() + '\n' + markdown;
560 this.cm.setValue(content);
561 this.cm.setCursor(cursorPos.line, cursorPos.ch);
564 // Prepend editor content
565 window.$events.listen('editor::prepend', (eventContent) => {
566 const cursorPos = this.cm.getCursor('from');
567 const markdown = getContentToInsert(eventContent);
568 const content = markdown + '\n' + this.cm.getValue();
569 this.cm.setValue(content);
570 const prependLineCount = markdown.split('\n').length;
571 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
574 // Insert editor content at the current location
575 window.$events.listen('editor::insert', (eventContent) => {
576 const markdown = getContentToInsert(eventContent);
577 this.cm.replaceSelection(markdown);
581 window.$events.listen('editor::focus', () => {
587 export default MarkdownEditor ;