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: create a reusable shortcut hints button
Adorian Doranfd8eaac71572
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex 1b48abad09..ee6e2913d4 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -451,10 +451,13 @@ 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. */+ /** Emitted with the hints collected from the focused component chain (via the+ * {@link CommandMappings.showShortcutHints} handler) or from a widget's help button, for the+ * shortcut-hints pane to render. When `anchor` is set the pane opens as a dropdown by it;+ * otherwise it opens in the bottom-right corner. */shortcutHintsRequested: {sections: ShortcutHintSection[];+ anchor?: HTMLElement | null;};beforeNoteSwitch: {noteContext: NoteContext;diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 7527cc24b7..092cf890c3 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1011,6 +1011,9 @@"last_image": "Last image"}},+ "shortcut_hints": {+ "show_button": "Show shortcut hints"+ },"zpetne_odkazy": {"backlink_one": "{{count}} Backlink","backlink_other": "{{count}} Backlinks",diff --git a/apps/client/src/widgets/react/ImageViewer.css b/apps/client/src/widgets/react/ImageViewer.cssindex 31848aedb3..2e9af76a81 100644--- a/apps/client/src/widgets/react/ImageViewer.css+++ b/apps/client/src/widgets/react/ImageViewer.css@@ -14,6 +14,14 @@z-index: 1;}+/* Shortcut-hints button pinned to the top-right corner of the viewport. */+.image-viewer-hint-button {+ position: absolute;+ inset-inline-end: 10px;+ top: 10px;+ z-index: 1;+}+/* Make the library's viewport fill the available space so the image fits and pans within it. */.image-viewer-viewport.react-transform-wrapper {width: 100%;diff --git a/apps/client/src/widgets/react/ImageViewer.tsx b/apps/client/src/widgets/react/ImageViewer.tsxindex 510b0cc181..ea71ecf38e 100644--- a/apps/client/src/widgets/react/ImageViewer.tsx+++ b/apps/client/src/widgets/react/ImageViewer.tsx@@ -7,6 +7,7 @@ import { type ReactZoomPanPinchRef, TransformComponent, TransformWrapper } fromimport { t } from "../../services/i18n";import type { ShortcutHintDefinition } from "../../services/shortcut_hints";import { isMobile } from "../../services/utils";+import ShortcutHintButton from "../shortcut_hints/shortcut_hint_button";import ContentErrorMessage from "./ContentErrorMessage";import { useContextualShortcutHints, useStaticTooltip } from "./hooks";import { useImageViewerKeyboard } from "./image_viewer_keyboard";@@ -179,6 +180,10 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.<ContentErrorMessage message={t("image_viewer.loading_error")} />)}+ {!isMobile() && loaded && (+ <ShortcutHintButton className="image-viewer-hint-button" />+ )}+{!isMobile() && loaded && (<div className="image-viewer-controls tn-overlay-control-group"><buttondiff --git a/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.css b/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.cssnew file mode 100644index 0000000000..54631ae6c4--- /dev/null+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.css@@ -0,0 +1,26 @@+.shortcut-hint-button {+ gap: 5px;+ white-space: nowrap;++ .shortcut-hint-button-key {+ font-size: 0.85em;+ }++ /* Match the CKEditor content keycap style (see `.ck-content kbd`). */+ kbd {+ display: inline-block;+ border: 1px solid var(--help-kbd-shortcut-border);+ border-radius: 5px;+ padding: 0 5px;+ background: var(--help-kbd-shortcut-background);+ box-shadow:+ 0 2px 0 var(--help-kbd-shortcut-border),+ inset 0 -1px 0 var(--help-kbd-shortcut-border);+ color: var(--help-kbd-shortcut-color);+ font-family: var(--main-font-family);+ font-size: 0.7em;+ font-weight: normal;+ line-height: 1.4;+ letter-spacing: 0.5pt;+ }+}diff --git a/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.spec.tsx b/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.spec.tsxnew file mode 100644index 0000000000..fd246e3257--- /dev/null+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.spec.tsx@@ -0,0 +1,60 @@+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: ["Alt+F1"] }) }+}));+vi.mock("../react/hooks.js", () => ({ useStaticTooltip: () => {} }));++import appContext from "../../components/app_context.js";+import Component from "../../components/component.js";+import type { ShortcutHintSection } from "../../services/shortcut_hints.js";+import { ParentComponent } from "../react/react_utils.js";+import ShortcutHintButton from "./shortcut_hint_button.js";++let container: HTMLDivElement;++afterEach(() => {+ act(() => render(null, container));+ container.remove();+ vi.restoreAllMocks();+});++function mountButton(host: Component) {+ container = document.createElement("div");+ document.body.appendChild(container);+ act(() => render(+ <ParentComponent.Provider value={host}><ShortcutHintButton className="my-position" /></ParentComponent.Provider>,+ container+ ));+ return container.querySelector("button");+}++describe("ShortcutHintButton", () => {+ it("renders the overlay button with a '?' keycap and the position class", () => {+ const button = mountButton(new Component());++ expect(container.querySelector(".tn-overlay-control-group.my-position")).not.toBeNull();+ expect(button?.classList.contains("tn-overlay-text-button")).toBe(true);+ expect(button?.getAttribute("aria-label")).toBe("shortcut_hints.show_button");+ expect(button?.querySelector("kbd")?.textContent).toBe("?");+ expect(button?.querySelector(".shortcut-hint-button-key")).not.toBeNull();+ });++ it("collects its context's hints and opens the pane anchored to itself on click", () => {+ const section: ShortcutHintSection = { hints: [{ keys: ["A"], labelKey: "a" }] };+ const host = new Component();+ host.getContextualShortcutHints = (collector) => collector.add(section);+ const triggerEvent = vi.spyOn(appContext, "triggerEvent").mockReturnValue(undefined);++ const button = mountButton(host);+ button?.click();++ expect(triggerEvent).toHaveBeenCalledWith("shortcutHintsRequested", {+ sections: [section],+ anchor: button+ });+ });+});diff --git a/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.tsx b/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.tsxnew file mode 100644index 0000000000..ba067a19a3--- /dev/null+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.tsx@@ -0,0 +1,52 @@+import "./shortcut_hint_button.css";++import clsx from "clsx";+import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";++import appContext from "../../components/app_context.js";+import { t } from "../../services/i18n.js";+import keyboard_actions from "../../services/keyboard_actions.js";+import { formatShortcut, joinShortcut } from "../../services/keyboard_shortcut_display.js";+import { collectShortcutHints } from "../../services/shortcut_hints.js";+import { useStaticTooltip } from "../react/hooks.js";+import { ParentComponent } from "../react/react_utils.js";++/**+ * Overlay button that opens the contextual shortcut-hints pane as a dropdown, collecting the hints+ * from its own widget context. Reusable across widgets (image viewer, media player, …); the caller+ * positions it via `className` on the overlay group.+ */+export default function ShortcutHintButton({ className }: { className?: string }) {+ const parentComponent = useContext(ParentComponent);+ const buttonRef = useRef<HTMLButtonElement>(null);+ const [ shortcut, setShortcut ] = useState("Alt+F1");++ useEffect(() => {+ keyboard_actions.getAction("showShortcutHints", true).then(action => {+ const first = action?.effectiveShortcuts?.[0];+ if (first) setShortcut(joinShortcut(formatShortcut(first), "+"));+ });+ }, []);++ useStaticTooltip(buttonRef, { title: t("shortcut_hints.show_button"), placement: "bottom" });++ const onClick = useCallback(() => {+ const sections = collectShortcutHints(parentComponent);+ appContext.triggerEvent("shortcutHintsRequested", { sections, anchor: buttonRef.current });+ }, [ parentComponent ]);++ return (+ <div className={clsx("tn-overlay-control-group", "shortcut-hint-button-group", className)}>+ <button+ ref={buttonRef}+ type="button"+ className="tn-overlay-text-button shortcut-hint-button"+ aria-label={t("shortcut_hints.show_button")}+ onClick={onClick}+ >+ <span className="shortcut-hint-button-key">{shortcut}</span>+ <kbd>?</kbd>+ </button>+ </div>+ );+}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.tsxindex 740d62e507..d74b1927f5 100644--- a/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.spec.tsx+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.spec.tsx@@ -106,4 +106,28 @@ describe("ShortcutHintsPanel", () => {act(() => { host.handleEvent("activeContextChanged", { noteContext: {} as never }); });expect(document.querySelector(".shortcut-hints-panel")).toBeNull();});++ it("opens as a dropdown positioned under an anchor, and clicking the anchor does not dismiss it", () => {+ const host = mountPanel();+ const anchor = document.createElement("button");+ document.body.appendChild(anchor);+ try {+ act(() => { host.handleEvent("shortcutHintsRequested", { sections: SECTIONS, anchor }); });++ const panel = document.querySelector<HTMLElement>(".shortcut-hints-panel");+ // Anchored positioning uses top/bottom-auto instead of the corner's bottom offset.+ expect(panel?.style.top).toBe("6px");+ expect(panel?.style.bottom).toBe("auto");++ // A mousedown on the anchor is left for its own toggle — the pane must not close.+ act(() => { anchor.dispatchEvent(new MouseEvent("mousedown", { bubbles: true })); });+ expect(document.querySelector(".shortcut-hints-panel")).not.toBeNull();++ // A mousedown elsewhere dismisses it.+ act(() => { document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true })); });+ expect(document.querySelector(".shortcut-hints-panel")).toBeNull();+ } finally {+ anchor.remove();+ }+ });});diff --git a/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.tsx b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.tsxindex b834952621..fe571c7117 100644--- a/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.tsx+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.tsx@@ -13,14 +13,25 @@ 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;+/** Gap between an anchor (help button) and the dropdown. */+const ANCHOR_GAP = 6;++interface OpenState {+ sections: ShortcutHintSection[];+ /** When set, the pane is a dropdown anchored to this element; otherwise it sits in the corner. */+ anchor: HTMLElement | null;+}export default function ShortcutHintsPanel() {- // `undefined` means closed. Only ever set to a non-empty array, so presence == open.- const [ sections, setSections ] = useState<ShortcutHintSection[]>();+ // `undefined` means closed. Only ever set with a non-empty section list, so presence == open.+ const [ state, setState ] = useState<OpenState>();const panelRef = useRef<HTMLDivElement>(null);const timerRef = useRef<number>();+ // Kept in a ref so the outside-click handler always sees the current anchor without re-subscribing.+ const anchorRef = useRef<HTMLElement | null>(null);+ anchorRef.current = state?.anchor ?? null;- const close = useCallback(() => setSections(undefined), []);+ const close = useCallback(() => setState(undefined), []);const clearTimer = useCallback(() => {if (timerRef.current !== undefined) {window.clearTimeout(timerRef.current);@@ -32,13 +43,13 @@ export default function ShortcutHintsPanel() {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);+ // Toggle: close if open, otherwise open (unless there's nothing to show).+ useTriliumEvent("shortcutHintsRequested", useCallback(({ sections, anchor }) => {+ setState(prev => (prev !== undefined || sections.length === 0) ? undefined : { sections, anchor: anchor ?? null });}, []));useTriliumEvent("activeContextChanged", close);- const isOpen = sections !== undefined;+ const isOpen = state !== undefined;useEffect(() => {if (!isOpen) {clearTimer();@@ -50,7 +61,10 @@ export default function ShortcutHintsPanel() {if (e.key === "Escape") close();}function onMouseDown(e: MouseEvent) {- if (panelRef.current && !panelRef.current.contains(e.target as Node)) close();+ const target = e.target as Node;+ // Clicks on the panel keep it open; clicks on the anchor are handled by its own toggle.+ if (panelRef.current?.contains(target) || anchorRef.current?.contains(target)) return;+ close();}document.addEventListener("keydown", onKeyDown);document.addEventListener("mousedown", onMouseDown);@@ -61,15 +75,22 @@ export default function ShortcutHintsPanel() {};}, [ isOpen, startTimer, clearTimer, close ]);- if (!sections) {+ if (!state) {return null;}+ // Anchored: position the dropdown under the anchor, right edges aligned. The rect is a genuinely+ // dynamic value, so it belongs in an inline style rather than CSS.+ const anchorRect = state.anchor?.getBoundingClientRect();+ const style = anchorRect+ ? { top: `${anchorRect.bottom + ANCHOR_GAP}px`, right: `${Math.max(ANCHOR_GAP, window.innerWidth - anchorRect.right)}px`, bottom: "auto" }+ : undefined;+// Portal to <body> so no transformed / contained / overflow-clipped ancestor breaks the fixed// positioning or hides it behind content.return createPortal(- <div ref={panelRef} className="shortcut-hints-panel" onMouseEnter={clearTimer} onMouseLeave={startTimer}>- <ShortcutHintsSections sections={sections} />+ <div ref={panelRef} className="shortcut-hints-panel" style={style} onMouseEnter={clearTimer} onMouseLeave={startTimer}>+ <ShortcutHintsSections sections={state.sections} /></div>,document.body);