]> BookStack Code Mirror - bookstack/blob - resources/js/components/markdown-editor.js
Improved loading for images with failed thumbnails
[bookstack] / resources / js / components / markdown-editor.js
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";
6
7 import DrawIO from "../services/drawio";
8
9 class MarkdownEditor {
10
11     setup() {
12         this.elem = this.$el;
13
14         this.pageId = this.$opts.pageId;
15         this.textDirection = this.$opts.textDirection;
16         this.imageUploadErrorText = this.$opts.imageUploadErrorText;
17         this.serverUploadLimitText = this.$opts.serverUploadLimitText;
18
19         this.markdown = new MarkdownIt({html: true});
20         this.markdown.use(mdTasksLists, {label: true});
21
22         this.display = this.elem.querySelector('.markdown-display');
23
24         this.displayStylesLoaded = false;
25         this.input = this.elem.querySelector('textarea');
26         this.cm = code.markdownEditor(this.input);
27
28         this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
29
30         const displayLoad = () => {
31             this.displayDoc = this.display.contentDocument;
32             this.init();
33         };
34
35         if (this.display.contentDocument.readyState === 'complete') {
36             displayLoad();
37         } else {
38             this.display.addEventListener('load', displayLoad.bind(this));
39         }
40
41         window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
42             markdownIt: this.markdown,
43             displayEl: this.display,
44             codeMirrorInstance: this.cm,
45         });
46     }
47
48     init() {
49
50         let lastClick = 0;
51
52         // Prevent markdown display link click redirect
53         this.displayDoc.addEventListener('click', event => {
54             let isDblClick = Date.now() - lastClick < 300;
55
56             let link = event.target.closest('a');
57             if (link !== null) {
58                 event.preventDefault();
59                 window.open(link.getAttribute('href'));
60                 return;
61             }
62
63             let drawing = event.target.closest('[drawio-diagram]');
64             if (drawing !== null && isDblClick) {
65                 this.actionEditDrawing(drawing);
66                 return;
67             }
68
69             lastClick = Date.now();
70         });
71
72         // Button actions
73         this.elem.addEventListener('click', event => {
74             let button = event.target.closest('button[data-action]');
75             if (button === null) return;
76
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();
82                 return;
83             }
84             if (action === 'insertDrawing') this.actionStartDrawing();
85             if (action === 'fullscreen') this.actionFullScreen();
86         });
87
88         // Mobile section toggling
89         this.elem.addEventListener('click', event => {
90             const toolbarLabel = event.target.closest('.editor-toolbar-label');
91             if (!toolbarLabel) return;
92
93             const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
94             for (let activeElem of currentActiveSections) {
95                 activeElem.classList.remove('active');
96             }
97
98             toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
99         });
100
101         window.$events.listen('editor-markdown-update', value => {
102             this.cm.setValue(value);
103             this.updateAndRender();
104         });
105
106         this.codeMirrorSetup();
107         this.listenForBookStackEditorEvents();
108
109         // Scroll to text if needed.
110         const queryParams = (new URL(window.location)).searchParams;
111         const scrollText = queryParams.get('content-text');
112         if (scrollText) {
113             this.scrollToText(scrollText);
114         }
115     }
116
117     // Update the input content and render the display.
118     updateAndRender() {
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);
124
125         // Set body content
126         this.displayDoc.body.className = 'page-content';
127         this.displayDoc.body.innerHTML = html;
128
129         // Copy styles from page head and set custom styles for editor
130         this.loadStylesIntoDisplay();
131     }
132
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
137
138         if (document.documentElement.classList.contains('dark-mode')) {
139             this.displayDoc.documentElement.style.backgroundColor = '#222';
140             this.displayDoc.documentElement.classList.add('dark-mode');
141         }
142
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);
148         }
149
150         this.displayStylesLoaded = true;
151     }
152
153     onMarkdownScroll(lineCount) {
154         const elems = this.displayDoc.body.children;
155         if (elems.length <= lineCount) return;
156
157         const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
158         topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
159     }
160
161     codeMirrorSetup() {
162         const cm = this.cm;
163         const context = this;
164
165         // Text direction
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 = `![${selectedText}](http://)`;
175             let cursorPos = cm.getCursor('from');
176             cm.replaceSelection(newText);
177             cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
178         };
179         // Save draft
180         extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
181         // Save page
182         extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
183         // Show link selector
184         extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
185         // Insert Link
186         extraKeys[`${metaKey}-K`] = cm => {insertLink()};
187         // FormatShortcuts
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);
201
202         // Update data on content change
203         cm.on('change', (instance, changeObj) => {
204             this.updateAndRender();
205         });
206
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;
211             if (atEnd) {
212                 this.onMarkdownScroll(-1);
213                 return;
214             }
215
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);
222         }, 100);
223
224         // Handle scroll to sync display view
225         cm.on('scroll', instance => {
226             onScrollDebounced(instance);
227         });
228
229         // Handle image paste
230         cm.on('paste', (cm, event) => {
231             const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
232
233             // Don't handle the event ourselves if no items exist of contains table-looking data
234             if (!clipboard.hasItems() || clipboard.containsTabularData()) {
235                 return;
236             }
237
238             const images = clipboard.getImages();
239             for (const image of images) {
240                 uploadImage(image);
241             }
242         });
243
244         // Handle image & content drag n drop
245         cm.on('drop', (cm, event) => {
246
247             const templateId = event.dataTransfer.getData('bookstack/template');
248             if (templateId) {
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);
255                 });
256             }
257
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) {
266                     uploadImage(image);
267                 }
268             }
269
270         });
271
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);
278         }
279
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];
286
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)});
292                 return;
293             }
294
295             let alreadySymbol = /^[#>`]/.test(lineStart);
296             let posDif = 0;
297             if (alreadySymbol) {
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;
303             }
304             cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
305             cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
306         }
307
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;
313
314             if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
315                 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
316             } else {
317                 newLineContent = `${start}${lineContent}${end}`;
318             }
319
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});
322         }
323
324         function wrapSelection(start, end) {
325             let selection = cm.getSelection();
326             if (selection === '') return wrapLine(start, end);
327
328             let newSelection = selection;
329             let frontDiff = 0;
330             let endDiff = 0;
331
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);
335             } else {
336                 newSelection = `${start}${selection}${end}`;
337                 endDiff = start.length + end.length;
338             }
339
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]);
346         }
347
348         // Handle image upload and add image into markdown content
349         function uploadImage(file) {
350             if (file === null || file.type.indexOf('image') !== 0) return;
351             let ext = 'png';
352
353             if (file.name) {
354                 let fileNameMatches = file.name.match(/\.(.+)$/);
355                 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
356             }
357
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 = `![${selectedText}](${placeholderImage})`;
363             const cursor = cm.getCursor();
364             cm.replaceSelection(placeHolderText);
365             cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
366
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);
371
372             window.$http.post('/images/gallery', formData).then(resp => {
373                 const newContent = `[![${selectedText}](${resp.data.thumbs.display})](${resp.data.url})`;
374                 replaceContent(placeHolderText, newContent);
375             }).catch(err => {
376                 window.$events.emit('error', context.imageUploadErrorText);
377                 replaceContent(placeHolderText, selectedText);
378                 console.log(err);
379             });
380         }
381
382         function insertLink() {
383             let cursorPos = cm.getCursor('from');
384             let selectedText = cm.getSelection() || '';
385             let newText = `[${selectedText}]()`;
386             cm.focus();
387             cm.replaceSelection(newText);
388             let cursorPosDiff = (selectedText === '') ? -3 : -1;
389             cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
390         }
391
392        this.updateAndRender();
393     }
394
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 = "[![" + (selectedText || image.name) + "](" + imageUrl + ")](" + image.url + ")";
401             this.cm.focus();
402             this.cm.replaceSelection(newText);
403             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
404         }, 'gallery');
405     }
406
407     actionShowImageManager() {
408         const cursorPos = this.cm.getCursor('from');
409         window.ImageManager.show(image => {
410             this.insertDrawing(image, cursorPos);
411         }, 'drawio');
412     }
413
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})`;
420             this.cm.focus();
421             this.cm.replaceSelection(newText);
422             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
423         });
424     }
425
426     getDrawioUrl() {
427         const drawioUrlElem = document.querySelector('[drawio-url]');
428         return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
429     }
430
431     // Show draw.io if enabled and handle save.
432     actionStartDrawing() {
433         const url = this.getDrawioUrl();
434         if (!url) return;
435
436         const cursorPos = this.cm.getCursor('from');
437
438         DrawIO.show(url,() => {
439             return Promise.resolve('');
440         }, (pngData) => {
441
442             const data = {
443                 image: pngData,
444                 uploaded_to: Number(this.pageId),
445             };
446
447             window.$http.post("/images/drawio", data).then(resp => {
448                 this.insertDrawing(resp.data, cursorPos);
449                 DrawIO.close();
450             }).catch(err => {
451                 this.handleDrawingUploadError(err);
452             });
453         });
454     }
455
456     insertDrawing(image, originalCursor) {
457         const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
458         this.cm.focus();
459         this.cm.replaceSelection(newText);
460         this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
461     }
462
463     // Show draw.io if enabled and handle save.
464     actionEditDrawing(imgContainer) {
465         const drawioUrl = this.getDrawioUrl();
466         if (!drawioUrl) {
467             return;
468         }
469
470         const cursorPos = this.cm.getCursor('from');
471         const drawingId = imgContainer.getAttribute('drawio-diagram');
472
473         DrawIO.show(drawioUrl, () => {
474             return DrawIO.load(drawingId);
475         }, (pngData) => {
476
477             let data = {
478                 image: pngData,
479                 uploaded_to: Number(this.pageId),
480             };
481
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) {
486                         return newText;
487                     }
488                     return line;
489                 }).join('\n');
490                 this.cm.setValue(newContent);
491                 this.cm.setCursor(cursorPos);
492                 this.cm.focus();
493                 DrawIO.close();
494             }).catch(err => {
495                 this.handleDrawingUploadError(err);
496             });
497         });
498     }
499
500     handleDrawingUploadError(error) {
501         if (error.status === 413) {
502             window.$events.emit('error', this.serverUploadLimitText);
503         } else {
504             window.$events.emit('error', this.imageUploadErrorText);
505         }
506         console.log(error);
507     }
508
509     // Make the editor full screen
510     actionFullScreen() {
511         const alreadyFullscreen = this.elem.classList.contains('fullscreen');
512         this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
513         document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
514     }
515
516     // Scroll to a specified text
517     scrollToText(searchText) {
518         if (!searchText) {
519             return;
520         }
521
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;
526         });
527
528         if (lineNumber === -1) {
529             return;
530         }
531
532         this.cm.scrollIntoView({
533             line: lineNumber,
534         }, 200);
535         this.cm.focus();
536         // set the cursor location.
537         this.cm.setCursor({
538             line: lineNumber,
539             char: lines[lineNumber].length
540         })
541     }
542
543     listenForBookStackEditorEvents() {
544
545         function getContentToInsert({html, markdown}) {
546             return markdown || html;
547         }
548
549         // Replace editor content
550         window.$events.listen('editor::replace', (eventContent) => {
551             const markdown = getContentToInsert(eventContent);
552             this.cm.setValue(markdown);
553         });
554
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);
562         });
563
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);
572         });
573
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);
578         });
579
580         // Focus on editor
581         window.$events.listen('editor::focus', () => {
582             this.cm.focus();
583         });
584     }
585 }
586
587 export default MarkdownEditor ;