Skip to content

Build your personal knowledge base with Trilium Notes

client/shortcut hints: create the shortcut hints panel

Adorian Doran47d492425f1d
diff --git a/apps/client/src/layouts/layout_commons.tsx b/apps/client/src/layouts/layout_commons.tsx
index 4d72861496..75f1fd45bf 100644
--- a/apps/client/src/layouts/layout_commons.tsx
+++ b/apps/client/src/layouts/layout_commons.tsx
@@ -7,6 +7,7 @@ import CallToActionDialog from "../widgets/dialogs/call_to_action.jsx";
import PopupEditorDialog from "../widgets/dialogs/PopupEditor.jsx";
import { useTriliumEvents } from "../widgets/react/hooks.jsx";
import { ParentComponent } from "../widgets/react/react_utils.jsx";
+import ShortcutHintsPanel from "../widgets/shortcut_hints/shortcut_hints_panel.jsx";
import ToastContainer from "../widgets/Toast.jsx";
export function applyModals(rootContainer: RootContainer) {
@@ -44,7 +45,9 @@ export function applyModals(rootContainer: RootContainer) {
// - Toast is needed immediately and continuously to surface messages/errors, including ones raised during startup.
.child(<PopupEditorDialog />)
.child(<CallToActionDialog />)
- .child(<ToastContainer />);
+ .child(<ToastContainer />)
+ // Auxiliary tooltip-style panel; always mounted (renders nothing until summoned), like the toast host.
+ .child(<ShortcutHintsPanel />);
}
interface LazyDialogProps {
diff --git a/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.css b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.css
new file mode 100644
index 0000000000..ded3fee7f3
--- /dev/null
+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.css
@@ -0,0 +1,49 @@
+.shortcut-hints-panel {
+ position: fixed;
+ right: 1rem;
+ bottom: 1rem;
+ z-index: 900;
+ max-width: 340px;
+ max-height: 60vh;
+ overflow-y: auto;
+ padding: 0.75rem 1rem;
+ background-color: var(--main-background-color);
+ border: 1px solid var(--main-border-color);
+ border-radius: 6px;
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
+ font-size: 0.9em;
+
+ .shortcut-hints-section {
+ &:not(:last-child) {
+ margin-bottom: 0.75rem;
+ }
+
+ ul {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ }
+ }
+
+ .shortcut-hints-section-title {
+ font-weight: bold;
+ margin-bottom: 0.25rem;
+ }
+
+ .shortcut-hint {
+ display: flex;
+ gap: 0.75rem;
+ align-items: baseline;
+ padding: 0.15rem 0;
+ }
+
+ .shortcut-hint-keys {
+ flex: 0 0 auto;
+ white-space: nowrap;
+ }
+
+ .shortcut-hint-description {
+ flex: 1 1 auto;
+ color: var(--muted-text-color);
+ }
+}
diff --git a/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.spec.tsx b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.spec.tsx
new file mode 100644
index 0000000000..6620e7faea
--- /dev/null
+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.spec.tsx
@@ -0,0 +1,106 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../../services/i18n.js", () => ({ t: (key: string) => key }));
+vi.mock("../../services/keyboard_actions.js", () => ({
+ default: { getAction: vi.fn().mockResolvedValue({ effectiveShortcuts: ["Ctrl+K"], friendlyName: "Jump to note" }) }
+}));
+
+import Component from "../../components/component.js";
+import type { ShortcutHintSection } from "../../services/shortcut_hints.js";
+import { ParentComponent } from "../react/react_utils.js";
+import ShortcutHintsPanel, { ShortcutHintsSections } from "./shortcut_hints_panel.js";
+
+let container: HTMLDivElement;
+
+afterEach(() => {
+ act(() => render(null, container));
+ container.remove();
+});
+
+function mount(vnode: preact.ComponentChild) {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ act(() => render(vnode, container));
+ return container;
+}
+
+function mountPanel() {
+ const host = new Component();
+ mount(<ParentComponent.Provider value={host}><ShortcutHintsPanel /></ParentComponent.Provider>);
+ return host;
+}
+
+const SECTIONS: ShortcutHintSection[] = [{ hints: [{ keys: ["A"], labelKey: "act.a" }] }];
+
+describe("ShortcutHintsSections", () => {
+ it("renders a section title, literal keys and the description", () => {
+ mount(<ShortcutHintsSections sections={[
+ { titleKey: "grp.nav", hints: [{ keys: ["Page Down", "Ctrl+>"], labelKey: "act.next" }] }
+ ]} />);
+
+ expect(container.querySelector(".shortcut-hints-section-title")?.textContent).toBe("grp.nav");
+ expect(container.querySelector(".shortcut-hint-description")?.textContent).toBe("act.next");
+ expect(container.querySelectorAll(".shortcut-hint-keys kbd").length).toBeGreaterThan(0);
+ });
+
+ it("resolves an action hint's keys and falls back to its friendly name", async () => {
+ mount(<ShortcutHintsSections sections={[{ hints: [{ action: "jumpToNote" }] }]} />);
+ await act(async () => { await Promise.resolve(); });
+
+ expect(container.querySelector(".shortcut-hint-description")?.textContent).toBe("Jump to note");
+ expect(container.querySelectorAll(".shortcut-hint-keys kbd").length).toBeGreaterThan(0);
+ });
+});
+
+describe("ShortcutHintsPanel", () => {
+ it("stays closed until summoned, opens on the event, and toggles closed on the next", () => {
+ const host = mountPanel();
+ expect(container.querySelector(".shortcut-hints-panel")).toBeNull();
+
+ act(() => host.handleEvent("shortcutHintsRequested", { sections: SECTIONS }));
+ expect(container.querySelector(".shortcut-hints-panel")).not.toBeNull();
+
+ act(() => host.handleEvent("shortcutHintsRequested", { sections: SECTIONS }));
+ expect(container.querySelector(".shortcut-hints-panel")).toBeNull();
+ });
+
+ it("does not open when there are no sections", () => {
+ const host = mountPanel();
+ act(() => host.handleEvent("shortcutHintsRequested", { sections: [] }));
+ expect(container.querySelector(".shortcut-hints-panel")).toBeNull();
+ });
+
+ it("closes on Escape", () => {
+ const host = mountPanel();
+ act(() => host.handleEvent("shortcutHintsRequested", { sections: SECTIONS }));
+ expect(container.querySelector(".shortcut-hints-panel")).not.toBeNull();
+
+ act(() => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })));
+ expect(container.querySelector(".shortcut-hints-panel")).toBeNull();
+ });
+
+ it("auto-dismisses after the timeout", () => {
+ vi.useFakeTimers();
+ try {
+ const host = mountPanel();
+ act(() => host.handleEvent("shortcutHintsRequested", { sections: SECTIONS }));
+ expect(container.querySelector(".shortcut-hints-panel")).not.toBeNull();
+
+ act(() => vi.advanceTimersByTime(5000));
+ expect(container.querySelector(".shortcut-hints-panel")).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("closes when the active note context changes", () => {
+ const host = mountPanel();
+ act(() => host.handleEvent("shortcutHintsRequested", { sections: SECTIONS }));
+ expect(container.querySelector(".shortcut-hints-panel")).not.toBeNull();
+
+ act(() => host.handleEvent("activeContextChanged", { noteContext: {} }));
+ expect(container.querySelector(".shortcut-hints-panel")).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.tsx b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.tsx
new file mode 100644
index 0000000000..c3ee7d619c
--- /dev/null
+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.tsx
@@ -0,0 +1,115 @@
+import "./shortcut_hints_panel.css";
+
+import { Fragment } from "preact";
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+
+import { t } from "../../services/i18n.js";
+import keyboard_actions from "../../services/keyboard_actions.js";
+import type { ShortcutHint, ShortcutHintSection } from "../../services/shortcut_hints.js";
+import { useTriliumEvent } from "../react/hooks.js";
+import { joinElements } from "../react/react_utils.js";
+import { renderShortcutKbds } from "../react/shortcut_kbd.js";
+
+/** How long the panel stays up when left untouched. Paused while hovered; other signals dismiss it sooner. */
+const AUTO_DISMISS_MS = 5000;
+
+export default function ShortcutHintsPanel() {
+ // `undefined` means closed. Only ever set to a non-empty array, so presence == open.
+ const [ sections, setSections ] = useState<ShortcutHintSection[]>();
+ const panelRef = useRef<HTMLDivElement>(null);
+ const timerRef = useRef<number>();
+
+ const close = useCallback(() => setSections(undefined), []);
+ const clearTimer = useCallback(() => {
+ if (timerRef.current !== undefined) {
+ window.clearTimeout(timerRef.current);
+ timerRef.current = undefined;
+ }
+ }, []);
+ const startTimer = useCallback(() => {
+ clearTimer();
+ timerRef.current = window.setTimeout(close, AUTO_DISMISS_MS);
+ }, [ clearTimer, close ]);
+
+ // Alt+F1 toggles: close if open, otherwise open (unless there's nothing to show).
+ useTriliumEvent("shortcutHintsRequested", useCallback(({ sections: incoming }) => {
+ setSections(prev => (prev !== undefined || incoming.length === 0) ? undefined : incoming);
+ }, []));
+ useTriliumEvent("activeContextChanged", close);
+
+ const isOpen = sections !== undefined;
+ useEffect(() => {
+ if (!isOpen) {
+ clearTimer();
+ return;
+ }
+ startTimer();
+
+ function onKeyDown(e: KeyboardEvent) {
+ if (e.key === "Escape") close();
+ }
+ function onMouseDown(e: MouseEvent) {
+ if (panelRef.current && !panelRef.current.contains(e.target as Node)) close();
+ }
+ document.addEventListener("keydown", onKeyDown);
+ document.addEventListener("mousedown", onMouseDown);
+ return () => {
+ clearTimer();
+ document.removeEventListener("keydown", onKeyDown);
+ document.removeEventListener("mousedown", onMouseDown);
+ };
+ }, [ isOpen, startTimer, clearTimer, close ]);
+
+ if (!sections) {
+ return null;
+ }
+
+ return (
+ <div ref={panelRef} className="shortcut-hints-panel" onMouseEnter={clearTimer} onMouseLeave={startTimer}>
+ <ShortcutHintsSections sections={sections} />
+ </div>
+ );
+}
+
+export function ShortcutHintsSections({ sections }: { sections: ShortcutHintSection[] }) {
+ return (
+ <>
+ {sections.map((section, i) => (
+ <div className="shortcut-hints-section" key={i}>
+ {section.titleKey && <div className="shortcut-hints-section-title">{t(section.titleKey)}</div>}
+ <ul>
+ {section.hints.map((hint, j) => <HintRow hint={hint} key={j} />)}
+ </ul>
+ </div>
+ ))}
+ </>
+ );
+}
+
+function HintRow({ hint }: { hint: ShortcutHint }) {
+ const [ shortcuts, setShortcuts ] = useState<string[]>(() => "keys" in hint ? hint.keys : []);
+ const [ friendlyName, setFriendlyName ] = useState<string>();
+
+ useEffect(() => {
+ if ("keys" in hint) {
+ setShortcuts(hint.keys);
+ return;
+ }
+ // `action` hints resolve to the user's current, rebindable binding.
+ keyboard_actions.getAction(hint.action).then(action => {
+ setShortcuts(action?.effectiveShortcuts ?? []);
+ setFriendlyName(action?.friendlyName);
+ });
+ }, [ hint ]);
+
+ const description = hint.labelKey ? t(hint.labelKey) : friendlyName ?? "";
+
+ return (
+ <li className="shortcut-hint">
+ <span className="shortcut-hint-keys">
+ {joinElements(shortcuts.map((shortcut, i) => <Fragment key={i}>{renderShortcutKbds(shortcut)}</Fragment>), ", ")}
+ </span>
+ <span className="shortcut-hint-description">{description}</span>
+ </li>
+ );
+}