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