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