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