]> BookStack Code Mirror - bookstack/blob - resources/js/markdown/actions.js
Merge branch 'feature/mail-verify-peer' into development
[bookstack] / resources / js / markdown / actions.js
1 import * as 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.error(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 += 1;
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 selectRange = this.#getSelectionRange();
262         const selectionText = this.#getSelectionText(selectRange);
263         if (!selectionText) {
264             this.#wrapLine(start, end);
265             return;
266         }
267
268         let newSelectionText = selectionText;
269         let newRange;
270
271         if (selectionText.startsWith(start) && selectionText.endsWith(end)) {
272             newSelectionText = selectionText.slice(start.length, selectionText.length - end.length);
273             newRange = selectRange.extend(selectRange.from, selectRange.to - (start.length + end.length));
274         } else {
275             newSelectionText = `${start}${selectionText}${end}`;
276             newRange = selectRange.extend(selectRange.from, selectRange.to + (start.length + end.length));
277         }
278
279         this.#dispatchChange(
280             selectRange.from,
281             selectRange.to,
282             newSelectionText,
283             newRange.anchor,
284             newRange.head,
285         );
286     }
287
288     replaceLineStartForOrderedList() {
289         const selectionRange = this.#getSelectionRange();
290         const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
291         const prevLine = this.editor.cm.state.doc.line(line.number - 1);
292
293         const listMatch = prevLine.text.match(/^(\s*)(\d)([).])\s/) || [];
294
295         const number = (Number(listMatch[2]) || 0) + 1;
296         const whiteSpace = listMatch[1] || '';
297         const listMark = listMatch[3] || '.';
298
299         const prefix = `${whiteSpace}${number}${listMark}`;
300         return this.replaceLineStart(prefix);
301     }
302
303     /**
304      * Cycles through the type of callout block within the selection.
305      * Creates a callout block if none existing, and removes it if cycling past the danger type.
306      */
307     cycleCalloutTypeAtSelection() {
308         const selectionRange = this.#getSelectionRange();
309         const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
310
311         const formats = ['info', 'success', 'warning', 'danger'];
312         const joint = formats.join('|');
313         const regex = new RegExp(`class="((${joint})\\s+callout|callout\\s+(${joint}))"`, 'i');
314         const matches = regex.exec(line.text);
315         const format = (matches ? (matches[2] || matches[3]) : '').toLowerCase();
316
317         if (format === formats[formats.length - 1]) {
318             this.#wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
319         } else if (format === '') {
320             this.#wrapLine('<p class="callout info">', '</p>');
321         } else {
322             const newFormatIndex = formats.indexOf(format) + 1;
323             const newFormat = formats[newFormatIndex];
324             const newContent = line.text.replace(matches[0], matches[0].replace(format, newFormat));
325             const lineDiff = newContent.length - line.text.length;
326             this.#dispatchChange(
327                 line.from,
328                 line.to,
329                 newContent,
330                 selectionRange.anchor + lineDiff,
331                 selectionRange.head + lineDiff,
332             );
333         }
334     }
335
336     syncDisplayPosition(event) {
337         // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
338         const scrollEl = event.target;
339         const atEnd = Math.abs(scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop) < 1;
340         if (atEnd) {
341             this.editor.display.scrollToIndex(-1);
342             return;
343         }
344
345         const blockInfo = this.editor.cm.lineBlockAtHeight(scrollEl.scrollTop);
346         const range = this.editor.cm.state.sliceDoc(0, blockInfo.from);
347         const parser = new DOMParser();
348         const doc = parser.parseFromString(this.editor.markdown.render(range), 'text/html');
349         const totalLines = doc.documentElement.querySelectorAll('body > *');
350         this.editor.display.scrollToIndex(totalLines.length);
351     }
352
353     /**
354      * Fetch and insert the template of the given ID.
355      * The page-relative position provided can be used to determine insert location if possible.
356      * @param {String} templateId
357      * @param {Number} posX
358      * @param {Number} posY
359      */
360     async insertTemplate(templateId, posX, posY) {
361         const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
362         const {data} = await window.$http.get(`/templates/${templateId}`);
363         const content = data.markdown || data.html;
364         this.#dispatchChange(cursorPos, cursorPos, content, cursorPos);
365     }
366
367     /**
368      * Insert multiple images from the clipboard from an event at the provided
369      * screen coordinates (Typically form a paste event).
370      * @param {File[]} images
371      * @param {Number} posX
372      * @param {Number} posY
373      */
374     insertClipboardImages(images, posX, posY) {
375         const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
376         for (const image of images) {
377             this.uploadImage(image, cursorPos);
378         }
379     }
380
381     /**
382      * Handle image upload and add image into markdown content
383      * @param {File} file
384      * @param {?Number} position
385      */
386     async uploadImage(file, position = null) {
387         if (file === null || file.type.indexOf('image') !== 0) return;
388         let ext = 'png';
389
390         if (position === null) {
391             position = this.#getSelectionRange().from;
392         }
393
394         if (file.name) {
395             const fileNameMatches = file.name.match(/\.(.+)$/);
396             if (fileNameMatches.length > 1) ext = fileNameMatches[1];
397         }
398
399         // Insert image into markdown
400         const id = `image-${Math.random().toString(16).slice(2)}`;
401         const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
402         const placeHolderText = `![](${placeholderImage})`;
403         this.#dispatchChange(position, position, placeHolderText, position);
404
405         const remoteFilename = `image-${Date.now()}.${ext}`;
406         const formData = new FormData();
407         formData.append('file', file, remoteFilename);
408         formData.append('uploaded_to', this.editor.config.pageId);
409
410         try {
411             const {data} = await window.$http.post('/images/gallery', formData);
412             const newContent = `[![](${data.thumbs.display})](${data.url})`;
413             this.#findAndReplaceContent(placeHolderText, newContent);
414         } catch (err) {
415             window.$events.emit('error', this.editor.config.text.imageUploadError);
416             this.#findAndReplaceContent(placeHolderText, '');
417             console.error(err);
418         }
419     }
420
421     /**
422      * Get the current text of the editor instance.
423      * @return {string}
424      */
425     #getText() {
426         return this.editor.cm.state.doc.toString();
427     }
428
429     /**
430      * Set the text of the current editor instance.
431      * @param {String} text
432      * @param {?SelectionRange} selectionRange
433      */
434     #setText(text, selectionRange = null) {
435         selectionRange = selectionRange || this.#getSelectionRange();
436         this.#dispatchChange(0, this.editor.cm.state.doc.length, text, selectionRange.from);
437         this.focus();
438     }
439
440     /**
441      * Replace the current selection and focus the editor.
442      * Takes an offset for the cursor, after the change, relative to the start of the provided string.
443      * Can be provided a selection range to use instead of the current selection range.
444      * @param {String} newContent
445      * @param {Number} cursorOffset
446      * @param {?SelectionRange} selectionRange
447      */
448     #replaceSelection(newContent, cursorOffset = 0, selectionRange = null) {
449         selectionRange = selectionRange || this.editor.cm.state.selection.main;
450         const selectFrom = selectionRange.from + cursorOffset;
451         this.#dispatchChange(selectionRange.from, selectionRange.to, newContent, selectFrom);
452         this.focus();
453     }
454
455     /**
456      * Get the text content of the main current selection.
457      * @param {SelectionRange} selectionRange
458      * @return {string}
459      */
460     #getSelectionText(selectionRange = null) {
461         selectionRange = selectionRange || this.#getSelectionRange();
462         return this.editor.cm.state.sliceDoc(selectionRange.from, selectionRange.to);
463     }
464
465     /**
466      * Get the range of the current main selection.
467      * @return {SelectionRange}
468      */
469     #getSelectionRange() {
470         return this.editor.cm.state.selection.main;
471     }
472
473     /**
474      * Cleans the given text to work with the editor.
475      * Standardises line endings to what's expected.
476      * @param {String} text
477      * @return {String}
478      */
479     #cleanTextForEditor(text) {
480         return text.replace(/\r\n|\r/g, '\n');
481     }
482
483     /**
484      * Find and replace the first occurrence of [search] with [replace]
485      * @param {String} search
486      * @param {String} replace
487      */
488     #findAndReplaceContent(search, replace) {
489         const newText = this.#getText().replace(search, replace);
490         this.#setText(newText);
491     }
492
493     /**
494      * Wrap the line in the given start and end contents.
495      * @param {String} start
496      * @param {String} end
497      */
498     #wrapLine(start, end) {
499         const selectionRange = this.#getSelectionRange();
500         const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
501         const lineContent = line.text;
502         let newLineContent;
503         let lineOffset = 0;
504
505         if (lineContent.startsWith(start) && lineContent.endsWith(end)) {
506             newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
507             lineOffset = -(start.length);
508         } else {
509             newLineContent = `${start}${lineContent}${end}`;
510             lineOffset = start.length;
511         }
512
513         this.#dispatchChange(line.from, line.to, newLineContent, selectionRange.from + lineOffset);
514     }
515
516     /**
517      * Dispatch changes to the editor.
518      * @param {Number} from
519      * @param {?Number} to
520      * @param {?String} text
521      * @param {?Number} selectFrom
522      * @param {?Number} selectTo
523      */
524     #dispatchChange(from, to = null, text = null, selectFrom = null, selectTo = null) {
525         const tr = {changes: {from, to, insert: text}};
526
527         if (selectFrom) {
528             tr.selection = {anchor: selectFrom};
529             if (selectTo) {
530                 tr.selection.head = selectTo;
531             }
532         }
533
534         this.editor.cm.dispatch(tr);
535     }
536
537     /**
538      * Set the current selection range.
539      * Optionally will scroll the new range into view.
540      * @param {Number} from
541      * @param {Number} to
542      * @param {Boolean} scrollIntoView
543      */
544     #setSelection(from, to, scrollIntoView = false) {
545         this.editor.cm.dispatch({
546             selection: {anchor: from, head: to},
547             scrollIntoView,
548         });
549     }
550
551 }