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