]> BookStack Code Mirror - bookstack/blob - resources/assets/js/components/markdown-editor.js
Merge pull request #528 from turbotankist/master
[bookstack] / resources / assets / js / components / markdown-editor.js
1 const MarkdownIt = require("markdown-it");
2 const mdTasksLists = require('markdown-it-task-lists');
3 const code = require('../code');
4
5 class MarkdownEditor {
6
7     constructor(elem) {
8         this.elem = elem;
9         this.markdown = new MarkdownIt({html: true});
10         this.markdown.use(mdTasksLists, {label: true});
11
12         this.display = this.elem.querySelector('.markdown-display');
13         this.input = this.elem.querySelector('textarea');
14         this.htmlInput = this.elem.querySelector('input[name=html]');
15         this.cm = code.markdownEditor(this.input);
16
17         this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
18         this.init();
19     }
20
21     init() {
22
23         // Prevent markdown display link click redirect
24         this.display.addEventListener('click', event => {
25             let link = event.target.closest('a');
26             if (link === null) return;
27
28             event.preventDefault();
29             window.open(link.getAttribute('href'));
30         });
31
32         // Button actions
33         this.elem.addEventListener('click', event => {
34             let button = event.target.closest('button[data-action]');
35             if (button === null) return;
36
37             let action = button.getAttribute('data-action');
38             if (action === 'insertImage') this.actionInsertImage();
39             if (action === 'insertLink') this.actionShowLinkSelector();
40         });
41
42         window.$events.listen('editor-markdown-update', value => {
43             this.cm.setValue(value);
44             this.updateAndRender();
45         });
46
47         this.codeMirrorSetup();
48     }
49
50     // Update the input content and render the display.
51     updateAndRender() {
52         let content = this.cm.getValue();
53         this.input.value = content;
54         let html = this.markdown.render(content);
55         window.$events.emit('editor-html-change', html);
56         window.$events.emit('editor-markdown-change', content);
57         this.display.innerHTML = html;
58         this.htmlInput.value = html;
59     }
60
61     onMarkdownScroll(lineCount) {
62         let elems = this.display.children;
63         if (elems.length <= lineCount) return;
64
65         let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
66         // TODO - Replace jQuery
67         $(this.display).animate({
68             scrollTop: topElem.offsetTop
69         }, {queue: false, duration: 200, easing: 'linear'});
70     }
71
72     codeMirrorSetup() {
73         let cm = this.cm;
74         // Custom key commands
75         let metaKey = code.getMetaKey();
76         const extraKeys = {};
77         // Insert Image shortcut
78         extraKeys[`${metaKey}-Alt-I`] = function(cm) {
79             let selectedText = cm.getSelection();
80             let newText = `![${selectedText}](http://)`;
81             let cursorPos = cm.getCursor('from');
82             cm.replaceSelection(newText);
83             cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
84         };
85         // Save draft
86         extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
87         // Show link selector
88         extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
89         // Insert Link
90         extraKeys[`${metaKey}-K`] = cm => {insertLink()};
91         // FormatShortcuts
92         extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
93         extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
94         extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
95         extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
96         extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
97         extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
98         extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
99         extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
100         extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
101         extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
102         extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
103         extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
104         cm.setOption('extraKeys', extraKeys);
105
106         // Update data on content change
107         cm.on('change', (instance, changeObj) => {
108             this.updateAndRender();
109         });
110
111         // Handle scroll to sync display view
112         cm.on('scroll', instance => {
113             // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
114             let scroll = instance.getScrollInfo();
115             let atEnd = scroll.top + scroll.clientHeight === scroll.height;
116             if (atEnd) {
117                 this.onMarkdownScroll(-1);
118                 return;
119             }
120
121             let lineNum = instance.lineAtHeight(scroll.top, 'local');
122             let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
123             let parser = new DOMParser();
124             let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
125             let totalLines = doc.documentElement.querySelectorAll('body > *');
126             this.onMarkdownScroll(totalLines.length);
127         });
128
129         // Handle image paste
130         cm.on('paste', (cm, event) => {
131             if (!event.clipboardData || !event.clipboardData.items) return;
132             for (let i = 0; i < event.clipboardData.items.length; i++) {
133                 uploadImage(event.clipboardData.items[i].getAsFile());
134             }
135         });
136
137         // Handle images on drag-drop
138         cm.on('drop', (cm, event) => {
139             event.stopPropagation();
140             event.preventDefault();
141             let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
142             cm.setCursor(cursorPos);
143             if (!event.dataTransfer || !event.dataTransfer.files) return;
144             for (let i = 0; i < event.dataTransfer.files.length; i++) {
145                 uploadImage(event.dataTransfer.files[i]);
146             }
147         });
148
149         // Helper to replace editor content
150         function replaceContent(search, replace) {
151             let text = cm.getValue();
152             let cursor = cm.listSelections();
153             cm.setValue(text.replace(search, replace));
154             cm.setSelections(cursor);
155         }
156
157         // Helper to replace the start of the line
158         function replaceLineStart(newStart) {
159             let cursor = cm.getCursor();
160             let lineContent = cm.getLine(cursor.line);
161             let lineLen = lineContent.length;
162             let lineStart = lineContent.split(' ')[0];
163
164             // Remove symbol if already set
165             if (lineStart === newStart) {
166                 lineContent = lineContent.replace(`${newStart} `, '');
167                 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
168                 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
169                 return;
170             }
171
172             let alreadySymbol = /^[#>`]/.test(lineStart);
173             let posDif = 0;
174             if (alreadySymbol) {
175                 posDif = newStart.length - lineStart.length;
176                 lineContent = lineContent.replace(lineStart, newStart).trim();
177             } else if (newStart !== '') {
178                 posDif = newStart.length + 1;
179                 lineContent = newStart + ' ' + lineContent;
180             }
181             cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
182             cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
183         }
184
185         function wrapLine(start, end) {
186             let cursor = cm.getCursor();
187             let lineContent = cm.getLine(cursor.line);
188             let lineLen = lineContent.length;
189             let newLineContent = lineContent;
190
191             if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
192                 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
193             } else {
194                 newLineContent = `${start}${lineContent}${end}`;
195             }
196
197             cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
198             cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
199         }
200
201         function wrapSelection(start, end) {
202             let selection = cm.getSelection();
203             if (selection === '') return wrapLine(start, end);
204
205             let newSelection = selection;
206             let frontDiff = 0;
207             let endDiff = 0;
208
209             if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
210                 newSelection = selection.slice(start.length, selection.length - end.length);
211                 endDiff = -(end.length + start.length);
212             } else {
213                 newSelection = `${start}${selection}${end}`;
214                 endDiff = start.length + end.length;
215             }
216
217             let selections = cm.listSelections()[0];
218             cm.replaceSelection(newSelection);
219             let headFirst = selections.head.ch <= selections.anchor.ch;
220             selections.head.ch += headFirst ? frontDiff : endDiff;
221             selections.anchor.ch += headFirst ? endDiff : frontDiff;
222             cm.setSelections([selections]);
223         }
224
225         // Handle image upload and add image into markdown content
226         function uploadImage(file) {
227             if (file === null || file.type.indexOf('image') !== 0) return;
228             let ext = 'png';
229
230             if (file.name) {
231                 let fileNameMatches = file.name.match(/\.(.+)$/);
232                 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
233             }
234
235             // Insert image into markdown
236             let id = "image-" + Math.random().toString(16).slice(2);
237             let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
238             let selectedText = cm.getSelection();
239             let placeHolderText = `![${selectedText}](${placeholderImage})`;
240             cm.replaceSelection(placeHolderText);
241
242             let remoteFilename = "image-" + Date.now() + "." + ext;
243             let formData = new FormData();
244             formData.append('file', file, remoteFilename);
245
246             window.$http.post('/images/gallery/upload', formData).then(resp => {
247                 replaceContent(placeholderImage, resp.data.thumbs.display);
248             }).catch(err => {
249                 events.emit('error', trans('errors.image_upload_error'));
250                 replaceContent(placeHolderText, selectedText);
251                 console.log(err);
252             });
253         }
254
255         function insertLink() {
256             let cursorPos = cm.getCursor('from');
257             let selectedText = cm.getSelection() || '';
258             let newText = `[${selectedText}]()`;
259             cm.focus();
260             cm.replaceSelection(newText);
261             let cursorPosDiff = (selectedText === '') ? -3 : -1;
262             cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
263         }
264
265        this.updateAndRender();
266     }
267
268     actionInsertImage() {
269         let cursorPos = this.cm.getCursor('from');
270         window.ImageManager.show(image => {
271             let selectedText = this.cm.getSelection();
272             let newText = "![" + (selectedText || image.name) + "](" + image.thumbs.display + ")";
273             this.cm.focus();
274             this.cm.replaceSelection(newText);
275             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
276         });
277     }
278
279     // Show the popup link selector and insert a link when finished
280     actionShowLinkSelector() {
281         let cursorPos = this.cm.getCursor('from');
282         window.EntitySelectorPopup.show(entity => {
283             let selectedText = this.cm.getSelection() || entity.name;
284             let newText = `[${selectedText}](${entity.link})`;
285             this.cm.focus();
286             this.cm.replaceSelection(newText);
287             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
288         });
289     }
290
291 }
292
293 module.exports = MarkdownEditor ;