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): drive the context menu from the keyboard (closes #1166)
Elian Doranee14cdda5f0a
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsindex 006ffb27ce..878a479404 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -16,6 +16,13 @@ vi.mock("../services/utils", async (importOriginal) => {default: { ...original.default, isMobile: () => layout.onMobile }};});+const focusTraps = vi.hoisted(() => ({ restore: vi.fn(), suspend: vi.fn() }));+vi.mock("../widgets/react/modal_focustrap", () => ({+ suspendModalFocusTraps: () => {+ focusTraps.suspend();+ return focusTraps.restore;+ }+}));// Key names are translated; the formatting has specs of its own.vi.mock("../services/keyboard_shortcut_display", () => ({formatShortcut: (shortcut: string) => shortcut.split("+"),@@ -559,6 +566,153 @@ describe("contextMenu", () => {document.removeEventListener("contextmenu", heard);});+ describe("keyboard", () => {+ const keyboardItems = [+ { title: "Cut" },+ { kind: "separator" as const },+ { title: "Copy", enabled: false },+ { title: "Paste" },+ { title: "Templates", items: [ { title: "Meeting" }, { title: "Weekly" } ] }+ ];++ async function openMenu(onSelect: (title: string) => void = () => {}) {+ buildPage();+ const editor = document.createElement("textarea");+ document.body.append(editor);+ editor.focus();+ const contextMenu = await buildContextMenu();+ await contextMenu.show({+ x: 10, y: 10, items: keyboardItems,+ selectMenuItemHandler: (item) => onSelect(String(item.title))+ });+ // The menu takes focus once it is placed, before which no key can reach it.+ await vi.waitFor(() => expect(document.activeElement).toBe(menuElement()));+ return { contextMenu, editor };+ }++ function key(name: string) {+ const event = new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true });+ (document.activeElement ?? document.body).dispatchEvent(event);+ return event;+ }++ /** The active row's title, as `aria-activedescendant` names it. */+ function activeRow() {+ const id = menuElement()?.getAttribute("aria-activedescendant");+ const row = id ? document.getElementById(id) : null;+ if (id && !row?.classList.contains("tn-menu-active")) throw new Error("the active row is not marked");+ return row?.querySelector(":scope > span")?.textContent ?? null;+ }++ afterEach(() => {+ focusTraps.suspend.mockClear();+ focusTraps.restore.mockClear();+ });++ it("takes focus while it is up, gives it back once hidden, and holds off the modals' focus traps meanwhile", async () => {+ // A browser does not focus an element under `visibility: hidden`, which `Menu.css`+ // keeps the menu under until it is placed. happy-dom loads no stylesheet and focuses it+ // regardless, so the spec records what the menu showed when it was asked to take focus.+ const visibilityOnFocus: string[] = [];+ const focus = HTMLElement.prototype.focus;+ vi.spyOn(HTMLElement.prototype, "focus").mockImplementation(function (this: HTMLElement, options) {+ if (this.id === "context-menu-container") visibilityOnFocus.push(this.style.visibility);+ focus.call(this, options);+ });+ const { contextMenu, editor } = await openMenu();++ await vi.waitFor(() => expect(document.activeElement).toBe(menuElement()));+ expect(visibilityOnFocus).toEqual([ "visible" ]);+ expect(focusTraps.suspend).toHaveBeenCalledTimes(1);+ expect(focusTraps.restore).not.toHaveBeenCalled();++ await contextMenu.hide();+ // A spelling fix acts on the editor's selection, so the editor has focus back by then.+ expect(document.activeElement).toBe(editor);+ expect(focusTraps.restore).toHaveBeenCalledTimes(1);+ });++ it("moves between the rows it can run, around from either end", async () => {+ await openMenu();+ expect(activeRow()).toBeNull();++ key("ArrowDown");+ await vi.waitFor(() => expect(activeRow()).toBe("Cut"));+ // Past the separator and the disabled row.+ key("ArrowDown");+ await vi.waitFor(() => expect(activeRow()).toBe("Paste"));+ key("ArrowDown");+ await vi.waitFor(() => expect(activeRow()).toBe("Templates"));+ key("ArrowDown");+ await vi.waitFor(() => expect(activeRow()).toBe("Cut"));+ key("ArrowUp");+ await vi.waitFor(() => expect(activeRow()).toBe("Templates"));+ key("Home");+ await vi.waitFor(() => expect(activeRow()).toBe("Cut"));+ key("End");+ await vi.waitFor(() => expect(activeRow()).toBe("Templates"));+ // Typing a row's first letters goes to it.+ key("p");+ await vi.waitFor(() => expect(activeRow()).toBe("Paste"));+ });++ it("opens a submenu towards it and closes it back, one level at a time", async () => {+ const dialogHeard = vi.fn();+ document.addEventListener("keydown", dialogHeard);+ const { contextMenu } = await openMenu();++ // Each key waits for the one before it to render, as a key press arrives in a task of its own.+ key("End");+ await vi.waitFor(() => expect(activeRow()).toBe("Templates"));+ key("ArrowRight");+ await vi.waitFor(() => expect(activeRow()).toBe("Meeting"));+ expect(menuElement()?.querySelector("div.dropdown-submenu")).not.toBeNull();++ key("ArrowLeft");+ await vi.waitFor(() => expect(activeRow()).toBe("Templates"));+ expect(menuElement()?.querySelector("div.dropdown-submenu")).toBeNull();++ key("ArrowRight");+ await vi.waitFor(() => expect(activeRow()).toBe("Meeting"));+ // Escape closes the submenu, then the menu, and a dialog under it hears neither.+ key("Escape");+ await vi.waitFor(() => expect(activeRow()).toBe("Templates"));+ expect(contextMenu.isShown).toBe(true);+ key("Escape");+ expect(contextMenu.isShown).toBe(false);+ expect(dialogHeard).not.toHaveBeenCalled();+ document.removeEventListener("keydown", dialogHeard);+ });++ it("runs the active row on Enter, with focus back where it was", async () => {+ const picked: string[] = [];+ const { contextMenu, editor } = await openMenu((title) => {+ picked.push(title);+ expect(document.activeElement).toBe(editor);+ });++ key("ArrowDown");+ await vi.waitFor(() => expect(activeRow()).toBe("Cut"));+ key("ArrowDown");+ await vi.waitFor(() => expect(activeRow()).toBe("Paste"));+ key("Enter");++ expect(picked).toEqual([ "Paste" ]);+ expect(contextMenu.isShown).toBe(false);+ });++ it("goes on from the row the pointer last pointed at", async () => {+ await openMenu();+ const paste = [ ...menuElement()?.querySelectorAll<HTMLElement>("li.dropdown-item") ?? [] ]+ .find((row) => row.textContent === "Paste");+ paste?.dispatchEvent(new PointerEvent("pointerenter"));+ await vi.waitFor(() => expect(activeRow()).toBe("Paste"));++ key("ArrowDown");+ await vi.waitFor(() => expect(activeRow()).toBe("Templates"));+ });+ });+describe("on a phone", () => {afterEach(() => {layout.onMobile = false;diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.tsindex 713a4860aa..268eb0d777 100644--- a/apps/client/src/menus/context_menu.ts+++ b/apps/client/src/menus/context_menu.ts@@ -5,6 +5,7 @@ import { h, JSX, render } from "preact";import note_tooltip from "../services/note_tooltip.js";import utils from "../services/utils.js";import Menu from "../widgets/react/Menu";+import { suspendModalFocusTraps } from "../widgets/react/modal_focustrap";export interface ContextMenuOptions<T> {x: number;@@ -75,7 +76,7 @@ export interface MenuCommandItem<T> {}export type MenuItem<T> = MenuCommandItem<T> | CustomMenuItem | MenuSeparatorItem | MenuHeader;-export type MenuHandler<T> = (item: MenuCommandItem<T>, e: MouseEvent) => void;+export type MenuHandler<T> = (item: MenuCommandItem<T>, e: MouseEvent | KeyboardEvent) => void;export type ContextMenuEvent = PointerEvent | MouseEvent | JQuery.ContextMenuEvent;class ContextMenu {@@ -85,6 +86,9 @@ class ContextMenu {private options?: ContextMenuOptions<any>;/** See {@link dismissedByLastPress}. */private pressDismissed = false;+ /** What had focus before the menu took it, and gets it back once the menu is hidden. */+ private focusBeforeShow: Element | null = null;+ private restoreModalFocusTraps?: () => void;constructor() {this.cover = utils.isMobile() ? document.getElementById("context-menu-cover") : null;@@ -102,7 +106,8 @@ class ContextMenu {setTimeout(() => this.pressDismissed = false);}, true);document.addEventListener("keydown", (e) => {- if (e.key !== "Escape" || !this.isShown) return;+ // Inside the menu, `Menu` closes one level at a time.+ if (e.key !== "Escape" || !this.isShown || this.host?.contains(e.target as Node)) return;// A dialog under the menu stays open.e.stopPropagation();void this.hide();@@ -119,6 +124,9 @@ class ContextMenu {}this.options = options;+ this.focusBeforeShow = document.activeElement;+ // The menu takes focus, which a modal's focus trap would otherwise pull back into the modal.+ this.restoreModalFocusTraps = suspendModalFocusTraps();// A browser showing an element fullscreen paints only that element, so the menu goes// inside it.this.host = document.createElement("div");@@ -164,11 +172,21 @@ class ContextMenu {this.cover?.classList.remove("show");document.body.classList.remove("context-menu-shown");+ const menuHadFocus = !!this.host?.contains(document.activeElement);if (this.host) {render(null, this.host);this.host.remove();this.host = undefined;}++ // Traps first: re-arming one focuses its modal, which the focus given back then moves on from.+ this.restoreModalFocusTraps?.();+ this.restoreModalFocusTraps = undefined;+ // Only while the menu still held it: a press outside has already moved it where it belongs.+ if (menuHadFocus && this.focusBeforeShow instanceof HTMLElement && this.focusBeforeShow.isConnected) {+ this.focusBeforeShow.focus({ preventScroll: true });+ }+ this.focusBeforeShow = null;options?.onHide?.();}}diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.cssindex c6dc41bf6c..739ca07c86 100644--- a/apps/client/src/widgets/react/Menu.css+++ b/apps/client/src/widgets/react/Menu.css@@ -41,8 +41,17 @@overflow-y: auto;}-/* The pointer leaves the row for its submenu, so the row stays marked while the submenu is open. */-body.desktop .dropdown-item.dropdown-submenu.submenu-open {+/* The menu holds focus for its keys; the row they act on shows where they are instead. */+.dropdown-menu.tn-menu:focus {+ outline: none;+}++/*+ * The pointer leaves the row for its submenu, so the row stays marked while the submenu is open.+ * The row the keyboard acts on is marked the same way.+ */+body.desktop .dropdown-item.dropdown-submenu.submenu-open,+.dropdown-item.tn-menu-active:not(.disabled) {color: var(--hover-item-text-color);background-color: var(--hover-item-background-color);}diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsxindex ea44d8a372..5873f9191f 100644--- a/apps/client/src/widgets/react/Menu.tsx+++ b/apps/client/src/widgets/react/Menu.tsx@@ -2,7 +2,7 @@ import "./Menu.css";import { autoUpdate, computePosition, flip, hide, offset, type Placement, type ReferenceElement, shift, size, type VirtualElement } from "@floating-ui/dom";import clsx from "clsx";-import { useCallback, useLayoutEffect, useRef, useState } from "preact/hooks";+import { useCallback, useId, useLayoutEffect, useRef, useState } from "preact/hooks";import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";import { getActionSync } from "../../services/keyboard_actions";@@ -29,8 +29,8 @@ export interface MenuProps<T> {*/bottomSheet?: boolean;items: MenuItem<T>[];- /** Called when an item is pressed with the primary button. */- onSelect(item: MenuCommandItem<T>, e: MouseEvent): void;+ /** Called when an item is pressed with the primary button, or run from the keyboard. */+ onSelect(item: MenuCommandItem<T>, e: MouseEvent | KeyboardEvent): void;/** Called on a click inside a custom item, which closes the menu like a pressed item does. */onClose(): void;}@@ -46,6 +46,15 @@ interface OpenSubmenu<T> {key: number;}+/** The row the keyboard acts on, and the level it stands at. */+interface ActiveRow<T> {+ level: number;+ item: MenuCommandItem<T>;+}++/** How long typed letters keep adding to the text a row is looked up by. */+const TYPEAHEAD_TIMEOUT = 500;+/** What every level of the menu shares. */interface MenuState<T> {onSelect: MenuProps<T>["onSelect"];@@ -57,6 +66,10 @@ interface MenuState<T> {openSubmenu(level: number, item?: MenuCommandItem<T>, anchor?: HTMLElement): void;/** The item whose submenu stands open at each level. */openItems: MenuCommandItem<T>[];+ active?: ActiveRow<T>;+ setActive(level: number, item: MenuCommandItem<T>): void;+ /** Each row's element, for `aria-activedescendant` and for anchoring a submenu the keyboard opens. */+ rows: Map<MenuCommandItem<T>, HTMLElement>;}export default function Menu<T>({ id, className, x, y, orientation, bottomSheet, items, onSelect, onClose }: MenuProps<T>) {@@ -71,26 +84,132 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,return item && anchor ? [ ...kept, { item, anchor, key: nextKey.current++ } ] : kept;});}, []);- const state: MenuState<T> = { onSelect, onClose, openSubmenu, openItems: submenus.map((submenu) => submenu.item) };+ const [ active, setActiveRow ] = useState<ActiveRow<T>>();+ const rows = useRef(new Map<MenuCommandItem<T>, HTMLElement>()).current;+ const typeahead = useRef({ text: "", timeout: 0 });++ const setActive = useCallback((level: number, item: MenuCommandItem<T>) => {+ setActiveRow({ level, item });+ rows.get(item)?.scrollIntoView?.({ block: "nearest" });+ }, [ rows ]);+ const state: MenuState<T> = {+ onSelect, onClose, openSubmenu, openItems: submenus.map((submenu) => submenu.item), active, setActive, rows+ };++ // After the commit: a submenu's rows register their elements only as they mount.+ useLayoutEffect(() => {+ const id = active && rows.get(active.item)?.id;+ if (id) menuRef.current?.setAttribute("aria-activedescendant", id);+ else menuRef.current?.removeAttribute("aria-activedescendant");+ }, [ active, submenus, rows ]);++ const keyHandler = useRef(onKeyDown);+ keyHandler.current = onKeyDown;+ useLayoutEffect(() => {+ // Captured at the window: Bootstrap captures keys at the document for anything inside a+ // `.dropdown-menu`, and takes them for a dropdown of its own. Only keys the menu itself+ // receives, so a control inside a custom item keeps its own.+ const listener = (e: KeyboardEvent) => {+ if (e.target === menuRef.current) keyHandler.current(e);+ };+ window.addEventListener("keydown", listener, true);+ return () => window.removeEventListener("keydown", listener, true);+ }, []);++ function onKeyDown(e: KeyboardEvent) {+ const level = active?.level ?? 0;+ const levelRows = runnableRows(level === 0 ? items : submenus[level - 1]?.item.items ?? []);+ const index = active ? levelRows.indexOf(active.item) : -1;+ const count = levelRows.length;+ const goTo = (position: number) => {+ const item = levelRows[((position % count) + count) % count];+ if (item) setActive(level, item);+ };+ const openActive = () => {+ const item = active?.item;+ const anchor = item && rows.get(item);+ if (!item?.items || !anchor || isMobile()) return;+ openSubmenu(level, item, anchor);+ const first = runnableRows(item.items)[0];+ if (first) setActive(level + 1, first);+ };+ const closeLevel = (closing: number) => {+ const parent = submenus[closing - 1];+ if (!parent) return;+ openSubmenu(closing - 1);+ setActive(closing - 1, parent.item);+ };+ const rtl = handleRightToLeftPlacement("right") !== "right";++ switch (e.key) {+ case "ArrowDown": goTo(index + 1); break;+ case "ArrowUp": goTo(index < 0 ? -1 : index - 1); break;+ case "Home": goTo(0); break;+ case "End": goTo(-1); break;+ case rtl ? "ArrowLeft" : "ArrowRight": openActive(); break;+ case rtl ? "ArrowRight" : "ArrowLeft": if (level > 0) closeLevel(level); break;+ case "Enter":+ case " ":+ if (!active) break;+ openActive();+ onSelect(active.item, e);+ break;+ case "Escape":+ // One level at a time, then the menu itself.+ if (submenus.length) closeLevel(submenus.length);+ else onClose();+ break;+ // Focus stays in the menu until it closes.+ case "Tab": break;+ default: {+ if (e.key.length !== 1 || e.ctrlKey || e.metaKey || e.altKey) return;+ const typed = typeahead.current;+ window.clearTimeout(typed.timeout);+ typed.timeout = window.setTimeout(() => typed.text = "", TYPEAHEAD_TIMEOUT);+ typed.text += e.key.toLowerCase();+ // A first letter looks past the active row, so pressing it again moves on.+ const skip = typed.text.length === 1 ? 1 : 0;+ for (let step = skip; step < count + skip; step++) {+ const item = levelRows[(index + step + count) % count];+ if (item && rows.get(item)?.textContent?.trim().toLowerCase().startsWith(typed.text)) {+ setActive(level, item);+ break;+ }+ }+ }+ }+ e.preventDefault();+ e.stopPropagation();+ }useLayoutEffect(() => {const menu = menuRef.current;if (!menu) return;+ // The keys go to the menu while it is up; `contextMenu` gives focus back once it is hidden.+ // A browser does not focus an element under `visibility: hidden`, so the menu takes focus+ // only once it is shown.+ const takeFocus = () => menu.focus({ preventScroll: true });if (bottomSheet) {// An inline `max-height` would override the sheet's own, which is not `!important`.menu.style.visibility = "visible";+ takeFocus();return;}const anchor = pointAt(x, y);const placement = orientation === "left" ? "left-start" : "right-start";+ let placed = false;// Places the menu now, and again whenever the viewport or the menu itself changes size.- return autoUpdate(anchor, menu, () => void placeMenu(menu, anchor, placement));+ return autoUpdate(anchor, menu, () => void placeMenu(menu, anchor, placement).then(() => {+ if (placed) return;+ placed = true;+ takeFocus();+ }));}, [ x, y, orientation, bottomSheet ]);return (<div- ref={menuRef} id={id} role="menu"+ ref={menuRef} id={id} role="menu" tabIndex={-1}className={clsx("dropdown-menu show tn-menu", bottomSheet && "mobile-bottom-menu", className)}// Neither the browser's menu nor another of the app's opens over this one. Every level// is inside this element, so one handler covers them all.@@ -187,21 +306,31 @@ function MenuRow<T>({ level, item, state }: { level: number, item: MenuCommandIt// A phone has no room beside the menu, so a submenu unfolds under its row instead.const [ unfolded, setUnfolded ] = useState(false);const open = isMobile() ? unfolded : state.openItems[level] === item;+ const active = state.active?.level === level && state.active.item === item;+ const id = useId();return (<li+ id={id}+ ref={(element) => {+ if (element) state.rows.set(item, element);+ else state.rows.delete(item);+ }}className={clsx("dropdown-item", hasSubmenu && "dropdown-submenu", open && "submenu-open",- disabled && "disabled", item.className)}+ active && "tn-menu-active", disabled && "disabled", item.className)}role="menuitem"aria-disabled={disabled || undefined}aria-haspopup={hasSubmenu ? "menu" : undefined}aria-expanded={hasSubmenu ? open : undefined}onPointerEnter={(e) => {if (isMobile()) return;+ // The keyboard goes on from the row the pointer last pointed at.+ if (!disabled) state.setActive(level, item);state.openSubmenu(level, hasSubmenu && !disabled ? item : undefined, e.currentTarget);}}// `mousedown` rather than `click`, and its default prevented, so the press does not move- // focus: a text editor keeps the selection that commands such as a spelling fix act on.+ // focus out of the menu: `contextMenu` hands it back to a text editor before the command+ // runs, with the selection that commands such as a spelling fix act on.onMouseDown={(e) => {if (e.button !== 0) return;e.preventDefault();@@ -268,6 +397,11 @@ function MenuIconSlot<T>({ item }: { item: MenuCommandItem<T> }) {: <span>{"\u00a0"}</span>;}+/** The rows the keyboard can reach: those that run something, and are enabled. */+function runnableRows<T>(items: MenuItem<T>[]) {+ return menuRows(items).filter((row): row is MenuCommandItem<T> => !("kind" in row) && row.enabled !== false);+}+/** The items with a run of separators reduced to one. */function menuRows<T>(items: MenuItem<T>[]) {const rows: MenuItem<T>[] = [];