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