- 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);
+ syncDisplayPosition(event) {
+ // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
+ const scrollEl = event.target;
+ const atEnd = Math.abs(scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop) < 1;
+ if (atEnd) {
+ this.editor.display.scrollToIndex(-1);
+ return;
+ }
+
+ 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 > *');
+ this.editor.display.scrollToIndex(totalLines.length);
+ }
+
+ /**
+ * Fetch and insert the template of the given ID.
+ * The page-relative position provided can be used to determine insert location if possible.
+ * @param {String} templateId
+ * @param {Number} posX
+ * @param {Number} posY
+ */
+ async insertTemplate(templateId, posX, posY) {
+ const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
+ const {data} = await window.$http.get(`/templates/${templateId}`);
+ const content = data.markdown || data.html;
+ this.#dispatchChange(cursorPos, cursorPos, content, cursorPos);
+ }
+
+ /**
+ * Insert multiple images from the clipboard from an event at the provided
+ * screen coordinates (Typically form a paste event).
+ * @param {File[]} images
+ * @param {Number} posX
+ * @param {Number} posY
+ */
+ insertClipboardImages(images, posX, posY) {
+ const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
+ for (const image of images) {
+ this.uploadImage(image, cursorPos);