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;
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');
25 this.cm = code.markdownEditor(this.input);
27 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
29 const displayLoad = () => {
30 this.displayDoc = this.display.contentDocument;
34 if (this.display.contentDocument.readyState === 'complete') {
37 this.display.addEventListener('load', displayLoad.bind(this));
40 window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
41 markdownIt: this.markdown,
42 displayEl: this.display,
43 codeMirrorInstance: this.cm,
51 // Prevent markdown display link click redirect
52 this.displayDoc.addEventListener('click', event => {
53 let isDblClick = Date.now() - lastClick < 300;
55 let link = event.target.closest('a');
57 event.preventDefault();
58 window.open(link.getAttribute('href'));
62 let drawing = event.target.closest('[drawio-diagram]');
63 if (drawing !== null && isDblClick) {
64 this.actionEditDrawing(drawing);
68 lastClick = Date.now();
72 this.elem.addEventListener('click', event => {
73 let button = event.target.closest('button[data-action]');
74 if (button === null) return;
76 let action = button.getAttribute('data-action');
77 if (action === 'insertImage') this.actionInsertImage();
78 if (action === 'insertLink') this.actionShowLinkSelector();
79 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
80 this.actionShowImageManager();
83 if (action === 'insertDrawing') this.actionStartDrawing();
84 if (action === 'fullscreen') this.actionFullScreen();
87 // Mobile section toggling
88 this.elem.addEventListener('click', event => {
89 const toolbarLabel = event.target.closest('.editor-toolbar-label');
90 if (!toolbarLabel) return;
92 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
93 for (let activeElem of currentActiveSections) {
94 activeElem.classList.remove('active');
97 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
100 window.$events.listen('editor-markdown-update', value => {
101 this.cm.setValue(value);
102 this.updateAndRender();
105 this.codeMirrorSetup();
106 this.listenForBookStackEditorEvents();
108 // Scroll to text if needed.
109 const queryParams = (new URL(window.location)).searchParams;
110 const scrollText = queryParams.get('content-text');
112 this.scrollToText(scrollText);
116 // Update the input content and render the display.
118 const content = this.cm.getValue();
119 this.input.value = content;
120 const html = this.markdown.render(content);
121 window.$events.emit('editor-html-change', html);
122 window.$events.emit('editor-markdown-change', content);
125 this.displayDoc.body.className = 'page-content';
126 this.displayDoc.body.innerHTML = html;
128 // Copy styles from page head and set custom styles for editor
129 this.loadStylesIntoDisplay();
132 loadStylesIntoDisplay() {
133 if (this.displayStylesLoaded) return;
134 this.displayDoc.documentElement.classList.add('markdown-editor-display');
135 // Set display to be dark mode if parent is
137 if (document.documentElement.classList.contains('dark-mode')) {
138 this.displayDoc.documentElement.style.backgroundColor = '#222';
139 this.displayDoc.documentElement.classList.add('dark-mode');
142 this.displayDoc.head.innerHTML = '';
143 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
144 for (let style of styles) {
145 const copy = style.cloneNode(true);
146 this.displayDoc.head.appendChild(copy);
149 this.displayStylesLoaded = true;
152 onMarkdownScroll(lineCount) {
153 const elems = this.displayDoc.body.children;
154 if (elems.length <= lineCount) return;
156 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
157 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
162 const context = this;
165 // cm.setOption('direction', this.textDirection);
166 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
167 // Custom key commands
168 let metaKey = code.getMetaKey();
169 const extraKeys = {};
170 // Insert Image shortcut
171 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
172 let selectedText = cm.getSelection();
173 let newText = ``;
174 let cursorPos = cm.getCursor('from');
175 cm.replaceSelection(newText);
176 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
179 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
181 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
182 // Show link selector
183 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
185 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
187 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
188 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
189 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
190 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
191 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
192 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
193 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
194 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
195 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
196 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
197 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
198 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
199 cm.setOption('extraKeys', extraKeys);
201 // Update data on content change
202 cm.on('change', (instance, changeObj) => {
203 this.updateAndRender();
206 const onScrollDebounced = debounce((instance) => {
207 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
208 let scroll = instance.getScrollInfo();
209 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
211 this.onMarkdownScroll(-1);
215 let lineNum = instance.lineAtHeight(scroll.top, 'local');
216 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
217 let parser = new DOMParser();
218 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
219 let totalLines = doc.documentElement.querySelectorAll('body > *');
220 this.onMarkdownScroll(totalLines.length);
223 // Handle scroll to sync display view
224 cm.on('scroll', instance => {
225 onScrollDebounced(instance);
228 // Handle image paste
229 cm.on('paste', (cm, event) => {
230 const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
232 // Don't handle the event ourselves if no items exist of contains table-looking data
233 if (!clipboard.hasItems() || clipboard.containsTabularData()) {
237 const images = clipboard.getImages();
238 for (const image of images) {
243 // Handle image & content drag n drop
244 cm.on('drop', (cm, event) => {
246 const templateId = event.dataTransfer.getData('bookstack/template');
248 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
249 cm.setCursor(cursorPos);
250 event.preventDefault();
251 window.$http.get(`/templates/${templateId}`).then(resp => {
252 const content = resp.data.markdown || resp.data.html;
253 cm.replaceSelection(content);
257 const clipboard = new Clipboard(event.dataTransfer);
258 if (clipboard.hasItems() && clipboard.getImages().length > 0) {
259 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
260 cm.setCursor(cursorPos);
261 event.stopPropagation();
262 event.preventDefault();
263 const images = clipboard.getImages();
264 for (const image of images) {
271 // Helper to replace editor content
272 function replaceContent(search, replace) {
273 let text = cm.getValue();
274 let cursor = cm.listSelections();
275 cm.setValue(text.replace(search, replace));
276 cm.setSelections(cursor);
279 // Helper to replace the start of the line
280 function replaceLineStart(newStart) {
281 let cursor = cm.getCursor();
282 let lineContent = cm.getLine(cursor.line);
283 let lineLen = lineContent.length;
284 let lineStart = lineContent.split(' ')[0];
286 // Remove symbol if already set
287 if (lineStart === newStart) {
288 lineContent = lineContent.replace(`${newStart} `, '');
289 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
290 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
294 let alreadySymbol = /^[#>`]/.test(lineStart);
297 posDif = newStart.length - lineStart.length;
298 lineContent = lineContent.replace(lineStart, newStart).trim();
299 } else if (newStart !== '') {
300 posDif = newStart.length + 1;
301 lineContent = newStart + ' ' + lineContent;
303 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
304 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
307 function wrapLine(start, end) {
308 let cursor = cm.getCursor();
309 let lineContent = cm.getLine(cursor.line);
310 let lineLen = lineContent.length;
311 let newLineContent = lineContent;
313 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
314 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
316 newLineContent = `${start}${lineContent}${end}`;
319 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
320 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
323 function wrapSelection(start, end) {
324 let selection = cm.getSelection();
325 if (selection === '') return wrapLine(start, end);
327 let newSelection = selection;
331 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
332 newSelection = selection.slice(start.length, selection.length - end.length);
333 endDiff = -(end.length + start.length);
335 newSelection = `${start}${selection}${end}`;
336 endDiff = start.length + end.length;
339 let selections = cm.listSelections()[0];
340 cm.replaceSelection(newSelection);
341 let headFirst = selections.head.ch <= selections.anchor.ch;
342 selections.head.ch += headFirst ? frontDiff : endDiff;
343 selections.anchor.ch += headFirst ? endDiff : frontDiff;
344 cm.setSelections([selections]);
347 // Handle image upload and add image into markdown content
348 function uploadImage(file) {
349 if (file === null || file.type.indexOf('image') !== 0) return;
353 let fileNameMatches = file.name.match(/\.(.+)$/);
354 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
357 // Insert image into markdown
358 const id = "image-" + Math.random().toString(16).slice(2);
359 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
360 const selectedText = cm.getSelection();
361 const placeHolderText = ``;
362 const cursor = cm.getCursor();
363 cm.replaceSelection(placeHolderText);
364 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
366 const remoteFilename = "image-" + Date.now() + "." + ext;
367 const formData = new FormData();
368 formData.append('file', file, remoteFilename);
369 formData.append('uploaded_to', context.pageId);
371 window.$http.post('/images/gallery', formData).then(resp => {
372 const newContent = `[](${resp.data.url})`;
373 replaceContent(placeHolderText, newContent);
375 window.$events.emit('error', context.imageUploadErrorText);
376 replaceContent(placeHolderText, selectedText);
381 function insertLink() {
382 let cursorPos = cm.getCursor('from');
383 let selectedText = cm.getSelection() || '';
384 let newText = `[${selectedText}]()`;
386 cm.replaceSelection(newText);
387 let cursorPosDiff = (selectedText === '') ? -3 : -1;
388 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
391 this.updateAndRender();
394 actionInsertImage() {
395 const cursorPos = this.cm.getCursor('from');
396 window.ImageManager.show(image => {
397 let selectedText = this.cm.getSelection();
398 let newText = "[](" + image.url + ")";
400 this.cm.replaceSelection(newText);
401 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
405 actionShowImageManager() {
406 const cursorPos = this.cm.getCursor('from');
407 window.ImageManager.show(image => {
408 this.insertDrawing(image, cursorPos);
412 // Show the popup link selector and insert a link when finished
413 actionShowLinkSelector() {
414 const cursorPos = this.cm.getCursor('from');
415 window.EntitySelectorPopup.show(entity => {
416 let selectedText = this.cm.getSelection() || entity.name;
417 let newText = `[${selectedText}](${entity.link})`;
419 this.cm.replaceSelection(newText);
420 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
425 const drawioUrlElem = document.querySelector('[drawio-url]');
426 return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
429 // Show draw.io if enabled and handle save.
430 actionStartDrawing() {
431 const url = this.getDrawioUrl();
434 const cursorPos = this.cm.getCursor('from');
436 DrawIO.show(url,() => {
437 return Promise.resolve('');
442 uploaded_to: Number(this.pageId),
445 window.$http.post("/images/drawio", data).then(resp => {
446 this.insertDrawing(resp.data, cursorPos);
449 window.$events.emit('error', trans('errors.image_upload_error'));
455 insertDrawing(image, originalCursor) {
456 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
458 this.cm.replaceSelection(newText);
459 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
462 // Show draw.io if enabled and handle save.
463 actionEditDrawing(imgContainer) {
464 const drawioUrl = this.getDrawioUrl();
469 const cursorPos = this.cm.getCursor('from');
470 const drawingId = imgContainer.getAttribute('drawio-diagram');
472 DrawIO.show(drawioUrl, () => {
473 return DrawIO.load(drawingId);
478 uploaded_to: Number(this.pageId),
481 window.$http.post("/images/drawio", data).then(resp => {
482 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
483 let newContent = this.cm.getValue().split('\n').map(line => {
484 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
489 this.cm.setValue(newContent);
490 this.cm.setCursor(cursorPos);
494 window.$events.emit('error', this.imageUploadErrorText);
500 // Make the editor full screen
502 const alreadyFullscreen = this.elem.classList.contains('fullscreen');
503 this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
504 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
507 // Scroll to a specified text
508 scrollToText(searchText) {
513 const content = this.cm.getValue();
514 const lines = content.split(/\r?\n/);
515 let lineNumber = lines.findIndex(line => {
516 return line && line.indexOf(searchText) !== -1;
519 if (lineNumber === -1) {
523 this.cm.scrollIntoView({
527 // set the cursor location.
530 char: lines[lineNumber].length
534 listenForBookStackEditorEvents() {
536 function getContentToInsert({html, markdown}) {
537 return markdown || html;
540 // Replace editor content
541 window.$events.listen('editor::replace', (eventContent) => {
542 const markdown = getContentToInsert(eventContent);
543 this.cm.setValue(markdown);
546 // Append editor content
547 window.$events.listen('editor::append', (eventContent) => {
548 const cursorPos = this.cm.getCursor('from');
549 const markdown = getContentToInsert(eventContent);
550 const content = this.cm.getValue() + '\n' + markdown;
551 this.cm.setValue(content);
552 this.cm.setCursor(cursorPos.line, cursorPos.ch);
555 // Prepend editor content
556 window.$events.listen('editor::prepend', (eventContent) => {
557 const cursorPos = this.cm.getCursor('from');
558 const markdown = getContentToInsert(eventContent);
559 const content = markdown + '\n' + this.cm.getValue();
560 this.cm.setValue(content);
561 const prependLineCount = markdown.split('\n').length;
562 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
565 // Insert editor content at the current location
566 window.$events.listen('editor::insert', (eventContent) => {
567 const markdown = getContentToInsert(eventContent);
568 this.cm.replaceSelection(markdown);
572 window.$events.listen('editor::focus', () => {
578 export default MarkdownEditor ;