Made a start on updating editor actions

This commit is contained in:
Dan Brown 2023-04-11 13:16:04 +01:00
parent da3e4f5f75
commit 9813c94720
No known key found for this signature in database
GPG Key ID: 46D9F943C24A2EF9
4 changed files with 118 additions and 100 deletions

View File

@ -29,72 +29,57 @@ export class Actions {
} }
showImageInsert() { showImageInsert() {
// TODO
const cursorPos = this.editor.cm.getCursor('from');
/** @type {ImageManager} **/ /** @type {ImageManager} **/
const imageManager = window.$components.first('image-manager'); const imageManager = window.$components.first('image-manager');
imageManager.show(image => { imageManager.show(image => {
const imageUrl = image.thumbs.display || image.url; const imageUrl = image.thumbs.display || image.url;
let selectedText = this.editor.cm.getSelection(); const selectedText = this.#getSelectionText();
let newText = "[![" + (selectedText || image.name) + "](" + imageUrl + ")](" + image.url + ")"; const newText = "[![" + (selectedText || image.name) + "](" + imageUrl + ")](" + image.url + ")";
this.editor.cm.focus(); this.#replaceSelection(newText, newText.length);
this.editor.cm.replaceSelection(newText);
this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
}, 'gallery'); }, 'gallery');
} }
insertImage() { insertImage() {
// TODO const newText = `![${this.#getSelectionText()}](http://)`;
const selectedText = this.editor.cm.getSelection(); this.#replaceSelection(newText, newText.length - 1);
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() { insertLink() {
// TODO const selectedText = this.#getSelectionText();
const cursorPos = this.editor.cm.getCursor('from');
const selectedText = this.editor.cm.getSelection() || '';
const newText = `[${selectedText}]()`; const newText = `[${selectedText}]()`;
this.editor.cm.focus();
this.editor.cm.replaceSelection(newText);
const cursorPosDiff = (selectedText === '') ? -3 : -1; const cursorPosDiff = (selectedText === '') ? -3 : -1;
this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff); this.#replaceSelection(newText, newText.length+cursorPosDiff);
} }
showImageManager() { showImageManager() {
// TODO const selectionRange = this.#getSelectionRange();
const cursorPos = this.editor.cm.getCursor('from');
/** @type {ImageManager} **/ /** @type {ImageManager} **/
const imageManager = window.$components.first('image-manager'); const imageManager = window.$components.first('image-manager');
imageManager.show(image => { imageManager.show(image => {
this.insertDrawing(image, cursorPos); this.#insertDrawing(image, selectionRange);
}, 'drawio'); }, 'drawio');
} }
// Show the popup link selector and insert a link when finished // Show the popup link selector and insert a link when finished
showLinkSelector() { showLinkSelector() {
// TODO const selectionRange = this.#getSelectionRange();
const cursorPos = this.editor.cm.getCursor('from');
/** @type {EntitySelectorPopup} **/ /** @type {EntitySelectorPopup} **/
const selector = window.$components.first('entity-selector-popup'); const selector = window.$components.first('entity-selector-popup');
selector.show(entity => { selector.show(entity => {
let selectedText = this.editor.cm.getSelection() || entity.name; const selectedText = this.#getSelectionText(selectionRange) || entity.name;
let newText = `[${selectedText}](${entity.link})`; const newText = `[${selectedText}](${entity.link})`;
this.editor.cm.focus(); this.#replaceSelection(newText, newText.length, selectionRange);
this.editor.cm.replaceSelection(newText);
this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
}); });
} }
// Show draw.io if enabled and handle save. // Show draw.io if enabled and handle save.
startDrawing() { startDrawing() {
// TODO
const url = this.editor.config.drawioUrl; const url = this.editor.config.drawioUrl;
if (!url) return; if (!url) return;
const cursorPos = this.editor.cm.getCursor('from'); const selectionRange = this.#getSelectionRange();
DrawIO.show(url,() => { DrawIO.show(url,() => {
return Promise.resolve(''); return Promise.resolve('');
@ -106,7 +91,7 @@ export class Actions {
}; };
window.$http.post("/images/drawio", data).then(resp => { window.$http.post("/images/drawio", data).then(resp => {
this.insertDrawing(resp.data, cursorPos); this.#insertDrawing(resp.data, selectionRange);
DrawIO.close(); DrawIO.close();
}).catch(err => { }).catch(err => {
this.handleDrawingUploadError(err); this.handleDrawingUploadError(err);
@ -114,12 +99,9 @@ export class Actions {
}); });
} }
insertDrawing(image, originalCursor) { #insertDrawing(image, originalSelectionRange) {
// TODO
const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`; const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
this.editor.cm.focus(); this.#replaceSelection(newText, newText.length, originalSelectionRange);
this.editor.cm.replaceSelection(newText);
this.editor.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
} }
// Show draw.io if enabled and handle save. // Show draw.io if enabled and handle save.
@ -161,7 +143,6 @@ export class Actions {
} }
handleDrawingUploadError(error) { handleDrawingUploadError(error) {
// TODO
if (error.status === 413) { if (error.status === 413) {
window.$events.emit('error', this.editor.config.text.serverUploadLimit); window.$events.emit('error', this.editor.config.text.serverUploadLimit);
} else { } else {
@ -172,7 +153,6 @@ export class Actions {
// Make the editor full screen // Make the editor full screen
fullScreen() { fullScreen() {
// TODO
const container = this.editor.config.container; const container = this.editor.config.container;
const alreadyFullscreen = container.classList.contains('fullscreen'); const alreadyFullscreen = container.classList.contains('fullscreen');
container.classList.toggle('fullscreen', !alreadyFullscreen); container.classList.toggle('fullscreen', !alreadyFullscreen);
@ -181,35 +161,37 @@ export class Actions {
// Scroll to a specified text // Scroll to a specified text
scrollToText(searchText) { scrollToText(searchText) {
// TODO
if (!searchText) { if (!searchText) {
return; return;
} }
const content = this.editor.cm.getValue(); const text = this.editor.cm.state.doc;
const lines = content.split(/\r?\n/); let lineCount = 1;
let lineNumber = lines.findIndex(line => { let scrollToLine = -1;
return line && line.indexOf(searchText) !== -1; for (const line of text.iterLines()) {
}); if (line.includes(searchText)) {
scrollToLine = lineCount;
break;
}
lineCount++;
}
if (lineNumber === -1) { if (scrollToLine === -1) {
return; return;
} }
this.editor.cm.scrollIntoView({ const line = text.line(scrollToLine);
line: lineNumber, this.editor.cm.dispatch({
}, 200); selection: {anchor: line.from, head: line.to},
this.editor.cm.focus(); scrollIntoView: true,
// set the cursor location. });
this.editor.cm.setCursor({ this.focus();
line: lineNumber,
char: lines[lineNumber].length
})
} }
focus() { focus() {
// TODO if (!this.editor.cm.hasFocus) {
this.editor.cm.focus(); this.editor.cm.focus();
}
} }
/** /**
@ -217,8 +199,7 @@ export class Actions {
* @param {String} content * @param {String} content
*/ */
insertContent(content) { insertContent(content) {
// TODO this.#replaceSelection(content, content.length);
this.editor.cm.replaceSelection(content);
} }
/** /**
@ -404,44 +385,6 @@ export class Actions {
} }
} }
/**
* 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';
if (file.name) {
let 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 placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
const selectedText = this.editor.cm.getSelection();
const placeHolderText = `![${selectedText}](${placeholderImage})`;
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 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 = `[![${selectedText}](${resp.data.thumbs.display})](${resp.data.url})`;
this.findAndReplaceContent(placeHolderText, newContent);
}).catch(err => {
window.$events.emit('error', this.editor.config.text.imageUploadError);
this.findAndReplaceContent(placeHolderText, selectedText);
console.log(err);
});
}
syncDisplayPosition(event) { syncDisplayPosition(event) {
// Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
const scrollEl = event.target; const scrollEl = event.target;
@ -485,7 +428,77 @@ export class Actions {
const cursorPos = this.editor.cm.coordsChar({left: event.pageX, top: event.pageY}); const cursorPos = this.editor.cm.coordsChar({left: event.pageX, top: event.pageY});
this.editor.cm.setCursor(cursorPos); this.editor.cm.setCursor(cursorPos);
for (const image of images) { for (const image of images) {
this.uploadImage(image); this.#uploadImage(image);
} }
} }
/**
* 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';
if (file.name) {
let 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 placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
const selectedText = this.editor.cm.getSelection();
const placeHolderText = `![${selectedText}](${placeholderImage})`;
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 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 = `[![${selectedText}](${resp.data.thumbs.display})](${resp.data.url})`;
this.findAndReplaceContent(placeHolderText, newContent);
}).catch(err => {
window.$events.emit('error', this.editor.config.text.imageUploadError);
this.findAndReplaceContent(placeHolderText, selectedText);
console.log(err);
});
}
/**
* Replace the current selection and focus the editor.
* Takes an offset for the cursor, after the change, relative to the start of the provided string.
* Can be provided a selection range to use instead of the current selection range.
* @param {String} newContent
* @param {Number} cursorOffset
* @param {?SelectionRange} selectionRange
*/
#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},
});
this.focus();
}
/**
* Get the text content of the main current selection.
* @param {SelectionRange} selectionRange
* @return {string}
*/
#getSelectionText(selectionRange = null) {
selectionRange = selectionRange || this.#getSelectionRange();
return this.editor.cm.state.sliceDoc(selectionRange.from, selectionRange.to);
}
#getSelectionRange() {
return this.editor.cm.state.selection.main;
}
} }

View File

@ -49,6 +49,6 @@ export async function init(config) {
* @property {Display} display * @property {Display} display
* @property {Markdown} markdown * @property {Markdown} markdown
* @property {Actions} actions * @property {Actions} actions
* @property {CodeMirror} cm * @property {EditorView} cm
* @property {Settings} settings * @property {Settings} settings
*/ */

View File

@ -7,7 +7,7 @@ function provide(editor) {
const shortcuts = {}; const shortcuts = {};
// Insert Image shortcut // Insert Image shortcut
shortcuts['Mod-Alt-i'] = () => editor.actions.insertImage(); shortcuts['Mod-Alt-i'] = cm => editor.actions.insertImage();
// Save draft // Save draft
shortcuts['Mod-s'] = cm => window.$events.emit('editor-save-draft'); shortcuts['Mod-s'] = cm => window.$events.emit('editor-save-draft');

View File

@ -412,6 +412,11 @@ span.CodeMirror-selectedtext { background: none; }
/** /**
* Custom BookStack overrides * Custom BookStack overrides
*/ */
.cm-editor {
@include lightDark(background-color, #FFF, #000);
}
// TODO - All below are old
.CodeMirror, .CodeMirror pre { .CodeMirror, .CodeMirror pre {
font-size: 12px; font-size: 12px;
} }