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