Skip to content

Build your personal knowledge base with Trilium Notes

feat(options): highlight conflicting keyboard shortcuts

Elian Doran9d55e98602f6
diff --git a/apps/client/src/services/shortcuts.spec.ts b/apps/client/src/services/shortcuts.spec.ts
index f20bfd55ae..b0f70033b4 100644
--- a/apps/client/src/services/shortcuts.spec.ts
+++ b/apps/client/src/services/shortcuts.spec.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import shortcuts, { type Handler, isIMEComposing, keyMatches, matchesShortcut, removeIndividualBinding } from "./shortcuts.js";
+import shortcuts, { canonicalizeShortcut, type Handler, isIMEComposing, keyMatches, matchesShortcut, removeIndividualBinding } from "./shortcuts.js";
import utils from "./utils.js";
// Mock utils module
@@ -33,6 +33,38 @@ describe("shortcuts", () => {
shortcuts.removeGlobalShortcut("test-namespace");
});
+ describe("canonicalizeShortcut", () => {
+ it("treats modifiers as an unordered set", () => {
+ expect(canonicalizeShortcut("Ctrl+Shift+J")).toBe(canonicalizeShortcut("Shift+Ctrl+J"));
+ expect(canonicalizeShortcut("Ctrl+Alt+Shift+Meta+K")).toBe(canonicalizeShortcut("Meta+Shift+Alt+Ctrl+K"));
+ });
+
+ it("collapses modifier aliases", () => {
+ expect(canonicalizeShortcut("Control+A")).toBe(canonicalizeShortcut("Ctrl+A"));
+ expect(canonicalizeShortcut("Cmd+A")).toBe(canonicalizeShortcut("Meta+A"));
+ expect(canonicalizeShortcut("Command+A")).toBe(canonicalizeShortcut("Meta+A"));
+ });
+
+ it("collapses key aliases via keyMap", () => {
+ expect(canonicalizeShortcut("Ctrl+Del")).toBe(canonicalizeShortcut("Ctrl+Delete"));
+ expect(canonicalizeShortcut("Ctrl+Enter")).toBe(canonicalizeShortcut("Ctrl+Return"));
+ expect(canonicalizeShortcut("Ctrl+Esc")).toBe(canonicalizeShortcut("Ctrl+Escape"));
+ });
+
+ it("is case insensitive and ignores surrounding whitespace", () => {
+ expect(canonicalizeShortcut("CTRL + j")).toBe(canonicalizeShortcut("ctrl+J"));
+ });
+
+ it("distinguishes genuinely different combinations", () => {
+ expect(canonicalizeShortcut("Ctrl+J")).not.toBe(canonicalizeShortcut("Ctrl+Shift+J"));
+ expect(canonicalizeShortcut("Ctrl+J")).not.toBe(canonicalizeShortcut("Alt+J"));
+ });
+
+ it("returns an empty string for an empty shortcut", () => {
+ expect(canonicalizeShortcut("")).toBe("");
+ });
+ });
+
describe("normalizeShortcut", () => {
it("should normalize shortcut to lowercase and remove whitespace", () => {
expect(shortcuts.normalizeShortcut("Ctrl + A")).toBe("ctrl+a");
diff --git a/apps/client/src/services/shortcuts.ts b/apps/client/src/services/shortcuts.ts
index 800576653d..da3590e62e 100644
--- a/apps/client/src/services/shortcuts.ts
+++ b/apps/client/src/services/shortcuts.ts
@@ -229,6 +229,36 @@ export function keyMatches(e: KeyboardEvent, key: string): boolean {
e.code.toLowerCase() === key.toLowerCase();
}
+/**
+ * Reduces a shortcut string to a canonical form so that two shortcuts that fire on the *same*
+ * physical key combination compare equal, mirroring the runtime semantics of {@link matchesShortcut}:
+ * - modifiers are compared as an unordered set (so `Ctrl+Shift+J` === `Shift+Ctrl+J`),
+ * - modifier aliases collapse (`Control`→`ctrl`, `Cmd`/`Command`→`meta`),
+ * - the final key is mapped through {@link keyMap} so aliases collapse (`Del`===`Delete`, `Enter`===`Return`).
+ *
+ * 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) {
+ return "";
+ }
+
+ const rawKey = parts[parts.length - 1];
+ const modifiers = new Set<string>();
+ for (const modifier of parts.slice(0, -1)) {
+ 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);
+ }
+
+ // Collapse key aliases (e.g. "del" and "delete" both resolve to the same canonical token).
+ const canonicalKey = keyMap[rawKey]?.[0]?.toLowerCase() ?? rawKey;
+
+ return [ ...[ ...modifiers ].sort(), canonicalKey ].join("+");
+}
+
/**
* Simple normalization - just lowercase and trim whitespace
*/
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 9a1323d566..3e4527cc13 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1737,7 +1737,8 @@
"recording_toast": "Press a key combination to assign it, or Esc to cancel.",
"make_global": "Make this a system-wide (global) shortcut",
"make_local": "Make this an in-app shortcut",
- "global_shortcut": "System-wide (global) shortcut, only active on the desktop app"
+ "global_shortcut": "System-wide (global) shortcut, only active on the desktop app",
+ "conflict_chip": "This combination is also assigned to: {{actions}}"
},
"spellcheck": {
"title": "Spell Check",
diff --git a/apps/client/src/widgets/type_widgets/options/shortcuts.css b/apps/client/src/widgets/type_widgets/options/shortcuts.css
index 6b94817f19..7050a667e5 100644
--- a/apps/client/src/widgets/type_widgets/options/shortcuts.css
+++ b/apps/client/src/widgets/type_widgets/options/shortcuts.css
@@ -63,6 +63,14 @@
border-radius: 6px;
}
+ .shortcut-chip.conflict {
+ box-shadow: inset 0 0 0 1px var(--icon-button-danger-color, #d9534f);
+ }
+
+ .shortcut-chip-conflict {
+ color: var(--icon-button-danger-color, #d9534f);
+ }
+
.shortcut-chip kbd {
background: none;
border: none;
diff --git a/apps/client/src/widgets/type_widgets/options/shortcuts.spec.ts b/apps/client/src/widgets/type_widgets/options/shortcuts.spec.ts
index 98825134b0..3366049210 100644
--- a/apps/client/src/widgets/type_widgets/options/shortcuts.spec.ts
+++ b/apps/client/src/widgets/type_widgets/options/shortcuts.spec.ts
@@ -1,11 +1,16 @@
+import { ActionKeyboardShortcut, KeyboardShortcut } from "@triliumnext/commons";
import { describe, expect, it } from "vitest";
-import { keyboardEventToShortcut } from "./shortcuts";
+import { computeConflicts, keyboardEventToShortcut } from "./shortcuts";
function keyEvent(init: KeyboardEventInit) {
return new KeyboardEvent("keydown", init);
}
+function action(actionName: string, friendlyName: string, effectiveShortcuts: string[]): ActionKeyboardShortcut {
+ return { actionName, friendlyName, effectiveShortcuts } as ActionKeyboardShortcut;
+}
+
describe("keyboardEventToShortcut", () => {
it("combines modifiers with the pressed key", () => {
expect(keyboardEventToShortcut(keyEvent({ key: "j", code: "KeyJ", ctrlKey: true }))).toBe("Ctrl+J");
@@ -59,3 +64,85 @@ describe("keyboardEventToShortcut", () => {
});
});
});
+
+describe("computeConflicts", () => {
+ it("reports no conflicts when every shortcut is unique", () => {
+ const conflicts = computeConflicts([
+ action("a", "Action A", [ "Ctrl+J" ]),
+ action("b", "Action B", [ "Ctrl+K" ])
+ ]);
+
+ expect(conflicts.size).toBe(0);
+ });
+
+ it("flags both actions sharing a combination, keyed by the original shortcut string", () => {
+ const conflicts = computeConflicts([
+ action("a", "Action A", [ "Ctrl+J" ]),
+ action("b", "Action B", [ "Ctrl+J" ])
+ ]);
+
+ expect(conflicts.get("a")?.get("Ctrl+J")).toEqual([ "Action B" ]);
+ expect(conflicts.get("b")?.get("Ctrl+J")).toEqual([ "Action A" ]);
+ });
+
+ it("detects conflicts across differing modifier order and key aliases", () => {
+ const conflicts = computeConflicts([
+ action("a", "Action A", [ "Ctrl+Shift+J" ]),
+ action("b", "Action B", [ "Shift+Ctrl+J" ]),
+ action("c", "Action C", [ "Ctrl+Del" ]),
+ action("d", "Action D", [ "Ctrl+Delete" ])
+ ]);
+
+ expect(conflicts.get("a")?.get("Ctrl+Shift+J")).toEqual([ "Action B" ]);
+ expect(conflicts.get("c")?.get("Ctrl+Del")).toEqual([ "Action D" ]);
+ });
+
+ it("treats a global shortcut as conflicting with its in-app equivalent", () => {
+ const conflicts = computeConflicts([
+ action("a", "Action A", [ "global:Ctrl+J" ]),
+ action("b", "Action B", [ "Ctrl+J" ])
+ ]);
+
+ expect(conflicts.get("a")?.get("global:Ctrl+J")).toEqual([ "Action B" ]);
+ expect(conflicts.get("b")?.get("Ctrl+J")).toEqual([ "Action A" ]);
+ });
+
+ it("lists every other action when more than two collide", () => {
+ const conflicts = computeConflicts([
+ action("a", "Action A", [ "Ctrl+J" ]),
+ action("b", "Action B", [ "Ctrl+J" ]),
+ action("c", "Action C", [ "Ctrl+J" ])
+ ]);
+
+ expect(conflicts.get("a")?.get("Ctrl+J")).toEqual([ "Action B", "Action C" ]);
+ });
+
+ it("only marks the conflicting shortcut on an action that also has unique ones", () => {
+ const conflicts = computeConflicts([
+ action("a", "Action A", [ "Ctrl+J", "Ctrl+K" ]),
+ action("b", "Action B", [ "Ctrl+K" ])
+ ]);
+
+ const perShortcut = conflicts.get("a");
+ expect(perShortcut?.has("Ctrl+J")).toBe(false);
+ expect(perShortcut?.get("Ctrl+K")).toEqual([ "Action B" ]);
+ });
+
+ it("does not treat an action's own duplicate shortcut as a conflict", () => {
+ const conflicts = computeConflicts([
+ action("a", "Action A", [ "Ctrl+J", "Ctrl+J" ])
+ ]);
+
+ expect(conflicts.size).toBe(0);
+ });
+
+ it("ignores separators", () => {
+ const conflicts = computeConflicts([
+ { separator: "Group" } as KeyboardShortcut,
+ action("a", "Action A", [ "Ctrl+J" ]),
+ action("b", "Action B", [ "Ctrl+J" ])
+ ]);
+
+ expect(conflicts.get("a")?.get("Ctrl+J")).toEqual([ "Action B" ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/shortcuts.tsx b/apps/client/src/widgets/type_widgets/options/shortcuts.tsx
index 4d46bf78c9..af3c370cd5 100644
--- a/apps/client/src/widgets/type_widgets/options/shortcuts.tsx
+++ b/apps/client/src/widgets/type_widgets/options/shortcuts.tsx
@@ -7,7 +7,7 @@ import dialog from "../../../services/dialog";
import { t } from "../../../services/i18n";
import options from "../../../services/options";
import server from "../../../services/server";
-import { KEYCODES_WITH_NO_MODIFIER } from "../../../services/shortcuts";
+import { canonicalizeShortcut, KEYCODES_WITH_NO_MODIFIER } from "../../../services/shortcuts";
import toast from "../../../services/toast";
import { arrayEqual, isElectron, reloadFrontendApp } from "../../../services/utils";
import ActionButton from "../../react/ActionButton";
@@ -79,6 +79,7 @@ export default function ShortcutSettings() {
const filterLowerCase = filter?.toLowerCase() ?? "";
const groups = useMemo(() => groupShortcuts(keyboardShortcuts), [ keyboardShortcuts ]);
+ const conflicts = useMemo(() => computeConflicts(keyboardShortcuts), [ keyboardShortcuts ]);
const filteredGroups = groups
.map((group) => ({
...group,
@@ -104,7 +105,7 @@ export default function ShortcutSettings() {
? filteredGroups.map((group) => (
<OptionsSection key={group.title} title={group.title}>
{group.actions.map((action) => (
- <ShortcutRow key={action.actionName} action={action} />
+ <ShortcutRow key={action.actionName} action={action} conflicts={conflicts.get(action.actionName)} />
))}
</OptionsSection>
))
@@ -149,6 +150,76 @@ function groupShortcuts(shortcuts: KeyboardShortcut[]): ShortcutGroup[] {
return groups;
}
+/**
+ * Maps a single shortcut string (as stored, e.g. `Ctrl+J` or `global:Ctrl+J`) to the friendly names
+ * of the *other* actions that fire on the same physical combination.
+ */
+type ShortcutConflicts = Map<string, string[]>;
+
+/**
+ * Detects shortcut conflicts in a single O(total shortcuts) pass and returns a render-ready lookup:
+ * `actionName → (shortcut string → conflicting action names)`. A row not present in the map has no
+ * conflicts, and a shortcut not present on a row's entry is conflict-free — so the render path is
+ * just two cheap map lookups, with all the canonicalization done up front.
+ *
+ * Two shortcuts conflict when their {@link canonicalizeShortcut} forms match. The `global:` prefix is
+ * stripped first: an OS-level global shortcut still swallows the same combination an in-app one wants.
+ */
+export function computeConflicts(shortcuts: KeyboardShortcut[]): Map<string, ShortcutConflicts> {
+ // First pass: bucket every action by the canonical combination of each of its shortcuts.
+ const byCombo = new Map<string, ActionKeyboardShortcut[]>();
+ for (const shortcut of shortcuts) {
+ if (!("actionName" in shortcut)) {
+ continue;
+ }
+
+ for (const combo of shortcut.effectiveShortcuts ?? []) {
+ const key = canonicalizeShortcut(stripGlobalPrefix(combo));
+ if (!key) {
+ continue;
+ }
+
+ let actions = byCombo.get(key);
+ if (!actions) {
+ byCombo.set(key, actions = []);
+ }
+ if (!actions.includes(shortcut)) {
+ actions.push(shortcut);
+ }
+ }
+ }
+
+ // Second pass: for combinations shared by 2+ actions, record the conflicting names per action.
+ const result = new Map<string, ShortcutConflicts>();
+ for (const shortcut of shortcuts) {
+ if (!("actionName" in shortcut)) {
+ continue;
+ }
+
+ for (const combo of shortcut.effectiveShortcuts ?? []) {
+ const actions = byCombo.get(canonicalizeShortcut(stripGlobalPrefix(combo)));
+ if (!actions || actions.length < 2) {
+ continue;
+ }
+
+ const others = actions
+ .filter((other) => other !== shortcut)
+ .map((other) => other.friendlyName ?? other.actionName);
+ if (!others.length) {
+ continue;
+ }
+
+ let perShortcut = result.get(shortcut.actionName);
+ if (!perShortcut) {
+ result.set(shortcut.actionName, perShortcut = new Map());
+ }
+ perShortcut.set(combo, [ ...new Set(others) ]);
+ }
+ }
+
+ return result;
+}
+
function isShortcutModified(action: ActionKeyboardShortcut) {
return !arrayEqual(action.effectiveShortcuts ?? [], action.defaultShortcuts ?? []);
}
@@ -171,7 +242,7 @@ function filterKeyboardAction(action: ActionKeyboardShortcut, filter: string) {
(action.description && action.description.toLowerCase().includes(filter));
}
-function ShortcutRow({ action }: { action: ActionKeyboardShortcut }) {
+function ShortcutRow({ action, conflicts }: { action: ActionKeyboardShortcut; conflicts?: ShortcutConflicts }) {
return (
<OptionsRow
name={action.actionName}
@@ -185,7 +256,7 @@ function ShortcutRow({ action }: { action: ActionKeyboardShortcut }) {
description={action.description}
>
<div class="shortcut-row-input">
- <ShortcutEditor keyboardShortcut={action} />
+ <ShortcutEditor keyboardShortcut={action} conflicts={conflicts} />
{/* Always reserve the slot so the revert button appearing/disappearing never shifts the row. */}
<span class="shortcut-revert-slot">
{isShortcutModified(action) &&
@@ -201,7 +272,7 @@ function ShortcutRow({ action }: { action: ActionKeyboardShortcut }) {
);
}
-function ShortcutEditor({ keyboardShortcut: action }: { keyboardShortcut: ActionKeyboardShortcut }) {
+function ShortcutEditor({ keyboardShortcut: action, conflicts }: { keyboardShortcut: ActionKeyboardShortcut; conflicts?: ShortcutConflicts }) {
const shortcuts = action.effectiveShortcuts ?? [];
const electron = isElectron();
@@ -225,8 +296,14 @@ function ShortcutEditor({ keyboardShortcut: action }: { keyboardShortcut: Action
<div class="shortcut-editor">
{shortcuts.map((shortcut) => {
const global = isGlobalShortcut(shortcut);
+ const conflictsWith = conflicts?.get(shortcut);
return (
- <span class={`shortcut-chip ${global ? "global" : ""}`} key={shortcut}>
+ <span class={`shortcut-chip ${global ? "global" : ""} ${conflictsWith ? "conflict" : ""}`} key={shortcut}>
+ {conflictsWith &&
+ <span
+ class="bx bx-error-circle shortcut-chip-conflict"
+ title={t("shortcuts.conflict_chip", { actions: conflictsWith.join(", ") })}
+ />}
{electron
? (
<button