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