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);
116 // Refresh CodeMirror on container resize
117 const resizeDebounced = debounce(() => code.updateLayout(this.cm), 100, false);
118 const observer = new ResizeObserver(resizeDebounced);
119 observer.observe(this.elem);
122 // Update the input content and render the display.
124 const content = this.cm.getValue();
125 this.input.value = content;
126 const html = this.markdown.render(content);
127 window.$events.emit('editor-html-change', html);
128 window.$events.emit('editor-markdown-change', content);
131 this.displayDoc.body.className = 'page-content';
132 this.displayDoc.body.innerHTML = html;
134 // Copy styles from page head and set custom styles for editor
135 this.loadStylesIntoDisplay();
138 loadStylesIntoDisplay() {
139 if (this.displayStylesLoaded) return;
140 this.displayDoc.documentElement.classList.add('markdown-editor-display');
141 // Set display to be dark mode if parent is
143 if (document.documentElement.classList.contains('dark-mode')) {
144 this.displayDoc.documentElement.style.backgroundColor = '#222';
145 this.displayDoc.documentElement.classList.add('dark-mode');
148 this.displayDoc.head.innerHTML = '';
149 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
150 for (let style of styles) {
151 const copy = style.cloneNode(true);
152 this.displayDoc.head.appendChild(copy);
155 this.displayStylesLoaded = true;
158 onMarkdownScroll(lineCount) {
159 const elems = this.displayDoc.body.children;
160 if (elems.length <= lineCount) return;
162 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
163 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
168 const context = this;
171 // cm.setOption('direction', this.textDirection);
172 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
173 // Custom key commands
174 let metaKey = code.getMetaKey();
175 const extraKeys = {};
176 // Insert Image shortcut
177 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
178 let selectedText = cm.getSelection();
179 let newText = ``;
180 let cursorPos = cm.getCursor('from');
181 cm.replaceSelection(newText);
182 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
185 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
187 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
188 // Show link selector
189 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
191 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
193 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
194 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
195 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
196 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
197 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
198 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
199 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
200 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
201 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
202 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
203 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
204 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
205 cm.setOption('extraKeys', extraKeys);
207 // Update data on content change
208 cm.on('change', (instance, changeObj) => {
209 this.updateAndRender();
212 const onScrollDebounced = debounce((instance) => {
213 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
214 let scroll = instance.getScrollInfo();
215 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
217 this.onMarkdownScroll(-1);
221 let lineNum = instance.lineAtHeight(scroll.top, 'local');
222 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
223 let parser = new DOMParser();
224 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
225 let totalLines = doc.documentElement.querySelectorAll('body > *');
226 this.onMarkdownScroll(totalLines.length);
229 // Handle scroll to sync display view
230 cm.on('scroll', instance => {
231 onScrollDebounced(instance);
234 // Handle image paste
235 cm.on('paste', (cm, event) => {
236 const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
238 // Don't handle the event ourselves if no items exist of contains table-looking data
239 if (!clipboard.hasItems() || clipboard.containsTabularData()) {
243 const images = clipboard.getImages();
244 for (const image of images) {
249 // Handle image & content drag n drop
250 cm.on('drop', (cm, event) => {
252 const templateId = event.dataTransfer.getData('bookstack/template');
254 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
255 cm.setCursor(cursorPos);
256 event.preventDefault();
257 window.$http.get(`/templates/${templateId}`).then(resp => {
258 const content = resp.data.markdown || resp.data.html;
259 cm.replaceSelection(content);
263 const clipboard = new Clipboard(event.dataTransfer);
264 if (clipboard.hasItems() && clipboard.getImages().length > 0) {
265 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
266 cm.setCursor(cursorPos);
267 event.stopPropagation();
268 event.preventDefault();
269 const images = clipboard.getImages();
270 for (const image of images) {
277 // Helper to replace editor content
278 function replaceContent(search, replace) {
279 let text = cm.getValue();
280 let cursor = cm.listSelections();
281 cm.setValue(text.replace(search, replace));
282 cm.setSelections(cursor);
285 // Helper to replace the start of the line
286 function replaceLineStart(newStart) {
287 let cursor = cm.getCursor();
288 let lineContent = cm.getLine(cursor.line);
289 let lineLen = lineContent.length;
290 let lineStart = lineContent.split(' ')[0];
292 // Remove symbol if already set
293 if (lineStart === newStart) {
294 lineContent = lineContent.replace(`${newStart} `, '');
295 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
296 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
300 let alreadySymbol = /^[#>`]/.test(lineStart);
303 posDif = newStart.length - lineStart.length;
304 lineContent = lineContent.replace(lineStart, newStart).trim();
305 } else if (newStart !== '') {
306 posDif = newStart.length + 1;
307 lineContent = newStart + ' ' + lineContent;
309 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
310 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
313 function wrapLine(start, end) {
314 let cursor = cm.getCursor();
315 let lineContent = cm.getLine(cursor.line);
316 let lineLen = lineContent.length;
317 let newLineContent = lineContent;
319 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
320 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
322 newLineContent = `${start}${lineContent}${end}`;
325 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
326 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
329 function wrapSelection(start, end) {
330 let selection = cm.getSelection();
331 if (selection === '') return wrapLine(start, end);
333 let newSelection = selection;
337 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
338 newSelection = selection.slice(start.length, selection.length - end.length);
339 endDiff = -(end.length + start.length);
341 newSelection = `${start}${selection}${end}`;
342 endDiff = start.length + end.length;
345 let selections = cm.listSelections()[0];
346 cm.replaceSelection(newSelection);
347 let headFirst = selections.head.ch <= selections.anchor.ch;
348 selections.head.ch += headFirst ? frontDiff : endDiff;
349 selections.anchor.ch += headFirst ? endDiff : frontDiff;
350 cm.setSelections([selections]);
353 // Handle image upload and add image into markdown content
354 function uploadImage(file) {
355 if (file === null || file.type.indexOf('image') !== 0) return;
359 let fileNameMatches = file.name.match(/\.(.+)$/);
360 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
363 // Insert image into markdown
364 const id = "image-" + Math.random().toString(16).slice(2);
365 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
366 const selectedText = cm.getSelection();
367 const placeHolderText = ``;
368 const cursor = cm.getCursor();
369 cm.replaceSelection(placeHolderText);
370 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
372 const remoteFilename = "image-" + Date.now() + "." + ext;
373 const formData = new FormData();
374 formData.append('file', file, remoteFilename);
375 formData.append('uploaded_to', context.pageId);
377 window.$http.post('/images/gallery', formData).then(resp => {
378 const newContent = `[](${resp.data.url})`;
379 replaceContent(placeHolderText, newContent);
381 window.$events.emit('error', context.imageUploadErrorText);
382 replaceContent(placeHolderText, selectedText);
387 function insertLink() {
388 let cursorPos = cm.getCursor('from');
389 let selectedText = cm.getSelection() || '';
390 let newText = `[${selectedText}]()`;
392 cm.replaceSelection(newText);
393 let cursorPosDiff = (selectedText === '') ? -3 : -1;
394 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
397 this.updateAndRender();
400 actionInsertImage() {
401 const cursorPos = this.cm.getCursor('from');
402 window.ImageManager.show(image => {
403 const imageUrl = image.thumbs.display || image.url;
404 let selectedText = this.cm.getSelection();
405 let newText = "[](" + image.url + ")";
407 this.cm.replaceSelection(newText);
408 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
412 actionShowImageManager() {
413 const cursorPos = this.cm.getCursor('from');
414 window.ImageManager.show(image => {
415 this.insertDrawing(image, cursorPos);
419 // Show the popup link selector and insert a link when finished
420 actionShowLinkSelector() {
421 const cursorPos = this.cm.getCursor('from');
422 window.EntitySelectorPopup.show(entity => {
423 let selectedText = this.cm.getSelection() || entity.name;
424 let newText = `[${selectedText}](${entity.link})`;
426 this.cm.replaceSelection(newText);
427 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
432 const drawioUrlElem = document.querySelector('[drawio-url]');
433 return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
436 // Show draw.io if enabled and handle save.
437 actionStartDrawing() {
438 const url = this.getDrawioUrl();
441 const cursorPos = this.cm.getCursor('from');
443 DrawIO.show(url,() => {
444 return Promise.resolve('');
449 uploaded_to: Number(this.pageId),
452 window.$http.post("/images/drawio", data).then(resp => {
453 this.insertDrawing(resp.data, cursorPos);
456 this.handleDrawingUploadError(err);
461 insertDrawing(image, originalCursor) {
462 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
464 this.cm.replaceSelection(newText);
465 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
468 // Show draw.io if enabled and handle save.
469 actionEditDrawing(imgContainer) {
470 const drawioUrl = this.getDrawioUrl();
475 const cursorPos = this.cm.getCursor('from');
476 const drawingId = imgContainer.getAttribute('drawio-diagram');
478 DrawIO.show(drawioUrl, () => {
479 return DrawIO.load(drawingId);
484 uploaded_to: Number(this.pageId),
487 window.$http.post("/images/drawio", data).then(resp => {
488 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
489 let newContent = this.cm.getValue().split('\n').map(line => {
490 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
495 this.cm.setValue(newContent);
496 this.cm.setCursor(cursorPos);
500 this.handleDrawingUploadError(err);
505 handleDrawingUploadError(error) {
506 if (error.status === 413) {
507 window.$events.emit('error', this.serverUploadLimitText);
509 window.$events.emit('error', this.imageUploadErrorText);
514 // Make the editor full screen
516 const alreadyFullscreen = this.elem.classList.contains('fullscreen');
517 this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
518 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
521 // Scroll to a specified text
522 scrollToText(searchText) {
527 const content = this.cm.getValue();
528 const lines = content.split(/\r?\n/);
529 let lineNumber = lines.findIndex(line => {
530 return line && line.indexOf(searchText) !== -1;
533 if (lineNumber === -1) {
537 this.cm.scrollIntoView({
541 // set the cursor location.
544 char: lines[lineNumber].length
548 listenForBookStackEditorEvents() {
550 function getContentToInsert({html, markdown}) {
551 return markdown || html;
554 // Replace editor content
555 window.$events.listen('editor::replace', (eventContent) => {
556 const markdown = getContentToInsert(eventContent);
557 this.cm.setValue(markdown);
560 // Append editor content
561 window.$events.listen('editor::append', (eventContent) => {
562 const cursorPos = this.cm.getCursor('from');
563 const markdown = getContentToInsert(eventContent);
564 const content = this.cm.getValue() + '\n' + markdown;
565 this.cm.setValue(content);
566 this.cm.setCursor(cursorPos.line, cursorPos.ch);
569 // Prepend editor content
570 window.$events.listen('editor::prepend', (eventContent) => {
571 const cursorPos = this.cm.getCursor('from');
572 const markdown = getContentToInsert(eventContent);
573 const content = markdown + '\n' + this.cm.getValue();
574 this.cm.setValue(content);
575 const prependLineCount = markdown.split('\n').length;
576 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
579 // Insert editor content at the current location
580 window.$events.listen('editor::insert', (eventContent) => {
581 const markdown = getContentToInsert(eventContent);
582 this.cm.replaceSelection(markdown);
586 window.$events.listen('editor::focus', () => {
592 export default MarkdownEditor ;