+ /**
+ * 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() {
+ const selectionRange = this.#getSelectionRange();
+ const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
+
+ 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(line.text);
+ 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 = line.text.replace(matches[0], matches[0].replace(format, newFormat));
+ const lineDiff = newContent.length - line.text.length;
+ this.#dispatchChange(
+ line.from,
+ line.to,
+ newContent,
+ selectionRange.anchor + lineDiff,
+ selectionRange.head + lineDiff,
+ );
+ }
+ }
+
+ 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);
+ }
+ }
+