Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat: add editor keyboard shortcuts

tianma-if0f14332525cd
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index d9855a1f..e0e4ad82 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -138,6 +138,7 @@ import { downloadMarkdownFile } from "@/lib/note-markdown-export";
import { NOTE_HTML_FULL_STYLES } from "@/lib/note-html-export-assets";
import { downloadNoteHtmlFile, getHtmlImageEmbedNoticeKind } from "@/lib/note-html-export";
import { openNotePrintPreview, serializeNoteDocumentForPrint } from "@/lib/note-print";
+import { saveAndSyncEditor } from "@/lib/editor-shortcuts";
import { isBrowserOffline } from "@/lib/network-status";
import {
EDITOR_LINK_OPEN_MODE_CHANGED_EVENT,
@@ -627,6 +628,9 @@ type EditorPaneProps = {
onSaveAsTemplate: (memo: MemoDetail, name: string) => Promise<void>;
searchFocusToken: number;
replaceFocusToken: number;
+ saveAndSyncToken: number;
+ editorModeToggleToken: number;
+ onSyncRequested: () => Promise<void>;
documentActionRequest?: MemoDocumentActionRequest | null;
onDocumentActionConsumed?: (requestId: number) => void;
selectionActionBar?: ReactNode;
@@ -694,6 +698,9 @@ const RichEditorPane = ({
onSaveAsTemplate,
searchFocusToken,
replaceFocusToken,
+ saveAndSyncToken,
+ editorModeToggleToken,
+ onSyncRequested,
documentActionRequest,
onDocumentActionConsumed,
selectionActionBar,
@@ -782,6 +789,8 @@ const RichEditorPane = ({
const [mobileImeDebugEvents, setMobileImeDebugEvents] = useState<MobileImeDebugEntry[]>([]);
const [wechatCopyState, setWechatCopyState] = useState<"idle" | "copying" | "copied" | "error">("idle");
const [memoIdCopyNotice, setMemoIdCopyNotice] = useState<{ status: "copied" | "error"; id: string } | null>(null);
+ const handledSaveAndSyncTokenRef = useRef(saveAndSyncToken);
+ const handledEditorModeToggleTokenRef = useRef(editorModeToggleToken);
const noteLinkModifier = useMemo(
() => typeof navigator !== "undefined" && /mac|iphone|ipad|ipod/i.test(navigator.platform) ? "⌘" : "Ctrl",
[]
@@ -2750,8 +2759,72 @@ const RichEditorPane = ({
// can starve a recovered draft indefinitely. These members are stable (or
// primitive) and are safe effect dependencies.
const mutateSave = saveMutation.mutate;
+ const mutateSaveAsync = saveMutation.mutateAsync;
const saveMutationPending = saveMutation.isPending;
+ const editorShortcutBlocked = Boolean(
+ historyOpen ||
+ shareOpen ||
+ aiAssistantOpen ||
+ systemInfoOpen ||
+ mobileNotebookSheetOpen ||
+ noteLinkPickerOpen ||
+ externalLinkDialogOpen ||
+ resourceDialog ||
+ imagePreview
+ );
+
+ useEffect(() => {
+ if (handledEditorModeToggleTokenRef.current === editorModeToggleToken) {
+ return;
+ }
+
+ handledEditorModeToggleTokenRef.current = editorModeToggleToken;
+ if (editorShortcutBlocked || useMobilePlainTextEditor) {
+ return;
+ }
+
+ handleMarkdownModeChange();
+ }, [editorModeToggleToken, editorShortcutBlocked, handleMarkdownModeChange, useMobilePlainTextEditor]);
+
+ useEffect(() => {
+ if (handledSaveAndSyncTokenRef.current === saveAndSyncToken || saveMutationPending) {
+ return;
+ }
+
+ handledSaveAndSyncTokenRef.current = saveAndSyncToken;
+ if (
+ editorShortcutBlocked ||
+ effectiveReadOnly ||
+ !memoRef.current ||
+ !isEditorReady(editorRef.current) ||
+ saveState === "conflict"
+ ) {
+ return;
+ }
+
+ void (async () => {
+ try {
+ await saveAndSyncEditor({
+ hasUnsavedChanges: hasUnsavedChangesRef.current,
+ save: mutateSaveAsync,
+ sync: onSyncRequested,
+ });
+ } catch {
+ // The save mutation owns its visible error/conflict state. Do not sync
+ // after a failed save because the queue may not contain this snapshot.
+ }
+ })();
+ }, [
+ editorShortcutBlocked,
+ effectiveReadOnly,
+ mutateSaveAsync,
+ onSyncRequested,
+ saveAndSyncToken,
+ saveMutationPending,
+ saveState,
+ ]);
+
const replaceAttachmentLabel = useCallback((target: AttachmentMenuTarget, filename: string) => {
const activeEditor = editorRef.current;
if (!isEditorReady(activeEditor)) return;
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index 020000d7..56aa997a 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -797,6 +797,8 @@ export const WorkspaceApp = ({
const [mobileSearchFocusToken, setMobileSearchFocusToken] = useState(0);
const [noteSearchFocusToken, setNoteSearchFocusToken] = useState(0);
const [noteReplaceFocusToken, setNoteReplaceFocusToken] = useState(0);
+ const [noteSaveAndSyncToken, setNoteSaveAndSyncToken] = useState(0);
+ const [noteEditorModeToggleToken, setNoteEditorModeToggleToken] = useState(0);
const [search, setSearch] = useState("");
const [memoFilterMode, setMemoFilterMode] = useState<MemoFilterMode>("all");
const [memoSortMode, setMemoSortMode] = useState<MemoSortMode>("updated-desc");
@@ -2533,10 +2535,6 @@ export const WorkspaceApp = ({
const targetElement = event.target instanceof Element ? event.target : null;
const isEditorTextTarget = Boolean(targetElement?.closest(".ProseMirror"));
- if ((action === "focusSearch" || action === "focusReplace") && isTextEntryTarget(event.target) && !isEditorTextTarget) {
- return;
- }
-
const transientLayerOpen = Boolean(
appNoticeDialog ||
rightView !== "editor" ||
@@ -2548,6 +2546,27 @@ export const WorkspaceApp = ({
templatesOpen
);
+ if (action === "saveAndSync" || action === "toggleEditorMode") {
+ // These replace browser-level commands, so consume them throughout the
+ // workspace even when the current editor cannot perform the action.
+ event.preventDefault();
+
+ if (event.repeat || event.isComposing || transientLayerOpen || !selectedMemoId || memoView === "trash") {
+ return;
+ }
+
+ if (action === "saveAndSync") {
+ setNoteSaveAndSyncToken((value) => value + 1);
+ } else {
+ setNoteEditorModeToggleToken((value) => value + 1);
+ }
+ return;
+ }
+
+ if ((action === "focusSearch" || action === "focusReplace") && isTextEntryTarget(event.target) && !isEditorTextTarget) {
+ return;
+ }
+
if (transientLayerOpen) {
return;
}
@@ -3023,6 +3042,9 @@ export const WorkspaceApp = ({
contentSearchQuery={search}
searchFocusToken={noteSearchFocusToken}
replaceFocusToken={noteReplaceFocusToken}
+ saveAndSyncToken={noteSaveAndSyncToken}
+ editorModeToggleToken={noteEditorModeToggleToken}
+ onSyncRequested={syncMemosManually}
documentActionRequest={memoDocumentActionRequest}
onDocumentActionConsumed={(requestId) => {
setMemoDocumentActionRequest((current) => current?.id === requestId ? null : current);
diff --git a/apps/web/src/lib/app-helpers.test.mjs b/apps/web/src/lib/app-helpers.test.mjs
index 2017958c..072254a6 100644
--- a/apps/web/src/lib/app-helpers.test.mjs
+++ b/apps/web/src/lib/app-helpers.test.mjs
@@ -1,15 +1,19 @@
import { afterEach, describe, expect, test } from "bun:test";
import {
+ DEFAULT_SHORTCUT_SETTINGS,
DEFAULT_SYNC_INTERVAL_MS,
DESKTOP_FOCUS_MODE_STORAGE_KEY,
EDITOR_CONTENT_ALIGNMENT_STORAGE_KEY,
NOTEBOOK_SORT_STORAGE_KEY,
+ SHORTCUT_SETTINGS_STORAGE_KEY,
SYNC_INTERVAL_STORAGE_KEY,
+ getShortcutActionForEvent,
getNotebookSortComparator,
readEditorContentAlignmentPreference,
readNotebookSortPreference,
readSyncIntervalPreference,
readDesktopFocusModePreference,
+ readShortcutSettingsPreference,
writeEditorContentAlignmentPreference,
writeNotebookSortPreference,
writeSyncIntervalPreference,
@@ -183,3 +187,52 @@ describe("automatic sync interval preference", () => {
expect(readSyncIntervalPreference()).toBe(30_000);
});
});
+
+describe("workspace shortcut preferences", () => {
+ test("provides save, sync, and editor mode defaults", () => {
+ expect(DEFAULT_SHORTCUT_SETTINGS.saveAndSync).toEqual({
+ key: "s",
+ ctrlOrMeta: true,
+ shift: false,
+ alt: false,
+ });
+ expect(DEFAULT_SHORTCUT_SETTINGS.toggleEditorMode).toEqual({
+ key: "/",
+ ctrlOrMeta: true,
+ shift: false,
+ alt: false,
+ });
+ });
+
+ test("fills new shortcut actions into legacy stored settings", () => {
+ const values = installLocalStorage();
+ values.set(SHORTCUT_SETTINGS_STORAGE_KEY, JSON.stringify({
+ createMemo: { key: "m", ctrlOrMeta: true, shift: false, alt: false },
+ }));
+
+ const settings = readShortcutSettingsPreference();
+ expect(settings.createMemo.key).toBe("m");
+ expect(settings.saveAndSync).toEqual(DEFAULT_SHORTCUT_SETTINGS.saveAndSync);
+ expect(settings.toggleEditorMode).toEqual(DEFAULT_SHORTCUT_SETTINGS.toggleEditorMode);
+ });
+
+ test("recognizes Ctrl and Command variants for the new actions", () => {
+ const keyboardEvent = (key, modifiers = {}) => ({
+ key,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ altKey: false,
+ ...modifiers,
+ });
+
+ expect(getShortcutActionForEvent(
+ keyboardEvent("s", { ctrlKey: true }),
+ DEFAULT_SHORTCUT_SETTINGS,
+ )).toBe("saveAndSync");
+ expect(getShortcutActionForEvent(
+ keyboardEvent("/", { metaKey: true }),
+ DEFAULT_SHORTCUT_SETTINGS,
+ )).toBe("toggleEditorMode");
+ });
+});
diff --git a/apps/web/src/lib/app-helpers.ts b/apps/web/src/lib/app-helpers.ts
index fa589c8e..735274e1 100644
--- a/apps/web/src/lib/app-helpers.ts
+++ b/apps/web/src/lib/app-helpers.ts
@@ -13,7 +13,13 @@ export type MemoSortMode = "updated-desc" | "created-desc" | "title-asc";
export type NotebookSortMode = "custom" | "name-asc" | "memo-count-desc" | "updated-desc";
export type EditorContentAlignment = "start" | "center";
export type MemoListDensity = "preview" | "compact";
-export type ShortcutAction = "createMemo" | "createNotebook" | "focusSearch" | "focusReplace";
+export type ShortcutAction =
+ | "createMemo"
+ | "createNotebook"
+ | "focusSearch"
+ | "focusReplace"
+ | "saveAndSync"
+ | "toggleEditorMode";
export type ShortcutBinding = {
key: string;
ctrlOrMeta: boolean;
@@ -180,6 +186,16 @@ export const getShortcutActionOptions = (
label: t("shortcuts.actions.focusReplace.label"),
description: t("shortcuts.actions.focusReplace.description"),
},
+ {
+ value: "saveAndSync",
+ label: t("shortcuts.actions.saveAndSync.label"),
+ description: t("shortcuts.actions.saveAndSync.description"),
+ },
+ {
+ value: "toggleEditorMode",
+ label: t("shortcuts.actions.toggleEditorMode.label"),
+ description: t("shortcuts.actions.toggleEditorMode.description"),
+ },
];
export const DEFAULT_SHORTCUT_SETTINGS: ShortcutSettings = {
@@ -187,13 +203,22 @@ export const DEFAULT_SHORTCUT_SETTINGS: ShortcutSettings = {
createNotebook: { key: "n", ctrlOrMeta: true, shift: true, alt: false },
focusSearch: { key: "f", ctrlOrMeta: true, shift: false, alt: false },
focusReplace: { key: "h", ctrlOrMeta: true, shift: false, alt: false },
+ saveAndSync: { key: "s", ctrlOrMeta: true, shift: false, alt: false },
+ toggleEditorMode: { key: "/", ctrlOrMeta: true, shift: false, alt: false },
};
const SHORTCUT_ALIASES: Partial<Record<ShortcutAction, ShortcutBinding[]>> = {
focusReplace: [{ key: "h", ctrlOrMeta: true, shift: true, alt: false }],
};
-const SHORTCUT_ACTION_VALUES: ShortcutAction[] = ["createMemo", "createNotebook", "focusSearch", "focusReplace"];
+const SHORTCUT_ACTION_VALUES: ShortcutAction[] = [
+ "createMemo",
+ "createNotebook",
+ "focusSearch",
+ "focusReplace",
+ "saveAndSync",
+ "toggleEditorMode",
+];
export const isDefaultMemoTitle = (title: string | null | undefined) => title?.trim() === DEFAULT_MEMO_TITLE;
diff --git a/apps/web/src/lib/editor-shortcuts.test.mjs b/apps/web/src/lib/editor-shortcuts.test.mjs
new file mode 100644
index 00000000..01161753
--- /dev/null
+++ b/apps/web/src/lib/editor-shortcuts.test.mjs
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "bun:test";
+import { saveAndSyncEditor } from "./editor-shortcuts.ts";
+
+describe("editor shortcut actions", () => {
+ test("saves dirty editor content before starting sync", async () => {
+ const calls = [];
+
+ await saveAndSyncEditor({
+ hasUnsavedChanges: true,
+ save: async () => calls.push("save"),
+ sync: async () => calls.push("sync"),
+ });
+
+ expect(calls).toEqual(["save", "sync"]);
+ });
+
+ test("syncs existing queued changes when the editor is already clean", async () => {
+ const calls = [];
+
+ await saveAndSyncEditor({
+ hasUnsavedChanges: false,
+ save: async () => calls.push("save"),
+ sync: async () => calls.push("sync"),
+ });
+
+ expect(calls).toEqual(["sync"]);
+ });
+
+ test("does not sync when saving the current snapshot fails", async () => {
+ const calls = [];
+
+ await expect(saveAndSyncEditor({
+ hasUnsavedChanges: true,
+ save: async () => {
+ calls.push("save");
+ throw new Error("save failed");
+ },
+ sync: async () => calls.push("sync"),
+ })).rejects.toThrow("save failed");
+
+ expect(calls).toEqual(["save"]);
+ });
+});
diff --git a/apps/web/src/lib/editor-shortcuts.ts b/apps/web/src/lib/editor-shortcuts.ts
new file mode 100644
index 00000000..6faedbac
--- /dev/null
+++ b/apps/web/src/lib/editor-shortcuts.ts
@@ -0,0 +1,15 @@
+export const saveAndSyncEditor = async ({
+ hasUnsavedChanges,
+ save,
+ sync,
+}: {
+ hasUnsavedChanges: boolean;
+ save: () => Promise<unknown>;
+ sync: () => Promise<unknown>;
+}) => {
+ if (hasUnsavedChanges) {
+ await save();
+ }
+
+ await sync();
+};
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 4a07cc66..42563d39 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -688,6 +688,14 @@ export const enUS = {
label: "Replace text",
description: "Open replace in the current note.",
},
+ saveAndSync: {
+ label: "Save and sync",
+ description: "Save the current note now and sync pending local changes.",
+ },
+ toggleEditorMode: {
+ label: "Switch editor mode",
+ description: "Switch between Markdown source and rich text editing.",
+ },
},
},
options: {
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 463c174d..f54cd7fd 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -688,6 +688,14 @@ export const zhCN = {
label: "替换文本",
description: "在当前笔记中打开替换。",
},
+ saveAndSync: {
+ label: "保存并同步",
+ description: "立即保存当前笔记,并同步等待中的本地更改。",
+ },
+ toggleEditorMode: {
+ label: "切换编辑模式",
+ description: "在 Markdown 源码与富文本编辑模式之间切换。",
+ },
},
},
options: {