-import DrawIO from "../services/drawio";
+import * as DrawIO from '../services/drawio.ts';
export class Actions {
+
/**
* @param {MarkdownEditor} editor
*/
}
showImageInsert() {
- /** @type {ImageManager} **/
+ /** @type {ImageManager} * */
const imageManager = window.$components.first('image-manager');
imageManager.show(image => {
- const imageUrl = image.thumbs.display || image.url;
+ const imageUrl = image.thumbs?.display || image.url;
const selectedText = this.#getSelectionText();
- const newText = "[](" + image.url + ")";
+ const newText = `[](${image.url})`;
this.#replaceSelection(newText, newText.length);
}, 'gallery');
}
const selectedText = this.#getSelectionText();
const newText = `[${selectedText}]()`;
const cursorPosDiff = (selectedText === '') ? -3 : -1;
- this.#replaceSelection(newText, newText.length+cursorPosDiff);
+ this.#replaceSelection(newText, newText.length + cursorPosDiff);
}
showImageManager() {
const selectionRange = this.#getSelectionRange();
- /** @type {ImageManager} **/
+ /** @type {ImageManager} * */
const imageManager = window.$components.first('image-manager');
imageManager.show(image => {
this.#insertDrawing(image, selectionRange);
showLinkSelector() {
const selectionRange = this.#getSelectionRange();
- /** @type {EntitySelectorPopup} **/
+ /** @type {EntitySelectorPopup} * */
const selector = window.$components.first('entity-selector-popup');
+ const selectionText = this.#getSelectionText(selectionRange);
selector.show(entity => {
- const selectedText = this.#getSelectionText(selectionRange) || entity.name;
+ const selectedText = selectionText || entity.name;
const newText = `[${selectedText}](${entity.link})`;
this.#replaceSelection(newText, newText.length, selectionRange);
+ }, {
+ initialValue: selectionText,
+ searchEndpoint: '/search/entity-selector',
+ entityTypes: 'page,book,chapter,bookshelf',
+ entityPermission: 'view',
});
}
const selectionRange = this.#getSelectionRange();
- DrawIO.show(url,() => {
- return Promise.resolve('');
- }, (pngData) => {
-
+ DrawIO.show(url, () => Promise.resolve(''), async pngData => {
const data = {
image: pngData,
uploaded_to: Number(this.editor.config.pageId),
};
- window.$http.post("/images/drawio", data).then(resp => {
+ try {
+ const resp = await window.$http.post('/images/drawio', data);
this.#insertDrawing(resp.data, selectionRange);
DrawIO.close();
- }).catch(err => {
+ } catch (err) {
this.handleDrawingUploadError(err);
- });
+ throw new Error(`Failed to save image with error: ${err}`);
+ }
});
}
// Show draw.io if enabled and handle save.
editDrawing(imgContainer) {
- const drawioUrl = this.editor.config.drawioUrl;
+ const {drawioUrl} = this.editor.config;
if (!drawioUrl) {
return;
}
const selectionRange = this.#getSelectionRange();
const drawingId = imgContainer.getAttribute('drawio-diagram');
- DrawIO.show(drawioUrl, () => {
- return DrawIO.load(drawingId);
- }, (pngData) => {
-
+ DrawIO.show(drawioUrl, () => DrawIO.load(drawingId), async pngData => {
const data = {
image: pngData,
uploaded_to: Number(this.editor.config.pageId),
};
- window.$http.post("/images/drawio", data).then(resp => {
+ try {
+ const resp = await window.$http.post('/images/drawio', data);
const newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
const newContent = this.#getText().split('\n').map(line => {
if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
}).join('\n');
this.#setText(newContent, selectionRange);
DrawIO.close();
- }).catch(err => {
+ } catch (err) {
this.handleDrawingUploadError(err);
- });
+ throw new Error(`Failed to save image with error: ${err}`);
+ }
});
}
} else {
window.$events.emit('error', this.editor.config.text.imageUploadError);
}
- console.log(error);
+ console.error(error);
}
// Make the editor full screen
fullScreen() {
- const container = this.editor.config.container;
+ const {container} = this.editor.config;
const alreadyFullscreen = container.classList.contains('fullscreen');
container.classList.toggle('fullscreen', !alreadyFullscreen);
document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
scrollToLine = lineCount;
break;
}
- lineCount++;
+ lineCount += 1;
}
if (scrollToLine === -1) {
}
const line = text.line(scrollToLine);
- this.editor.cm.dispatch({
- selection: {anchor: line.from, head: line.to},
- scrollIntoView: true,
- });
+ this.#setSelection(line.from, line.to, true);
this.focus();
}
prependContent(content) {
content = this.#cleanTextForEditor(content);
const selectionRange = this.#getSelectionRange();
- this.editor.cm.dispatch({
- changes: {from: 0, to: 0, insert: content + '\n'},
- selection: {anchor: selectionRange.from + content.length + 1}
- });
+ const selectFrom = selectionRange.from + content.length + 1;
+ this.#dispatchChange(0, 0, `${content}\n`, selectFrom);
this.focus();
}
*/
appendContent(content) {
content = this.#cleanTextForEditor(content);
- this.editor.cm.dispatch({
- changes: {from: this.editor.cm.state.doc.length, insert: '\n' + content},
- });
+ this.#dispatchChange(this.editor.cm.state.doc.length, `\n${content}`);
this.focus();
}
* @param {String} content
*/
replaceContent(content) {
- this.#setText(content)
+ this.#setText(content);
}
/**
// Remove symbol if already set
if (lineStart === newStart) {
const newLineContent = lineContent.replace(`${newStart} `, '');
- this.editor.cm.dispatch({
- changes: {from: line.from, to: line.to, insert: newLineContent},
- selection: {anchor: selectionRange.from + (newLineContent.length - lineContent.length)}
- });
+ const selectFrom = selectionRange.from + (newLineContent.length - lineContent.length);
+ this.#dispatchChange(line.from, line.to, newLineContent, selectFrom);
return;
}
if (alreadySymbol) {
newLineContent = lineContent.replace(lineStart, newStart).trim();
} else if (newStart !== '') {
- newLineContent = newStart + ' ' + lineContent;
+ newLineContent = `${newStart} ${lineContent}`;
}
- this.editor.cm.dispatch({
- changes: {from: line.from, to: line.to, insert: newLineContent},
- selection: {anchor: selectionRange.from + (newLineContent.length - lineContent.length)}
- });
+ const selectFrom = selectionRange.from + (newLineContent.length - lineContent.length);
+ this.#dispatchChange(line.from, line.to, newLineContent, selectFrom);
}
/**
* @param {String} end
*/
wrapSelection(start, end) {
- const selectionRange = this.#getSelectionRange();
- const selectionText = this.#getSelectionText(selectionRange);
- if (!selectionText) return this.#wrapLine(start, end);
+ const selectRange = this.#getSelectionRange();
+ const selectionText = this.#getSelectionText(selectRange);
+ if (!selectionText) {
+ this.#wrapLine(start, end);
+ return;
+ }
let newSelectionText = selectionText;
let newRange;
if (selectionText.startsWith(start) && selectionText.endsWith(end)) {
newSelectionText = selectionText.slice(start.length, selectionText.length - end.length);
- newRange = selectionRange.extend(selectionRange.from, selectionRange.to - (start.length + end.length));
+ newRange = selectRange.extend(selectRange.from, selectRange.to - (start.length + end.length));
} else {
newSelectionText = `${start}${selectionText}${end}`;
- newRange = selectionRange.extend(selectionRange.from, selectionRange.to + (start.length + end.length));
+ newRange = selectRange.extend(selectRange.from, selectRange.to + (start.length + end.length));
}
- this.editor.cm.dispatch({
- changes: {from: selectionRange.from, to: selectionRange.to, insert: newSelectionText},
- selection: {anchor: newRange.anchor, head: newRange.head},
- });
+ this.#dispatchChange(
+ selectRange.from,
+ selectRange.to,
+ newSelectionText,
+ newRange.anchor,
+ newRange.head,
+ );
}
replaceLineStartForOrderedList() {
- // TODO
- const cursor = this.editor.cm.getCursor();
- const prevLineContent = this.editor.cm.getLine(cursor.line - 1) || '';
- const listMatch = prevLineContent.match(/^(\s*)(\d)([).])\s/) || [];
+ const selectionRange = this.#getSelectionRange();
+ const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
+ const prevLine = this.editor.cm.state.doc.line(line.number - 1);
+
+ const listMatch = prevLine.text.match(/^(\s*)(\d)([).])\s/) || [];
const number = (Number(listMatch[2]) || 0) + 1;
const whiteSpace = listMatch[1] || '';
- const listMark = listMatch[3] || '.'
+ const listMark = listMatch[3] || '.';
const prefix = `${whiteSpace}${number}${listMark}`;
return this.replaceLineStart(prefix);
* 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 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(lineContent);
+ 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>');
+ this.#wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
} else if (format === '') {
- this.wrapLine('<p class="callout info">', '</p>');
+ 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);
+ 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,
+ );
}
}
* @param {Number} posX
* @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 => {
- const content = resp.data.markdown || resp.data.html;
- this.editor.cm.replaceSelection(content);
- });
+ 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.
+ * 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) {
- // TODO
- const cursorPos = this.editor.cm.coordsChar({left: event.pageX, top: event.pageY});
- this.editor.cm.setCursor(cursorPos);
+ insertClipboardImages(images, posX, posY) {
+ const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
for (const image of images) {
- this.#uploadImage(image);
+ this.uploadImage(image, cursorPos);
}
}
/**
* Handle image upload and add image into markdown content
* @param {File} file
+ * @param {?Number} position
*/
- #uploadImage(file) {
- // TODO
+ async uploadImage(file, position = null) {
if (file === null || file.type.indexOf('image') !== 0) return;
let ext = 'png';
+ if (position === null) {
+ position = this.#getSelectionRange().from;
+ }
+
if (file.name) {
- let fileNameMatches = file.name.match(/\.(.+)$/);
+ const fileNameMatches = file.name.match(/\.(.+)$/);
if (fileNameMatches.length > 1) ext = fileNameMatches[1];
}
// Insert image into markdown
- const id = "image-" + Math.random().toString(16).slice(2);
+ const id = `image-${Math.random().toString(16).slice(2)}`;
const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
- const selectedText = this.editor.cm.getSelection();
- const placeHolderText = ``;
- const cursor = this.editor.cm.getCursor();
- this.editor.cm.replaceSelection(placeHolderText);
- this.editor.cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
+ const placeHolderText = ``;
+ this.#dispatchChange(position, position, placeHolderText, position);
- const remoteFilename = "image-" + Date.now() + "." + ext;
+ const remoteFilename = `image-${Date.now()}.${ext}`;
const formData = new FormData();
formData.append('file', file, remoteFilename);
formData.append('uploaded_to', this.editor.config.pageId);
- window.$http.post('/images/gallery', formData).then(resp => {
- const newContent = `[](${resp.data.url})`;
+ try {
+ const {data} = await window.$http.post('/images/gallery', formData);
+ const newContent = `[](${data.url})`;
this.#findAndReplaceContent(placeHolderText, newContent);
- }).catch(err => {
- window.$events.emit('error', this.editor.config.text.imageUploadError);
- this.#findAndReplaceContent(placeHolderText, selectedText);
- console.log(err);
- });
+ } catch (err) {
+ window.$events.error(err?.data?.message || this.editor.config.text.imageUploadError);
+ this.#findAndReplaceContent(placeHolderText, '');
+ console.error(err);
+ }
}
/**
*/
#setText(text, selectionRange = null) {
selectionRange = selectionRange || this.#getSelectionRange();
- this.editor.cm.dispatch({
- changes: {from: 0, to: this.editor.cm.state.doc.length, insert: text},
- selection: {anchor: selectionRange.from},
- });
-
+ const newDoc = this.editor.cm.state.toText(text);
+ const newSelectFrom = Math.min(selectionRange.from, newDoc.length);
+ this.#dispatchChange(0, this.editor.cm.state.doc.length, text, newSelectFrom);
this.focus();
}
*/
#replaceSelection(newContent, cursorOffset = 0, selectionRange = null) {
selectionRange = selectionRange || this.editor.cm.state.selection.main;
- this.editor.cm.dispatch({
- changes: {from: selectionRange.from, to: selectionRange.to, insert: newContent},
- selection: {anchor: selectionRange.from + cursorOffset},
- });
-
+ const selectFrom = selectionRange.from + cursorOffset;
+ this.#dispatchChange(selectionRange.from, selectionRange.to, newContent, selectFrom);
this.focus();
}
* @return {String}
*/
#cleanTextForEditor(text) {
- return text.replace(/\r\n|\r/g, "\n");
+ return text.replace(/\r\n|\r/g, '\n');
}
/**
lineOffset = start.length;
}
+ this.#dispatchChange(line.from, line.to, newLineContent, selectionRange.from + lineOffset);
+ }
+
+ /**
+ * Dispatch changes to the editor.
+ * @param {Number} from
+ * @param {?Number} to
+ * @param {?String} text
+ * @param {?Number} selectFrom
+ * @param {?Number} selectTo
+ */
+ #dispatchChange(from, to = null, text = null, selectFrom = null, selectTo = null) {
+ const tr = {changes: {from, to, insert: text}};
+
+ if (selectFrom) {
+ tr.selection = {anchor: selectFrom};
+ if (selectTo) {
+ tr.selection.head = selectTo;
+ }
+ }
+
+ this.editor.cm.dispatch(tr);
+ }
+
+ /**
+ * Set the current selection range.
+ * Optionally will scroll the new range into view.
+ * @param {Number} from
+ * @param {Number} to
+ * @param {Boolean} scrollIntoView
+ */
+ #setSelection(from, to, scrollIntoView = false) {
this.editor.cm.dispatch({
- changes: {from: line.from, to: line.to, insert: newLineContent},
- selection: {anchor: selectionRange.from + lineOffset}
+ selection: {anchor: from, head: to},
+ scrollIntoView,
});
}
-}
\ No newline at end of file
+
+}