]> BookStack Code Mirror - bookstack/blobdiff - resources/js/markdown/actions.js
Got md shortcuts working, marked actions for update
[bookstack] / resources / js / markdown / actions.js
index 96093d833942bccd39878c8acd4f3dfe9b54abe6..dfbe89c5a302f94979ea5547770821786e875f38 100644 (file)
@@ -6,19 +6,30 @@ export class Actions {
      */
     constructor(editor) {
         this.editor = editor;
+        this.lastContent = {
+            html: '',
+            markdown: '',
+        };
     }
 
     updateAndRender() {
-        const content = this.editor.cm.getValue();
+        const content = this.editor.cm.state.doc.toString();
         this.editor.config.inputEl.value = content;
 
         const html = this.editor.markdown.render(content);
-        window.$events.emit('editor-html-change', html);
-        window.$events.emit('editor-markdown-change', content);
+        window.$events.emit('editor-html-change', '');
+        window.$events.emit('editor-markdown-change', '');
+        this.lastContent.html = html;
+        this.lastContent.markdown = content;
         this.editor.display.patchWithHtml(html);
     }
 
-    insertImage() {
+    getContent() {
+        return this.lastContent;
+    }
+
+    showImageInsert() {
+        // TODO
         const cursorPos = this.editor.cm.getCursor('from');
         /** @type {ImageManager} **/
         const imageManager = window.$components.first('image-manager');
@@ -32,7 +43,17 @@ export class Actions {
         }, 'gallery');
     }
 
+    insertImage() {
+        // TODO
+        const selectedText = this.editor.cm.getSelection();
+        const newText = `![${selectedText}](http://)`;
+        const cursorPos = this.editor.cm.getCursor('from');
+        this.editor.cm.replaceSelection(newText);
+        this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
+    }
+
     insertLink() {
+        // TODO
         const cursorPos = this.editor.cm.getCursor('from');
         const selectedText = this.editor.cm.getSelection() || '';
         const newText = `[${selectedText}]()`;
@@ -43,6 +64,7 @@ export class Actions {
     }
 
     showImageManager() {
+        // TODO
         const cursorPos = this.editor.cm.getCursor('from');
         /** @type {ImageManager} **/
         const imageManager = window.$components.first('image-manager');
@@ -53,6 +75,7 @@ export class Actions {
 
     // Show the popup link selector and insert a link when finished
     showLinkSelector() {
+        // TODO
         const cursorPos = this.editor.cm.getCursor('from');
         /** @type {EntitySelectorPopup} **/
         const selector = window.$components.first('entity-selector-popup');
@@ -67,6 +90,7 @@ export class Actions {
 
     // Show draw.io if enabled and handle save.
     startDrawing() {
+        // TODO
         const url = this.editor.config.drawioUrl;
         if (!url) return;
 
@@ -78,7 +102,7 @@ export class Actions {
 
             const data = {
                 image: pngData,
-                uploaded_to: Number(this.pageId),
+                uploaded_to: Number(this.editor.config.pageId),
             };
 
             window.$http.post("/images/drawio", data).then(resp => {
@@ -91,6 +115,7 @@ export class Actions {
     }
 
     insertDrawing(image, originalCursor) {
+        // TODO
         const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
         this.editor.cm.focus();
         this.editor.cm.replaceSelection(newText);
@@ -99,6 +124,7 @@ export class Actions {
 
     // Show draw.io if enabled and handle save.
     editDrawing(imgContainer) {
+        // TODO
         const drawioUrl = this.editor.config.drawioUrl;
         if (!drawioUrl) {
             return;
@@ -135,6 +161,7 @@ export class Actions {
     }
 
     handleDrawingUploadError(error) {
+        // TODO
         if (error.status === 413) {
             window.$events.emit('error', this.editor.config.text.serverUploadLimit);
         } else {
@@ -145,6 +172,7 @@ export class Actions {
 
     // Make the editor full screen
     fullScreen() {
+        // TODO
         const container = this.editor.config.container;
         const alreadyFullscreen = container.classList.contains('fullscreen');
         container.classList.toggle('fullscreen', !alreadyFullscreen);
@@ -153,6 +181,7 @@ export class Actions {
 
     // Scroll to a specified text
     scrollToText(searchText) {
+        // TODO
         if (!searchText) {
             return;
         }
@@ -179,6 +208,7 @@ export class Actions {
     }
 
     focus() {
+        // TODO
         this.editor.cm.focus();
     }
 
@@ -187,6 +217,7 @@ export class Actions {
      * @param {String} content
      */
     insertContent(content) {
+        // TODO
         this.editor.cm.replaceSelection(content);
     }
 
@@ -195,6 +226,7 @@ export class Actions {
      * @param {String} content
      */
     prependContent(content) {
+        // TODO
         const cursorPos = this.editor.cm.getCursor('from');
         const newContent = content + '\n' + this.editor.cm.getValue();
         this.editor.cm.setValue(newContent);
@@ -207,6 +239,7 @@ export class Actions {
      * @param {String} content
      */
     appendContent(content) {
+        // TODO
         const cursorPos = this.editor.cm.getCursor('from');
         const newContent = this.editor.cm.getValue() + '\n' + content;
         this.editor.cm.setValue(newContent);
@@ -218,6 +251,7 @@ export class Actions {
      * @param {String} content
      */
     replaceContent(content) {
+        // TODO
         this.editor.cm.setValue(content);
     }
 
@@ -226,6 +260,7 @@ export class Actions {
      * @param {String} replace
      */
     findAndReplaceContent(search, replace) {
+        // TODO
         const text = this.editor.cm.getValue();
         const cursor = this.editor.cm.listSelections();
         this.editor.cm.setValue(text.replace(search, replace));
@@ -237,6 +272,7 @@ export class Actions {
      * @param {String} newStart
      */
     replaceLineStart(newStart) {
+        // TODO
         const cursor = this.editor.cm.getCursor();
         let lineContent = this.editor.cm.getLine(cursor.line);
         const lineLen = lineContent.length;
@@ -269,6 +305,7 @@ export class Actions {
      * @param {String} end
      */
     wrapLine(start, end) {
+        // TODO
         const cursor = this.editor.cm.getCursor();
         const lineContent = this.editor.cm.getLine(cursor.line);
         const lineLen = lineContent.length;
@@ -290,6 +327,7 @@ export class Actions {
      * @param {String} end
      */
     wrapSelection(start, end) {
+        // TODO
         const selection = this.editor.cm.getSelection();
         if (selection === '') return this.wrapLine(start, end);
 
@@ -314,6 +352,7 @@ export class Actions {
     }
 
     replaceLineStartForOrderedList() {
+        // TODO
         const cursor = this.editor.cm.getCursor();
         const prevLineContent = this.editor.cm.getLine(cursor.line - 1) || '';
         const listMatch = prevLineContent.match(/^(\s*)(\d)([).])\s/) || [];
@@ -326,11 +365,51 @@ export class Actions {
         return this.replaceLineStart(prefix);
     }
 
+    /**
+     * Cycles through the type of callout block within the selection.
+     * Creates a callout block if none existing, and removes it if cycling past the danger type.
+     */
+    cycleCalloutTypeAtSelection() {
+        // TODO
+        const selectionRange = this.editor.cm.listSelections()[0];
+        const lineContent = this.editor.cm.getLine(selectionRange.anchor.line);
+        const lineLength = lineContent.length;
+        const contentRange = {
+            anchor: {line: selectionRange.anchor.line, ch: 0},
+            head: {line: selectionRange.anchor.line, ch: lineLength},
+        };
+
+        const formats = ['info', 'success', 'warning', 'danger'];
+        const joint = formats.join('|');
+        const regex = new RegExp(`class="((${joint})\\s+callout|callout\\s+(${joint}))"`, 'i');
+        const matches = regex.exec(lineContent);
+        const format = (matches ? (matches[2] || matches[3]) : '').toLowerCase();
+
+        if (format === formats[formats.length - 1]) {
+            this.wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
+        } else if (format === '') {
+            this.wrapLine('<p class="callout info">', '</p>');
+        } else {
+            const newFormatIndex = formats.indexOf(format) + 1;
+            const newFormat = formats[newFormatIndex];
+            const newContent = lineContent.replace(matches[0], matches[0].replace(format, newFormat));
+            this.editor.cm.replaceRange(newContent, contentRange.anchor, contentRange.head);
+
+            const chDiff = newContent.length - lineContent.length;
+            selectionRange.anchor.ch += chDiff;
+            if (selectionRange.anchor !== selectionRange.head) {
+                selectionRange.head.ch += chDiff;
+            }
+            this.editor.cm.setSelection(selectionRange.anchor, selectionRange.head);
+        }
+    }
+
     /**
      * Handle image upload and add image into markdown content
      * @param {File} file
      */
     uploadImage(file) {
+        // TODO
         if (file === null || file.type.indexOf('image') !== 0) return;
         let ext = 'png';
 
@@ -363,21 +442,21 @@ export class Actions {
         });
     }
 
-    syncDisplayPosition() {
+    syncDisplayPosition(event) {
         // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
-        const scroll = this.editor.cm.getScrollInfo();
-        const atEnd = scroll.top + scroll.clientHeight === scroll.height;
+        const scrollEl = event.target;
+        const atEnd = Math.abs(scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop) < 1;
         if (atEnd) {
-            editor.display.scrollToIndex(-1);
+            this.editor.display.scrollToIndex(-1);
             return;
         }
 
-        const lineNum = this.editor.cm.lineAtHeight(scroll.top, 'local');
-        const range = this.editor.cm.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
+        const blockInfo = this.editor.cm.lineBlockAtHeight(scrollEl.scrollTop);
+        const range = this.editor.cm.state.sliceDoc(0, blockInfo.from);
         const parser = new DOMParser();
         const doc = parser.parseFromString(this.editor.markdown.render(range), 'text/html');
         const totalLines = doc.documentElement.querySelectorAll('body > *');
-        editor.display.scrollToIndex(totalLines.length);
+        this.editor.display.scrollToIndex(totalLines.length);
     }
 
     /**
@@ -388,6 +467,7 @@ export class Actions {
      * @param {Number} posY
      */
     insertTemplate(templateId, posX, posY) {
+        // TODO
         const cursorPos = this.editor.cm.coordsChar({left: posX, top: posY});
         this.editor.cm.setCursor(cursorPos);
         window.$http.get(`/templates/${templateId}`).then(resp => {
@@ -401,10 +481,11 @@ export class Actions {
      * @param {File[]} images
      */
     insertClipboardImages(images) {
+        // TODO
         const cursorPos = this.editor.cm.coordsChar({left: event.pageX, top: event.pageY});
         this.editor.cm.setCursor(cursorPos);
         for (const image of images) {
-            editor.actions.uploadImage(image);
+            this.uploadImage(image);
         }
     }
 }
\ No newline at end of file