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