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