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