Skip to content

Build your personal knowledge base with Trilium Notes

client/ui/menus: move the filter input field at bottom for bottom-anchored menus

Adorian Doranddf2c8fec71a
diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsx
index 41a171070a..56e0d6a95f 100644
--- a/apps/client/src/widgets/react/FormList.tsx
+++ b/apps/client/src/widgets/react/FormList.tsx
@@ -730,8 +730,10 @@ function SubmenuPage({ rowId, level, title, slide, filter, children }: {
* One level of a menu: its rows in a scrolling list and, for a level with a {@link filter}, the
* filter input above that list. The input stays in place while the rows scroll.
*/
-export function MenuList({ filter, children }: {
+export function MenuList({ filter, bottomUp, children }: {
filter: MenuFilter | undefined,
+ /** Puts the filter input below the list, for a menu that opens above its anchor. */
+ bottomUp?: boolean,
children: ComponentChildren
}) {
// The rows scroll here and not in the frame, so the theme's `::before` blur stays behind
@@ -742,8 +744,9 @@ export function MenuList({ filter, children }: {
{/* One box, so a phone's submenu page hides and slides the input with the rows. */}
{filter ? (
<div className="tn-menu-filterable">
- <MenuFilterInput filter={filter} />
+ {!bottomUp && <MenuFilterInput filter={filter} />}
{list}
+ {bottomUp && <MenuFilterInput filter={filter} />}
</div>
) : list}
</MenuFilterContext.Provider>
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.css
index 899d260ffd..f189996453 100644
--- a/apps/client/src/widgets/react/Menu.css
+++ b/apps/client/src/widgets/react/Menu.css
@@ -206,6 +206,10 @@ body.desktop .dropdown-item.dropdown-submenu.submenu-open,
scroll-padding-top: 0;
}
+ .tn-menu-scroll + & {
+ padding: 4px var(--tn-popup-padding) var(--tn-popup-padding);
+ }
+
.tn-menu-filter-box {
display: flex;
align-items: center;
@@ -232,6 +236,13 @@ body.desktop .dropdown-item.dropdown-submenu.submenu-open,
}
}
+.tn-menu-scroll:has(+ .tn-menu-filter) {
+ border-end-start-radius: 0;
+ border-end-end-radius: 0;
+ padding-bottom: 0;
+ scroll-padding-bottom: 0;
+}
+
.tn-menu-filter-empty {
padding: 0.25rem 0.75rem;
color: var(--muted-text-color);
diff --git a/apps/client/src/widgets/react/Menu.spec.tsx b/apps/client/src/widgets/react/Menu.spec.tsx
index 54a0a9cc3e..a0b3bc7bd7 100644
--- a/apps/client/src/widgets/react/Menu.spec.tsx
+++ b/apps/client/src/widgets/react/Menu.spec.tsx
@@ -1,11 +1,11 @@
import { Tooltip } from "bootstrap";
import { render } from "preact";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { MenuItem } from "../../menus/context_menu";
import { formatShortcut, joinShortcut } from "../../services/keyboard_shortcut_display";
import { FormDropdownDivider, FormDropdownSubmenu, FormListHeader, FormListItem } from "./FormList";
-import Menu, { type MenuProps } from "./Menu";
+import Menu, { bottomUpOrder, type MenuProps } from "./Menu";
import { shouldDropStart } from "./menu_context";
vi.mock("../../services/keyboard_actions", async (importOriginal) => {
@@ -441,3 +441,134 @@ describe("Menu with an action row", () => {
await vi.waitFor(() => expect(active(menu)).toBe("Cut"));
});
});
+
+describe("bottomUpOrder", () => {
+ const header = (title: string): MenuItem<unknown> => ({ kind: "header", title });
+ const separator: MenuItem<unknown> = { kind: "separator" };
+ const row = (title: string): MenuItem<unknown> => ({ title });
+ /** The titles of `items` in the order a bottom-up menu draws them, top to bottom. */
+ const drawn = (items: MenuItem<unknown>[]) => bottomUpOrder(items)
+ .map((index) => items[index])
+ .map((item) => (item && "title" in item ? item.title : "---"));
+
+ it("reverses the rows, keeping headers above their rows and separators between groups", () => {
+ expect(drawn([ row("a"), row("b"), separator, row("Configure") ]))
+ .toEqual([ "Configure", "---", "b", "a" ]);
+ expect(drawn([ header("H1"), row("a"), row("b"), separator, header("H2"), row("c") ]))
+ .toEqual([ "H2", "c", "---", "H1", "b", "a" ]);
+ expect(drawn([ row("a"), separator, header("H1"), row("b") ]))
+ .toEqual([ "H1", "b", "---", "a" ]);
+ expect(drawn([ header("H1"), row("a"), separator, row("b") ]))
+ .toEqual([ "H1", "b", "---", "a" ]);
+ expect(drawn([])).toEqual([]);
+ });
+});
+
+describe("Menu of items above its anchor", () => {
+ const host = document.createElement("div");
+ const toggle = document.createElement("button");
+ document.body.append(host, toggle);
+ /** How tall happy-dom, which lays nothing out, is made to draw each row. */
+ const ROW_HEIGHT = 30;
+
+ beforeEach(() => {
+ vi.spyOn(document.documentElement, "clientWidth", "get").mockReturnValue(1000);
+ vi.spyOn(document.documentElement, "clientHeight", "get").mockReturnValue(800);
+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(200);
+ // As tall as its rows, so filtering shrinks it.
+ const height = function (this: HTMLElement) {
+ return this.matches(".tn-popup") ? ROW_HEIGHT * this.querySelectorAll("li").length : 0;
+ };
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation(height);
+ });
+
+ afterEach(() => {
+ render(null, host);
+ vi.restoreAllMocks();
+ });
+
+ /** Opens a menu from a toggle at `y`, as the status bar's are at the bottom of the window. */
+ async function openAt(y: number, props: Partial<MenuProps<unknown>>) {
+ const rect = DOMRect.fromRect({ x: 100, y, width: 80, height: 30 });
+ vi.spyOn(toggle, "getBoundingClientRect").mockReturnValue(rect);
+ render(<Menu anchor={toggle} onClose={vi.fn()} {...props} />, host);
+ const menu = document.querySelector<HTMLElement>(".tn-popup.tn-menu");
+ if (!menu) throw new Error("expected the menu to render");
+ await vi.waitFor(() => expect(menu.style.visibility).toBe("visible"));
+ return menu;
+ }
+
+ /** The rows of `list` top to bottom, a separator as `---`. */
+ const rowsOf = (list: Element | null | undefined) =>
+ [ ...list?.querySelectorAll(":scope > li") ?? [] ].map((item) => item.textContent || "---");
+ const classesOf = (element: Element | null | undefined) =>
+ [ ...element?.children ?? [] ].map((child) => child.className);
+ const activeRow = (menu: HTMLElement) => menu.querySelector("li.tn-menu-active")?.textContent;
+ const key = (menu: HTMLElement, name: string) => menu.dispatchEvent(
+ new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true })
+ );
+
+ it("draws a filterable menu bottom-up, first row lowest and active as it opens", async () => {
+ const menu = await openAt(700, { filterable: true, items: [
+ { kind: "header", title: "Recent" }, { title: "Python" }, { title: "JavaScript" },
+ { kind: "separator" },
+ { kind: "header", title: "All" }, { title: "Plain text" }, { title: "Markdown" }
+ ] });
+ const box = menu.querySelector(":scope > .tn-menu-filterable");
+ const list = () => box?.querySelector(":scope > .tn-menu-scroll");
+ // The input next to the toggle, and the rows reversed, each header still above its rows.
+ expect(classesOf(box)).toEqual([ "tn-menu-scroll", "tn-menu-filter" ]);
+ expect(rowsOf(list()))
+ .toEqual([ "All", "Markdown", "Plain text", "---", "Recent", "JavaScript", "Python" ]);
+ expect(activeRow(menu)).toBe("Python");
+ // The keys move as the rows are drawn.
+ key(menu, "ArrowUp");
+ await vi.waitFor(() => expect(activeRow(menu)).toBe("JavaScript"));
+
+ // The best match goes lowest, and is the one Enter runs.
+ key(menu, "p");
+ await vi.waitFor(() => expect(rowsOf(list()))
+ .toEqual([ "JavaScript", "Plain text", "Python" ]));
+ expect(activeRow(menu)).toBe("Python");
+ key(menu, "ArrowUp");
+ await vi.waitFor(() => expect(activeRow(menu)).toBe("Plain text"));
+ });
+
+ it("keeps its submenus top-down, as it does a menu with no filter", async () => {
+ const menu = await openAt(760, { filterable: true, items: [
+ { title: "Python" },
+ { title: "More", filterable: true, items: [ { title: "Ruby" }, { title: "Rust" } ] }
+ ] });
+ const topLevel = menu.querySelector(":scope > .tn-menu-filterable > .tn-menu-scroll");
+ expect(rowsOf(topLevel)).toEqual([ "More", "Python" ]);
+ key(menu, "ArrowUp");
+ await vi.waitFor(() => expect(activeRow(menu)).toBe("More"));
+ key(menu, "ArrowRight");
+ await vi.waitFor(() => expect(activeRow(menu)).toBe("Ruby"));
+ const layer = menu.querySelector(".dropdown-submenu .tn-menu-filterable");
+ expect(classesOf(layer)).toEqual([ "tn-menu-filter", "tn-menu-scroll" ]);
+ const layerRows = rowsOf(layer?.querySelector(":scope > .tn-menu-scroll"));
+ expect(layerRows).toEqual([ "Ruby", "Rust" ]);
+
+ render(null, host);
+ const plain = await openAt(760, { items: [ { title: "Python" }, { title: "Ruby" } ] });
+ const plainRows = rowsOf(plain.querySelector(":scope > .tn-menu-scroll"));
+ expect(plainRows).toEqual([ "Python", "Ruby" ]);
+ expect(activeRow(plain)).toBeUndefined();
+ });
+
+ it("stays above its toggle while filtering shrinks it enough to fit below", async () => {
+ const menu = await openAt(640, { filterable: true, items: [
+ { title: "Python" }, { title: "JavaScript" }, { title: "Plain text" },
+ { title: "Markdown" }, { title: "Ruby" }
+ ] });
+ // Five rows, too tall for the room below the toggle: 640 - 5 × 30.
+ expect(menu.style.top).toBe("490px");
+
+ key(menu, "p");
+ key(menu, "y");
+ await vi.waitFor(() => expect(menu.querySelectorAll("li")).toHaveLength(1));
+ window.dispatchEvent(new Event("resize"));
+ await vi.waitFor(() => expect(menu.style.top).toBe("610px"));
+ });
+});
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 90c620311e..27374ba658 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -1,8 +1,10 @@
import "./Menu.css";
import "./slide_animations.css";
+import type { Placement } from "@floating-ui/dom";
import clsx from "clsx";
import type { ComponentChildren } from "preact";
+import { flushSync } from "preact/compat";
import { useCallback, useContext, useLayoutEffect, useRef, useState } from "preact/hooks";
import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";
@@ -52,7 +54,8 @@ export interface MenuProps<T> extends Pick<PopupProps, "anchor" | "offset" | "co
items?: MenuItem<T>[];
/**
* For a menu of {@link items}: offers an input at its top that filters every item, at any depth,
- * as `MenuCommandItem.filterable` does for a submenu.
+ * as `MenuCommandItem.filterable` does for a submenu. Placed above its anchor, the menu is
+ * drawn bottom-up: the input at the bottom, and the first row lowest and active as it opens.
*/
filterable?: boolean;
/** Called when one of {@link items} is pressed with the primary button, or run from the keyboard. */
@@ -119,6 +122,9 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
}, []);
/** Whether the keys moved the menu since the pointer last did. See `Menu.css`. */
const [ keyboardDriven, setKeyboardDriven ] = useState(false);
+ /** The placement above its anchor of a filterable menu, which is then drawn bottom-up. */
+ const [ upwardPlacement, setUpwardPlacement ] = useState<Placement>();
+ const bottomUp = !!upwardPlacement;
/** Whether the menu has asked to close, which it does once. */
const closed = useRef(false);
const close = useCallback(() => {
@@ -165,9 +171,13 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
return found.map(([ rowId ]) => rowId);
}
- /** Makes the first row at `level` that runs something the active one, if the level has rendered. */
+ /**
+ * Makes the first row at `level` that runs something the active one, if the level has rendered.
+ * The first row of a bottom-up menu is the lowest one.
+ */
function activateFirstRow(level: number) {
- const first = navigableRows(level).find((rowId) => !rows.get(rowId)?.custom);
+ const runnable = navigableRows(level).filter((rowId) => !rows.get(rowId)?.custom);
+ const first = level === 0 && bottomUp ? runnable.at(-1) : runnable[0];
if (first) setActive(level, first);
return !!first;
}
@@ -374,13 +384,14 @@ export default function Menu<T>({ id, className, anchor, placement, 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.
- function takeFocus() {
+ function takeFocus(isBottomUp: boolean) {
// A menu already closing, as one whose row ran before it was placed, leaves focus alone.
if (closed.current || isWanted?.() === false) return;
menuRef.current?.focus({ preventScroll: true });
- if (!startAt) return;
+ if (!startAt && !isBottomUp) return;
const rowIds = navigableRows(0);
- const first = startAt === "first" ? rowIds[0] : rowIds.at(-1);
+ // A bottom-up menu starts at its lowest row, however it was opened.
+ const first = startAt === "first" && !isBottomUp ? rowIds[0] : rowIds.at(-1);
if (first) setActive(0, first);
setKeyboardDriven(true);
}
@@ -388,22 +399,28 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
const topLevelFilter = items && filterable
? { ...TOP_LEVEL, text: filter?.level === TOP_LEVEL.level ? filter.text : "" }
: undefined;
+ const defaultPlacement = anchor instanceof HTMLElement ? "bottom-start" : "right-start";
return (
<MenuContext.Provider value={context}>
<Popup
{...popupProps}
anchor={anchor}
- placement={placement ?? (anchor instanceof HTMLElement ? "bottom-start" : "right-start")}
+ // A bottom-up menu keeps its side, so its input stays by the anchor as it shrinks.
+ placement={upwardPlacement ?? placement ?? defaultPlacement}
placedByStylesheet={popupProps.placedByStylesheet || bottomSheet || inline}
reveal={!inline}
- onPlaced={() => {
+ onPlaced={(placed) => {
+ const isBottomUp = !!topLevelFilter
+ && placed !== "stylesheet" && placed.startsWith("top");
+ // The rows reorder before `takeFocus()` picks the row to start at.
+ if (isBottomUp) flushSync(() => setUpwardPlacement(placed));
const menu = menuRef.current;
if (menu) {
setDropStart(0, shouldDropStart(menu.getBoundingClientRect(),
document.documentElement.clientWidth, isRightToLeft(), false));
}
- takeFocus();
+ takeFocus(isBottomUp);
}}
onDismiss={onDismiss && (() => onDismiss())}
escapeDismisses={false}
@@ -428,8 +445,10 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
e.stopPropagation();
}}
>
- <MenuList filter={topLevelFilter}>
- {items ? <MenuItems items={items} onSelect={onSelect} /> : children}
+ <MenuList filter={topLevelFilter} bottomUp={bottomUp}>
+ {items
+ ? <MenuItems items={items} bottomUp={bottomUp} onSelect={onSelect} />
+ : children}
</MenuList>
{/* The submenus' layers follow the scroller in here, portaled by their rows. */}
</Popup>
@@ -452,16 +471,23 @@ export function MenuItemRows<T>({ items }: { items: MenuItem<T>[] }) {
);
}
-function MenuItems<T>({ items, onSelect }: {
+function MenuItems<T>({ items, bottomUp, onSelect }: {
items: MenuItem<T>[],
+ /** Draws the rows from the bottom up, the first row lowest. See {@link bottomUpOrder}. */
+ bottomUp?: boolean,
onSelect: MenuProps<T>["onSelect"]
}) {
const filter = useContext(MenuFilterContext);
if (filter?.text) {
- return <FilteredMenuItems items={items} text={filter.text} onSelect={onSelect} />;
+ return <FilteredMenuItems
+ items={items} text={filter.text} bottomUp={bottomUp} onSelect={onSelect}
+ />;
}
- return <>{menuRows(items).map((row, index) => (
- <MenuItemRow key={index} row={row} onSelect={onSelect} />
+ const rows = menuRows(items);
+ // Keyed by their place in `rows`, so a row keeps its element as the order changes.
+ const order = bottomUp ? bottomUpOrder(rows) : [ ...rows.keys() ];
+ return <>{order.map((index) => (
+ <MenuItemRow key={index} row={rows[index]} onSelect={onSelect} />
))}</>;
}
@@ -469,15 +495,18 @@ function MenuItems<T>({ items, onSelect }: {
* The items of a filtered submenu: every item inside it, at any depth, that matches what was
* typed, each with the submenus it stands in and the matching part of its title marked.
*/
-function FilteredMenuItems<T>({ items, text, onSelect }: {
+function FilteredMenuItems<T>({ items, text, bottomUp, onSelect }: {
items: MenuItem<T>[],
text: string,
+ /** Draws the best match lowest. */
+ bottomUp?: boolean,
onSelect: MenuProps<T>["onSelect"]
}) {
- const matches = filterMenuItems(items, text);
+ const matches = [ ...filterMenuItems(items, text).entries() ];
+ if (bottomUp) matches.reverse();
return <>
{matches.length === 0 && <li className="tn-menu-filter-empty" role="none">{t("menu.no_matches")}</li>}
- {matches.map(({ item, title, path }, index) => (
+ {matches.map(([ index, { item, title, path } ]) => (
<FormListItem
key={index}
icon={item.uiIcon ?? "bx bx-empty"} iconClassName={item.iconColorClass}
@@ -716,6 +745,33 @@ function focusTarget(row: HTMLElement | undefined) {
return row?.querySelector<HTMLElement>("[tabindex='0']") ?? null;
}
+/**
+ * The indexes of `rows` in the order a bottom-up menu draws them, top to bottom: reversed, except
+ * that each header stays above the rows it introduces. Separators that ended a header's group stay
+ * between that group and the one now drawn above it.
+ */
+export function bottomUpOrder<T>(rows: MenuItem<T>[]): number[] {
+ // A group starts at each header, and at the first row.
+ const groups: number[][] = [];
+ for (const [ index, row ] of rows.entries()) {
+ const group = groups.at(-1);
+ if (!group || isHeader(row)) groups.push([ index ]);
+ else group.push(index);
+ }
+
+ const order: number[] = [];
+ for (const group of groups.reverse()) {
+ const header = isHeader(rows[group[0]]) ? group.shift() : undefined;
+ group.reverse();
+ const firstRow = group.findIndex((index) => !isSeparator(rows[index]));
+ const separators = group.splice(0, firstRow < 0 ? group.length : firstRow);
+ order.push(...separators);
+ if (header !== undefined) order.push(header);
+ order.push(...group);
+ }
+ return order;
+}
+
/** The items with a run of separators reduced to one. */
function menuRows<T>(items: MenuItem<T>[]) {
const rows: MenuItem<T>[] = [];
@@ -730,3 +786,7 @@ function menuRows<T>(items: MenuItem<T>[]) {
function isSeparator<T>(item: MenuItem<T>) {
return "kind" in item && item.kind === "separator";
}
+
+function isHeader<T>(item: MenuItem<T>) {
+ return "kind" in item && item.kind === "header";
+}
diff --git a/apps/client/src/widgets/react/Popup.tsx b/apps/client/src/widgets/react/Popup.tsx
index 3b11049093..93f59a5112 100644
--- a/apps/client/src/widgets/react/Popup.tsx
+++ b/apps/client/src/widgets/react/Popup.tsx
@@ -55,8 +55,11 @@ export interface PopupProps extends Pick<HTMLAttributes<HTMLDivElement>, "id" |
* of suggestions that changes as the user types.
*/
reveal?: boolean;
- /** Called once it is first placed and shown: a browser focuses nothing inside it before. */
- onPlaced?(): void;
+ /**
+ * Called once it is first placed and shown: a browser focuses nothing inside it before. Gets
+ * the placement Floating UI chose, or `"stylesheet"` when {@link placedByStylesheet}.
+ */
+ onPlaced?(placement: Placement | "stylesheet"): void;
/**
* Called on a press outside it and its anchor, and on Escape. A press on the anchor is left to
* the anchor, as a dropdown's toggle closes its own popup. A popup opened inside it counts as
@@ -91,11 +94,11 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap
const reveals = useRef(reveal);
reveals.current = reveal;
/** Says it is placed, and names the side it reveals itself from, which CSS animates once. */
- const reportPlaced = (side: string) => {
+ const reportPlaced = (side: Placement | "stylesheet") => {
if (hasPlaced.current) return;
hasPlaced.current = true;
if (reveals.current && popupRef.current) popupRef.current.dataset.reveal = side;
- placed.current?.();
+ placed.current?.(side);
};
// A popup opened inside this one stands in the page's body too, so it registers here to
// count as inside this one.