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