]> BookStack Code Mirror - bookstack/blob - resources/js/components/markdown-editor.js
Updated minimum php version from 7.3 to 7.4
[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         // 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);
120     }
121
122     // Update the input content and render the display.
123     updateAndRender() {
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);
129
130         // Set body content
131         this.displayDoc.body.className = 'page-content';
132         this.displayDoc.body.innerHTML = html;
133
134         // Copy styles from page head and set custom styles for editor
135         this.loadStylesIntoDisplay();
136     }
137
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
142
143         if (document.documentElement.classList.contains('dark-mode')) {
144             this.displayDoc.documentElement.style.backgroundColor = '#222';
145             this.displayDoc.documentElement.classList.add('dark-mode');
146         }
147
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);
153         }
154
155         this.displayStylesLoaded = true;
156     }
157
158     onMarkdownScroll(lineCount) {
159         const elems = this.displayDoc.body.children;
160         if (elems.length <= lineCount) return;
161
162         const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
163         topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
164     }
165
166     codeMirrorSetup() {
167         const cm = this.cm;
168         const context = this;
169
170         // Text direction
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 = `![${selectedText}](http://)`;
180             let cursorPos = cm.getCursor('from');
181             cm.replaceSelection(newText);
182             cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
183         };
184         // Save draft
185         extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
186         // Save page
187         extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
188         // Show link selector
189         extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
190         // Insert Link
191         extraKeys[`${metaKey}-K`] = cm => {insertLink()};
192         // FormatShortcuts
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);
206
207         // Update data on content change
208         cm.on('change', (instance, changeObj) => {
209             this.updateAndRender();
210         });
211
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;
216             if (atEnd) {
217                 this.onMarkdownScroll(-1);
218                 return;
219             }
220
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);
227         }, 100);
228
229         // Handle scroll to sync display view
230         cm.on('scroll', instance => {
231             onScrollDebounced(instance);
232         });
233
234         // Handle image paste
235         cm.on('paste', (cm, event) => {
236             const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
237
238             // Don't handle the event ourselves if no items exist of contains table-looking data
239             if (!clipboard.hasItems() || clipboard.containsTabularData()) {
240                 return;
241             }
242
243             const images = clipboard.getImages();
244             for (const image of images) {
245                 uploadImage(image);
246             }
247         });
248
249         // Handle image & content drag n drop
250         cm.on('drop', (cm, event) => {
251
252             const templateId = event.dataTransfer.getData('bookstack/template');
253             if (templateId) {
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);
260                 });
261             }
262
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) {
271                     uploadImage(image);
272                 }
273             }
274
275         });
276
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);
283         }
284
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];
291
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)});
297                 return;
298             }
299
300             let alreadySymbol = /^[#>`]/.test(lineStart);
301             let posDif = 0;
302             if (alreadySymbol) {
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;
308             }
309             cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
310             cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
311         }
312
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;
318
319             if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
320                 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
321             } else {
322                 newLineContent = `${start}${lineContent}${end}`;
323             }
324
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});
327         }
328
329         function wrapSelection(start, end) {
330             let selection = cm.getSelection();
331             if (selection === '') return wrapLine(start, end);
332
333             let newSelection = selection;
334             let frontDiff = 0;
335             let endDiff = 0;
336
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);
340             } else {
341                 newSelection = `${start}${selection}${end}`;
342                 endDiff = start.length + end.length;
343             }
344
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]);
351         }
352
353         // Handle image upload and add image into markdown content
354         function uploadImage(file) {
355             if (file === null || file.type.indexOf('image') !== 0) return;
356             let ext = 'png';
357
358             if (file.name) {
359                 let fileNameMatches = file.name.match(/\.(.+)$/);
360                 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
361             }
362
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 = `![${selectedText}](${placeholderImage})`;
368             const cursor = cm.getCursor();
369             cm.replaceSelection(placeHolderText);
370             cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
371
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);
376
377             window.$http.post('/images/gallery', formData).then(resp => {
378                 const newContent = `[![${selectedText}](${resp.data.thumbs.display})](${resp.data.url})`;
379                 replaceContent(placeHolderText, newContent);
380             }).catch(err => {
381                 window.$events.emit('error', context.imageUploadErrorText);
382                 replaceContent(placeHolderText, selectedText);
383                 console.log(err);
384             });
385         }
386
387         function insertLink() {
388             let cursorPos = cm.getCursor('from');
389             let selectedText = cm.getSelection() || '';
390             let newText = `[${selectedText}]()`;
391             cm.focus();
392             cm.replaceSelection(newText);
393             let cursorPosDiff = (selectedText === '') ? -3 : -1;
394             cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
395         }
396
397        this.updateAndRender();
398     }
399
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 = "[![" + (selectedText || image.name) + "](" + imageUrl + ")](" + image.url + ")";
406             this.cm.focus();
407             this.cm.replaceSelection(newText);
408             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
409         }, 'gallery');
410     }
411
412     actionShowImageManager() {
413         const cursorPos = this.cm.getCursor('from');
414         window.ImageManager.show(image => {
415             this.insertDrawing(image, cursorPos);
416         }, 'drawio');
417     }
418
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})`;
425             this.cm.focus();
426             this.cm.replaceSelection(newText);
427             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
428         });
429     }
430
431     getDrawioUrl() {
432         const drawioUrlElem = document.querySelector('[drawio-url]');
433         return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
434     }
435
436     // Show draw.io if enabled and handle save.
437     actionStartDrawing() {
438         const url = this.getDrawioUrl();
439         if (!url) return;
440
441         const cursorPos = this.cm.getCursor('from');
442
443         DrawIO.show(url,() => {
444             return Promise.resolve('');
445         }, (pngData) => {
446
447             const data = {
448                 image: pngData,
449                 uploaded_to: Number(this.pageId),
450             };
451
452             window.$http.post("/images/drawio", data).then(resp => {
453                 this.insertDrawing(resp.data, cursorPos);
454                 DrawIO.close();
455             }).catch(err => {
456                 this.handleDrawingUploadError(err);
457             });
458         });
459     }
460
461     insertDrawing(image, originalCursor) {
462         const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
463         this.cm.focus();
464         this.cm.replaceSelection(newText);
465         this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
466     }
467
468     // Show draw.io if enabled and handle save.
469     actionEditDrawing(imgContainer) {
470         const drawioUrl = this.getDrawioUrl();
471         if (!drawioUrl) {
472             return;
473         }
474
475         const cursorPos = this.cm.getCursor('from');
476         const drawingId = imgContainer.getAttribute('drawio-diagram');
477
478         DrawIO.show(drawioUrl, () => {
479             return DrawIO.load(drawingId);
480         }, (pngData) => {
481
482             let data = {
483                 image: pngData,
484                 uploaded_to: Number(this.pageId),
485             };
486
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) {
491                         return newText;
492                     }
493                     return line;
494                 }).join('\n');
495                 this.cm.setValue(newContent);
496                 this.cm.setCursor(cursorPos);
497                 this.cm.focus();
498                 DrawIO.close();
499             }).catch(err => {
500                 this.handleDrawingUploadError(err);
501             });
502         });
503     }
504
505     handleDrawingUploadError(error) {
506         if (error.status === 413) {
507             window.$events.emit('error', this.serverUploadLimitText);
508         } else {
509             window.$events.emit('error', this.imageUploadErrorText);
510         }
511         console.log(error);
512     }
513
514     // Make the editor full screen
515     actionFullScreen() {
516         const alreadyFullscreen = this.elem.classList.contains('fullscreen');
517         this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
518         document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
519     }
520
521     // Scroll to a specified text
522     scrollToText(searchText) {
523         if (!searchText) {
524             return;
525         }
526
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;
531         });
532
533         if (lineNumber === -1) {
534             return;
535         }
536
537         this.cm.scrollIntoView({
538             line: lineNumber,
539         }, 200);
540         this.cm.focus();
541         // set the cursor location.
542         this.cm.setCursor({
543             line: lineNumber,
544             char: lines[lineNumber].length
545         })
546     }
547
548     listenForBookStackEditorEvents() {
549
550         function getContentToInsert({html, markdown}) {
551             return markdown || html;
552         }
553
554         // Replace editor content
555         window.$events.listen('editor::replace', (eventContent) => {
556             const markdown = getContentToInsert(eventContent);
557             this.cm.setValue(markdown);
558         });
559
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);
567         });
568
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);
577         });
578
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);
583         });
584
585         // Focus on editor
586         window.$events.listen('editor::focus', () => {
587             this.cm.focus();
588         });
589     }
590 }
591
592 export default MarkdownEditor ;