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): reach a row of actions from the keyboard
Elian Doranfe00b36264eb
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.cssindex b6583387f1..57bec507d5 100644--- a/apps/client/src/widgets/react/Menu.css+++ b/apps/client/src/widgets/react/Menu.css@@ -260,11 +260,17 @@ body.desktop .dropdown-item.dropdown-submenu.submenu-open,font-size: 0.85em;line-height: 1.2;- &:hover:not(:disabled) {+ &:hover:not(:disabled),+ &.tn-menu-active {color: var(--hover-item-text-color);background-color: var(--hover-item-background-color);}+ .tn-menu-keyboard &:hover:not(.tn-menu-active) {+ color: var(--menu-text-color);+ background-color: transparent;+ }+&:disabled > * {opacity: var(--menu-item-disabled-opacity);}diff --git a/apps/client/src/widgets/react/Menu.spec.tsx b/apps/client/src/widgets/react/Menu.spec.tsxindex 54ce8d3c62..39b5d1bc90 100644--- a/apps/client/src/widgets/react/Menu.spec.tsx+++ b/apps/client/src/widgets/react/Menu.spec.tsx@@ -1,6 +1,7 @@import { render } from "preact";import { afterEach, describe, expect, it, vi } from "vitest";+import type { MenuItem } from "../../menus/context_menu";import { FormDropdownDivider, FormDropdownSubmenu, FormListHeader, FormListItem } from "./FormList";import Menu, { type MenuProps } from "./Menu";import { shouldDropStart } from "./menu_context";@@ -260,3 +261,77 @@ describe("Menu with declared rows", () => {}});});++describe("Menu with an action row", () => {+ const host = document.createElement("div");+ document.body.append(host);+ afterEach(() => {+ render(null, host);+ window.glob.isRtl = false;+ });++ function renderMenu() {+ const onSelect = vi.fn();+ const items: MenuItem<string>[] = [+ {+ kind: "actions",+ items: [+ { title: "Cut", command: "cut", uiIcon: "bx bx-cut" },+ { title: "Copy", command: "copy", uiIcon: "bx bx-copy", enabled: false },+ { title: "Delete", command: "delete", uiIcon: "bx bx-trash" }+ ]+ },+ { kind: "separator" },+ { title: "Rename", command: "rename" },+ { title: "More", items: [ { title: "Inner", command: "inner" } ] }+ ];+ render(<Menu anchor={{ x: 10, y: 10 }} items={items} onSelect={onSelect} onClose={vi.fn()} />, host);++ const menu = document.querySelector<HTMLElement>(".tn-popup.tn-menu");+ if (!menu) throw new Error("expected the menu to render");+ return { menu, onSelect };+ }++ const key = (menu: HTMLElement, name: string) =>+ menu.dispatchEvent(new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true }));+ const active = (menu: HTMLElement) =>+ menu.querySelector(".tn-menu-active .tn-menu-action-title, li.tn-menu-active > span")?.textContent;++ it("steps through the actions as rows, the arrow towards the end moving on as Down does", async () => {+ const { menu, onSelect } = renderMenu();++ key(menu, "ArrowDown");+ await vi.waitFor(() => expect(active(menu)).toBe("Cut"));+ // The disabled "Copy" is passed over, and the last action leads on to the rows below.+ key(menu, "ArrowRight");+ await vi.waitFor(() => expect(active(menu)).toBe("Delete"));+ key(menu, "ArrowRight");+ await vi.waitFor(() => expect(active(menu)).toBe("Rename"));+ key(menu, "ArrowUp");+ await vi.waitFor(() => expect(active(menu)).toBe("Delete"));+ key(menu, "ArrowLeft");+ await vi.waitFor(() => expect(active(menu)).toBe("Cut"));++ key(menu, "Enter");+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ command: "cut" }), expect.any(KeyboardEvent));+ });++ it("keeps Right and Left for the submenus on the other rows, mirrored right to left", async () => {+ const { menu } = renderMenu();++ key(menu, "ArrowUp");+ await vi.waitFor(() => expect(active(menu)).toBe("More"));+ key(menu, "ArrowRight");+ await vi.waitFor(() => expect(active(menu)).toBe("Inner"));+ key(menu, "ArrowLeft");+ await vi.waitFor(() => expect(active(menu)).toBe("More"));++ window.glob.isRtl = true;+ key(menu, "Home");+ await vi.waitFor(() => expect(active(menu)).toBe("Cut"));+ key(menu, "ArrowLeft");+ await vi.waitFor(() => expect(active(menu)).toBe("Delete"));+ key(menu, "ArrowRight");+ await vi.waitFor(() => expect(active(menu)).toBe("Cut"));+ });+});diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsxindex 0cb31f457d..6e0f178f73 100644--- a/apps/client/src/widgets/react/Menu.tsx+++ b/apps/client/src/widgets/react/Menu.tsx@@ -10,7 +10,8 @@ import { t } from "../../services/i18n";import { isMobile } from "../../services/utils";import { FormDropdownDivider, FormDropdownSubmenu, FormListCustomItem, FormListHeader, FormListItem } from "./FormList";import FormTextBox from "./FormTextBox";-import { type ActiveRow, isRightToLeft, MenuContext, type MenuContextValue, type MenuFilter, MenuFilterContext, type OpenSubmenu, pointerMoved, type RowEntry, shouldDropStart, useMenu } from "./menu_context";+import { useUniqueName } from "./hooks";+import { type ActiveRow, isRightToLeft, MenuContext, type MenuContextValue, type MenuFilter, MenuFilterContext, MenuLevelContext, type OpenSubmenu, pointerMoved, type RowEntry, shouldDropStart, useMenu } from "./menu_context";import Popup, { type PopupProps } from "./Popup";/**@@ -282,6 +283,8 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,closeLevel(level);menuRef.current?.focus({ preventScroll: true });}+ } else if (activeRow?.inline && !filterInput && (e.key === "ArrowLeft" || e.key === "ArrowRight")) {+ goTo(e.key === (rtl ? "ArrowLeft" : "ArrowRight") ? index + 1 : index - 1);} else if (filterInput || !filterKey(e, level, activeRow)) {switch (e.key) {case "ArrowDown": goTo(index + 1); break;@@ -547,24 +550,50 @@ function MenuItemRow<T>({ row, onSelect }: { row: MenuItem<T>, onSelect: MenuPro);}-/** A row of items side by side, each its icon over its title. */+/**+ * A row of items side by side, each its icon over its title. Each registers with the menu as a row+ * of its own, so the keys step through them in order.+ */function MenuActions<T>({ items, onSelect }: { items: MenuCommandItem<T>[], onSelect: MenuProps<T>["onSelect"] }) {return (<li className="tn-menu-actions" role="group">- {items.map((item, index) => (- <button- key={index} type="button" role="menuitem" className="tn-menu-action"- disabled={item.enabled === false} onClick={(e) => onSelect?.(item, e)}- >- <span className={`tn-icon ${item.uiIcon ?? "bx bx-empty"}`} aria-hidden="true" />- {/* Callers pass HTML, as for a row's title. */}- <span className="tn-menu-action-title" dangerouslySetInnerHTML={{ __html: item.title }} />- </button>- ))}+ {items.map((item, index) => <MenuAction key={index} item={item} onSelect={onSelect} />)}</li>);}+function MenuAction<T>({ item, onSelect }: { item: MenuCommandItem<T>, onSelect: MenuProps<T>["onSelect"] }) {+ const menu = useContext(MenuContext);+ const level = useContext(MenuLevelContext);+ const id = useUniqueName("menu-row");+ const disabled = item.enabled === false;+ const select = (e: MouseEvent | KeyboardEvent) => onSelect?.(item, e);++ return (+ <button+ ref={(element) => {+ menu?.registerRow(id, element+ ? { level, element, custom: false, disabled, hasSubmenu: false, inline: true, select }+ : undefined);+ }}+ id={menu ? id : undefined} type="button" role="menuitem"+ className={clsx("tn-menu-action", menu?.active?.id === id && "tn-menu-active")}+ disabled={disabled} tabIndex={menu ? -1 : undefined}+ // The keyboard goes on from the action the pointer last pointed at, as from a row.+ onPointerMove={(e) => {+ if (menu && !disabled && menu.active?.id !== id && pointerMoved(e)) menu.setActive(level, id);+ }}+ // A press keeps focus where it was, as on a row.+ onMouseDown={(e) => e.preventDefault()}+ onClick={select}+ >+ <span className={`tn-icon ${item.uiIcon ?? "bx bx-empty"}`} aria-hidden="true" />+ {/* Callers pass HTML, as for a row's title. */}+ <span className="tn-menu-action-title" dangerouslySetInnerHTML={{ __html: item.title }} />+ </button>+ );+}+interface MenuMatch<T> {item: MenuCommandItem<T>;/** The title as text. */diff --git a/apps/client/src/widgets/react/menu_context.ts b/apps/client/src/widgets/react/menu_context.tsindex 98435c2ddf..37484c1810 100644--- a/apps/client/src/widgets/react/menu_context.ts+++ b/apps/client/src/widgets/react/menu_context.ts@@ -30,6 +30,11 @@ export interface RowEntry {hasSubmenu: boolean;/** Whether typing while its submenu is open filters it. */filterable?: boolean;+ /**+ * Stands beside its neighbours in a row of actions, where the arrow towards the end moves on+ * as Down does and the one towards the start moves back as Up does.+ */+ inline?: boolean;/** Runs the row, as a press or Enter does, once its submenu, if it has one, is open. */select(e: MouseEvent | KeyboardEvent): void;}