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";
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;
130 const html = this.markdown.render(content);
131 window.$events.emit('editor-html-change', html);
132 window.$events.emit('editor-markdown-change', content);
135 this.displayDoc.body.className = 'page-content';
136 this.displayDoc.body.innerHTML = html;
138 // Copy styles from page head and set custom styles for editor
139 this.loadStylesIntoDisplay();
142 loadStylesIntoDisplay() {
143 if (this.displayStylesLoaded) return;
144 this.displayDoc.documentElement.classList.add('markdown-editor-display');
145 // Set display to be dark mode if parent is
147 if (document.documentElement.classList.contains('dark-mode')) {
148 this.displayDoc.documentElement.style.backgroundColor = '#222';
149 this.displayDoc.documentElement.classList.add('dark-mode');
152 this.displayDoc.head.innerHTML = '';
153 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
154 for (let style of styles) {
155 const copy = style.cloneNode(true);
156 this.displayDoc.head.appendChild(copy);
159 this.displayStylesLoaded = true;
162 onMarkdownScroll(lineCount) {
163 const elems = this.displayDoc.body.children;
164 if (elems.length <= lineCount) return;
166 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
167 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
170 codeMirrorSetup(cm) {
171 const context = this;
174 // cm.setOption('direction', this.textDirection);
175 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
176 // Custom key commands
177 let metaKey = this.Code.getMetaKey();
178 const extraKeys = {};
179 // Insert Image shortcut
180 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
181 let selectedText = cm.getSelection();
182 let newText = ``;
183 let cursorPos = cm.getCursor('from');
184 cm.replaceSelection(newText);
185 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
188 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
190 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
191 // Show link selector
192 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
194 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
196 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
197 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
198 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
199 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
200 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
201 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
202 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
203 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
204 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
205 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
206 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
207 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
208 cm.setOption('extraKeys', extraKeys);
210 // Update data on content change
211 cm.on('change', (instance, changeObj) => {
212 this.updateAndRender();
215 const onScrollDebounced = debounce((instance) => {
216 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
217 let scroll = instance.getScrollInfo();
218 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
220 this.onMarkdownScroll(-1);
224 let lineNum = instance.lineAtHeight(scroll.top, 'local');
225 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
226 let parser = new DOMParser();
227 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
228 let totalLines = doc.documentElement.querySelectorAll('body > *');
229 this.onMarkdownScroll(totalLines.length);
232 // Handle scroll to sync display view
233 cm.on('scroll', instance => {
234 onScrollDebounced(instance);
237 // Handle image paste
238 cm.on('paste', (cm, event) => {
239 const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
241 // Don't handle the event ourselves if no items exist of contains table-looking data
242 if (!clipboard.hasItems() || clipboard.containsTabularData()) {
246 const images = clipboard.getImages();
247 for (const image of images) {
252 // Handle image & content drag n drop
253 cm.on('drop', (cm, event) => {
255 const templateId = event.dataTransfer.getData('bookstack/template');
257 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
258 cm.setCursor(cursorPos);
259 event.preventDefault();
260 window.$http.get(`/templates/${templateId}`).then(resp => {
261 const content = resp.data.markdown || resp.data.html;
262 cm.replaceSelection(content);
266 const clipboard = new Clipboard(event.dataTransfer);
267 if (clipboard.hasItems() && clipboard.getImages().length > 0) {
268 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
269 cm.setCursor(cursorPos);
270 event.stopPropagation();
271 event.preventDefault();
272 const images = clipboard.getImages();
273 for (const image of images) {
280 // Helper to replace editor content
281 function replaceContent(search, replace) {
282 let text = cm.getValue();
283 let cursor = cm.listSelections();
284 cm.setValue(text.replace(search, replace));
285 cm.setSelections(cursor);
288 // Helper to replace the start of the line
289 function replaceLineStart(newStart) {
290 let cursor = cm.getCursor();
291 let lineContent = cm.getLine(cursor.line);
292 let lineLen = lineContent.length;
293 let lineStart = lineContent.split(' ')[0];
295 // Remove symbol if already set
296 if (lineStart === newStart) {
297 lineContent = lineContent.replace(`${newStart} `, '');
298 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
299 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
303 let alreadySymbol = /^[#>`]/.test(lineStart);
306 posDif = newStart.length - lineStart.length;
307 lineContent = lineContent.replace(lineStart, newStart).trim();
308 } else if (newStart !== '') {
309 posDif = newStart.length + 1;
310 lineContent = newStart + ' ' + lineContent;
312 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
313 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
316 function wrapLine(start, end) {
317 let cursor = cm.getCursor();
318 let lineContent = cm.getLine(cursor.line);
319 let lineLen = lineContent.length;
320 let newLineContent = lineContent;
322 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
323 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
325 newLineContent = `${start}${lineContent}${end}`;
328 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
329 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
332 function wrapSelection(start, end) {
333 let selection = cm.getSelection();
334 if (selection === '') return wrapLine(start, end);
336 let newSelection = selection;
340 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
341 newSelection = selection.slice(start.length, selection.length - end.length);
342 endDiff = -(end.length + start.length);
344 newSelection = `${start}${selection}${end}`;
345 endDiff = start.length + end.length;
348 let selections = cm.listSelections()[0];
349 cm.replaceSelection(newSelection);
350 let headFirst = selections.head.ch <= selections.anchor.ch;
351 selections.head.ch += headFirst ? frontDiff : endDiff;
352 selections.anchor.ch += headFirst ? endDiff : frontDiff;
353 cm.setSelections([selections]);
356 // Handle image upload and add image into markdown content
357 function uploadImage(file) {
358 if (file === null || file.type.indexOf('image') !== 0) return;
362 let fileNameMatches = file.name.match(/\.(.+)$/);
363 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
366 // Insert image into markdown
367 const id = "image-" + Math.random().toString(16).slice(2);
368 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
369 const selectedText = cm.getSelection();
370 const placeHolderText = ``;
371 const cursor = cm.getCursor();
372 cm.replaceSelection(placeHolderText);
373 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
375 const remoteFilename = "image-" + Date.now() + "." + ext;
376 const formData = new FormData();
377 formData.append('file', file, remoteFilename);
378 formData.append('uploaded_to', context.pageId);
380 window.$http.post('/images/gallery', formData).then(resp => {
381 const newContent = `[](${resp.data.url})`;
382 replaceContent(placeHolderText, newContent);
384 window.$events.emit('error', context.imageUploadErrorText);
385 replaceContent(placeHolderText, selectedText);
390 function insertLink() {
391 let cursorPos = cm.getCursor('from');
392 let selectedText = cm.getSelection() || '';
393 let newText = `[${selectedText}]()`;
395 cm.replaceSelection(newText);
396 let cursorPosDiff = (selectedText === '') ? -3 : -1;
397 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
400 this.updateAndRender();
403 actionInsertImage() {
404 const cursorPos = this.cm.getCursor('from');
405 window.ImageManager.show(image => {
406 const imageUrl = image.thumbs.display || image.url;
407 let selectedText = this.cm.getSelection();
408 let newText = "[](" + image.url + ")";
410 this.cm.replaceSelection(newText);
411 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
415 actionShowImageManager() {
416 const cursorPos = this.cm.getCursor('from');
417 window.ImageManager.show(image => {
418 this.insertDrawing(image, cursorPos);
422 // Show the popup link selector and insert a link when finished
423 actionShowLinkSelector() {
424 const cursorPos = this.cm.getCursor('from');
425 window.EntitySelectorPopup.show(entity => {
426 let selectedText = this.cm.getSelection() || entity.name;
427 let newText = `[${selectedText}](${entity.link})`;
429 this.cm.replaceSelection(newText);
430 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
435 const drawioUrlElem = document.querySelector('[drawio-url]');
436 return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
439 // Show draw.io if enabled and handle save.
440 actionStartDrawing() {
441 const url = this.getDrawioUrl();
444 const cursorPos = this.cm.getCursor('from');
446 DrawIO.show(url,() => {
447 return Promise.resolve('');
452 uploaded_to: Number(this.pageId),
455 window.$http.post("/images/drawio", data).then(resp => {
456 this.insertDrawing(resp.data, cursorPos);
459 this.handleDrawingUploadError(err);
464 insertDrawing(image, originalCursor) {
465 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
467 this.cm.replaceSelection(newText);
468 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
471 // Show draw.io if enabled and handle save.
472 actionEditDrawing(imgContainer) {
473 const drawioUrl = this.getDrawioUrl();
478 const cursorPos = this.cm.getCursor('from');
479 const drawingId = imgContainer.getAttribute('drawio-diagram');
481 DrawIO.show(drawioUrl, () => {
482 return DrawIO.load(drawingId);
487 uploaded_to: Number(this.pageId),
490 window.$http.post("/images/drawio", data).then(resp => {
491 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
492 let newContent = this.cm.getValue().split('\n').map(line => {
493 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
498 this.cm.setValue(newContent);
499 this.cm.setCursor(cursorPos);
503 this.handleDrawingUploadError(err);
508 handleDrawingUploadError(error) {
509 if (error.status === 413) {
510 window.$events.emit('error', this.serverUploadLimitText);
512 window.$events.emit('error', this.imageUploadErrorText);
517 // Make the editor full screen
519 const alreadyFullscreen = this.elem.classList.contains('fullscreen');
520 this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
521 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
524 // Scroll to a specified text
525 scrollToText(searchText) {
530 const content = this.cm.getValue();
531 const lines = content.split(/\r?\n/);
532 let lineNumber = lines.findIndex(line => {
533 return line && line.indexOf(searchText) !== -1;
536 if (lineNumber === -1) {
540 this.cm.scrollIntoView({
544 // set the cursor location.
547 char: lines[lineNumber].length
551 listenForBookStackEditorEvents() {
553 function getContentToInsert({html, markdown}) {
554 return markdown || html;
557 // Replace editor content
558 window.$events.listen('editor::replace', (eventContent) => {
559 const markdown = getContentToInsert(eventContent);
560 this.cm.setValue(markdown);
563 // Append editor content
564 window.$events.listen('editor::append', (eventContent) => {
565 const cursorPos = this.cm.getCursor('from');
566 const markdown = getContentToInsert(eventContent);
567 const content = this.cm.getValue() + '\n' + markdown;
568 this.cm.setValue(content);
569 this.cm.setCursor(cursorPos.line, cursorPos.ch);
572 // Prepend editor content
573 window.$events.listen('editor::prepend', (eventContent) => {
574 const cursorPos = this.cm.getCursor('from');
575 const markdown = getContentToInsert(eventContent);
576 const content = markdown + '\n' + this.cm.getValue();
577 this.cm.setValue(content);
578 const prependLineCount = markdown.split('\n').length;
579 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
582 // Insert editor content at the current location
583 window.$events.listen('editor::insert', (eventContent) => {
584 const markdown = getContentToInsert(eventContent);
585 this.cm.replaceSelection(markdown);
589 window.$events.listen('editor::focus', () => {
595 export default MarkdownEditor ;