]> BookStack Code Mirror - bookstack/blob - resources/js/components/markdown-editor.js
New translations settings.php (Chinese Simplified)
[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
17         this.markdown = new MarkdownIt({html: true});
18         this.markdown.use(mdTasksLists, {label: true});
19
20         this.display = this.elem.querySelector('.markdown-display');
21
22         this.displayStylesLoaded = false;
23         this.input = this.elem.querySelector('textarea');
24         this.htmlInput = this.elem.querySelector('input[name=html]');
25         this.cm = code.markdownEditor(this.input);
26
27         this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
28
29         const displayLoad = () => {
30             this.displayDoc = this.display.contentDocument;
31             this.init();
32         };
33
34         if (this.display.contentDocument.readyState === 'complete') {
35             displayLoad();
36         } else {
37             this.display.addEventListener('load', displayLoad.bind(this));
38         }
39
40         window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
41             markdownIt: this.markdown,
42             displayEl: this.display,
43             codeMirrorInstance: this.cm,
44         });
45     }
46
47     init() {
48
49         let lastClick = 0;
50
51         // Prevent markdown display link click redirect
52         this.displayDoc.addEventListener('click', event => {
53             let isDblClick = Date.now() - lastClick < 300;
54
55             let link = event.target.closest('a');
56             if (link !== null) {
57                 event.preventDefault();
58                 window.open(link.getAttribute('href'));
59                 return;
60             }
61
62             let drawing = event.target.closest('[drawio-diagram]');
63             if (drawing !== null && isDblClick) {
64                 this.actionEditDrawing(drawing);
65                 return;
66             }
67
68             lastClick = Date.now();
69         });
70
71         // Button actions
72         this.elem.addEventListener('click', event => {
73             let button = event.target.closest('button[data-action]');
74             if (button === null) return;
75
76             let action = button.getAttribute('data-action');
77             if (action === 'insertImage') this.actionInsertImage();
78             if (action === 'insertLink') this.actionShowLinkSelector();
79             if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
80                 this.actionShowImageManager();
81                 return;
82             }
83             if (action === 'insertDrawing') this.actionStartDrawing();
84             if (action === 'fullscreen') this.actionFullScreen();
85         });
86
87         // Mobile section toggling
88         this.elem.addEventListener('click', event => {
89             const toolbarLabel = event.target.closest('.editor-toolbar-label');
90             if (!toolbarLabel) return;
91
92             const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
93             for (let activeElem of currentActiveSections) {
94                 activeElem.classList.remove('active');
95             }
96
97             toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
98         });
99
100         window.$events.listen('editor-markdown-update', value => {
101             this.cm.setValue(value);
102             this.updateAndRender();
103         });
104
105         this.codeMirrorSetup();
106         this.listenForBookStackEditorEvents();
107
108         // Scroll to text if needed.
109         const queryParams = (new URL(window.location)).searchParams;
110         const scrollText = queryParams.get('content-text');
111         if (scrollText) {
112             this.scrollToText(scrollText);
113         }
114     }
115
116     // Update the input content and render the display.
117     updateAndRender() {
118         const content = this.cm.getValue();
119         this.input.value = content;
120         const html = this.markdown.render(content);
121         window.$events.emit('editor-html-change', html);
122         window.$events.emit('editor-markdown-change', content);
123
124         // Set body content
125         this.displayDoc.body.className = 'page-content';
126         this.displayDoc.body.innerHTML = html;
127         this.htmlInput.value = 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', trans('errors.image_upload_error'));
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             let selectedText = this.cm.getSelection();
399             let newText = "[![" + (selectedText || image.name) + "](" + image.thumbs.display + ")](" + image.url + ")";
400             this.cm.focus();
401             this.cm.replaceSelection(newText);
402             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
403         }, 'gallery');
404     }
405
406     actionShowImageManager() {
407         const cursorPos = this.cm.getCursor('from');
408         window.ImageManager.show(image => {
409             this.insertDrawing(image, cursorPos);
410         }, 'drawio');
411     }
412
413     // Show the popup link selector and insert a link when finished
414     actionShowLinkSelector() {
415         const cursorPos = this.cm.getCursor('from');
416         window.EntitySelectorPopup.show(entity => {
417             let selectedText = this.cm.getSelection() || entity.name;
418             let newText = `[${selectedText}](${entity.link})`;
419             this.cm.focus();
420             this.cm.replaceSelection(newText);
421             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
422         });
423     }
424
425     getDrawioUrl() {
426         const drawioUrlElem = document.querySelector('[drawio-url]');
427         return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
428     }
429
430     // Show draw.io if enabled and handle save.
431     actionStartDrawing() {
432         const url = this.getDrawioUrl();
433         if (!url) return;
434
435         const cursorPos = this.cm.getCursor('from');
436
437         DrawIO.show(url,() => {
438             return Promise.resolve('');
439         }, (pngData) => {
440
441             const data = {
442                 image: pngData,
443                 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
444             };
445
446             window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
447                 this.insertDrawing(resp.data, cursorPos);
448                 DrawIO.close();
449             }).catch(err => {
450                 window.$events.emit('error', trans('errors.image_upload_error'));
451                 console.log(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(document.getElementById('page-editor').getAttribute('page-id'))
480             };
481
482             window.$http.post(window.baseUrl(`/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                 window.$events.emit('error', trans('errors.image_upload_error'));
496                 console.log(err);
497             });
498         });
499     }
500
501     // Make the editor full screen
502     actionFullScreen() {
503         const alreadyFullscreen = this.elem.classList.contains('fullscreen');
504         this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
505         document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
506     }
507
508     // Scroll to a specified text
509     scrollToText(searchText) {
510         if (!searchText) {
511             return;
512         }
513
514         const content = this.cm.getValue();
515         const lines = content.split(/\r?\n/);
516         let lineNumber = lines.findIndex(line => {
517             return line && line.indexOf(searchText) !== -1;
518         });
519
520         if (lineNumber === -1) {
521             return;
522         }
523
524         this.cm.scrollIntoView({
525             line: lineNumber,
526         }, 200);
527         this.cm.focus();
528         // set the cursor location.
529         this.cm.setCursor({
530             line: lineNumber,
531             char: lines[lineNumber].length
532         })
533     }
534
535     listenForBookStackEditorEvents() {
536
537         function getContentToInsert({html, markdown}) {
538             return markdown || html;
539         }
540
541         // Replace editor content
542         window.$events.listen('editor::replace', (eventContent) => {
543             const markdown = getContentToInsert(eventContent);
544             this.cm.setValue(markdown);
545         });
546
547         // Append editor content
548         window.$events.listen('editor::append', (eventContent) => {
549             const cursorPos = this.cm.getCursor('from');
550             const markdown = getContentToInsert(eventContent);
551             const content = this.cm.getValue() + '\n' + markdown;
552             this.cm.setValue(content);
553             this.cm.setCursor(cursorPos.line, cursorPos.ch);
554         });
555
556         // Prepend editor content
557         window.$events.listen('editor::prepend', (eventContent) => {
558             const cursorPos = this.cm.getCursor('from');
559             const markdown = getContentToInsert(eventContent);
560             const content = markdown + '\n' + this.cm.getValue();
561             this.cm.setValue(content);
562             const prependLineCount = markdown.split('\n').length;
563             this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
564         });
565
566         // Insert editor content at the current location
567         window.$events.listen('editor::insert', (eventContent) => {
568             const markdown = getContentToInsert(eventContent);
569             this.cm.replaceSelection(markdown);
570         });
571
572         // Focus on editor
573         window.$events.listen('editor::focus', () => {
574             this.cm.focus();
575         });
576     }
577 }
578
579 export default MarkdownEditor ;