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