]> BookStack Code Mirror - bookstack/blob - resources/assets/js/components/markdown-editor.js
Merge branch 'fix/registraion-form-validation' of git://github.com/cw1998/BookStack...
[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             if (!event.clipboardData || !event.clipboardData.items) return;
184             for (let i = 0; i < event.clipboardData.items.length; i++) {
185                 uploadImage(event.clipboardData.items[i].getAsFile());
186             }
187         });
188
189         // Handle images on drag-drop
190         cm.on('drop', (cm, event) => {
191             event.stopPropagation();
192             event.preventDefault();
193             let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
194             cm.setCursor(cursorPos);
195             if (!event.dataTransfer || !event.dataTransfer.files) return;
196             for (let i = 0; i < event.dataTransfer.files.length; i++) {
197                 uploadImage(event.dataTransfer.files[i]);
198             }
199         });
200
201         // Helper to replace editor content
202         function replaceContent(search, replace) {
203             let text = cm.getValue();
204             let cursor = cm.listSelections();
205             cm.setValue(text.replace(search, replace));
206             cm.setSelections(cursor);
207         }
208
209         // Helper to replace the start of the line
210         function replaceLineStart(newStart) {
211             let cursor = cm.getCursor();
212             let lineContent = cm.getLine(cursor.line);
213             let lineLen = lineContent.length;
214             let lineStart = lineContent.split(' ')[0];
215
216             // Remove symbol if already set
217             if (lineStart === newStart) {
218                 lineContent = lineContent.replace(`${newStart} `, '');
219                 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
220                 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
221                 return;
222             }
223
224             let alreadySymbol = /^[#>`]/.test(lineStart);
225             let posDif = 0;
226             if (alreadySymbol) {
227                 posDif = newStart.length - lineStart.length;
228                 lineContent = lineContent.replace(lineStart, newStart).trim();
229             } else if (newStart !== '') {
230                 posDif = newStart.length + 1;
231                 lineContent = newStart + ' ' + lineContent;
232             }
233             cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
234             cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
235         }
236
237         function wrapLine(start, end) {
238             let cursor = cm.getCursor();
239             let lineContent = cm.getLine(cursor.line);
240             let lineLen = lineContent.length;
241             let newLineContent = lineContent;
242
243             if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
244                 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
245             } else {
246                 newLineContent = `${start}${lineContent}${end}`;
247             }
248
249             cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
250             cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
251         }
252
253         function wrapSelection(start, end) {
254             let selection = cm.getSelection();
255             if (selection === '') return wrapLine(start, end);
256
257             let newSelection = selection;
258             let frontDiff = 0;
259             let endDiff = 0;
260
261             if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
262                 newSelection = selection.slice(start.length, selection.length - end.length);
263                 endDiff = -(end.length + start.length);
264             } else {
265                 newSelection = `${start}${selection}${end}`;
266                 endDiff = start.length + end.length;
267             }
268
269             let selections = cm.listSelections()[0];
270             cm.replaceSelection(newSelection);
271             let headFirst = selections.head.ch <= selections.anchor.ch;
272             selections.head.ch += headFirst ? frontDiff : endDiff;
273             selections.anchor.ch += headFirst ? endDiff : frontDiff;
274             cm.setSelections([selections]);
275         }
276
277         // Handle image upload and add image into markdown content
278         function uploadImage(file) {
279             if (file === null || file.type.indexOf('image') !== 0) return;
280             let ext = 'png';
281
282             if (file.name) {
283                 let fileNameMatches = file.name.match(/\.(.+)$/);
284                 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
285             }
286
287             // Insert image into markdown
288             const id = "image-" + Math.random().toString(16).slice(2);
289             const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
290             const selectedText = cm.getSelection();
291             const placeHolderText = `![${selectedText}](${placeholderImage})`;
292             const cursor = cm.getCursor();
293             cm.replaceSelection(placeHolderText);
294             cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
295
296             const remoteFilename = "image-" + Date.now() + "." + ext;
297             const formData = new FormData();
298             formData.append('file', file, remoteFilename);
299             formData.append('uploaded_to', context.pageId);
300
301             window.$http.post('/images/gallery/upload', formData).then(resp => {
302                 const newContent = `[![${selectedText}](${resp.data.thumbs.display})](${resp.data.url})`;
303                 replaceContent(placeHolderText, newContent);
304             }).catch(err => {
305                 window.$events.emit('error', trans('errors.image_upload_error'));
306                 replaceContent(placeHolderText, selectedText);
307                 console.log(err);
308             });
309         }
310
311         function insertLink() {
312             let cursorPos = cm.getCursor('from');
313             let selectedText = cm.getSelection() || '';
314             let newText = `[${selectedText}]()`;
315             cm.focus();
316             cm.replaceSelection(newText);
317             let cursorPosDiff = (selectedText === '') ? -3 : -1;
318             cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
319         }
320
321        this.updateAndRender();
322     }
323
324     actionInsertImage() {
325         const cursorPos = this.cm.getCursor('from');
326         window.ImageManager.show(image => {
327             let selectedText = this.cm.getSelection();
328             let newText = "[![" + (selectedText || image.name) + "](" + image.thumbs.display + ")](" + image.url + ")";
329             this.cm.focus();
330             this.cm.replaceSelection(newText);
331             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
332         }, 'gallery');
333     }
334
335     actionShowImageManager() {
336         const cursorPos = this.cm.getCursor('from');
337         window.ImageManager.show(image => {
338             this.insertDrawing(image, cursorPos);
339         }, 'drawio');
340     }
341
342     // Show the popup link selector and insert a link when finished
343     actionShowLinkSelector() {
344         const cursorPos = this.cm.getCursor('from');
345         window.EntitySelectorPopup.show(entity => {
346             let selectedText = this.cm.getSelection() || entity.name;
347             let newText = `[${selectedText}](${entity.link})`;
348             this.cm.focus();
349             this.cm.replaceSelection(newText);
350             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
351         });
352     }
353
354     // Show draw.io if enabled and handle save.
355     actionStartDrawing() {
356         if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
357         let cursorPos = this.cm.getCursor('from');
358
359         DrawIO.show(() => {
360             return Promise.resolve('');
361         }, (pngData) => {
362             // let id = "image-" + Math.random().toString(16).slice(2);
363             // let loadingImage = window.baseUrl('/loading.gif');
364             let data = {
365                 image: pngData,
366                 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
367             };
368
369             window.$http.post(window.baseUrl('/images/drawing/upload'), data).then(resp => {
370                 this.insertDrawing(resp.data, cursorPos);
371                 DrawIO.close();
372             }).catch(err => {
373                 window.$events.emit('error', trans('errors.image_upload_error'));
374                 console.log(err);
375             });
376         });
377     }
378
379     insertDrawing(image, originalCursor) {
380         const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
381         this.cm.focus();
382         this.cm.replaceSelection(newText);
383         this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
384     }
385
386     // Show draw.io if enabled and handle save.
387     actionEditDrawing(imgContainer) {
388         const drawingDisabled = document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true';
389         if (drawingDisabled) {
390             return;
391         }
392
393         const cursorPos = this.cm.getCursor('from');
394         const drawingId = imgContainer.getAttribute('drawio-diagram');
395
396         DrawIO.show(() => {
397             return window.$http.get(window.baseUrl(`/images/base64/${drawingId}`)).then(resp => {
398                 return `data:image/png;base64,${resp.data.content}`;
399             });
400         }, (pngData) => {
401
402             let data = {
403                 image: pngData,
404                 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
405             };
406
407             window.$http.post(window.baseUrl(`/images/drawing/upload`), data).then(resp => {
408                 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
409                 let newContent = this.cm.getValue().split('\n').map(line => {
410                     if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
411                         return newText;
412                     }
413                     return line;
414                 }).join('\n');
415                 this.cm.setValue(newContent);
416                 this.cm.setCursor(cursorPos);
417                 this.cm.focus();
418                 DrawIO.close();
419             }).catch(err => {
420                 window.$events.emit('error', trans('errors.image_upload_error'));
421                 console.log(err);
422             });
423         });
424     }
425
426     // Scroll to a specified text
427     scrollToText(searchText) {
428         if (!searchText) {
429             return;
430         }
431
432         const content = this.cm.getValue();
433         const lines = content.split(/\r?\n/);
434         let lineNumber = lines.findIndex(line => {
435             return line && line.indexOf(searchText) !== -1;
436         });
437
438         if (lineNumber === -1) {
439             return;
440         }
441
442         this.cm.scrollIntoView({
443             line: lineNumber,
444         }, 200);
445         this.cm.focus();
446         // set the cursor location.
447         this.cm.setCursor({
448             line: lineNumber,
449             char: lines[lineNumber].length
450         })
451     }
452
453 }
454
455 export default MarkdownEditor ;