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.$refs.display;
22 this.input = this.$refs.input;
26 const cmLoadPromise = window.importVersioned('code').then(Code => {
27 this.cm = Code.markdownEditor(this.input);
32 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
33 window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
34 markdownIt: this.markdown,
35 displayEl: this.display,
36 codeMirrorInstance: this.cm,
39 this.init(cmLoadPromise);
46 // Prevent markdown display link click redirect
47 this.display.addEventListener('click', event => {
48 const isDblClick = Date.now() - lastClick < 300;
50 const link = event.target.closest('a');
52 event.preventDefault();
53 window.open(link.getAttribute('href'));
57 const drawing = event.target.closest('[drawio-diagram]');
58 if (drawing !== null && isDblClick) {
59 this.actionEditDrawing(drawing);
63 lastClick = Date.now();
67 this.elem.addEventListener('click', event => {
68 const button = event.target.closest('button[data-action]');
69 if (button === null) return;
71 const action = button.getAttribute('data-action');
72 if (action === 'insertImage') this.actionInsertImage();
73 if (action === 'insertLink') this.actionShowLinkSelector();
74 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
75 this.actionShowImageManager();
78 if (action === 'insertDrawing') this.actionStartDrawing();
79 if (action === 'fullscreen') this.actionFullScreen();
82 // Mobile section toggling
83 this.elem.addEventListener('click', event => {
84 const toolbarLabel = event.target.closest('.editor-toolbar-label');
85 if (!toolbarLabel) return;
87 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
88 for (let activeElem of currentActiveSections) {
89 activeElem.classList.remove('active');
92 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
95 cmLoadPromise.then(cm => {
96 this.codeMirrorSetup(cm);
98 // Refresh CodeMirror on container resize
99 const resizeDebounced = debounce(() => this.Code.updateLayout(cm), 100, false);
100 const observer = new ResizeObserver(resizeDebounced);
101 observer.observe(this.elem);
104 this.listenForBookStackEditorEvents();
106 // Scroll to text if needed.
107 const queryParams = (new URL(window.location)).searchParams;
108 const scrollText = queryParams.get('content-text');
110 this.scrollToText(scrollText);
114 // Update the input content and render the display.
116 const content = this.cm.getValue();
117 this.input.value = content;
118 const html = this.markdown.render(content);
119 window.$events.emit('editor-html-change', html);
120 window.$events.emit('editor-markdown-change', content);
123 this.display.innerHTML = html;
126 onMarkdownScroll(lineCount) {
127 const elems = this.display.children;
128 if (elems.length <= lineCount) return;
130 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
131 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
134 codeMirrorSetup(cm) {
135 const context = this;
138 // cm.setOption('direction', this.textDirection);
139 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
140 // Custom key commands
141 let metaKey = this.Code.getMetaKey();
142 const extraKeys = {};
143 // Insert Image shortcut
144 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
145 let selectedText = cm.getSelection();
146 let newText = ``;
147 let cursorPos = cm.getCursor('from');
148 cm.replaceSelection(newText);
149 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
152 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
154 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
155 // Show link selector
156 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
158 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
160 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
161 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
162 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
163 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
164 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
165 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
166 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
167 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
168 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
169 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
170 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
171 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
172 cm.setOption('extraKeys', extraKeys);
174 // Update data on content change
175 cm.on('change', (instance, changeObj) => {
176 this.updateAndRender();
179 const onScrollDebounced = debounce((instance) => {
180 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
181 let scroll = instance.getScrollInfo();
182 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
184 this.onMarkdownScroll(-1);
188 let lineNum = instance.lineAtHeight(scroll.top, 'local');
189 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
190 let parser = new DOMParser();
191 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
192 let totalLines = doc.documentElement.querySelectorAll('body > *');
193 this.onMarkdownScroll(totalLines.length);
196 // Handle scroll to sync display view
197 cm.on('scroll', instance => {
198 onScrollDebounced(instance);
201 // Handle image paste
202 cm.on('paste', (cm, event) => {
203 const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
205 // Don't handle the event ourselves if no items exist of contains table-looking data
206 if (!clipboard.hasItems() || clipboard.containsTabularData()) {
210 const images = clipboard.getImages();
211 for (const image of images) {
216 // Handle image & content drag n drop
217 cm.on('drop', (cm, event) => {
219 const templateId = event.dataTransfer.getData('bookstack/template');
221 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
222 cm.setCursor(cursorPos);
223 event.preventDefault();
224 window.$http.get(`/templates/${templateId}`).then(resp => {
225 const content = resp.data.markdown || resp.data.html;
226 cm.replaceSelection(content);
230 const clipboard = new Clipboard(event.dataTransfer);
231 if (clipboard.hasItems() && clipboard.getImages().length > 0) {
232 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
233 cm.setCursor(cursorPos);
234 event.stopPropagation();
235 event.preventDefault();
236 const images = clipboard.getImages();
237 for (const image of images) {
244 // Helper to replace editor content
245 function replaceContent(search, replace) {
246 let text = cm.getValue();
247 let cursor = cm.listSelections();
248 cm.setValue(text.replace(search, replace));
249 cm.setSelections(cursor);
252 // Helper to replace the start of the line
253 function replaceLineStart(newStart) {
254 let cursor = cm.getCursor();
255 let lineContent = cm.getLine(cursor.line);
256 let lineLen = lineContent.length;
257 let lineStart = lineContent.split(' ')[0];
259 // Remove symbol if already set
260 if (lineStart === newStart) {
261 lineContent = lineContent.replace(`${newStart} `, '');
262 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
263 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
267 let alreadySymbol = /^[#>`]/.test(lineStart);
270 posDif = newStart.length - lineStart.length;
271 lineContent = lineContent.replace(lineStart, newStart).trim();
272 } else if (newStart !== '') {
273 posDif = newStart.length + 1;
274 lineContent = newStart + ' ' + lineContent;
276 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
277 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
280 function wrapLine(start, end) {
281 let cursor = cm.getCursor();
282 let lineContent = cm.getLine(cursor.line);
283 let lineLen = lineContent.length;
286 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
287 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
289 newLineContent = `${start}${lineContent}${end}`;
292 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
293 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
296 function wrapSelection(start, end) {
297 let selection = cm.getSelection();
298 if (selection === '') return wrapLine(start, end);
304 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
305 newSelection = selection.slice(start.length, selection.length - end.length);
306 endDiff = -(end.length + start.length);
308 newSelection = `${start}${selection}${end}`;
309 endDiff = start.length + end.length;
312 let selections = cm.listSelections()[0];
313 cm.replaceSelection(newSelection);
314 let headFirst = selections.head.ch <= selections.anchor.ch;
315 selections.head.ch += headFirst ? frontDiff : endDiff;
316 selections.anchor.ch += headFirst ? endDiff : frontDiff;
317 cm.setSelections([selections]);
320 // Handle image upload and add image into markdown content
321 function uploadImage(file) {
322 if (file === null || file.type.indexOf('image') !== 0) return;
326 let fileNameMatches = file.name.match(/\.(.+)$/);
327 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
330 // Insert image into markdown
331 const id = "image-" + Math.random().toString(16).slice(2);
332 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
333 const selectedText = cm.getSelection();
334 const placeHolderText = ``;
335 const cursor = cm.getCursor();
336 cm.replaceSelection(placeHolderText);
337 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
339 const remoteFilename = "image-" + Date.now() + "." + ext;
340 const formData = new FormData();
341 formData.append('file', file, remoteFilename);
342 formData.append('uploaded_to', context.pageId);
344 window.$http.post('/images/gallery', formData).then(resp => {
345 const newContent = `[](${resp.data.url})`;
346 replaceContent(placeHolderText, newContent);
348 window.$events.emit('error', context.imageUploadErrorText);
349 replaceContent(placeHolderText, selectedText);
354 function insertLink() {
355 let cursorPos = cm.getCursor('from');
356 let selectedText = cm.getSelection() || '';
357 let newText = `[${selectedText}]()`;
359 cm.replaceSelection(newText);
360 let cursorPosDiff = (selectedText === '') ? -3 : -1;
361 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
364 this.updateAndRender();
367 actionInsertImage() {
368 const cursorPos = this.cm.getCursor('from');
369 window.ImageManager.show(image => {
370 const imageUrl = image.thumbs.display || image.url;
371 let selectedText = this.cm.getSelection();
372 let newText = "[](" + image.url + ")";
374 this.cm.replaceSelection(newText);
375 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
379 actionShowImageManager() {
380 const cursorPos = this.cm.getCursor('from');
381 window.ImageManager.show(image => {
382 this.insertDrawing(image, cursorPos);
386 // Show the popup link selector and insert a link when finished
387 actionShowLinkSelector() {
388 const cursorPos = this.cm.getCursor('from');
389 window.EntitySelectorPopup.show(entity => {
390 let selectedText = this.cm.getSelection() || entity.name;
391 let newText = `[${selectedText}](${entity.link})`;
393 this.cm.replaceSelection(newText);
394 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
399 const drawioUrlElem = document.querySelector('[drawio-url]');
400 return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
403 // Show draw.io if enabled and handle save.
404 actionStartDrawing() {
405 const url = this.getDrawioUrl();
408 const cursorPos = this.cm.getCursor('from');
410 DrawIO.show(url,() => {
411 return Promise.resolve('');
412 }, (drawingData) => {
416 uploaded_to: Number(this.pageId),
419 window.$http.post("/images/drawio", data).then(resp => {
420 this.insertDrawing(resp.data, cursorPos);
423 this.handleDrawingUploadError(err);
428 insertDrawing(image, originalCursor) {
429 const newText = DrawIO.buildDrawingContentHtml(image);
431 this.cm.replaceSelection(newText);
432 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
435 // Show draw.io if enabled and handle save.
436 actionEditDrawing(imgContainer) {
437 const drawioUrl = this.getDrawioUrl();
442 const cursorPos = this.cm.getCursor('from');
443 const drawingId = imgContainer.getAttribute('drawio-diagram');
445 DrawIO.show(drawioUrl, () => {
446 return DrawIO.load(drawingId);
447 }, (drawingData) => {
451 uploaded_to: Number(this.pageId),
454 window.$http.post("/images/drawio", data).then(resp => {
455 const image = resp.data;
456 const newText = DrawIO.buildDrawingContentHtml(image);
458 const newContent = this.cm.getValue().split('\n').map(line => {
459 const isDrawing = line.includes(`drawio-diagram="${drawingId}"`);
460 return isDrawing ? newText : line;
463 this.cm.setValue(newContent);
464 this.cm.setCursor(cursorPos);
468 this.handleDrawingUploadError(err);
473 handleDrawingUploadError(error) {
474 if (error.status === 413) {
475 window.$events.emit('error', this.serverUploadLimitText);
477 window.$events.emit('error', this.imageUploadErrorText);
482 // Make the editor full screen
484 const alreadyFullscreen = this.elem.classList.contains('fullscreen');
485 this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
486 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
489 // Scroll to a specified text
490 scrollToText(searchText) {
495 const content = this.cm.getValue();
496 const lines = content.split(/\r?\n/);
497 let lineNumber = lines.findIndex(line => {
498 return line && line.indexOf(searchText) !== -1;
501 if (lineNumber === -1) {
505 this.cm.scrollIntoView({
509 // set the cursor location.
512 char: lines[lineNumber].length
516 listenForBookStackEditorEvents() {
518 function getContentToInsert({html, markdown}) {
519 return markdown || html;
522 // Replace editor content
523 window.$events.listen('editor::replace', (eventContent) => {
524 const markdown = getContentToInsert(eventContent);
525 this.cm.setValue(markdown);
528 // Append editor content
529 window.$events.listen('editor::append', (eventContent) => {
530 const cursorPos = this.cm.getCursor('from');
531 const markdown = getContentToInsert(eventContent);
532 const content = this.cm.getValue() + '\n' + markdown;
533 this.cm.setValue(content);
534 this.cm.setCursor(cursorPos.line, cursorPos.ch);
537 // Prepend editor content
538 window.$events.listen('editor::prepend', (eventContent) => {
539 const cursorPos = this.cm.getCursor('from');
540 const markdown = getContentToInsert(eventContent);
541 const content = markdown + '\n' + this.cm.getValue();
542 this.cm.setValue(content);
543 const prependLineCount = markdown.split('\n').length;
544 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
547 // Insert editor content at the current location
548 window.$events.listen('editor::insert', (eventContent) => {
549 const markdown = getContentToInsert(eventContent);
550 this.cm.replaceSelection(markdown);
554 window.$events.listen('editor::focus', () => {
560 export default MarkdownEditor ;