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
client/shortcut hints: implement the dispatcher and command entry
Adorian Doran0199c30cfc9b
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex 60817e2677..1b48abad09 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -12,6 +12,7 @@ import linkService, { type ViewScope } from "../services/link.js";import type LoadResults from "../services/load_results.js";import type { CreateNoteOpts } from "../services/note_create.js";import options from "../services/options.js";+import type { ShortcutHintSection } from "../services/shortcut_hints.js";import toast from "../services/toast.js";import utils from "../services/utils.js";import { ReactWrappedWidget } from "../widgets/basic_widget.js";@@ -331,6 +332,7 @@ export type CommandMappings = {showSQLConsole: CommandData;showBackendLog: CommandData;showCheatsheet: CommandData;+ showShortcutHints: CommandData;showHelp: CommandData;addLinkToText: CommandData;followLinkUnderCursor: CommandData;@@ -449,6 +451,11 @@ type EventMappings = {activeContextChanged: {noteContext: NoteContext;};+ /** Emitted by the {@link CommandMappings.showShortcutHints} handler with the hints collected from+ * the focused component chain, for the shortcut-hints pane to render. */+ shortcutHintsRequested: {+ sections: ShortcutHintSection[];+ };beforeNoteSwitch: {noteContext: NoteContext;};diff --git a/apps/client/src/components/root_command_executor.ts b/apps/client/src/components/root_command_executor.tsindex aaaa09493e..9d8b4e9303 100644--- a/apps/client/src/components/root_command_executor.ts+++ b/apps/client/src/components/root_command_executor.ts@@ -3,6 +3,7 @@ import froca from "../services/froca.js";import openService from "../services/open.js";import options from "../services/options.js";import protectedSessionService from "../services/protected_session.js";+import { collectShortcutHints } from "../services/shortcut_hints.js";import treeService from "../services/tree.js";import utils, { openInReusableSplit } from "../services/utils.js";import appContext, { type CommandListenerData } from "./app_context.js";@@ -17,6 +18,11 @@ export default class RootCommandExecutor extends Component {}}+ async showShortcutHintsCommand() {+ const sections = collectShortcutHints(await resolveFocusedComponent());+ appContext.triggerEvent("shortcutHintsRequested", { sections });+ }+async showSQLConsoleCommand() {const sqlConsoleNote = await dateNoteService.createSqlConsole();if (!sqlConsoleNote) {@@ -245,3 +251,19 @@ export default class RootCommandExecutor extends Component {}}++/**+ * The component to start collecting shortcut hints from: the one owning the focused element, or —+ * when nothing focusable is (e.g. the image/media viewers) — the active pane's type widget.+ */+async function resolveFocusedComponent(): Promise<Component | undefined> {+ const activeEl = document.activeElement;+ if (activeEl instanceof HTMLElement) {+ const component = appContext.getComponentByEl(activeEl) as Component | undefined;+ if (component) {+ return component;+ }+ }++ return appContext.tabManager.getActiveContext()?.getTypeWidget();+}diff --git a/apps/client/src/services/shortcut_hints.spec.ts b/apps/client/src/services/shortcut_hints.spec.tsnew file mode 100644index 0000000000..73b709f8e4--- /dev/null+++ b/apps/client/src/services/shortcut_hints.spec.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from "vitest";++import Component from "../components/component.js";+import { collectShortcutHints, ShortcutHintCollector, type ShortcutHintSection } from "./shortcut_hints.js";++function componentWithHints(sections: ShortcutHintSection[] | null): Component {+ const component = new Component();+ if (sections) {+ component.getContextualShortcutHints = (collector) => collector.add(...sections);+ }+ return component;+}++describe("ShortcutHintCollector", () => {+ it("appends sections in call order", () => {+ const collector = new ShortcutHintCollector();+ const a: ShortcutHintSection = { hints: [{ keys: ["A"], labelKey: "a" }] };+ const b: ShortcutHintSection = { hints: [{ keys: ["B"], labelKey: "b" }] };++ collector.add(a);+ collector.add(b);++ expect(collector.sections).toEqual([a, b]);+ });+});++describe("collectShortcutHints", () => {+ it("returns nothing for a missing start component", () => {+ expect(collectShortcutHints(undefined)).toEqual([]);+ expect(collectShortcutHints(null)).toEqual([]);+ });++ it("collects from the start component", () => {+ const section: ShortcutHintSection = { titleKey: "leaf", hints: [{ keys: ["A"], labelKey: "a" }] };+ expect(collectShortcutHints(componentWithHints([section]))).toEqual([section]);+ });++ it("walks up the parent chain, focused component first then ancestors", () => {+ const leafSection: ShortcutHintSection = { titleKey: "leaf", hints: [{ keys: ["A"], labelKey: "a" }] };+ const rootSection: ShortcutHintSection = { titleKey: "root", hints: [{ action: "jumpToNote" }] };++ const root = componentWithHints([rootSection]);+ const middle = componentWithHints(null); // no hints — should be skipped+ const leaf = componentWithHints([leafSection]);+ root.child(middle);+ middle.child(leaf);++ expect(collectShortcutHints(leaf)).toEqual([leafSection, rootSection]);+ });+});diff --git a/apps/client/src/services/shortcut_hints.ts b/apps/client/src/services/shortcut_hints.tsnew file mode 100644index 0000000000..e22c829390--- /dev/null+++ b/apps/client/src/services/shortcut_hints.ts@@ -0,0 +1,68 @@+import type { KeyboardActionNames } from "@triliumnext/commons";++import type Component from "../components/component";++/**+ * A single contextual shortcut hint. Either:+ * - references a registered keyboard action, so the "Shortcut Hints" pane shows the user's current+ * (rebindable) binding formatted for their platform; or+ * - lists literal keys for widget-local shortcuts that aren't in the global action registry (e.g.+ * the image viewer's zoom `+` / `-` / `0`).+ *+ * `labelKey` is an i18n key describing what the shortcut does. It is optional for the `action`+ * variant (the pane falls back to the action's friendly name) and required for the `keys` variant.+ */+export type ShortcutHint =+ | { action: KeyboardActionNames; labelKey?: string }+ | { keys: string[]; labelKey: string };++/** A titled group of hints (e.g. "Zoom", "Navigation"). Omit `titleKey` for an untitled group. */+export interface ShortcutHintSection {+ /** i18n key for the section header. */+ titleKey?: string;+ hints: ShortcutHint[];+}++/** The declarative shape a widget defines and hands to `useContextualShortcutHints`. */+export type ShortcutHintDefinition = ShortcutHintSection[];++/**+ * Handed to a component's {@link ShortcutHintProvider} so it can push its sections in. Because the+ * dispatcher walks *up* the focused ancestor chain, several components can each contribute a+ * section (e.g. the image viewer's keys plus a global section beneath), so this only ever appends.+ */+export class ShortcutHintCollector {+ readonly sections: ShortcutHintSection[] = [];++ add(...sections: ShortcutHintSection[]) {+ this.sections.push(...sections);+ }+}++export type ShortcutHintProvider = (collector: ShortcutHintCollector) => void;++/**+ * Walks up from `startComponent` through its ancestors, letting each contribute its sections. The+ * focused widget's hints come first, broader/global ones below.+ */+export function collectShortcutHints(startComponent: Component | null | undefined): ShortcutHintSection[] {+ const collector = new ShortcutHintCollector();+ let component: Component | undefined = startComponent ?? undefined;+ while (component) {+ component.getContextualShortcutHints?.(collector);+ component = component.parent as Component | undefined;+ }+ return collector.sections;+}++declare module "../components/component" {+ export default interface Component {+ /**+ * Contributes this component's contextual shortcut hints. Implemented directly by legacy+ * widgets, or via the `useContextualShortcutHints` hook for React components. Called on each+ * component in the focused ancestor chain when the user requests contextual shortcut help,+ * so the hints appear only while this widget (or a descendant) is focused.+ */+ getContextualShortcutHints?: ShortcutHintProvider;+ }+}diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex 325f827dce..0cc0c2c336 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -19,6 +19,7 @@ import { parseNavigationStateFromUrl, ViewScope } from "../../services/link";import options, { type OptionValue } from "../../services/options";import protected_session_holder from "../../services/protected_session_holder";import server from "../../services/server";+import { ShortcutHintDefinition, ShortcutHintProvider } from "../../services/shortcut_hints";import shortcuts, { Handler, removeIndividualBinding } from "../../services/shortcuts";import SpacedUpdate, { type StateCallback } from "../../services/spaced_update";import { getEffectiveThemeStyle } from "../../services/theme";@@ -1156,6 +1157,35 @@ export function useLegacyImperativeHandlers(handlers: Record<string, Function>)}, [ handlers ]);}+/**+ * Registers this widget's contextual shortcut hints on its host component. When the user requests+ * contextual shortcut help (Shift+F1 by default), the dispatcher walks up from the focused element+ * and asks each component in the chain to contribute its hints — so these appear only while this+ * widget (or one of its descendants) is focused. The registration is removed automatically on unmount.+ *+ * @param hints the sections to contribute, or a function returning them (use the function form when+ * the hints depend on component state).+ */+export function useContextualShortcutHints(hints: ShortcutHintDefinition | (() => ShortcutHintDefinition)) {+ const parentComponent = useContext(ParentComponent);+ useEffect(() => {+ if (!parentComponent) return;++ const provider: ShortcutHintProvider = (collector) => {+ collector.add(...(typeof hints === "function" ? hints() : hints));+ };+ parentComponent.getContextualShortcutHints = provider;++ return () => {+ // Only clear our own registration, in case another provider replaced it in the meantime.+ if (parentComponent.getContextualShortcutHints === provider) {+ delete parentComponent.getContextualShortcutHints;+ }+ };+ }, [ parentComponent, hints ]);+ useDebugValue("contextual-shortcut-hints");+}+export function useSyncedRef<T>(externalRef?: Ref<T>, initialValue: T | null = null): RefObject<T> {const ref = useRef<T>(initialValue);diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex ccfab64356..ce1af2f5ca 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -40,6 +40,7 @@"show-backend-log": "Open \"Backend Log\" page","show-help": "Open the built-in User Guide","show-cheatsheet": "Show a modal with common keyboard operations",+ "show-shortcut-hints": "Show keyboard shortcuts for the focused widget","text-note-operations": "Text note operations","add-link-to-text": "Open dialog to add link to the text","follow-link-under-cursor": "Follow link within which the caret is placed",@@ -129,6 +130,7 @@"show-backend-log": "Show Backend Log","show-help": "Show Help","show-cheatsheet": "Show Cheatsheet",+ "show-shortcut-hints": "Show Shortcut Hints","add-link-to-text": "Add Link to Text","follow-link-under-cursor": "Follow Link Under Cursor","insert-date-and-time-to-text": "Insert Date and Time to Text",diff --git a/packages/commons/src/lib/keyboard_actions_interface.ts b/packages/commons/src/lib/keyboard_actions_interface.tsindex 3ca128df4d..6e1393ad93 100644--- a/packages/commons/src/lib/keyboard_actions_interface.ts+++ b/packages/commons/src/lib/keyboard_actions_interface.ts@@ -57,6 +57,7 @@ const enum KeyboardActionNamesEnum {showSQLConsole,showBackendLog,showCheatsheet,+ showShortcutHints,showHelp,addLinkToText,followLinkUnderCursor,diff --git a/packages/trilium-core/src/services/keyboard_actions.ts b/packages/trilium-core/src/services/keyboard_actions.tsindex a484226f68..a83f44c4e5 100644--- a/packages/trilium-core/src/services/keyboard_actions.ts+++ b/packages/trilium-core/src/services/keyboard_actions.ts@@ -488,6 +488,14 @@ function getDefaultKeyboardActions() {description: t("keyboard_actions.show-cheatsheet"),scope: "window"},+ {+ friendlyName: t("keyboard_action_names.show-shortcut-hints"),+ actionName: "showShortcutHints",+ iconClass: "bx bx-help-circle",+ defaultShortcuts: ["Alt+F1"],+ description: t("keyboard_actions.show-shortcut-hints"),+ scope: "window"+ },{separator: t("keyboard_actions.text-note-operations")