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