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