Skip to content

Build your personal knowledge base with Trilium Notes

feat(menu): start a context menu a key opened at its first row

Elian Doran57ffd3c7d6a5
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index a1d228f97e..a3c5473faa 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -656,6 +656,25 @@ describe("contextMenu", () => {
focusTraps.restore.mockClear();
});
+ it("starts at its first row when a key opened it, as the Menu key or Shift+F10 does", async () => {
+ buildPage();
+ const contextMenu = await buildContextMenu();
+ const show = () => contextMenu.show({ x: 10, y: 10, items: keyboardItems, selectMenuItemHandler: () => {} });
+
+ // The key that opens it comes first, then the `contextmenu` event its caller answers.
+ document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "ContextMenu", bubbles: true }));
+ await show();
+ await vi.waitFor(() => expect(activeRow()).toBe("Cut"));
+ // Keyed from the start, so a pointer resting on another row does not mark it too.
+ expect(menuElement()?.classList.contains("tn-menu-keyboard")).toBe(true);
+
+ // A press opens it with nothing active, for the pointer to choose.
+ document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 2 }));
+ await show();
+ await vi.waitFor(() => expect(document.activeElement).toBe(menuElement()));
+ expect(activeRow()).toBeNull();
+ });
+
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
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index 268eb0d777..3570c8b01e 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -89,6 +89,11 @@ class ContextMenu {
/** 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;
+ /**
+ * Whether a key came after the last press. A menu opened then was opened by a key, such as the
+ * Menu key or Shift+F10, as callers pass no event to tell by.
+ */
+ private lastInputWasKey = false;
constructor() {
this.cover = utils.isMobile() ? document.getElementById("context-menu-cover") : null;
@@ -97,6 +102,7 @@ class ContextMenu {
// keep them from here. `pointerdown` covers every button, including a Ctrl+right-click
// that fires no `click`, and a tap on the mobile cover.
document.addEventListener("pointerdown", (e) => {
+ this.lastInputWasKey = false;
const outside = this.isShown && !this.host?.contains(e.target as Node);
this.pressDismissed = outside;
if (outside) void this.hide();
@@ -106,6 +112,7 @@ class ContextMenu {
setTimeout(() => this.pressDismissed = false);
}, true);
document.addEventListener("keydown", (e) => {
+ this.lastInputWasKey = true;
// 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.
@@ -142,6 +149,8 @@ class ContextMenu {
y: options.y,
orientation: options.orientation,
bottomSheet: utils.isMobile() && !options.forcePositionOnMobile,
+ // As a native menu opened from the keyboard, it starts at its first row.
+ startAtFirstRow: this.lastInputWasKey,
items: options.items,
onSelect: (item, e) => {
// A submenu's row stays up to be opened, unless it runs something of its own.
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 05969c6c8f..efd5a27a74 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -28,6 +28,8 @@ export interface MenuProps<T> {
* {@link y}. The `.mobile-bottom-menu` rules place and cap it.
*/
bottomSheet?: boolean;
+ /** Makes the first row the active one as the menu takes focus, for a menu a key opened. */
+ startAtFirstRow?: boolean;
items: MenuItem<T>[];
/** Called when an item is pressed with the primary button, or run from the keyboard. */
onSelect(item: MenuCommandItem<T>, e: MouseEvent | KeyboardEvent): void;
@@ -83,7 +85,7 @@ interface MenuState<T> {
rows: Map<NavigableItem<T>, HTMLElement>;
}
-export default function Menu<T>({ id, className, x, y, orientation, bottomSheet, items, onSelect, onClose }: MenuProps<T>) {
+export default function Menu<T>({ id, className, x, y, orientation, bottomSheet, startAtFirstRow, items, onSelect, onClose }: MenuProps<T>) {
const menuRef = useRef<HTMLDivElement>(null);
const [ submenus, setSubmenus ] = useState<OpenSubmenu<T>[]>([]);
const nextKey = useRef(0);
@@ -145,12 +147,17 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,
return () => window.removeEventListener("keydown", listener, true);
}, []);
- function onKeyDown(e: KeyboardEvent) {
- const level = active?.level ?? 0;
- const levelRows = menuRows(level === 0 ? items : submenus[level - 1]?.item.items ?? [])
+ /** The rows the keys can stand on at `level`: those that run something, and custom rows with something to focus. */
+ function navigableRows(level: number) {
+ return menuRows(level === 0 ? items : submenus[level - 1]?.item.items ?? [])
.filter((row): row is NavigableItem<T> => isCustom(row)
? !!focusTarget(rows.get(row))
: isRunnable(row));
+ }
+
+ function onKeyDown(e: KeyboardEvent) {
+ const level = active?.level ?? 0;
+ const levelRows = navigableRows(level);
const index = active ? levelRows.indexOf(active.item) : -1;
const count = levelRows.length;
// A submenu goes with its row's highlight, as in a native menu, until Right opens it again.
@@ -241,7 +248,13 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,
// 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 });
+ const takeFocus = () => {
+ menu.focus({ preventScroll: true });
+ if (!startAtFirstRow) return;
+ const first = navigableRows(0)[0];
+ if (first) setActive(0, first);
+ setKeyboardDriven(true);
+ };
if (bottomSheet) {
// An inline `max-height` would override the sheet's own, which is not `!important`.
menu.style.visibility = "visible";