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): move across a column submenu's columns with the arrow keys
Elian Doran37e1a5702963
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsindex 878a479404..8959485a5b 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -701,6 +701,44 @@ describe("contextMenu", () => {expect(contextMenu.isShown).toBe(false);});+ it("moves across a submenu's columns, and leaves it from its first", async () => {+ buildPage();+ const contextMenu = await buildContextMenu();+ await contextMenu.show({+ x: 10, y: 10, selectMenuItemHandler: () => {},+ items: [ {+ title: "Insert child note", columns: 2,+ items: [ { title: "Text" }, { title: "Code" }, { title: "Meeting" }, { title: "Weekly" } ]+ } ]+ });+ await vi.waitFor(() => expect(document.activeElement).toBe(menuElement()));++ key("ArrowDown");+ await vi.waitFor(() => expect(activeRow()).toBe("Insert child note"));+ key("ArrowRight");+ await vi.waitFor(() => expect(activeRow()).toBe("Text"));+ // Where the browser broke the columns: happy-dom lays out nothing.+ const boxes: Record<string, [number, number]> = { Text: [ 0, 0 ], Code: [ 0, 24 ], Meeting: [ 150, 0 ], Weekly: [ 150, 24 ] };+ for (const layerRow of menuElement()?.querySelectorAll<HTMLElement>("div.dropdown-submenu li") ?? []) {+ const [ left, top ] = boxes[layerRow.textContent ?? ""] ?? [ 0, 0 ];+ vi.spyOn(layerRow, "getBoundingClientRect").mockReturnValue(DOMRect.fromRect({ x: left, y: top, width: 140, height: 24 }));+ }++ key("ArrowDown");+ await vi.waitFor(() => expect(activeRow()).toBe("Code"));+ key("ArrowRight");+ await vi.waitFor(() => expect(activeRow()).toBe("Weekly"));+ // Nothing further right, so it stays.+ key("ArrowRight");+ key("ArrowLeft");+ await vi.waitFor(() => expect(activeRow()).toBe("Code"));+ // From the first column, Left closes the submenu as before.+ key("ArrowLeft");+ await vi.waitFor(() => expect(activeRow()).toBe("Insert child note"));+ expect(menuElement()?.querySelector("div.dropdown-submenu")).toBeNull();+ vi.restoreAllMocks();+ });+it("goes on from the row the pointer last pointed at", async () => {await openMenu();const paste = [ ...menuElement()?.querySelectorAll<HTMLElement>("li.dropdown-item") ?? [] ]diff --git a/apps/client/src/widgets/react/Menu.spec.tsx b/apps/client/src/widgets/react/Menu.spec.tsxnew file mode 100644index 0000000000..24cbee4bd0--- /dev/null+++ b/apps/client/src/widgets/react/Menu.spec.tsx@@ -0,0 +1,38 @@+import { describe, expect, it } from "vitest";++import { rowInNextColumn } from "./Menu";++/** A row 20px tall, `left` into the menu and `top` down it. */+function row(left: number, top: number) {+ return { left, top, bottom: top + 20 };+}++describe("rowInNextColumn", () => {+ // Three rows in the first column, two in the second, one in the third.+ const columns = [+ row(0, 0), row(0, 20), row(0, 40),+ row(100, 0), row(100, 20),+ row(200, 0)+ ];++ it("goes to the row at the same height in the column beside", () => {+ expect(rowInNextColumn(columns, 1, "right")).toBe(4);+ expect(rowInNextColumn(columns, 4, "left")).toBe(1);+ // The nearest column, not the one after it.+ expect(rowInNextColumn(columns, 0, "right")).toBe(3);+ });++ it("goes to the nearest row where the column beside is shorter", () => {+ expect(rowInNextColumn(columns, 2, "right")).toBe(4);+ expect(rowInNextColumn(columns, 4, "right")).toBe(5);+ });++ it("finds nothing past the outermost column, in a single column, or for a row it cannot place", () => {+ expect(rowInNextColumn(columns, 0, "left")).toBeUndefined();+ expect(rowInNextColumn(columns, 5, "right")).toBeUndefined();+ expect(rowInNextColumn([ row(0, 0), row(0, 20) ], 0, "right")).toBeUndefined();+ expect(rowInNextColumn(columns, -1, "right")).toBeUndefined();+ // A row not laid out yet is passed over.+ expect(rowInNextColumn([ row(0, 0), undefined, row(100, 0) ], 0, "right")).toBe(2);+ });+});diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsxindex 5873f9191f..f0f0905cd0 100644--- a/apps/client/src/widgets/react/Menu.tsx+++ b/apps/client/src/widgets/react/Menu.tsx@@ -141,13 +141,29 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,};const rtl = handleRightToLeftPlacement("right") !== "right";+ /** Moves to the row beside the active one in a menu laid out in columns, if there is one. */+ const moveAcross = (towards: "left" | "right") => {+ const boxes = levelRows.map((item) => rows.get(item)?.getBoundingClientRect());+ const target = rowInNextColumn(boxes, index, towards);+ const item = target !== undefined ? levelRows[target] : undefined;+ if (item) setActive(level, item);+ return !!item;+ };+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;+ // Into the active row's submenu, or else across to the next column.+ case rtl ? "ArrowLeft" : "ArrowRight":+ if (active?.item.items) openActive();+ else moveAcross(e.key === "ArrowRight" ? "right" : "left");+ break;+ // Back across a column, or else out of the submenu.+ case rtl ? "ArrowRight" : "ArrowLeft":+ if (!moveAcross(e.key === "ArrowRight" ? "right" : "left") && level > 0) closeLevel(level);+ break;case "Enter":case " ":if (!active) break;@@ -397,6 +413,44 @@ function MenuIconSlot<T>({ item }: { item: MenuCommandItem<T> }) {: <span>{"\u00a0"}</span>;}+/** How far apart, in pixels, two rows' left edges can be and still stand in one column. */+const COLUMN_TOLERANCE = 1;++/**+ * In a menu laid out in columns, the index of the row beside `boxes[index]` in the nearest column+ * towards `towards`: the one whose middle is nearest its middle. The browser decides where CSS+ * columns break, so the rows' boxes are all there is to go by. Rows without a box are passed over.+ */+export function rowInNextColumn(+ boxes: (Pick<DOMRect, "left" | "top" | "bottom"> | undefined)[],+ index: number,+ towards: "left" | "right"+): number | undefined {+ const from = boxes[index];+ if (!from) return undefined;++ const middle = (box: Pick<DOMRect, "top" | "bottom">) => (box.top + box.bottom) / 2;+ const beyond: { box: Pick<DOMRect, "left" | "top" | "bottom">, index: number }[] = [];+ for (const [ candidateIndex, box ] of boxes.entries()) {+ if (!box) continue;+ const offset = box.left - from.left;+ if (towards === "right" ? offset > COLUMN_TOLERANCE : offset < -COLUMN_TOLERANCE) {+ beyond.push({ box, index: candidateIndex });+ }+ }+ if (!beyond.length) return undefined;++ const lefts = beyond.map(({ box }) => box.left);+ const columnLeft = towards === "right" ? Math.min(...lefts) : Math.max(...lefts);+ let nearest: { box: Pick<DOMRect, "left" | "top" | "bottom">, index: number } | undefined;+ for (const candidate of beyond) {+ if (Math.abs(candidate.box.left - columnLeft) > COLUMN_TOLERANCE) continue;+ const distance = Math.abs(middle(candidate.box) - middle(from));+ if (!nearest || distance < Math.abs(middle(nearest.box) - middle(from))) nearest = candidate;+ }+ return nearest?.index;+}+/** 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);