]> BookStack Code Mirror - bookstack/blob - resources/js/markdown/actions.js
Ran eslint fix on existing codebase
[bookstack] / resources / js / markdown / actions.js
1 import DrawIO from '../services/drawio';
2
3 export class Actions {
4
5     /**
6      * @param {MarkdownEditor} editor
7      */
8     constructor(editor) {
9         this.editor = editor;
10         this.lastContent = {
11             html: '',
12             markdown: '',
13         };
14     }
15
16     updateAndRender() {
17         const content = this.#getText();
18         this.editor.config.inputEl.value = content;
19
20         const html = this.editor.markdown.render(content);
21         window.$events.emit('editor-html-change', '');
22         window.$events.emit('editor-markdown-change', '');
23         this.lastContent.html = html;
24         this.lastContent.markdown = content;
25         this.editor.display.patchWithHtml(html);
26     }
27
28     getContent() {
29         return this.lastContent;
30     }
31
32     showImageInsert() {
33         /** @type {ImageManager} * */
34         const imageManager = window.$components.first('image-manager');
35
36         imageManager.show(image => {
37             const imageUrl = image.thumbs.display || image.url;
38             const selectedText = this.#getSelectionText();
39             const newText = `[![${selectedText || image.name}](${imageUrl})](${image.url})`;
40             this.#replaceSelection(newText, newText.length);
41         }, 'gallery');
42     }
43
44     insertImage() {
45         const newText = `![${this.#getSelectionText()}](http://)`;
46         this.#replaceSelection(newText, newText.length - 1);
47     }
48
49     insertLink() {
50         const selectedText = this.#getSelectionText();
51         const newText = `[${selectedText}]()`;
52         const cursorPosDiff = (selectedText === '') ? -3 : -1;
53         this.#replaceSelection(newText, newText.length + cursorPosDiff);
54     }
55
56     showImageManager() {
57         const selectionRange = this.#getSelectionRange();
58         /** @type {ImageManager} * */
59         const imageManager = window.$components.first('image-manager');
60         imageManager.show(image => {
61             this.#insertDrawing(image, selectionRange);
62         }, 'drawio');
63     }
64
65     // Show the popup link selector and insert a link when finished
66     showLinkSelector() {
67         const selectionRange = this.#getSelectionRange();
68
69         /** @type {EntitySelectorPopup} * */
70         const selector = window.$components.first('entity-selector-popup');
71         selector.show(entity => {
72             const selectedText = this.#getSelectionText(selectionRange) || entity.name;
73             const newText = `[${selectedText}](${entity.link})`;
74             this.#replaceSelection(newText, newText.length, selectionRange);
75         });
76     }
77
78     // Show draw.io if enabled and handle save.
79     startDrawing() {
80         const url = this.editor.config.drawioUrl;
81         if (!url) return;
82
83         const selectionRange = this.#getSelectionRange();
84
85         DrawIO.show(url, () => Promise.resolve(''), pngData => {
86             const data = {
87                 image: pngData,
88                 uploaded_to: Number(this.editor.config.pageId),
89             };
90
91             window.$http.post('/images/drawio', data).then(resp => {
92                 this.#insertDrawing(resp.data, selectionRange);
93                 DrawIO.close();
94             }).catch(err => {
95                 this.handleDrawingUploadError(err);
96             });
97         });
98     }
99
100     #insertDrawing(image, originalSelectionRange) {
101         const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
102         this.#replaceSelection(newText, newText.length, originalSelectionRange);
103     }
104
105     // Show draw.io if enabled and handle save.
106     editDrawing(imgContainer) {
107         const {drawioUrl} = this.editor.config;
108         if (!drawioUrl) {
109             return;
110         }
111
112         const selectionRange = this.#getSelectionRange();
113         const drawingId = imgContainer.getAttribute('drawio-diagram');
114
115         DrawIO.show(drawioUrl, () => DrawIO.load(drawingId), pngData => {
116             const data = {
117                 image: pngData,
118                 uploaded_to: Number(this.editor.config.pageId),
119             };
120
121             window.$http.post('/images/drawio', data).then(resp => {
122                 const newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
123                 const newContent = this.#getText().split('\n').map(line => {
124                     if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
125                         return newText;
126                     }
127                     return line;
128                 }).join('\n');
129                 this.#setText(newContent, selectionRange);
130                 DrawIO.close();
131             }).catch(err => {
132                 this.handleDrawingUploadError(err);
133             });
134         });
135     }
136
137     handleDrawingUploadError(error) {
138         if (error.status === 413) {
139             window.$events.emit('error', this.editor.config.text.serverUploadLimit);
140         } else {
141             window.$events.emit('error', this.editor.config.text.imageUploadError);
142         }
143         console.log(error);
144     }
145
146     // Make the editor full screen
147     fullScreen() {
148         const {container} = this.editor.config;
149         const alreadyFullscreen = container.classList.contains('fullscreen');
150         container.classList.toggle('fullscreen', !alreadyFullscreen);
151         document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
152     }
153
154     // Scroll to a specified text
155     scrollToText(searchText) {
156         if (!searchText) {
157             return;
158         }
159
160         const text = this.editor.cm.state.doc;
161         let lineCount = 1;
162         let scrollToLine = -1;
163         for (const line of text.iterLines()) {
164             if (line.includes(searchText)) {
165                 scrollToLine = lineCount;
166                 break;
167             }
168             lineCount++;
169         }
170
171         if (scrollToLine === -1) {
172             return;
173         }
174
175         const line = text.line(scrollToLine);
176         this.#setSelection(line.from, line.to, true);
177         this.focus();
178     }
179
180     focus() {
181         if (!this.editor.cm.hasFocus) {
182             this.editor.cm.focus();
183         }
184     }
185
186     /**
187      * Insert content into the editor.
188      * @param {String} content
189      */
190     insertContent(content) {
191         this.#replaceSelection(content, content.length);
192     }
193
194     /**
195      * Prepend content to the editor.
196      * @param {String} content
197      */
198     prependContent(content) {
199         content = this.#cleanTextForEditor(content);
200         const selectionRange = this.#getSelectionRange();
201         const selectFrom = selectionRange.from + content.length + 1;
202         this.#dispatchChange(0, 0, `${content}\n`, selectFrom);
203         this.focus();
204     }
205
206     /**
207      * Append content to the editor.
208      * @param {String} content
209      */
210     appendContent(content) {
211         content = this.#cleanTextForEditor(content);
212         this.#dispatchChange(this.editor.cm.state.doc.length, `\n${content}`);
213         this.focus();
214     }
215
216     /**
217      * Replace the editor's contents
218      * @param {String} content
219      */
220     replaceContent(content) {
221         this.#setText(content);
222     }
223
224     /**
225      * Replace the start of the line
226      * @param {String} newStart
227      */
228     replaceLineStart(newStart) {
229         const selectionRange = this.#getSelectionRange();
230         const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
231
232         const lineContent = line.text;
233         const lineStart = lineContent.split(' ')[0];
234
235         // Remove symbol if already set
236         if (lineStart === newStart) {
237             const newLineContent = lineContent.replace(`${newStart} `, '');
238             const selectFrom = selectionRange.from + (newLineContent.length - lineContent.length);
239             this.#dispatchChange(line.from, line.to, newLineContent, selectFrom);
240             return;
241         }
242
243         let newLineContent = lineContent;
244         const alreadySymbol = /^[#>`]/.test(lineStart);
245         if (alreadySymbol) {
246             newLineContent = lineContent.replace(lineStart, newStart).trim();
247         } else if (newStart !== '') {
248             newLineContent = `${newStart} ${lineContent}`;
249         }
250
251         const selectFrom = selectionRange.from + (newLineContent.length - lineContent.length);
252         this.#dispatchChange(line.from, line.to, newLineContent, selectFrom);
253     }
254
255     /**
256      * Wrap the selection in the given contents start and end contents.
257      * @param {String} start
258      * @param {String} end
259      */
260     wrapSelection(start, end) {
261         const selectionRange = this.#getSelectionRange();
262         const selectionText = this.#getSelectionText(selectionRange);
263         if (!selectionText) return this.#wrapLine(start, end);
264
265         let newSelectionText = selectionText;
266         let newRange;
267
268         if (selectionText.startsWith(start) && selectionText.endsWith(end)) {
269             newSelectionText = selectionText.slice(start.length, selectionText.length - end.length);
270             newRange = selectionRange.extend(selectionRange.from, selectionRange.to - (start.length + end.length));
271         } else {
272             newSelectionText = `${start}${selectionText}${end}`;
273             newRange = selectionRange.extend(selectionRange.from, selectionRange.to + (start.length + end.length));
274         }
275
276         this.#dispatchChange(selectionRange.from, selectionRange.to, newSelectionText, newRange.anchor, newRange.head);
277     }
278
279     replaceLineStartForOrderedList() {
280         const selectionRange = this.#getSelectionRange();
281         const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
282         const prevLine = this.editor.cm.state.doc.line(line.number - 1);
283
284         const listMatch = prevLine.text.match(/^(\s*)(\d)([).])\s/) || [];
285
286         const number = (Number(listMatch[2]) || 0) + 1;
287         const whiteSpace = listMatch[1] || '';
288         const listMark = listMatch[3] || '.';
289
290         const prefix = `${whiteSpace}${number}${listMark}`;
291         return this.replaceLineStart(prefix);
292     }
293
294     /**
295      * Cycles through the type of callout block within the selection.
296      * Creates a callout block if none existing, and removes it if cycling past the danger type.
297      */
298     cycleCalloutTypeAtSelection() {
299         const selectionRange = this.#getSelectionRange();
300         const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
301
302         const formats = ['info', 'success', 'warning', 'danger'];
303         const joint = formats.join('|');
304         const regex = new RegExp(`class="((${joint})\\s+callout|callout\\s+(${joint}))"`, 'i');
305         const matches = regex.exec(line.text);
306         const format = (matches ? (matches[2] || matches[3]) : '').toLowerCase();
307
308         if (format === formats[formats.length - 1]) {
309             this.#wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
310         } else if (format === '') {
311             this.#wrapLine('<p class="callout info">', '</p>');
312         } else {
313             const newFormatIndex = formats.indexOf(format) + 1;
314             const newFormat = formats[newFormatIndex];
315             const newContent = line.text.replace(matches[0], matches[0].replace(format, newFormat));
316             const lineDiff = newContent.length - line.text.length;
317             this.#dispatchChange(line.from, line.to, newContent, selectionRange.anchor + lineDiff, selectionRange.head + lineDiff);
318         }
319     }
320
321     syncDisplayPosition(event) {
322         // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
323         const scrollEl = event.target;
324         const atEnd = Math.abs(scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop) < 1;
325         if (atEnd) {
326             this.editor.display.scrollToIndex(-1);
327             return;
328         }
329
330         const blockInfo = this.editor.cm.lineBlockAtHeight(scrollEl.scrollTop);
331         const range = this.editor.cm.state.sliceDoc(0, blockInfo.from);
332         const parser = new DOMParser();
333         const doc = parser.parseFromString(this.editor.markdown.render(range), 'text/html');
334         const totalLines = doc.documentElement.querySelectorAll('body > *');
335         this.editor.display.scrollToIndex(totalLines.length);
336     }
337
338     /**
339      * Fetch and insert the template of the given ID.
340      * The page-relative position provided can be used to determine insert location if possible.
341      * @param {String} templateId
342      * @param {Number} posX
343      * @param {Number} posY
344      */
345     async insertTemplate(templateId, posX, posY) {
346         const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
347         const {data} = await window.$http.get(`/templates/${templateId}`);
348         const content = data.markdown || data.html;
349         this.#dispatchChange(cursorPos, cursorPos, content, cursorPos);
350     }
351
352     /**
353      * Insert multiple images from the clipboard from an event at the provided
354      * screen coordinates (Typically form a paste event).
355      * @param {File[]} images
356      * @param {Number} posX
357      * @param {Number} posY
358      */
359     insertClipboardImages(images, posX, posY) {
360         const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
361         for (const image of images) {
362             this.uploadImage(image, cursorPos);
363         }
364     }
365
366     /**
367      * Handle image upload and add image into markdown content
368      * @param {File} file
369      * @param {?Number} position
370      */
371     async uploadImage(file, position = null) {
372         if (file === null || file.type.indexOf('image') !== 0) return;
373         let ext = 'png';
374
375         if (position === null) {
376             position = this.#getSelectionRange().from;
377         }
378
379         if (file.name) {
380             const fileNameMatches = file.name.match(/\.(.+)$/);
381             if (fileNameMatches.length > 1) ext = fileNameMatches[1];
382         }
383
384         // Insert image into markdown
385         const id = `image-${Math.random().toString(16).slice(2)}`;
386         const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
387         const placeHolderText = `![](${placeholderImage})`;
388         this.#dispatchChange(position, position, placeHolderText, position);
389
390         const remoteFilename = `image-${Date.now()}.${ext}`;
391         const formData = new FormData();
392         formData.append('file', file, remoteFilename);
393         formData.append('uploaded_to', this.editor.config.pageId);
394
395         try {
396             const {data} = await window.$http.post('/images/gallery', formData);
397             const newContent = `[![](${data.thumbs.display})](${data.url})`;
398             this.#findAndReplaceContent(placeHolderText, newContent);
399         } catch (err) {
400             window.$events.emit('error', this.editor.config.text.imageUploadError);
401             this.#findAndReplaceContent(placeHolderText, '');
402             console.log(err);
403         }
404     }
405
406     /**
407      * Get the current text of the editor instance.
408      * @return {string}
409      */
410     #getText() {
411         return this.editor.cm.state.doc.toString();
412     }
413
414     /**
415      * Set the text of the current editor instance.
416      * @param {String} text
417      * @param {?SelectionRange} selectionRange
418      */
419     #setText(text, selectionRange = null) {
420         selectionRange = selectionRange || this.#getSelectionRange();
421         this.#dispatchChange(0, this.editor.cm.state.doc.length, text, selectionRange.from);
422         this.focus();
423     }
424
425     /**
426      * Replace the current selection and focus the editor.
427      * Takes an offset for the cursor, after the change, relative to the start of the provided string.
428      * Can be provided a selection range to use instead of the current selection range.
429      * @param {String} newContent
430      * @param {Number} cursorOffset
431      * @param {?SelectionRange} selectionRange
432      */
433     #replaceSelection(newContent, cursorOffset = 0, selectionRange = null) {
434         selectionRange = selectionRange || this.editor.cm.state.selection.main;
435         this.#dispatchChange(selectionRange.from, selectionRange.to, newContent, selectionRange.from + cursorOffset);
436         this.focus();
437     }
438
439     /**
440      * Get the text content of the main current selection.
441      * @param {SelectionRange} selectionRange
442      * @return {string}
443      */
444     #getSelectionText(selectionRange = null) {
445         selectionRange = selectionRange || this.#getSelectionRange();
446         return this.editor.cm.state.sliceDoc(selectionRange.from, selectionRange.to);
447     }
448
449     /**
450      * Get the range of the current main selection.
451      * @return {SelectionRange}
452      */
453     #getSelectionRange() {
454         return this.editor.cm.state.selection.main;
455     }
456
457     /**
458      * Cleans the given text to work with the editor.
459      * Standardises line endings to what's expected.
460      * @param {String} text
461      * @return {String}
462      */
463     #cleanTextForEditor(text) {
464         return text.replace(/\r\n|\r/g, '\n');
465     }
466
467     /**
468      * Find and replace the first occurrence of [search] with [replace]
469      * @param {String} search
470      * @param {String} replace
471      */
472     #findAndReplaceContent(search, replace) {
473         const newText = this.#getText().replace(search, replace);
474         this.#setText(newText);
475     }
476
477     /**
478      * Wrap the line in the given start and end contents.
479      * @param {String} start
480      * @param {String} end
481      */
482     #wrapLine(start, end) {
483         const selectionRange = this.#getSelectionRange();
484         const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
485         const lineContent = line.text;
486         let newLineContent;
487         let lineOffset = 0;
488
489         if (lineContent.startsWith(start) && lineContent.endsWith(end)) {
490             newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
491             lineOffset = -(start.length);
492         } else {
493             newLineContent = `${start}${lineContent}${end}`;
494             lineOffset = start.length;
495         }
496
497         this.#dispatchChange(line.from, line.to, newLineContent, selectionRange.from + lineOffset);
498     }
499
500     /**
501      * Dispatch changes to the editor.
502      * @param {Number} from
503      * @param {?Number} to
504      * @param {?String} text
505      * @param {?Number} selectFrom
506      * @param {?Number} selectTo
507      */
508     #dispatchChange(from, to = null, text = null, selectFrom = null, selectTo = null) {
509         const tr = {changes: {from, to, insert: text}};
510
511         if (selectFrom) {
512             tr.selection = {anchor: selectFrom};
513         }
514
515         this.editor.cm.dispatch(tr);
516     }
517
518     /**
519      * Set the current selection range.
520      * Optionally will scroll the new range into view.
521      * @param {Number} from
522      * @param {Number} to
523      * @param {Boolean} scrollIntoView
524      */
525     #setSelection(from, to, scrollIntoView = false) {
526         this.editor.cm.dispatch({
527             selection: {anchor: from, head: to},
528             scrollIntoView,
529         });
530     }
531
532 }