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