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