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