]> BookStack Code Mirror - bookstack/blob - resources/assets/js/components/markdown-editor.js
Extracted draw.io functionality to own file
[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('../libs/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         // Save page
88         extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
89         // Show link selector
90         extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
91         // Insert Link
92         extraKeys[`${metaKey}-K`] = cm => {insertLink()};
93         // FormatShortcuts
94         extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
95         extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
96         extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
97         extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
98         extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
99         extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
100         extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
101         extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
102         extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
103         extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
104         extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
105         extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
106         cm.setOption('extraKeys', extraKeys);
107
108         // Update data on content change
109         cm.on('change', (instance, changeObj) => {
110             this.updateAndRender();
111         });
112
113         // Handle scroll to sync display view
114         cm.on('scroll', instance => {
115             // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
116             let scroll = instance.getScrollInfo();
117             let atEnd = scroll.top + scroll.clientHeight === scroll.height;
118             if (atEnd) {
119                 this.onMarkdownScroll(-1);
120                 return;
121             }
122
123             let lineNum = instance.lineAtHeight(scroll.top, 'local');
124             let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
125             let parser = new DOMParser();
126             let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
127             let totalLines = doc.documentElement.querySelectorAll('body > *');
128             this.onMarkdownScroll(totalLines.length);
129         });
130
131         // Handle image paste
132         cm.on('paste', (cm, event) => {
133             if (!event.clipboardData || !event.clipboardData.items) return;
134             for (let i = 0; i < event.clipboardData.items.length; i++) {
135                 uploadImage(event.clipboardData.items[i].getAsFile());
136             }
137         });
138
139         // Handle images on drag-drop
140         cm.on('drop', (cm, event) => {
141             event.stopPropagation();
142             event.preventDefault();
143             let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
144             cm.setCursor(cursorPos);
145             if (!event.dataTransfer || !event.dataTransfer.files) return;
146             for (let i = 0; i < event.dataTransfer.files.length; i++) {
147                 uploadImage(event.dataTransfer.files[i]);
148             }
149         });
150
151         // Helper to replace editor content
152         function replaceContent(search, replace) {
153             let text = cm.getValue();
154             let cursor = cm.listSelections();
155             cm.setValue(text.replace(search, replace));
156             cm.setSelections(cursor);
157         }
158
159         // Helper to replace the start of the line
160         function replaceLineStart(newStart) {
161             let cursor = cm.getCursor();
162             let lineContent = cm.getLine(cursor.line);
163             let lineLen = lineContent.length;
164             let lineStart = lineContent.split(' ')[0];
165
166             // Remove symbol if already set
167             if (lineStart === newStart) {
168                 lineContent = lineContent.replace(`${newStart} `, '');
169                 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
170                 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
171                 return;
172             }
173
174             let alreadySymbol = /^[#>`]/.test(lineStart);
175             let posDif = 0;
176             if (alreadySymbol) {
177                 posDif = newStart.length - lineStart.length;
178                 lineContent = lineContent.replace(lineStart, newStart).trim();
179             } else if (newStart !== '') {
180                 posDif = newStart.length + 1;
181                 lineContent = newStart + ' ' + lineContent;
182             }
183             cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
184             cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
185         }
186
187         function wrapLine(start, end) {
188             let cursor = cm.getCursor();
189             let lineContent = cm.getLine(cursor.line);
190             let lineLen = lineContent.length;
191             let newLineContent = lineContent;
192
193             if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
194                 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
195             } else {
196                 newLineContent = `${start}${lineContent}${end}`;
197             }
198
199             cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
200             cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
201         }
202
203         function wrapSelection(start, end) {
204             let selection = cm.getSelection();
205             if (selection === '') return wrapLine(start, end);
206
207             let newSelection = selection;
208             let frontDiff = 0;
209             let endDiff = 0;
210
211             if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
212                 newSelection = selection.slice(start.length, selection.length - end.length);
213                 endDiff = -(end.length + start.length);
214             } else {
215                 newSelection = `${start}${selection}${end}`;
216                 endDiff = start.length + end.length;
217             }
218
219             let selections = cm.listSelections()[0];
220             cm.replaceSelection(newSelection);
221             let headFirst = selections.head.ch <= selections.anchor.ch;
222             selections.head.ch += headFirst ? frontDiff : endDiff;
223             selections.anchor.ch += headFirst ? endDiff : frontDiff;
224             cm.setSelections([selections]);
225         }
226
227         // Handle image upload and add image into markdown content
228         function uploadImage(file) {
229             if (file === null || file.type.indexOf('image') !== 0) return;
230             let ext = 'png';
231
232             if (file.name) {
233                 let fileNameMatches = file.name.match(/\.(.+)$/);
234                 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
235             }
236
237             // Insert image into markdown
238             let id = "image-" + Math.random().toString(16).slice(2);
239             let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
240             let selectedText = cm.getSelection();
241             let placeHolderText = `![${selectedText}](${placeholderImage})`;
242             cm.replaceSelection(placeHolderText);
243
244             let remoteFilename = "image-" + Date.now() + "." + ext;
245             let formData = new FormData();
246             formData.append('file', file, remoteFilename);
247
248             window.$http.post('/images/gallery/upload', formData).then(resp => {
249                 replaceContent(placeholderImage, resp.data.thumbs.display);
250             }).catch(err => {
251                 events.emit('error', trans('errors.image_upload_error'));
252                 replaceContent(placeHolderText, selectedText);
253                 console.log(err);
254             });
255         }
256
257         function insertLink() {
258             let cursorPos = cm.getCursor('from');
259             let selectedText = cm.getSelection() || '';
260             let newText = `[${selectedText}]()`;
261             cm.focus();
262             cm.replaceSelection(newText);
263             let cursorPosDiff = (selectedText === '') ? -3 : -1;
264             cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
265         }
266
267        this.updateAndRender();
268     }
269
270     actionInsertImage() {
271         let cursorPos = this.cm.getCursor('from');
272         window.ImageManager.show(image => {
273             let selectedText = this.cm.getSelection();
274             let newText = "![" + (selectedText || image.name) + "](" + image.thumbs.display + ")";
275             this.cm.focus();
276             this.cm.replaceSelection(newText);
277             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
278         });
279     }
280
281     // Show the popup link selector and insert a link when finished
282     actionShowLinkSelector() {
283         let cursorPos = this.cm.getCursor('from');
284         window.EntitySelectorPopup.show(entity => {
285             let selectedText = this.cm.getSelection() || entity.name;
286             let newText = `[${selectedText}](${entity.link})`;
287             this.cm.focus();
288             this.cm.replaceSelection(newText);
289             this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
290         });
291     }
292
293 }
294
295 module.exports = MarkdownEditor ;