]> BookStack Code Mirror - bookstack/blob - resources/js/components/markdown-editor.js
Merge pull request #3512 from BookStackApp/code_manager_updates
[bookstack] / resources / js / components / markdown-editor.js
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";
5 import {patchDomFromHtmlString} from "../services/vdom";
6 import DrawIO from "../services/drawio";
7
8 class MarkdownEditor {
9
10     setup() {
11         this.elem = this.$el;
12
13         this.pageId = this.$opts.pageId;
14         this.textDirection = this.$opts.textDirection;
15         this.imageUploadErrorText = this.$opts.imageUploadErrorText;
16         this.serverUploadLimitText = this.$opts.serverUploadLimitText;
17
18         this.markdown = new MarkdownIt({html: true});
19         this.markdown.use(mdTasksLists, {label: true});
20
21         this.display = this.elem.querySelector('.markdown-display');
22
23         this.displayStylesLoaded = false;
24         this.input = this.elem.querySelector('textarea');
25
26         this.cm = null;
27         this.Code = null;
28         const cmLoadPromise = window.importVersioned('code').then(Code => {
29             this.cm = Code.markdownEditor(this.input);
30             this.Code = Code;
31             return this.cm;
32         });
33
34         this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
35
36         const displayLoad = () => {
37             this.displayDoc = this.display.contentDocument;
38             this.init(cmLoadPromise);
39         };
40
41         if (this.display.contentDocument.readyState === 'complete') {
42             displayLoad();
43         } else {
44             this.display.addEventListener('load', displayLoad.bind(this));
45         }
46
47         window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
48             markdownIt: this.markdown,
49             displayEl: this.display,
50             codeMirrorInstance: this.cm,
51         });
52     }
53
54     init(cmLoadPromise) {
55
56         let lastClick = 0;
57
58         // Prevent markdown display link click redirect
59         this.displayDoc.addEventListener('click', event => {
60             let isDblClick = Date.now() - lastClick < 300;
61
62             let link = event.target.closest('a');
63             if (link !== null) {
64                 event.preventDefault();
65                 window.open(link.getAttribute('href'));
66                 return;
67             }
68
69             let drawing = event.target.closest('[drawio-diagram]');
70             if (drawing !== null && isDblClick) {
71                 this.actionEditDrawing(drawing);
72                 return;
73             }
74
75             lastClick = Date.now();
76         });
77
78         // Button actions
79         this.elem.addEventListener('click', event => {
80             let button = event.target.closest('button[data-action]');
81             if (button === null) return;
82
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();
88                 return;
89             }
90             if (action === 'insertDrawing') this.actionStartDrawing();
91             if (action === 'fullscreen') this.actionFullScreen();
92         });
93
94         // Mobile section toggling
95         this.elem.addEventListener('click', event => {
96             const toolbarLabel = event.target.closest('.editor-toolbar-label');
97             if (!toolbarLabel) return;
98
99             const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
100             for (let activeElem of currentActiveSections) {
101                 activeElem.classList.remove('active');
102             }
103
104             toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
105         });
106
107         cmLoadPromise.then(cm => {
108             this.codeMirrorSetup(cm);
109
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);
114         });
115
116         this.listenForBookStackEditorEvents();
117
118         // Scroll to text if needed.
119         const queryParams = (new URL(window.location)).searchParams;
120         const scrollText = queryParams.get('content-text');
121         if (scrollText) {
122             this.scrollToText(scrollText);
123         }
124     }
125
126     // Update the input content and render the display.
127     updateAndRender() {
128         const content = this.cm.getValue();
129         this.input.value = content;
130
131         const html = this.markdown.render(content);
132         window.$events.emit('editor-html-change', html);
133         window.$events.emit('editor-markdown-change', content);
134
135         // Set body content
136         const target = this.getDisplayTarget();
137         this.displayDoc.body.className = 'page-content';
138         patchDomFromHtmlString(target, html);
139
140         // Copy styles from page head and set custom styles for editor
141         this.loadStylesIntoDisplay();
142     }
143
144     getDisplayTarget() {
145         const body = this.displayDoc.body;
146
147         if (body.children.length === 0) {
148             const wrap = document.createElement('div');
149             this.displayDoc.body.append(wrap);
150         }
151
152         return body.children[0];
153     }
154
155     loadStylesIntoDisplay() {
156         if (this.displayStylesLoaded) return;
157         this.displayDoc.documentElement.classList.add('markdown-editor-display');
158         // Set display to be dark mode if parent is
159
160         if (document.documentElement.classList.contains('dark-mode')) {
161             this.displayDoc.documentElement.style.backgroundColor = '#222';
162             this.displayDoc.documentElement.classList.add('dark-mode');
163         }
164
165         this.displayDoc.head.innerHTML = '';
166         const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
167         for (let style of styles) {
168             const copy = style.cloneNode(true);
169             this.displayDoc.head.appendChild(copy);
170         }
171
172         this.displayStylesLoaded = true;
173     }
174
175     onMarkdownScroll(lineCount) {
176         const elems = this.displayDoc.body.children;
177         if (elems.length <= lineCount) return;
178
179         const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
180         topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
181     }
182
183     codeMirrorSetup(cm) {
184         const context = this;
185
186         // Text direction
187         // cm.setOption('direction', this.textDirection);
188         cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
189         // Custom key commands
190         let metaKey = this.Code.getMetaKey();
191         const extraKeys = {};
192         // Insert Image shortcut
193         extraKeys[`${metaKey}-Alt-I`] = function(cm) {
194             let selectedText = cm.getSelection();
195             let newText = `![${selectedText}](http://)`;
196             let cursorPos = cm.getCursor('from');
197             cm.replaceSelection(newText);
198             cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
199         };
200         // Save draft
201         extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
202         // Save page
203         extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
204         // Show link selector
205         extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
206         // Insert Link
207         extraKeys[`${metaKey}-K`] = cm => {insertLink()};
208         // FormatShortcuts
209         extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
210         extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
211         extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
212         extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
213         extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
214         extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
215         extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
216         extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
217         extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
218         extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
219         extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
220         extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
221         cm.setOption('extraKeys', extraKeys);
222
223         // Update data on content change
224         cm.on('change', (instance, changeObj) => {
225             this.updateAndRender();
226         });
227
228         const onScrollDebounced = debounce((instance) => {
229             // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
230             let scroll = instance.getScrollInfo();
231             let atEnd = scroll.top + scroll.clientHeight === scroll.height;
232             if (atEnd) {
233                 this.onMarkdownScroll(-1);
234                 return;
235             }
236
237             let lineNum = instance.lineAtHeight(scroll.top, 'local');
238             let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
239             let parser = new DOMParser();
240             let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
241             let totalLines = doc.documentElement.querySelectorAll('body > *');
242             this.onMarkdownScroll(totalLines.length);
243         }, 100);
244
245         // Handle scroll to sync display view
246         cm.on('scroll', instance => {
247             onScrollDebounced(instance);
248         });
249
250         // Handle image paste
251         cm.on('paste', (cm, event) => {
252             const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
253
254             // Don't handle the event ourselves if no items exist of contains table-looking data
255             if (!clipboard.hasItems() || clipboard.containsTabularData()) {
256                 return;
257             }
258
259             const images = clipboard.getImages();
260             for (const image of images) {
261                 uploadImage(image);
262             }
263         });
264
265         // Handle image & content drag n drop
266         cm.on('drop', (cm, event) => {
267
268             const templateId = event.dataTransfer.getData('bookstack/template');
269             if (templateId) {
270                 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
271                 cm.setCursor(cursorPos);
272                 event.preventDefault();
273                 window.$http.get(`/templates/${templateId}`).then(resp => {
274                     const content = resp.data.markdown || resp.data.html;
275                     cm.replaceSelection(content);
276                 });
277             }
278
279             const clipboard = new Clipboard(event.dataTransfer);
280             if (clipboard.hasItems() && clipboard.getImages().length > 0) {
281                 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
282                 cm.setCursor(cursorPos);
283                 event.stopPropagation();
284                 event.preventDefault();
285                 const images = clipboard.getImages();
286                 for (const image of images) {
287                     uploadImage(image);
288                 }
289             }
290
291         });
292
293         // Helper to replace editor content
294         function replaceContent(search, replace) {
295             let text = cm.getValue();
296             let cursor = cm.listSelections();
297             cm.setValue(text.replace(search, replace));
298             cm.setSelections(cursor);
299         }
300
301         // Helper to replace the start of the line
302         function replaceLineStart(newStart) {
303             let cursor = cm.getCursor();
304             let lineContent = cm.getLine(cursor.line);
305             let lineLen = lineContent.length;
306             let lineStart = lineContent.split(' ')[0];
307
308             // Remove symbol if already set
309             if (lineStart === newStart) {
310                 lineContent = lineContent.replace(`${newStart} `, '');
311                 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
312                 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
313                 return;
314             }
315
316             let alreadySymbol = /^[#>`]/.test(lineStart);
317             let posDif = 0;
318             if (alreadySymbol) {
319                 posDif = newStart.length - lineStart.length;
320                 lineContent = lineContent.replace(lineStart, newStart).trim();
321             } else if (newStart !== '') {
322                 posDif = newStart.length + 1;
323                 lineContent = newStart + ' ' + lineContent;
324             }
325             cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
326             cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
327         }
328
329         function wrapLine(start, end) {
330             let cursor = cm.getCursor();
331             let lineContent = cm.getLine(cursor.line);
332             let lineLen = lineContent.length;
333             let newLineContent = lineContent;
334
335             if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
336                 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
337             } else {
338                 newLineContent = `${start}${lineContent}${end}`;
339             }
340
341             cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
342             cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
343         }
344
345         function wrapSelection(start, end) {
346             let selection = cm.getSelection();
347             if (selection === '') return wrapLine(start, end);
348
349             let newSelection = selection;
350             let frontDiff = 0;
351             let endDiff = 0;
352
353             if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
354                 newSelection = selection.slice(start.length, selection.length - end.length);
355                 endDiff = -(end.length + start.length);
356             } else {
357                 newSelection = `${start}${selection}${end}`;
358                 endDiff = start.length + end.length;
359             }
360
361             let selections = cm.listSelections()[0];
362             cm.replaceSelection(newSelection);
363             let headFirst = selections.head.ch <= selections.anchor.ch;
364             selections.head.ch += headFirst ? frontDiff : endDiff;
365             selections.anchor.ch += headFirst ? endDiff : frontDiff;
366             cm.setSelections([selections]);
367         }
368
369         // Handle image upload and add image into markdown content
370         function uploadImage(file) {
371             if (file === null || file.type.indexOf('image') !== 0) return;
372             let ext = 'png';
373
374             if (file.name) {
375                 let fileNameMatches = file.name.match(/\.(.+)$/);
376                 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
377             }
378
379             // Insert image into markdown
380             const id = "image-" + Math.random().toString(16).slice(2);
381             const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
382             const selectedText = cm.getSelection();
383             const placeHolderText = `![${selectedText}](${placeholderImage})`;
384             const cursor = cm.getCursor();
385             cm.replaceSelection(placeHolderText);
386             cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
387
388             const remoteFilename = "image-" + Date.now() + "." + ext;
389             const formData = new FormData();
390             formData.append('file', file, remoteFilename);
391             formData.append('uploaded_to', context.pageId);
392
393             window.$http.post('/images/gallery', formData).then(resp => {
394                 const newContent = `[![${selectedText}](${resp.data.thumbs.display})](${resp.data.url})`;
395                 replaceContent(placeHolderText, newContent);
396             }).catch(err => {
397                 window.$events.emit('error', context.imageUploadErrorText);
398                 replaceContent(placeHolderText, selectedText);
399                 console.log(err);
400             });
401         }
402
403         function insertLink() {
404             let cursorPos = cm.getCursor('from');
405             let selectedText = cm.getSelection() || '';
406             let newText = `[${selectedText}]()`;
407             cm.focus();
408             cm.replaceSelection(newText);
409             let cursorPosDiff = (selectedText === '') ? -3 : -1;
410             cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
411         }
412
413        this.updateAndRender();
414     }
415
416     actionInsertImage() {
417         const cursorPos = this.cm.getCursor('from');
418         window.ImageManager.show(image => {
419             const imageUrl = image.thumbs.display || image.url;
420             let selectedText = this.cm.getSelection();
421             let newText = "[![" + (selectedText || image.name) + "](" + imageUrl + ")](" + image.url + ")";
422             this.cm.focus();
423             this.cm.replaceSelection(newText);
424             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
425         }, 'gallery');
426     }
427
428     actionShowImageManager() {
429         const cursorPos = this.cm.getCursor('from');
430         window.ImageManager.show(image => {
431             this.insertDrawing(image, cursorPos);
432         }, 'drawio');
433     }
434
435     // Show the popup link selector and insert a link when finished
436     actionShowLinkSelector() {
437         const cursorPos = this.cm.getCursor('from');
438         window.EntitySelectorPopup.show(entity => {
439             let selectedText = this.cm.getSelection() || entity.name;
440             let newText = `[${selectedText}](${entity.link})`;
441             this.cm.focus();
442             this.cm.replaceSelection(newText);
443             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
444         });
445     }
446
447     getDrawioUrl() {
448         const drawioUrlElem = document.querySelector('[drawio-url]');
449         return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
450     }
451
452     // Show draw.io if enabled and handle save.
453     actionStartDrawing() {
454         const url = this.getDrawioUrl();
455         if (!url) return;
456
457         const cursorPos = this.cm.getCursor('from');
458
459         DrawIO.show(url,() => {
460             return Promise.resolve('');
461         }, (pngData) => {
462
463             const data = {
464                 image: pngData,
465                 uploaded_to: Number(this.pageId),
466             };
467
468             window.$http.post("/images/drawio", data).then(resp => {
469                 this.insertDrawing(resp.data, cursorPos);
470                 DrawIO.close();
471             }).catch(err => {
472                 this.handleDrawingUploadError(err);
473             });
474         });
475     }
476
477     insertDrawing(image, originalCursor) {
478         const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
479         this.cm.focus();
480         this.cm.replaceSelection(newText);
481         this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
482     }
483
484     // Show draw.io if enabled and handle save.
485     actionEditDrawing(imgContainer) {
486         const drawioUrl = this.getDrawioUrl();
487         if (!drawioUrl) {
488             return;
489         }
490
491         const cursorPos = this.cm.getCursor('from');
492         const drawingId = imgContainer.getAttribute('drawio-diagram');
493
494         DrawIO.show(drawioUrl, () => {
495             return DrawIO.load(drawingId);
496         }, (pngData) => {
497
498             let data = {
499                 image: pngData,
500                 uploaded_to: Number(this.pageId),
501             };
502
503             window.$http.post("/images/drawio", data).then(resp => {
504                 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
505                 let newContent = this.cm.getValue().split('\n').map(line => {
506                     if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
507                         return newText;
508                     }
509                     return line;
510                 }).join('\n');
511                 this.cm.setValue(newContent);
512                 this.cm.setCursor(cursorPos);
513                 this.cm.focus();
514                 DrawIO.close();
515             }).catch(err => {
516                 this.handleDrawingUploadError(err);
517             });
518         });
519     }
520
521     handleDrawingUploadError(error) {
522         if (error.status === 413) {
523             window.$events.emit('error', this.serverUploadLimitText);
524         } else {
525             window.$events.emit('error', this.imageUploadErrorText);
526         }
527         console.log(error);
528     }
529
530     // Make the editor full screen
531     actionFullScreen() {
532         const alreadyFullscreen = this.elem.classList.contains('fullscreen');
533         this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
534         document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
535     }
536
537     // Scroll to a specified text
538     scrollToText(searchText) {
539         if (!searchText) {
540             return;
541         }
542
543         const content = this.cm.getValue();
544         const lines = content.split(/\r?\n/);
545         let lineNumber = lines.findIndex(line => {
546             return line && line.indexOf(searchText) !== -1;
547         });
548
549         if (lineNumber === -1) {
550             return;
551         }
552
553         this.cm.scrollIntoView({
554             line: lineNumber,
555         }, 200);
556         this.cm.focus();
557         // set the cursor location.
558         this.cm.setCursor({
559             line: lineNumber,
560             char: lines[lineNumber].length
561         })
562     }
563
564     listenForBookStackEditorEvents() {
565
566         function getContentToInsert({html, markdown}) {
567             return markdown || html;
568         }
569
570         // Replace editor content
571         window.$events.listen('editor::replace', (eventContent) => {
572             const markdown = getContentToInsert(eventContent);
573             this.cm.setValue(markdown);
574         });
575
576         // Append editor content
577         window.$events.listen('editor::append', (eventContent) => {
578             const cursorPos = this.cm.getCursor('from');
579             const markdown = getContentToInsert(eventContent);
580             const content = this.cm.getValue() + '\n' + markdown;
581             this.cm.setValue(content);
582             this.cm.setCursor(cursorPos.line, cursorPos.ch);
583         });
584
585         // Prepend editor content
586         window.$events.listen('editor::prepend', (eventContent) => {
587             const cursorPos = this.cm.getCursor('from');
588             const markdown = getContentToInsert(eventContent);
589             const content = markdown + '\n' + this.cm.getValue();
590             this.cm.setValue(content);
591             const prependLineCount = markdown.split('\n').length;
592             this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
593         });
594
595         // Insert editor content at the current location
596         window.$events.listen('editor::insert', (eventContent) => {
597             const markdown = getContentToInsert(eventContent);
598             this.cm.replaceSelection(markdown);
599         });
600
601         // Focus on editor
602         window.$events.listen('editor::focus', () => {
603             this.cm.focus();
604         });
605     }
606 }
607
608 export default MarkdownEditor ;