Skip to content

Build your personal knowledge base with Trilium Notes

client/ui/menus: keep the filter input fixed in place for scrollable menus

Adorian Doran924b3bd56e4b
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index cd970f6608..3cf626c5cf 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -50,7 +50,9 @@ function menuElement() {
/** The top level's rows, which scroll inside the menu. */
function menuRows() {
- return [ ...menuElement()?.querySelector(":scope > .tn-menu-scroll")?.children ?? [] ];
+ const list = menuElement()
+ ?.querySelector(":scope > .tn-menu-scroll, :scope > .tn-menu-filterable > .tn-menu-scroll");
+ return [ ...list?.children ?? [] ];
}
/** Puts an element on a screen of its own, as the browser reports one. */
@@ -336,7 +338,7 @@ describe("contextMenu", () => {
]);
});
- it("offers an input above the items of a filterable menu, which filters them", async () => {
+ it("filters a filterable menu from an input above its scrolling list", async () => {
buildPage();
const contextMenu = await buildContextMenu();
@@ -345,13 +347,17 @@ describe("contextMenu", () => {
items: [ { title: "Plain text" }, { title: "Python" } ]
});
- const input = menuRows()[0]
- ?.querySelector<HTMLInputElement>("input.tn-menu-filter-input");
+ // The input stays in place above the list its rows scroll in.
+ const box = menuElement()?.querySelector(":scope > .tn-menu-filterable");
+ expect([ ...box?.children ?? [] ].map((child) => child.className))
+ .toEqual([ "tn-menu-filter", "tn-menu-scroll" ]);
+ const input = box?.querySelector<HTMLInputElement>("input.tn-menu-filter-input");
if (!input) throw new Error("no filter input");
+ expect(menuRows().map((row) => row.textContent)).toEqual([ "Plain text", "Python" ]);
input.value = "pyt";
input.dispatchEvent(new Event("input", { bubbles: true }));
await vi.waitFor(() => {
- expect(menuRows().slice(1).map((row) => row.textContent)).toEqual([ "Python" ]);
+ expect(menuRows().map((row) => row.textContent)).toEqual([ "Python" ]);
});
});
@@ -980,6 +986,10 @@ describe("contextMenu", () => {
// There before anything is typed, empty, and with the keys still on the rows.
expect(layer()).toEqual({ filter: "", rows: unfiltered, empty: false });
expect(document.activeElement).toBe(menuElement());
+ // Above the list the rows scroll in, so it stays in place as they scroll.
+ const box = menuElement()?.querySelector(".dropdown-submenu .tn-menu-filterable");
+ expect([ ...box?.children ?? [] ].map((child) => child.className))
+ .toEqual([ "tn-menu-filter", "tn-menu-scroll" ]);
type("p");
await vi.waitFor(() => expect(document.activeElement).toBe(filterInput()));
@@ -1168,7 +1178,7 @@ describe("contextMenu", () => {
}
});
- it("scrolls back to the input when the keys come round to the first row", async () => {
+ it("scrolls the list to the top when the keys wrap to the first row", async () => {
await openFilterable();
await openSubmenuByKeys();
const list = menuElement()?.querySelector<HTMLElement>("div.dropdown-submenu .tn-menu-scroll");
@@ -1182,7 +1192,7 @@ describe("contextMenu", () => {
await vi.waitFor(() => expect(activeRow()).toBe("Meeting & notes"));
key("ArrowDown");
await vi.waitFor(() => expect(activeRow()).toBe("Text"));
- // As far up as the list goes, so the input above the first row shows again.
+ // As far up as the list goes, so anything above the first row shows too.
expect(scrollTo).toHaveBeenLastCalledWith({ top: 0 });
// From the input, as Up and Down go through the rows from there too.
diff --git a/apps/client/src/widgets/react/Dropdown.spec.tsx b/apps/client/src/widgets/react/Dropdown.spec.tsx
index 5e73a34b2d..572410afb9 100644
--- a/apps/client/src/widgets/react/Dropdown.spec.tsx
+++ b/apps/client/src/widgets/react/Dropdown.spec.tsx
@@ -143,6 +143,9 @@ describe("Dropdown", () => {
key(onMobile ? "Enter" : "ArrowRight");
await vi.waitFor(() => expect(input()).not.toBeNull());
expect(titles()).toEqual([ "Python", "JavaScript" ]);
+ // Above the list the rows scroll in, on a page as in a layer.
+ const header = input()?.closest(".tn-menu-filter");
+ expect(header?.nextElementSibling?.className).toBe("tn-menu-scroll");
key("j");
await vi.waitFor(() => expect(document.activeElement).toBe(input()));
diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsx
index 56de26884c..41a171070a 100644
--- a/apps/client/src/widgets/react/FormList.tsx
+++ b/apps/client/src/widgets/react/FormList.tsx
@@ -10,11 +10,12 @@ import { useContext, useLayoutEffect, useMemo, useRef } from "preact/hooks";
import { t } from "../../services/i18n";
import { getActionSync } from "../../services/keyboard_actions";
import { handleRightToLeftPlacement, isMobile, openInAppHelpFromUrl } from "../../services/utils";
+import FormTextBox from "./FormTextBox";
import FormToggle from "./FormToggle";
import { useStaticTooltip, useSyncedRef, useUniqueName } from "./hooks";
import Icon, { SvgIcon } from "./Icon";
import { MasterDetailHeader } from "./master_detail";
-import { isRightToLeft, MenuContext, type MenuContextValue, MenuFilterContext, MenuLevelContext, type OpenSubmenu, pointerMoved, shouldDropStart, useMenu } from "./menu_context";
+import { isRightToLeft, MenuContext, type MenuContextValue, type MenuFilter, MenuFilterContext, MenuLevelContext, type OpenSubmenu, pointerMoved, shouldDropStart, useMenu } from "./menu_context";
import { placeFloating } from "./Popup";
import { joinElements } from "./react_utils";
import { renderShortcutKbds } from "./shortcut_kbd";
@@ -497,13 +498,15 @@ function MenuSubmenu({ menu, icon, iconSvg, title, description, children, onDrop
const layer = isMobile()
// A phone has no room beside the menu, so a submenu replaces it as a page of its own.
? (open || pageSlide.from !== undefined) && menu.layerHost && createPortal((
- <SubmenuPage rowId={id} level={level + 1} title={title} slide={pageSlide}>
- <MenuFilterContext.Provider value={filter}>{children}</MenuFilterContext.Provider>
+ <SubmenuPage
+ rowId={id} level={level + 1} title={title} slide={pageSlide} filter={filter}
+ >
+ {children}
</SubmenuPage>
), menu.layerHost)
: open && openSubmenu && menu.layerHost && createPortal((
- <SubmenuLayer level={level + 1} submenu={openSubmenu} pinned={!!filter?.text}>
- <MenuFilterContext.Provider value={filter}>{children}</MenuFilterContext.Provider>
+ <SubmenuLayer level={level + 1} submenu={openSubmenu} filter={filter}>
+ {children}
</SubmenuLayer>
), menu.layerHost);
@@ -603,19 +606,19 @@ function MenuSubmenu({ menu, icon, iconSvg, title, description, children, onDrop
/**
* A submenu opened on the desktop, placed beside the row it opened from rather than nested in it,
- * so a scrolling menu neither clips it nor scrolls it away. While {@link pinned}, as while it is
- * filtered, it keeps the top it had when pinned, relative to its row, and only its height follows
- * its content.
+ * so a scrolling menu neither clips it nor scrolls it away. While its {@link filter} has text, the
+ * layer keeps its top position relative to its row, and only its height changes with the matches.
*/
-function SubmenuLayer({ level, submenu, pinned, children }: {
+function SubmenuLayer({ level, submenu, filter, children }: {
level: number,
submenu: OpenSubmenu,
- pinned?: boolean,
+ filter: MenuFilter | undefined,
children: ComponentChildren
}) {
const layerRef = useRef<HTMLDivElement>(null);
const { dropStart: dropStartLevels, setDropStart } = useMenu();
const dropStart = !!dropStartLevels[level - 1];
+ const pinned = !!filter?.text;
/** How far below its row's top the layer stands while pinned. */
const pinnedOffset = useRef<number | undefined>(undefined);
@@ -674,8 +677,7 @@ function SubmenuLayer({ level, submenu, pinned, children }: {
ref={layerRef} role="menu" aria-labelledby={titleId(submenu.anchor.id)}
className={clsx("dropdown-menu show tn-menu", submenu.immediate && "tn-menu-immediate")}
>
- {/* Like the top level, so the blur on the layer's `::before` stays behind its rows. */}
- <menu className="tn-menu-scroll" role="none">{children}</menu>
+ <MenuList filter={filter}>{children}</MenuList>
</div>
</div>
</MenuLevelContext.Provider>
@@ -686,12 +688,13 @@ function SubmenuLayer({ level, submenu, pinned, children }: {
* A submenu opened on a phone: a page that takes the menu's place, headed by the submenu's title and
* a way back. The level it covers stays mounted, as the row that owns this page stands in it.
*/
-function SubmenuPage({ rowId, level, title, slide, children }: {
+function SubmenuPage({ rowId, level, title, slide, filter, children }: {
rowId: string,
level: number,
title: ComponentChildren,
/** The slide of whether the page is open: from closed as it arrives, from open as it leaves. */
slide: Slide<boolean>,
+ filter: MenuFilter | undefined,
children: ComponentChildren
}) {
const menu = useMenu();
@@ -717,12 +720,69 @@ function SubmenuPage({ rowId, level, title, slide, children }: {
>
<MasterDetailHeader inPage onBack={back} backTitle={t("menu.back")} pageTitle={title} listTitle={title} />
</div>
- <menu className="tn-menu-scroll" role="none">{children}</menu>
+ <MenuList filter={filter}>{children}</MenuList>
</div>
</MenuLevelContext.Provider>
);
}
+/**
+ * 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 }: {
+ filter: MenuFilter | undefined,
+ children: ComponentChildren
+}) {
+ // The rows scroll here and not in the frame, so the theme's `::before` blur stays behind
+ // them. `role="none"` exposes the rows as the menu's own items.
+ const list = <menu className="tn-menu-scroll" role="none">{children}</menu>;
+ return (
+ <MenuFilterContext.Provider value={filter}>
+ {/* 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} />
+ {list}
+ </div>
+ ) : list}
+ </MenuFilterContext.Provider>
+ );
+}
+
+/**
+ * The filter input above a filterable level's rows. The input handles the editing keys; the menu
+ * handles Up, Down, Enter, Escape and Tab, so a match can be picked while focus is in the input.
+ */
+function MenuFilterInput({ filter }: { filter: MenuFilter }) {
+ const menu = useMenu();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+
+ // An input unmounted while focused, as when the pointer closes its submenu, returns focus to
+ // the menu and not to the page.
+ useLayoutEffect(() => () => {
+ if (document.activeElement !== inputRef.current) return;
+ menu.layerHost?.focus({ preventScroll: true });
+ }, [ menu.layerHost ]);
+
+ return (
+ <div className="tn-menu-filter">
+ <label className="tn-menu-filter-box tn-input-field">
+ <FormTextBox
+ inputRef={inputRef} className="tn-menu-filter-input"
+ data-level={filter.level + 1} currentValue={filter.text}
+ autoComplete="off" spellcheck={false}
+ placeholder={t("menu.filter_placeholder")} aria-label={t("menu.filter")}
+ onChange={(text) => menu.setFilter(text
+ ? { rowId: filter.rowId, level: filter.level, text }
+ : undefined)}
+ />
+ <span className="bx bx-search" aria-hidden="true" />
+ </label>
+ </div>
+ );
+}
+
/** The id of a row's title, which names the submenu it opens. */
function titleId(rowId: string) {
return `${rowId}-title`;
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.css
index 2903c09263..899d260ffd 100644
--- a/apps/client/src/widgets/react/Menu.css
+++ b/apps/client/src/widgets/react/Menu.css
@@ -51,7 +51,8 @@ body.desktop .dropdown-submenu > .dropdown-menu.tn-menu.tn-menu-immediate {
animation: none;
}
-.tn-menu-page {
+.tn-menu-page,
+.tn-menu-filterable {
--tn-popup-padding: var(--padding, var(--menu-padding-size));
display: flex;
flex-direction: column;
@@ -67,6 +68,10 @@ body.desktop .dropdown-submenu > .dropdown-menu.tn-menu.tn-menu-immediate {
}
}
+.tn-menu-page > .tn-menu-filterable {
+ margin: 0;
+}
+
.tn-menu-page-header {
padding: var(--tn-popup-padding) var(--tn-popup-padding) 0;
}
@@ -75,7 +80,7 @@ body.desktop .dropdown-submenu > .dropdown-menu.tn-menu.tn-menu-immediate {
overflow-x: hidden;
}
-.dropdown-menu.tn-menu > :is(.tn-menu-scroll, .tn-menu-page) {
+.dropdown-menu.tn-menu > :is(.tn-menu-scroll, .tn-menu-filterable, .tn-menu-page) {
&:has(+ .tn-menu-page:not(.tn-menu-page-leaving)) {
position: absolute;
inset: 0;
@@ -108,11 +113,11 @@ body.desktop .dropdown-submenu > .dropdown-menu.tn-menu.tn-menu-immediate {
}
body[dir="rtl"] .dropdown-menu.tn-menu {
- > :is(.tn-menu-scroll, .tn-menu-page):has(+ .tn-menu-page-entering) {
+ > :is(.tn-menu-scroll, .tn-menu-filterable, .tn-menu-page):has(+ .tn-menu-page-entering) {
animation-name: tn-slide-out-to-right;
}
- > :is(.tn-menu-scroll, .tn-menu-page):has(+ .tn-menu-page-leaving) {
+ > :is(.tn-menu-scroll, .tn-menu-filterable, .tn-menu-page):has(+ .tn-menu-page-leaving) {
animation-name: tn-slide-in-from-right;
}
@@ -190,8 +195,16 @@ body.desktop .dropdown-item.dropdown-submenu.submenu-open,
border-color: transparent !important;
}
-.tn-menu-filter-row {
- padding-bottom: 4px;
+.tn-menu-filter {
+ flex: none;
+ padding: var(--tn-popup-padding) var(--tn-popup-padding) 4px;
+
+ + .tn-menu-scroll {
+ border-start-start-radius: 0;
+ border-start-end-radius: 0;
+ padding-top: 0;
+ scroll-padding-top: 0;
+ }
.tn-menu-filter-box {
display: flex;
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 13158d2497..90c620311e 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -8,11 +8,10 @@ import { useCallback, useContext, useLayoutEffect, useRef, useState } from "prea
import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";
import { t } from "../../services/i18n";
import { isMobile } from "../../services/utils";
-import { FormDropdownDivider, FormDropdownSubmenu, FormListCustomItem, FormListHeader, FormListItem } from "./FormList";
-import FormTextBox from "./FormTextBox";
+import { FormDropdownDivider, FormDropdownSubmenu, FormListCustomItem, FormListHeader, FormListItem, MenuList } from "./FormList";
import { useStaticTooltipWithKeyboardShortcut, useUniqueName } from "./hooks";
import { SvgIcon } from "./Icon";
-import { type ActiveRow, isRightToLeft, MenuContext, type MenuContextValue, type MenuFilter, MenuFilterContext, MenuLevelContext, type OpenSubmenu, pointerMoved, type RowEntry, shouldDropStart, useMenu } from "./menu_context";
+import { type ActiveRow, isRightToLeft, MenuContext, type MenuContextValue, type MenuFilter, MenuFilterContext, MenuLevelContext, type OpenSubmenu, pointerMoved, type RowEntry, shouldDropStart } from "./menu_context";
import Popup, { type PopupProps } from "./Popup";
/**
@@ -131,7 +130,7 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
setActiveRow({ level, id: rowId });
const element = rows.get(rowId)?.element;
// The first row of a scrolling list brings what stands above it back into view, such as a
- // filter input or a header, which scrolling only as far as the row would leave hidden.
+ // header, which scrolling only as far as the row would leave hidden.
const list = element?.parentElement;
if (list?.classList.contains("tn-menu-scroll") && !hasRowBefore(element)) list.scrollTo?.({ top: 0 });
else element?.scrollIntoView?.({ block: "nearest" });
@@ -386,6 +385,10 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
setKeyboardDriven(true);
}
+ const topLevelFilter = items && filterable
+ ? { ...TOP_LEVEL, text: filter?.level === TOP_LEVEL.level ? filter.text : "" }
+ : undefined;
+
return (
<MenuContext.Provider value={context}>
<Popup
@@ -425,18 +428,9 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
e.stopPropagation();
}}
>
- {/* The rows scroll in here rather than the menu itself, so the theme's blur on the
- menu's `::before` stays behind them. A `<menu>`, as rows are its list items, out of
- the accessibility tree so they read as the menu's own. */}
- <menu className="tn-menu-scroll" role="none">
- {items && filterable && (
- <MenuFilterContext.Provider value={{ ...TOP_LEVEL, text: filter?.level === TOP_LEVEL.level ? filter.text : "" }}>
- <MenuItems items={items} onSelect={onSelect} />
- </MenuFilterContext.Provider>
- )}
- {items && !filterable && <MenuItems items={items} onSelect={onSelect} />}
- {!items && children}
- </menu>
+ <MenuList filter={topLevelFilter}>
+ {items ? <MenuItems items={items} onSelect={onSelect} /> : children}
+ </MenuList>
{/* The submenus' layers follow the scroller in here, portaled by their rows. */}
</Popup>
</MenuContext.Provider>
@@ -463,39 +457,12 @@ function MenuItems<T>({ items, onSelect }: {
onSelect: MenuProps<T>["onSelect"]
}) {
const filter = useContext(MenuFilterContext);
- const rows = filter?.text
- ? <FilteredMenuItems items={items} text={filter.text} onSelect={onSelect} />
- : menuRows(items).map((row, index) => <MenuItemRow key={index} row={row} onSelect={onSelect} />);
- return <>{filter && <MenuFilterInput filter={filter} />}{rows}</>;
-}
-
-/**
- * The input at the top of a filterable submenu. It edits as any input does; the menu keeps Up,
- * Down, Enter, Escape and Tab, to pick from the matches while focus stays here.
- */
-function MenuFilterInput({ filter }: { filter: MenuFilter }) {
- const menu = useMenu();
- const inputRef = useRef<HTMLInputElement | null>(null);
-
- // Leaving with focus, as when the pointer moves on and closes the submenu, it hands the keys
- // back to the menu rather than to the page.
- useLayoutEffect(() => () => {
- if (document.activeElement === inputRef.current) menu.layerHost?.focus({ preventScroll: true });
- }, [ menu.layerHost ]);
-
- return (
- <li className="tn-menu-filter-row" role="none">
- <label className="tn-menu-filter-box tn-input-field">
- <FormTextBox
- inputRef={inputRef} className="tn-menu-filter-input" data-level={filter.level + 1}
- currentValue={filter.text} placeholder={t("menu.filter_placeholder")} aria-label={t("menu.filter")}
- autoComplete="off" spellcheck={false}
- onChange={(text) => menu.setFilter(text ? { rowId: filter.rowId, level: filter.level, text } : undefined)}
- />
- <span className="bx bx-search" aria-hidden="true" />
- </label>
- </li>
- );
+ if (filter?.text) {
+ return <FilteredMenuItems items={items} text={filter.text} onSelect={onSelect} />;
+ }
+ return <>{menuRows(items).map((row, index) => (
+ <MenuItemRow key={index} row={row} onSelect={onSelect} />
+ ))}</>;
}
/**
diff --git a/apps/client/src/widgets/react/Popup.css b/apps/client/src/widgets/react/Popup.css
index f375d42e58..bbea574850 100644
--- a/apps/client/src/widgets/react/Popup.css
+++ b/apps/client/src/widgets/react/Popup.css
@@ -138,7 +138,7 @@ body[dir=rtl] .tn-popup[data-reveal]:is([data-reveal="bottom-end"], [data-reveal
* `::before` covers it whatever its content scrolls to. The content scrolls inside, in the height
* `placeFloating()` caps the frame to.
*/
-.dropdown-menu:has(> :is(.tn-menu-scroll, .tn-panel-scroll)) {
+.dropdown-menu:has(> :is(.tn-menu-scroll, .tn-menu-filterable, .tn-panel-scroll)) {
display: flex;
flex-direction: column;
}