]> BookStack Code Mirror - bookstack/blob - resources/js/components/markdown-editor.js
Added editor instance event hooks
[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 {debounce} from "../services/util";
5
6 import DrawIO from "../services/drawio";
7
8 class MarkdownEditor {
9
10     constructor(elem) {
11         this.elem = elem;
12
13         const pageEditor = document.getElementById('page-editor');
14         this.pageId = pageEditor.getAttribute('page-id');
15         this.textDirection = pageEditor.getAttribute('text-direction');
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         this.display.addEventListener('load', () => {
30             this.displayDoc = this.display.contentDocument;
31             this.init();
32         });
33
34         window.$events.emitPublic(elem, 'editor-markdown::setup', {
35             markdownIt: this.markdown,
36             displayEl: this.display,
37             codeMirrorInstance: this.cm,
38         });
39     }
40
41     init() {
42
43         let lastClick = 0;
44
45         // Prevent markdown display link click redirect
46         this.displayDoc.addEventListener('click', event => {
47             let isDblClick = Date.now() - lastClick < 300;
48
49             let link = event.target.closest('a');
50             if (link !== null) {
51                 event.preventDefault();
52                 window.open(link.getAttribute('href'));
53                 return;
54             }
55
56             let drawing = event.target.closest('[drawio-diagram]');
57             if (drawing !== null && isDblClick) {
58                 this.actionEditDrawing(drawing);
59                 return;
60             }
61
62             lastClick = Date.now();
63         });
64
65         // Button actions
66         this.elem.addEventListener('click', event => {
67             let button = event.target.closest('button[data-action]');
68             if (button === null) return;
69
70             let action = button.getAttribute('data-action');
71             if (action === 'insertImage') this.actionInsertImage();
72             if (action === 'insertLink') this.actionShowLinkSelector();
73             if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
74                 this.actionShowImageManager();
75                 return;
76             }
77             if (action === 'insertDrawing') this.actionStartDrawing();
78         });
79
80         // Mobile section toggling
81         this.elem.addEventListener('click', event => {
82             const toolbarLabel = event.target.closest('.editor-toolbar-label');
83             if (!toolbarLabel) return;
84
85             const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
86             for (let activeElem of currentActiveSections) {
87                 activeElem.classList.remove('active');
88             }
89
90             toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
91         });
92
93         window.$events.listen('editor-markdown-update', value => {
94             this.cm.setValue(value);
95             this.updateAndRender();
96         });
97
98         this.codeMirrorSetup();
99         this.listenForBookStackEditorEvents();
100
101         // Scroll to text if needed.
102         const queryParams = (new URL(window.location)).searchParams;
103         const scrollText = queryParams.get('content-text');
104         if (scrollText) {
105             this.scrollToText(scrollText);
106         }
107     }
108
109     // Update the input content and render the display.
110     updateAndRender() {
111         const content = this.cm.getValue();
112         this.input.value = content;
113         const html = this.markdown.render(content);
114         window.$events.emit('editor-html-change', html);
115         window.$events.emit('editor-markdown-change', content);
116
117         // Set body content
118         this.displayDoc.body.className = 'page-content';
119         this.displayDoc.body.innerHTML = html;
120         this.htmlInput.value = html;
121
122         // Copy styles from page head and set custom styles for editor
123         this.loadStylesIntoDisplay();
124     }
125
126     loadStylesIntoDisplay() {
127         if (this.displayStylesLoaded) return;
128         this.displayDoc.documentElement.className = 'markdown-editor-display';
129
130         this.displayDoc.head.innerHTML = '';
131         const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
132         for (let style of styles) {
133             const copy = style.cloneNode(true);
134             this.displayDoc.head.appendChild(copy);
135         }
136
137         this.displayStylesLoaded = true;
138     }
139
140     onMarkdownScroll(lineCount) {
141         const elems = this.displayDoc.body.children;
142         if (elems.length <= lineCount) return;
143
144         const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
145         topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
146     }
147
148     codeMirrorSetup() {
149         const cm = this.cm;
150         const context = this;
151
152         // Text direction
153         // cm.setOption('direction', this.textDirection);
154         cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
155         // Custom key commands
156         let metaKey = code.getMetaKey();
157         const extraKeys = {};
158         // Insert Image shortcut
159         extraKeys[`${metaKey}-Alt-I`] = function(cm) {
160             let selectedText = cm.getSelection();
161             let newText = `![${selectedText}](http://)`;
162             let cursorPos = cm.getCursor('from');
163             cm.replaceSelection(newText);
164             cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
165         };
166         // Save draft
167         extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
168         // Save page
169         extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
170         // Show link selector
171         extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
172         // Insert Link
173         extraKeys[`${metaKey}-K`] = cm => {insertLink()};
174         // FormatShortcuts
175         extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
176         extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
177         extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
178         extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
179         extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
180         extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
181         extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
182         extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
183         extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
184         extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
185         extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
186         extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
187         cm.setOption('extraKeys', extraKeys);
188
189         // Update data on content change
190         cm.on('change', (instance, changeObj) => {
191             this.updateAndRender();
192         });
193
194         const onScrollDebounced = debounce((instance) => {
195             // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
196             let scroll = instance.getScrollInfo();
197             let atEnd = scroll.top + scroll.clientHeight === scroll.height;
198             if (atEnd) {
199                 this.onMarkdownScroll(-1);
200                 return;
201             }
202
203             let lineNum = instance.lineAtHeight(scroll.top, 'local');
204             let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
205             let parser = new DOMParser();
206             let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
207             let totalLines = doc.documentElement.querySelectorAll('body > *');
208             this.onMarkdownScroll(totalLines.length);
209         }, 100);
210
211         // Handle scroll to sync display view
212         cm.on('scroll', instance => {
213             onScrollDebounced(instance);
214         });
215
216         // Handle image paste
217         cm.on('paste', (cm, event) => {
218             const clipboardItems = event.clipboardData.items;
219             if (!event.clipboardData || !clipboardItems) return;
220
221             // Don't handle if clipboard includes text content
222             for (let clipboardItem of clipboardItems) {
223                 if (clipboardItem.type.includes('text/')) {
224                     return;
225                 }
226             }
227
228             for (let clipboardItem of clipboardItems) {
229                 if (clipboardItem.type.includes("image")) {
230                     uploadImage(clipboardItem.getAsFile());
231                 }
232             }
233         });
234
235         // Handle image & content drag n drop
236         cm.on('drop', (cm, event) => {
237
238             const templateId = event.dataTransfer.getData('bookstack/template');
239             if (templateId) {
240                 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
241                 cm.setCursor(cursorPos);
242                 event.preventDefault();
243                 window.$http.get(`/templates/${templateId}`).then(resp => {
244                     const content = resp.data.markdown || resp.data.html;
245                     cm.replaceSelection(content);
246                 });
247             }
248
249             if (event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files.length > 0) {
250                 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
251                 cm.setCursor(cursorPos);
252                 event.stopPropagation();
253                 event.preventDefault();
254                 for (let i = 0; i < event.dataTransfer.files.length; i++) {
255                     uploadImage(event.dataTransfer.files[i]);
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     // Show draw.io if enabled and handle save.
415     actionStartDrawing() {
416         if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
417         let cursorPos = this.cm.getCursor('from');
418
419         DrawIO.show(() => {
420             return Promise.resolve('');
421         }, (pngData) => {
422             // let id = "image-" + Math.random().toString(16).slice(2);
423             // let loadingImage = window.baseUrl('/loading.gif');
424             let data = {
425                 image: pngData,
426                 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
427             };
428
429             window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
430                 this.insertDrawing(resp.data, cursorPos);
431                 DrawIO.close();
432             }).catch(err => {
433                 window.$events.emit('error', trans('errors.image_upload_error'));
434                 console.log(err);
435             });
436         });
437     }
438
439     insertDrawing(image, originalCursor) {
440         const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
441         this.cm.focus();
442         this.cm.replaceSelection(newText);
443         this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
444     }
445
446     // Show draw.io if enabled and handle save.
447     actionEditDrawing(imgContainer) {
448         const drawingDisabled = document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true';
449         if (drawingDisabled) {
450             return;
451         }
452
453         const cursorPos = this.cm.getCursor('from');
454         const drawingId = imgContainer.getAttribute('drawio-diagram');
455
456         DrawIO.show(() => {
457             return DrawIO.load(drawingId);
458         }, (pngData) => {
459
460             let data = {
461                 image: pngData,
462                 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
463             };
464
465             window.$http.post(window.baseUrl(`/images/drawio`), data).then(resp => {
466                 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
467                 let newContent = this.cm.getValue().split('\n').map(line => {
468                     if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
469                         return newText;
470                     }
471                     return line;
472                 }).join('\n');
473                 this.cm.setValue(newContent);
474                 this.cm.setCursor(cursorPos);
475                 this.cm.focus();
476                 DrawIO.close();
477             }).catch(err => {
478                 window.$events.emit('error', trans('errors.image_upload_error'));
479                 console.log(err);
480             });
481         });
482     }
483
484     // Scroll to a specified text
485     scrollToText(searchText) {
486         if (!searchText) {
487             return;
488         }
489
490         const content = this.cm.getValue();
491         const lines = content.split(/\r?\n/);
492         let lineNumber = lines.findIndex(line => {
493             return line && line.indexOf(searchText) !== -1;
494         });
495
496         if (lineNumber === -1) {
497             return;
498         }
499
500         this.cm.scrollIntoView({
501             line: lineNumber,
502         }, 200);
503         this.cm.focus();
504         // set the cursor location.
505         this.cm.setCursor({
506             line: lineNumber,
507             char: lines[lineNumber].length
508         })
509     }
510
511     listenForBookStackEditorEvents() {
512
513         function getContentToInsert({html, markdown}) {
514             return markdown || html;
515         }
516
517         // Replace editor content
518         window.$events.listen('editor::replace', (eventContent) => {
519             const markdown = getContentToInsert(eventContent);
520             this.cm.setValue(markdown);
521         });
522
523         // Append editor content
524         window.$events.listen('editor::append', (eventContent) => {
525             const cursorPos = this.cm.getCursor('from');
526             const markdown = getContentToInsert(eventContent);
527             const content = this.cm.getValue() + '\n' + markdown;
528             this.cm.setValue(content);
529             this.cm.setCursor(cursorPos.line, cursorPos.ch);
530         });
531
532         // Prepend editor content
533         window.$events.listen('editor::prepend', (eventContent) => {
534             const cursorPos = this.cm.getCursor('from');
535             const markdown = getContentToInsert(eventContent);
536             const content = markdown + '\n' + this.cm.getValue();
537             this.cm.setValue(content);
538             const prependLineCount = markdown.split('\n').length;
539             this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
540         });
541     }
542 }
543
544 export default MarkdownEditor ;