Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(shortcuts): bind the + key so zoom-in works on non-US keyboards, closes #9741
Elian Doran7dfe754cb073
diff --git a/apps/client/src/services/shortcuts.spec.ts b/apps/client/src/services/shortcuts.spec.tsindex b0f70033b4..c3ff82cc7c 100644--- a/apps/client/src/services/shortcuts.spec.ts+++ b/apps/client/src/services/shortcuts.spec.ts@@ -602,6 +602,67 @@ describe("shortcuts", () => {});});+ describe("the plus key (German / European layouts)", () => {+ // On QWERTZ and most European layouts "+" is its own key (e.code "BracketRight"), not+ // Shift+"=". Because "+" doubles as the shortcut separator, it used to be impossible to bind.+ const ctrlPlus = (extra: Partial<KeyboardEvent> = {}) => ({+ key: "+",+ code: "BracketRight",+ ctrlKey: true,+ altKey: false,+ shiftKey: false,+ metaKey: false,+ ...extra+ } as KeyboardEvent);++ it("matches the raw '++' encoding (e.g. a stored or hand-typed Ctrl++)", () => {+ expect(matchesShortcut(ctrlPlus(), "Ctrl++")).toBe(true);+ expect(matchesShortcut(ctrlPlus({ shiftKey: true }), "Ctrl++")).toBe(false);+ });++ it("matches the named 'Plus' token", () => {+ expect(matchesShortcut(ctrlPlus(), "Ctrl+Plus")).toBe(true);+ expect(matchesShortcut(ctrlPlus({ ctrlKey: false }), "Ctrl+Plus")).toBe(false);+ });++ it("matches the numpad plus key", () => {+ const numpadPlus = ctrlPlus({ code: "NumpadAdd" });+ expect(matchesShortcut(numpadPlus, "Ctrl+Plus")).toBe(true);+ expect(matchesShortcut(numpadPlus, "Ctrl++")).toBe(true);+ });++ it("does not confuse the plus key with the equals key", () => {+ // US layout zoom-in default is Ctrl+= (Shift+= produces "+"); these must stay distinct.+ const ctrlEquals = ctrlPlus({ key: "=", code: "Equal" });+ expect(matchesShortcut(ctrlEquals, "Ctrl++")).toBe(false);+ expect(matchesShortcut(ctrlPlus(), "Ctrl+=")).toBe(false);+ });++ it("matchesShortcut with multiple modifiers and the plus key", () => {+ expect(matchesShortcut(ctrlPlus({ shiftKey: true }), "Ctrl+Shift++")).toBe(true);+ expect(matchesShortcut(ctrlPlus({ shiftKey: true }), "Ctrl+Shift+Plus")).toBe(true);+ });++ it("keyMatches resolves the 'plus' token to the '+' character", () => {+ expect(keyMatches({ key: "+", code: "BracketRight" } as KeyboardEvent, "plus")).toBe(true);+ expect(keyMatches({ key: "=", code: "Equal" } as KeyboardEvent, "plus")).toBe(false);+ });++ it("canonicalizes the raw and named plus forms to the same combination", () => {+ expect(canonicalizeShortcut("Ctrl++")).toBe(canonicalizeShortcut("Ctrl+Plus"));+ expect(canonicalizeShortcut("Ctrl++")).not.toBe(canonicalizeShortcut("Ctrl+="));+ });++ it("normalizeShortcut keeps a valid Ctrl++ without warning", () => {+ const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});++ expect(shortcuts.normalizeShortcut("Ctrl++")).toBe("ctrl++");++ expect(consoleSpy).not.toHaveBeenCalled();+ consoleSpy.mockRestore();+ });+ });+describe("matchesShortcut empty-key guard", () => {it("should warn and return false when the key part is only whitespace", () => {const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});diff --git a/apps/client/src/services/shortcuts.ts b/apps/client/src/services/shortcuts.tsindex da3590e62e..d0284cc175 100644--- a/apps/client/src/services/shortcuts.ts+++ b/apps/client/src/services/shortcuts.ts@@ -32,7 +32,11 @@ const keyMap: { [key: string]: string[] } = {'up': ['ArrowUp'],'down': ['ArrowDown'],'left': ['ArrowLeft'],- 'right': ['ArrowRight']+ 'right': ['ArrowRight'],+ // "+" doubles as the shortcut separator, so the plus key is referred to by the named "plus" token+ // (e.g. "Ctrl+Plus"). Matches any key that produces "+": the dedicated key on QWERTZ/AZERTY+ // layouts, Shift+"=" on US layouts, and the numpad "+".+ 'plus': ['+']};// Function keys@@ -162,9 +166,7 @@ export function matchesShortcut(e: KeyboardEvent, shortcut: string): boolean {return false;}- const parts = shortcut.toLowerCase().split('+');- const key = parts[parts.length - 1]; // Last part is the actual key- const modifiers = parts.slice(0, -1); // Everything before is modifiers+ const { modifiers, key } = splitShortcut(shortcut);// Defensive check - ensure we have a valid keyif (!key || key.trim() === '') {@@ -239,26 +241,47 @@ export function keyMatches(e: KeyboardEvent, key: string): boolean {* Intended for conflict detection in the settings UI, not for binding.*/export function canonicalizeShortcut(shortcut: string): string {- const parts = shortcut.toLowerCase().split("+").map((p) => p.trim()).filter(Boolean);- if (parts.length === 0) {+ const { modifiers: rawModifiers, key: rawKey } = splitShortcut(shortcut);+ if (!rawKey) {return "";}- const rawKey = parts[parts.length - 1];const modifiers = new Set<string>();- for (const modifier of parts.slice(0, -1)) {+ for (const modifier of rawModifiers) {if (modifier === "ctrl" || modifier === "control") modifiers.add("ctrl");else if (modifier === "meta" || modifier === "cmd" || modifier === "command") modifiers.add("meta");else if (modifier === "alt" || modifier === "shift") modifiers.add(modifier);- else modifiers.add(modifier);+ else if (modifier) modifiers.add(modifier);}- // Collapse key aliases (e.g. "del" and "delete" both resolve to the same canonical token).+ // Collapse key aliases (e.g. "del" and "delete" both resolve to the same canonical token, and+ // the named "plus" token resolves to the raw "+" key).const canonicalKey = keyMap[rawKey]?.[0]?.toLowerCase() ?? rawKey;return [ ...[ ...modifiers ].sort(), canonicalKey ].join("+");}+/**+ * Splits a shortcut string into its modifier list and final key, returning both lowercased and+ * trimmed. Handles the one key that collides with the "+" separator: the plus key is encoded either+ * as a lone "+" (no modifiers) or as a trailing "++" (e.g. "Ctrl++"), both of which yield a key of+ * "+". Aliases like the named "plus" token are left untouched here and collapsed by the callers via+ * {@link keyMap}.+ */+function splitShortcut(shortcut: string): { modifiers: string[]; key: string } {+ const lower = (shortcut ?? "").toLowerCase().trim();++ // A trailing "+" (the whole string is "+", or it ends in "++") denotes the plus key, since a key+ // is always the final token and "+" is otherwise the separator.+ if (lower === "+" || lower.endsWith("++")) {+ const modifiers = lower.slice(0, -1).split("+").map((p) => p.trim()).filter(Boolean);+ return { modifiers, key: "+" };+ }++ const parts = lower.split("+").map((p) => p.trim());+ return { modifiers: parts.slice(0, -1), key: parts[parts.length - 1] };+}+/*** Simple normalization - just lowercase and trim whitespace*/@@ -269,8 +292,11 @@ function normalizeShortcut(shortcut: string): string {const normalized = shortcut.toLowerCase().trim().replace(/\s+/g, '');- // Warn about potentially problematic shortcuts- if (normalized.endsWith('+') || normalized.startsWith('+') || normalized.includes('++')) {+ // Warn about potentially problematic shortcuts: a missing key (e.g. "ctrl+") or an empty modifier+ // (e.g. "+a" or the double-separator "ctrl++a"). A genuine plus-key binding like "ctrl++" parses+ // to a "+" key with no empty modifiers and is left alone.+ const { modifiers, key } = splitShortcut(normalized);+ if (!key || modifiers.some((modifier) => !modifier)) {console.warn('Potentially malformed shortcut:', shortcut, '-> normalized to:', normalized);}diff --git a/apps/client/src/widgets/type_widgets/options/shortcuts.spec.ts b/apps/client/src/widgets/type_widgets/options/shortcuts.spec.tsindex 8806a567c4..a9f95f6960 100644--- a/apps/client/src/widgets/type_widgets/options/shortcuts.spec.ts+++ b/apps/client/src/widgets/type_widgets/options/shortcuts.spec.ts@@ -32,6 +32,13 @@ describe("keyboardEventToShortcut", () => {expect(keyboardEventToShortcut(keyEvent({ key: "1", code: "Numpad1", ctrlKey: true }))).toBe("Ctrl+1");});+ it("records the plus key as the named 'Plus' token", () => {+ // On a German/QWERTZ layout "+" is its own key (code "BracketRight"); storing it verbatim as+ // "Ctrl++" collides with the separator, so it is normalized to a stable "Plus" token.+ expect(keyboardEventToShortcut(keyEvent({ key: "+", code: "BracketRight", ctrlKey: true }))).toBe("Ctrl+Plus");+ expect(keyboardEventToShortcut(keyEvent({ key: "+", code: "NumpadAdd", ctrlKey: true }))).toBe("Ctrl+Plus");+ });+it("maps arrow and space keys to the stored names", () => {expect(keyboardEventToShortcut(keyEvent({ key: "ArrowLeft", code: "ArrowLeft", altKey: true }))).toBe("Alt+Left");expect(keyboardEventToShortcut(keyEvent({ key: "ArrowUp", code: "ArrowUp", ctrlKey: true }))).toBe("Ctrl+Up");diff --git a/apps/client/src/widgets/type_widgets/options/shortcuts.tsx b/apps/client/src/widgets/type_widgets/options/shortcuts.tsxindex 5024f16c24..3e5e24bc98 100644--- a/apps/client/src/widgets/type_widgets/options/shortcuts.tsx+++ b/apps/client/src/widgets/type_widgets/options/shortcuts.tsx@@ -633,7 +633,10 @@ const MODIFIER_KEYS = new Set([ "Control", "Alt", "Shift", "Meta" ]);const NAMED_KEYS: Record<string, string> = {ArrowUp: "Up", ArrowDown: "Down", ArrowLeft: "Left", ArrowRight: "Right",- " ": "Space", Spacebar: "Space"+ " ": "Space", Spacebar: "Space",+ // "+" collides with the shortcut separator, so it is stored as the named "Plus" token instead of+ // a literal "+". On QWERTZ/AZERTY this is a dedicated key; on US layouts it is Shift+"=".+ "+": "Plus"};/**diff --git a/packages/trilium-core/src/services/keyboard_actions.spec.ts b/packages/trilium-core/src/services/keyboard_actions.spec.tsindex ce8b3bdc69..169d53a6e0 100644--- a/packages/trilium-core/src/services/keyboard_actions.spec.ts+++ b/packages/trilium-core/src/services/keyboard_actions.spec.ts@@ -39,6 +39,18 @@ describe("keyboard_actions service", () => {expect(actions.some((a) => "actionName" in a && a.actionName === "jumpToNote")).toBe(true);});+ it("zoomIn is bound to the plus key as well as equals, so it works on non-US layouts", () => {+ const actions = keyboardActions.getDefaultKeyboardActions();+ const zoomIn = actions.find((a) => "actionName" in a && a.actionName === "zoomIn");+ const shortcuts = (zoomIn && "defaultShortcuts" in zoomIn && zoomIn.defaultShortcuts) || [];++ // Electron-only action: present with both bindings under Electron, empty otherwise.+ if (shortcuts.length > 0) {+ expect(shortcuts.some((s) => s.endsWith("+Plus"))).toBe(true);+ expect(shortcuts.some((s) => s.endsWith("+="))).toBe(true);+ }+ });+it("throws if loaded before translations are available", async () => {// keyboard_actions was already evaluated during the bootstrap (binding the// real i18next), so re-import a fresh copy that picks up the mocked module.diff --git a/packages/trilium-core/src/services/keyboard_actions.ts b/packages/trilium-core/src/services/keyboard_actions.tsindex 19a3b486b4..323051c859 100644--- a/packages/trilium-core/src/services/keyboard_actions.ts+++ b/packages/trilium-core/src/services/keyboard_actions.ts@@ -779,7 +779,9 @@ function getDefaultKeyboardActions() {actionName: "zoomIn",friendlyName: t("keyboard_action_names.zoom-in"),iconClass: "bx bx-zoom-in",- defaultShortcuts: isElectron() ? ["CommandOrControl+="] : [],+ // "=" covers US layouts (where "+" is Shift+"="); "Plus" covers QWERTZ/AZERTY and the+ // numpad, where "+" is a dedicated key that "=" never matches. See keyMap in shortcuts.ts.+ defaultShortcuts: isElectron() ? ["CommandOrControl+=", "CommandOrControl+Plus"] : [],isElectronOnly: true,scope: "window"},