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
feat(menu): show the context menu items' keyboard shortcuts
Elian Dorandbb449eda840
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsindex d0fb404f73..25cb27846d 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -1,6 +1,16 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";vi.mock("../services/note_tooltip", () => ({ default: { dismissAllTooltips: vi.fn() } }));+vi.mock("../services/keyboard_actions", () => ({+ getActionSync: (name: string) => ({+ effectiveShortcuts: name === "copyNotesToClipboard" ? [ "Ctrl+C", "Ctrl+Insert" ] : []+ })+}));+// Key names are translated; the formatting has specs of its own.+vi.mock("../services/keyboard_shortcut_display", () => ({+ formatShortcut: (shortcut: string) => shortcut.split("+"),+ joinShortcut: (tokens: string[]) => tokens.join("+")+}));/** The page as the shell leaves it. */function buildPage() {@@ -127,6 +137,29 @@ describe("contextMenu", () => {expect(menuElement()?.querySelectorAll(".use-note-color")).toHaveLength(1);});+ it("shows a keyboard action's shortcuts, or a literal shortcut, after the title", async () => {+ buildPage();+ const contextMenu = await buildContextMenu();++ await contextMenu.show({+ x: 10, y: 10, selectMenuItemHandler: () => {},+ items: [+ { title: "Copy", keyboardShortcut: "copyNotesToClipboard" },+ { title: "Paste", shortcut: "Ctrl+V" },+ { title: "Cut", keyboardShortcut: "cutNotesToClipboard" }+ ]+ });++ const shortcuts = [ ...menuElement()?.querySelectorAll("li.dropdown-item > span") ?? [] ]+ .map(row => row.lastElementChild?.outerHTML);+ expect(shortcuts).toEqual([+ `<span class="keyboard-shortcut"><kbd>Ctrl</kbd>+<kbd>C</kbd>,<kbd>Ctrl</kbd>+<kbd>Insert</kbd></span>`,+ "<kbd>Ctrl+V</kbd>",+ // An action with no shortcut assigned shows none.+ `<span>Cut</span>`+ ]);+ });+it("runs an item pressed with the primary button, then hides", async () => {buildPage();const contextMenu = await buildContextMenu();diff --git a/apps/client/src/menus/context_menu_legacy.ts b/apps/client/src/menus/context_menu_legacy.tsindex f676128258..18fb7b1884 100644--- a/apps/client/src/menus/context_menu_legacy.ts+++ b/apps/client/src/menus/context_menu_legacy.ts@@ -5,8 +5,6 @@ import { KeyboardActionNames } from "@triliumnext/commons";import { Tooltip } from "bootstrap";import { h, JSX, render } from "preact";-import keyboardActionService, { getActionSync } from "../services/keyboard_actions.js";-import { formatShortcut, joinShortcut } from "../services/keyboard_shortcut_display.js";import note_tooltip from "../services/note_tooltip.js";import utils from "../services/utils.js";@@ -124,8 +122,6 @@ class ContextMenu {this.$widget.empty();this.addItems(this.$widget, options.items);-- keyboardActionService.updateDisplayedShortcuts(this.$widget);}/**@@ -270,28 +266,6 @@ class ContextMenu {}}- if ("keyboardShortcut" in item && item.keyboardShortcut) {- const shortcuts = getActionSync(item.keyboardShortcut).effectiveShortcuts;- if (shortcuts) {- const allShortcuts: string[] = [];- for (const effectiveShortcut of shortcuts) {- const tokens = formatShortcut(effectiveShortcut);- // On macOS the glyphs sit in one <kbd> (⇧⌘J); elsewhere each token gets its own.- allShortcuts.push(utils.isMac()- ? `<kbd>${joinShortcut(tokens)}</kbd>`- : tokens.map(key => `<kbd>${key}</kbd>`).join("+"));- }-- if (allShortcuts.length) {- const container = $("<span>").addClass("keyboard-shortcut");- container.append($(allShortcuts.join(",")));- $link.append(container);- }- }- } else if ("shortcut" in item && item.shortcut) {- $link.append($("<kbd>").text(item.shortcut));- }-if ("trailingIcon" in item && item.trailingIcon) {$link.append($("<span>").addClass([ item.trailingIcon, "tn-icon", "menu-trailing-icon" ]));diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsxindex e6ccf84938..d11210ada0 100644--- a/apps/client/src/widgets/react/Menu.tsx+++ b/apps/client/src/widgets/react/Menu.tsx@@ -5,7 +5,10 @@ import clsx from "clsx";import { useCallback, useLayoutEffect, useRef } from "preact/hooks";import type { MenuCommandItem, MenuItem, MenuSeparatorItem } from "../../menus/context_menu";+import { getActionSync } from "../../services/keyboard_actions";import { useResizeObserver } from "./hooks";+import { joinElements } from "./react_utils";+import { renderShortcutKbds } from "./shortcut_kbd";/*** A menu of commands, drawn with the markup Bootstrap's dropdowns use (`.dropdown-menu`,@@ -67,11 +70,30 @@ function MenuRow<T>({ item, onSelect }: { item: MenuCommandItem<T>, onSelect: Me<span className="tn-menu-gap" />{/* Callers pass HTML: titles escaped with `escapeHtml()` or boxed by `menuName()`. */}<span dangerouslySetInnerHTML={{ __html: item.title }} />+ <MenuShortcut item={item} /></span></li>);}+/**+ * The shortcuts of the item's `keyboardShortcut` action as the user configured them, or else its+ * literal `shortcut`. Read synchronously, so the menu is placed at its final width.+ */+function MenuShortcut<T>({ item }: { item: MenuCommandItem<T> }) {+ if (item.keyboardShortcut) {+ const shortcuts = getActionSync(item.keyboardShortcut)?.effectiveShortcuts;+ if (!shortcuts?.length) return null;+ return (+ <span className="keyboard-shortcut">+ {joinElements(shortcuts.map(shortcut => renderShortcutKbds(shortcut)), ",")}+ </span>+ );+ }++ return item.shortcut ? <kbd>{item.shortcut}</kbd> : null;+}+/*** The icon, or a check mark in its place. An item that sets `uiIcon` to nothing gets a blank slot,* and one without `uiIcon` or `checked` an empty one.