mirror of
https://github.com/usememos/memos.git
synced 2025-11-11 18:00:53 +08:00
43 lines
1.7 KiB
TypeScript
43 lines
1.7 KiB
TypeScript
import { EditorRefActions } from "./Editor";
|
|
|
|
export const handleEditorKeydownWithMarkdownShortcuts = (event: React.KeyboardEvent, editorRef: EditorRefActions) => {
|
|
if (event.key === "b") {
|
|
const boldDelimiter = "**";
|
|
event.preventDefault();
|
|
styleHighlightedText(editorRef, boldDelimiter);
|
|
} else if (event.key === "i") {
|
|
const italicsDelimiter = "*";
|
|
event.preventDefault();
|
|
styleHighlightedText(editorRef, italicsDelimiter);
|
|
} else if (event.key === "k") {
|
|
event.preventDefault();
|
|
hyperlinkHighlightedText(editorRef);
|
|
}
|
|
};
|
|
|
|
const styleHighlightedText = (editor: EditorRefActions, delimiter: string) => {
|
|
const cursorPosition = editor.getCursorPosition();
|
|
const selectedContent = editor.getSelectedContent();
|
|
if (selectedContent.startsWith(delimiter) && selectedContent.endsWith(delimiter)) {
|
|
editor.insertText(selectedContent.slice(delimiter.length, -delimiter.length));
|
|
const newContentLength = selectedContent.length - delimiter.length * 2;
|
|
editor.setCursorPosition(cursorPosition, cursorPosition + newContentLength);
|
|
} else {
|
|
editor.insertText(`${delimiter}${selectedContent}${delimiter}`);
|
|
editor.setCursorPosition(cursorPosition + delimiter.length, cursorPosition + delimiter.length + selectedContent.length);
|
|
}
|
|
};
|
|
|
|
const hyperlinkHighlightedText = (editor: EditorRefActions, url?: string) => {
|
|
const cursorPosition = editor.getCursorPosition();
|
|
const selectedContent = editor.getSelectedContent();
|
|
const blankURL = "url";
|
|
url = url ?? blankURL;
|
|
|
|
editor.insertText(`[${selectedContent}](${url})`);
|
|
|
|
if (url === blankURL) {
|
|
const newCursorStart = cursorPosition + selectedContent.length + 3;
|
|
editor.setCursorPosition(newCursorStart, newCursorStart + url.length);
|
|
}
|
|
};
|