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