Skip to content

Build your personal knowledge base with Trilium Notes

feat(client): translatable keyboard shortcut display formatter

Elian Doran3417dae9083a
diff --git a/apps/client/src/services/keyboard_shortcut_display.spec.ts b/apps/client/src/services/keyboard_shortcut_display.spec.ts
new file mode 100644
index 0000000000..89c58eb6d2
--- /dev/null
+++ b/apps/client/src/services/keyboard_shortcut_display.spec.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ formatShortcut,
+ formatShortcutKey,
+ SHORTCUT_KEY_PREFIX,
+ splitShortcutForDisplay,
+ type ShortcutKeyTranslator
+} from "./keyboard_shortcut_display.js";
+
+/** Fake i18n resolver: uppercases the id and prefixes `L·` so translated output is unmistakable. */
+const fakeTranslate: ShortcutKeyTranslator = (id) => `L·${id.toUpperCase()}`;
+
+describe("keyboard_shortcut_display", () => {
+ describe("splitShortcutForDisplay", () => {
+ it("splits modifiers and the final key, preserving order and casing", () => {
+ expect(splitShortcutForDisplay("Ctrl+Shift+J")).toEqual([ "Ctrl", "Shift", "J" ]);
+ expect(splitShortcutForDisplay("Alt+Left")).toEqual([ "Alt", "Left" ]);
+ expect(splitShortcutForDisplay("F5")).toEqual([ "F5" ]);
+ });
+
+ it("keeps punctuation keys as their own token", () => {
+ expect(splitShortcutForDisplay("Meta+[")).toEqual([ "Meta", "[" ]);
+ expect(splitShortcutForDisplay("Ctrl+=")).toEqual([ "Ctrl", "=" ]);
+ expect(splitShortcutForDisplay("Alt+-")).toEqual([ "Alt", "-" ]);
+ expect(splitShortcutForDisplay("Ctrl+.")).toEqual([ "Ctrl", "." ]);
+ });
+
+ it("handles the plus key encoded as a lone or trailing '+'", () => {
+ expect(splitShortcutForDisplay("+")).toEqual([ "+" ]);
+ expect(splitShortcutForDisplay("Ctrl++")).toEqual([ "Ctrl", "+" ]);
+ expect(splitShortcutForDisplay("Ctrl+Alt++")).toEqual([ "Ctrl", "Alt", "+" ]);
+ });
+
+ it("strips a leading global: prefix so it never reaches the display", () => {
+ expect(splitShortcutForDisplay("global:Meta+Plus")).toEqual([ "Meta", "Plus" ]);
+ expect(splitShortcutForDisplay("global:Ctrl+Alt+P")).toEqual([ "Ctrl", "Alt", "P" ]);
+ });
+
+ it("trims surrounding whitespace and returns [] for empty/nullish input", () => {
+ expect(splitShortcutForDisplay(" Ctrl+J ")).toEqual([ "Ctrl", "J" ]);
+ expect(splitShortcutForDisplay("")).toEqual([]);
+ expect(splitShortcutForDisplay(" ")).toEqual([]);
+ expect(splitShortcutForDisplay(undefined as unknown as string)).toEqual([]);
+ });
+ });
+
+ describe("formatShortcutKey", () => {
+ it("maps modifiers and their aliases to a single canonical English label", () => {
+ expect(formatShortcutKey("Ctrl")).toBe("Ctrl");
+ expect(formatShortcutKey("Control")).toBe("Ctrl");
+ expect(formatShortcutKey("CommandOrControl")).toBe("Ctrl");
+ expect(formatShortcutKey("Meta")).toBe("Meta");
+ expect(formatShortcutKey("Cmd")).toBe("Meta");
+ expect(formatShortcutKey("Command")).toBe("Meta");
+ });
+
+ it("maps named-key aliases to one label and matches case-insensitively", () => {
+ expect(formatShortcutKey("Enter")).toBe("Enter");
+ expect(formatShortcutKey("Return")).toBe("Enter");
+ expect(formatShortcutKey("Del")).toBe("Delete");
+ expect(formatShortcutKey("delete")).toBe("Delete");
+ expect(formatShortcutKey("ESC")).toBe("Esc");
+ expect(formatShortcutKey("ArrowUp")).toBe("Up");
+ expect(formatShortcutKey("up")).toBe("Up");
+ expect(formatShortcutKey("PageDown")).toBe("Page Down");
+ });
+
+ it("renders the plus key (named token or glyph) as '+'", () => {
+ expect(formatShortcutKey("Plus")).toBe("+");
+ expect(formatShortcutKey("+")).toBe("+");
+ });
+
+ it("passes non-table tokens through verbatim (letters, digits, function keys, punctuation)", () => {
+ expect(formatShortcutKey("J")).toBe("J");
+ expect(formatShortcutKey("5")).toBe("5");
+ expect(formatShortcutKey("F11")).toBe("F11");
+ expect(formatShortcutKey("[")).toBe("[");
+ expect(formatShortcutKey("=")).toBe("=");
+ });
+
+ it("uses the translator for known tokens and ignores it for pass-through tokens", () => {
+ expect(formatShortcutKey("Ctrl", fakeTranslate)).toBe("L·CTRL");
+ expect(formatShortcutKey("ArrowLeft", fakeTranslate)).toBe("L·LEFT");
+ // Letters have no id, so the translator is never consulted.
+ expect(formatShortcutKey("J", fakeTranslate)).toBe("J");
+ });
+
+ it("falls back to the English default when the translator returns a nullish value", () => {
+ const emptyTranslate: ShortcutKeyTranslator = () => undefined;
+ const blankTranslate: ShortcutKeyTranslator = () => "";
+ expect(formatShortcutKey("Shift", emptyTranslate)).toBe("Shift");
+ expect(formatShortcutKey("Shift", blankTranslate)).toBe("Shift");
+ });
+ });
+
+ describe("formatShortcut", () => {
+ it("produces an ordered list of English labels by default", () => {
+ expect(formatShortcut("Ctrl+Shift+J")).toEqual([ "Ctrl", "Shift", "J" ]);
+ expect(formatShortcut("Alt+Left")).toEqual([ "Alt", "Left" ]);
+ expect(formatShortcut("Meta+Plus")).toEqual([ "Meta", "+" ]);
+ expect(formatShortcut("F5")).toEqual([ "F5" ]);
+ });
+
+ it("translates every table token while leaving pass-through tokens intact", () => {
+ expect(formatShortcut("Ctrl+Shift+Up", fakeTranslate)).toEqual([ "L·CTRL", "L·SHIFT", "L·UP" ]);
+ expect(formatShortcut("Ctrl+J", fakeTranslate)).toEqual([ "L·CTRL", "J" ]);
+ });
+
+ it("strips global: and normalizes aliases end-to-end", () => {
+ expect(formatShortcut("global:CommandOrControl+Alt+P")).toEqual([ "Ctrl", "Alt", "P" ]);
+ expect(formatShortcut("Cmd+ArrowRight")).toEqual([ "Meta", "Right" ]);
+ });
+
+ it("returns [] for an empty shortcut", () => {
+ expect(formatShortcut("")).toEqual([]);
+ });
+ });
+
+ it("exposes the i18n key prefix for the integration layer", () => {
+ expect(SHORTCUT_KEY_PREFIX).toBe("keyboard_shortcut_keys");
+ });
+});
diff --git a/apps/client/src/services/keyboard_shortcut_display.ts b/apps/client/src/services/keyboard_shortcut_display.ts
new file mode 100644
index 0000000000..461ea2f811
--- /dev/null
+++ b/apps/client/src/services/keyboard_shortcut_display.ts
@@ -0,0 +1,127 @@
+/**
+ * Translatable, display-only formatting of keyboard shortcut strings.
+ *
+ * Shortcuts are *stored* in a canonical, language-independent format (e.g. `Ctrl+Shift+J`,
+ * `Alt+Left`, `Meta+Plus`). That stored form is load-bearing — it drives keystroke matching,
+ * conflict detection, option persistence, and Electron global-shortcut registration — so it must
+ * never be translated. This module translates a shortcut only at the moment it is *shown* to the
+ * user, leaving the stored value untouched.
+ *
+ * The single rule is: split the shortcut on `+`, then look up each token in {@link TRANSLATABLE_KEYS}.
+ * A token found in the table is replaced by its translated (or default English) label; a token not in
+ * the table — letters, digits, function keys, punctuation — is emitted verbatim, since those are
+ * identical across languages.
+ *
+ * The core is a pure function that takes an injected `translate` callback, so it can be unit-tested
+ * (and used) without booting the i18n runtime. Callers that want localized output pass a `translate`
+ * that resolves `${SHORTCUT_KEY_PREFIX}.<id>`.
+ */
+
+/** i18n key prefix under which the per-token labels live once this mapper is wired to translations. */
+export const SHORTCUT_KEY_PREFIX = "keyboard_shortcut_keys";
+
+/** Resolves a token id (e.g. `"ctrl"`) to a localized label, or a nullish value when untranslated. */
+export type ShortcutKeyTranslator = (id: string) => string | null | undefined;
+
+const GLOBAL_PREFIX = "global:";
+
+/**
+ * Formats a single stored shortcut string into an ordered list of display tokens. The array is the
+ * flexible primitive every display site can build on: wrap each token in its own `<kbd>`, join with
+ * `+`, or join with spaces, as that site prefers.
+ *
+ * A leading `global:` prefix (a storage detail) is stripped so it never leaks into the display.
+ *
+ * @param shortcut a stored shortcut, e.g. `"Ctrl+Shift+J"`, `"global:Meta+Plus"`, `"F5"`.
+ * @param translate optional token-id → label resolver; omit for the built-in English labels.
+ */
+export function formatShortcut(shortcut: string, translate?: ShortcutKeyTranslator): string[] {
+ return splitShortcutForDisplay(shortcut).map((token) => formatShortcutKey(token, translate));
+}
+
+/**
+ * Splits a stored shortcut into its ordered tokens (modifiers followed by the final key), preserving
+ * original casing. Mirrors the plus-key handling of the matcher in `shortcuts.ts`: `+` doubles as the
+ * separator, so the plus key is encoded either as the named token `Plus` or as a lone/trailing `+`
+ * (`"+"`, or a string ending in `"++"` such as `"Ctrl++"`), all of which yield a `"+"` token here.
+ */
+export function splitShortcutForDisplay(shortcut: string): string[] {
+ const bare = stripGlobalPrefix((shortcut ?? "").trim());
+ if (!bare) {
+ return [];
+ }
+
+ if (bare === "+" || bare.endsWith("++")) {
+ const modifiers = bare.slice(0, -1).split("+").filter((part) => part.trim() !== "");
+ return [ ...modifiers, "+" ];
+ }
+
+ return bare.split("+");
+}
+
+/**
+ * Translates one shortcut token. Tokens present in {@link TRANSLATABLE_KEYS} (modifiers and named
+ * keys, matched case-insensitively) resolve to their localized label, falling back to the built-in
+ * English default when `translate` is absent or returns nothing. Any other token — a letter, digit,
+ * function key, or punctuation key — is returned unchanged.
+ */
+export function formatShortcutKey(token: string, translate?: ShortcutKeyTranslator): string {
+ const entry = TRANSLATABLE_KEYS[token.toLowerCase()];
+ if (!entry) {
+ return token;
+ }
+
+ const translated = translate?.(entry.id);
+ return translated ? translated : entry.en;
+}
+
+function stripGlobalPrefix(shortcut: string): string {
+ return shortcut.startsWith(GLOBAL_PREFIX) ? shortcut.substring(GLOBAL_PREFIX.length) : shortcut;
+}
+
+/**
+ * Maps a raw shortcut token (lowercased, aliases collapsed) to its stable translation `id` and the
+ * built-in English label used when no translation is available. Tokens absent from this table are
+ * rendered verbatim, so only modifiers and named keys — the parts that differ across languages — need
+ * an entry.
+ */
+const TRANSLATABLE_KEYS: Record<string, { id: string; en: string }> = {
+ // Modifiers.
+ ctrl: { id: "ctrl", en: "Ctrl" },
+ control: { id: "ctrl", en: "Ctrl" },
+ // Resolved to a concrete modifier server-side; folded to Ctrl here defensively for display.
+ commandorcontrol: { id: "ctrl", en: "Ctrl" },
+ alt: { id: "alt", en: "Alt" },
+ shift: { id: "shift", en: "Shift" },
+ meta: { id: "meta", en: "Meta" },
+ cmd: { id: "meta", en: "Meta" },
+ command: { id: "meta", en: "Meta" },
+
+ // Named keys.
+ enter: { id: "enter", en: "Enter" },
+ return: { id: "enter", en: "Enter" },
+ escape: { id: "escape", en: "Esc" },
+ esc: { id: "escape", en: "Esc" },
+ delete: { id: "delete", en: "Delete" },
+ del: { id: "delete", en: "Delete" },
+ backspace: { id: "backspace", en: "Backspace" },
+ space: { id: "space", en: "Space" },
+ tab: { id: "tab", en: "Tab" },
+ home: { id: "home", en: "Home" },
+ end: { id: "end", en: "End" },
+ pageup: { id: "page_up", en: "Page Up" },
+ pagedown: { id: "page_down", en: "Page Down" },
+ up: { id: "up", en: "Up" },
+ arrowup: { id: "up", en: "Up" },
+ down: { id: "down", en: "Down" },
+ arrowdown: { id: "down", en: "Down" },
+ left: { id: "left", en: "Left" },
+ arrowleft: { id: "left", en: "Left" },
+ right: { id: "right", en: "Right" },
+ arrowright: { id: "right", en: "Right" },
+ // The plus key is stored as the named token `Plus`; displayed as the "+" glyph.
+ plus: { id: "plus", en: "+" },
+ "+": { id: "plus", en: "+" },
+ insert: { id: "insert", en: "Insert" },
+ ins: { id: "insert", en: "Insert" }
+};