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