Skip to content

Build your personal knowledge base with Trilium Notes

feat(tree): filter the insert menus from an input at their top

Elian Doran713fc2d4af5c
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index a00b7a4575..be52707224 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -825,6 +825,236 @@ describe("contextMenu", () => {
await vi.waitFor(() => expect(activeRow()).toBe("Paste"));
});
+ describe("filtering a filterable submenu", () => {
+ const filterableItems = [
+ { title: "Cut" },
+ {
+ title: "Insert child note", filterable: true, items: [
+ { title: "Text" },
+ { title: "Code", items: [ { title: "Plain text" }, { title: "Python" }, { title: "JavaScript" } ] },
+ { kind: "separator" as const },
+ { title: "Collection", items: [ { title: "Table" }, { title: "Board", badges: [ { title: "New" } ] } ] },
+ { kind: "header" as const, title: "Templates" },
+ { title: "Meeting &amp; <b>notes</b>" }
+ ]
+ }
+ ];
+ const unfiltered = [ "Text|", "Code|", "Collection|", "Meeting & notes|" ];
+
+ async function openFilterable(picked: string[] = []) {
+ buildPage();
+ const contextMenu = await buildContextMenu();
+ await contextMenu.show({
+ x: 10, y: 10, items: filterableItems,
+ selectMenuItemHandler: (item) => picked.push(String(item.title))
+ });
+ await vi.waitFor(() => expect(document.activeElement).toBe(menuElement()));
+ return contextMenu;
+ }
+
+ /** Goes down to the filterable row and into its submenu, a key at a time. */
+ async function openSubmenuByKeys() {
+ key("ArrowDown");
+ await vi.waitFor(() => expect(activeRow()).toBe("Cut"));
+ key("ArrowDown");
+ await vi.waitFor(() => expect(activeRow()).toBe("Insert child note"));
+ key("ArrowRight");
+ await vi.waitFor(() => expect(activeRow()).toBe("Text"));
+ }
+
+ function filterInput() {
+ return menuElement()?.querySelector<HTMLInputElement>("div.dropdown-submenu input.tn-menu-filter-input") ?? null;
+ }
+
+ /** Sets what the input holds, as typing, deleting or pasting into it does. */
+ function edit(value: string) {
+ const input = filterInput();
+ if (!input) throw new Error("no filter input");
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+
+ /**
+ * Types without waiting, as fast typing does: a key while the menu has focus, the
+ * input's own editing once it has.
+ */
+ function type(text: string) {
+ for (const character of text) {
+ const input = filterInput();
+ if (input && document.activeElement === input) edit(input.value + character);
+ else key(character);
+ }
+ }
+
+ /** The open layer: what the input holds, and each row as its title and the path it came from. */
+ function layer() {
+ const list = menuElement()?.querySelector("div.dropdown-submenu .tn-menu-scroll");
+ const rows = [ ...list?.querySelectorAll<HTMLElement>("li.dropdown-item") ?? [] ];
+ return {
+ filter: filterInput()?.value ?? null,
+ rows: rows.map((row) => [
+ row.querySelector(".tn-menu-filter-title")?.textContent ?? row.textContent,
+ row.querySelector(".tn-menu-filter-path")?.textContent ?? ""
+ ].join("|")),
+ empty: !!list?.querySelector(".tn-menu-filter-empty")
+ };
+ }
+
+ it("offers an input to filter with, which typing from the menu moves into", async () => {
+ await openFilterable();
+ await openSubmenuByKeys();
+ // 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());
+
+ type("p");
+ await vi.waitFor(() => expect(document.activeElement).toBe(filterInput()));
+ expect(filterInput()?.selectionStart).toBe(1);
+ expect(layer().filter).toBe("p");
+ // Those starting with it first, then those holding it, each group in menu order.
+ expect(layer().rows).toEqual([ "Plain text|Code", "Python|Code", "JavaScript|Code" ]);
+ expect(activeRow()).toMatch(/^Plain text/);
+
+ type("y");
+ await vi.waitFor(() => expect(layer().rows).toEqual([ "Python|Code" ]));
+ expect(menuElement()?.querySelector(".tn-menu-filter-title mark")?.textContent).toBe("Py");
+ expect(activeRow()).toMatch(/^Python/);
+
+ edit("p");
+ await vi.waitFor(() => expect(layer().rows).toHaveLength(3));
+ // Emptied, it lists the submenu as it was, and keeps focus for more typing.
+ edit("");
+ await vi.waitFor(() => expect(layer().rows).toEqual(unfiltered));
+ expect(document.activeElement).toBe(filterInput());
+ expect(activeRow()).toBe("Text");
+ });
+
+ it("leaves editing to the input, and keeps the keys that pick a match", async () => {
+ const picked: string[] = [];
+ const contextMenu = await openFilterable(picked);
+ await openSubmenuByKeys();
+ type("p");
+ await vi.waitFor(() => expect(document.activeElement).toBe(filterInput()));
+
+ // The caret's keys are the input's: nothing moves in the menu, and the submenu stays.
+ for (const name of [ "Home", "End", "ArrowLeft", "ArrowRight", "Backspace", " " ]) {
+ expect(key(name).defaultPrevented).toBe(false);
+ }
+ expect(activeRow()).toMatch(/^Plain text/);
+ expect(filterInput()).not.toBeNull();
+
+ // Up and Down go through the matches, with focus kept in the input.
+ expect(key("ArrowDown").defaultPrevented).toBe(true);
+ await vi.waitFor(() => expect(activeRow()).toMatch(/^Python/));
+ expect(document.activeElement).toBe(filterInput());
+ key("ArrowUp");
+ await vi.waitFor(() => expect(activeRow()).toMatch(/^Plain text/));
+ expect(key("Tab").defaultPrevented).toBe(true);
+
+ key("Enter");
+ expect(picked).toEqual([ "Plain text" ]);
+ expect(contextMenu.isShown).toBe(false);
+ });
+
+ it("matches the submenus a row stands in, every word apart, and the text a title shows", async () => {
+ await openFilterable();
+ await openSubmenuByKeys();
+
+ type("collection");
+ await vi.waitFor(() => expect(layer().rows).toEqual([ "Table|Collection", "Board|Collection" ]));
+ // A badge stays with its row.
+ expect(menuElement()?.querySelector(".tn-menu-scroll .badge")?.textContent).toBe("New");
+
+ edit("code java");
+ await vi.waitFor(() => expect(layer().rows).toEqual([ "JavaScript|Code" ]));
+
+ edit("& n");
+ // The title is HTML; what is matched and shown is its text, and none of its markup.
+ await vi.waitFor(() => expect(layer().rows).toEqual([ "Meeting & notes|" ]));
+ expect(menuElement()?.querySelector(".tn-menu-filter-title b")).toBeNull();
+
+ edit("& nzz");
+ await vi.waitFor(() => expect(layer().empty).toBe(true));
+ expect(layer().rows).toEqual([]);
+ });
+
+ it("filters right after the pointer opened the submenu, and runs the match on Enter", async () => {
+ const picked: string[] = [];
+ const contextMenu = await openFilterable(picked);
+ const parent = [ ...menuElement()?.querySelectorAll<HTMLElement>("li.dropdown-submenu") ?? [] ]
+ .find((row) => row.textContent?.includes("Insert child note"));
+ parent?.dispatchEvent(new PointerEvent("pointerenter"));
+ await vi.waitFor(() => expect(filterInput()).not.toBeNull());
+
+ type("boa");
+ await vi.waitFor(() => expect(layer().rows).toEqual([ "Board|Collection" ]));
+ expect(activeRow()).toMatch(/^Board/);
+ key("Enter");
+ expect(picked).toEqual([ "Board" ]);
+ expect(contextMenu.isShown).toBe(false);
+ });
+
+ it("takes a press into the input, as a phone needs to bring up its keyboard", async () => {
+ await openFilterable();
+ const parent = [ ...menuElement()?.querySelectorAll<HTMLElement>("li.dropdown-submenu") ?? [] ]
+ .find((row) => row.textContent?.includes("Insert child note"));
+ parent?.dispatchEvent(new PointerEvent("pointerenter"));
+ await vi.waitFor(() => expect(filterInput()).not.toBeNull());
+
+ const press = new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 });
+ filterInput()?.dispatchEvent(press);
+ expect(press.defaultPrevented).toBe(false);
+ filterInput()?.focus();
+ edit("tab");
+ await vi.waitFor(() => expect(layer().rows).toEqual([ "Table|Collection" ]));
+ expect(activeRow()).toMatch(/^Table/);
+ });
+
+ it("lets Escape empty the input before it closes anything, and gives the menu its keys back", async () => {
+ const contextMenu = await openFilterable();
+ // Not a filterable level: the first letters go to a row, and no input is offered.
+ type("c");
+ await vi.waitFor(() => expect(activeRow()).toBe("Cut"));
+ expect(menuElement()?.querySelector("input.tn-menu-filter-input")).toBeNull();
+
+ key("ArrowDown");
+ await vi.waitFor(() => expect(activeRow()).toBe("Insert child note"));
+ key("ArrowRight");
+ await vi.waitFor(() => expect(activeRow()).toBe("Text"));
+ type("ta");
+ await vi.waitFor(() => expect(layer().rows).toEqual([ "Table|Collection" ]));
+
+ key("Escape");
+ await vi.waitFor(() => expect(layer()).toEqual({ filter: "", rows: unfiltered, empty: false }));
+ expect(document.activeElement).toBe(filterInput());
+ expect(contextMenu.isShown).toBe(true);
+
+ // Empty, Escape closes the submenu, and the menu has the keys again.
+ key("Escape");
+ await vi.waitFor(() => expect(activeRow()).toBe("Insert child note"));
+ expect(filterInput()).toBeNull();
+ expect(document.activeElement).toBe(menuElement());
+
+ // The submenu closing under a filled input, as the pointer moving on does, ends the
+ // filter and gives the menu its keys too.
+ key("ArrowRight");
+ await vi.waitFor(() => expect(activeRow()).toBe("Text"));
+ type("ta");
+ await vi.waitFor(() => expect(document.activeElement).toBe(filterInput()));
+ const cut = [ ...menuElement()?.querySelectorAll<HTMLElement>("li.dropdown-item") ?? [] ]
+ .find((row) => row.textContent === "Cut");
+ cut?.dispatchEvent(new PointerEvent("pointermove", { bubbles: true, movementX: 3 }));
+ await vi.waitFor(() => expect(filterInput()).toBeNull());
+ expect(document.activeElement).toBe(menuElement());
+ key("ArrowRight");
+ key("ArrowDown");
+ await vi.waitFor(() => expect(activeRow()).toBe("Insert child note"));
+ key("ArrowRight");
+ await vi.waitFor(() => expect(layer().filter).toBe(""));
+ expect(layer().rows).toEqual(unfiltered);
+ });
+ });
+
it("opens a submenu towards it and closes it back, one level at a time", async () => {
const dialogHeard = vi.fn();
document.addEventListener("keydown", dialogHeard);
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index 5dda99bc19..d5ea715338 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -73,6 +73,11 @@ export interface MenuCommandItem<T> {
* icon standing — for a list where that icon is what tells one entry from another.
*/
trailingIcon?: string;
+ /**
+ * For an item with {@link items}: typing while its submenu is open filters every item inside
+ * it, at any depth, into one list, which shows what was typed.
+ */
+ filterable?: boolean;
}
export type MenuItem<T> = MenuCommandItem<T> | CustomMenuItem | MenuSeparatorItem | MenuHeader;
diff --git a/apps/client/src/menus/tree_context_menu.ts b/apps/client/src/menus/tree_context_menu.ts
index 6efde7d98c..84d7a8af6f 100644
--- a/apps/client/src/menus/tree_context_menu.ts
+++ b/apps/client/src/menus/tree_context_menu.ts
@@ -166,6 +166,7 @@ export async function buildTreeContextMenuItems(ctx: TreeContextMenuContext): Pr
keyboardShortcut: "createNoteAfter",
uiIcon: "bx bx-plus",
items: insertNoteAfterItems,
+ filterable: true,
enabled: insertNoteAfterEnabled && noSelectedNotes && notOptionsOrHelp
},
@@ -175,6 +176,7 @@ export async function buildTreeContextMenuItems(ctx: TreeContextMenuContext): Pr
keyboardShortcut: "createNoteInto",
uiIcon: "bx bx-subdirectory-right",
items: insertChildNoteItems,
+ filterable: true,
enabled: notSearch && noSelectedNotes && notOptionsOrHelp && !hasSubtreeHidden && !isSpotlighted
},
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 8a5ec2e44d..b72e9f72d9 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4587,5 +4587,10 @@
},
"split_button": {
"more_actions": "More actions"
+ },
+ "menu": {
+ "no_matches": "No matches",
+ "filter": "Filter",
+ "filter_placeholder": "Type to filter…"
}
}
diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsx
index 1d324f17b8..49c237164a 100644
--- a/apps/client/src/widgets/react/FormList.tsx
+++ b/apps/client/src/widgets/react/FormList.tsx
@@ -13,7 +13,7 @@ import FormToggle from "./FormToggle";
import HelpTooltipButton from "./HelpTooltipButton";
import { useStaticTooltip, useSyncedRef, useUniqueName } from "./hooks";
import Icon, { SvgIcon } from "./Icon";
-import { isRightToLeft, MenuContext, type MenuContextValue, MenuLevelContext, type OpenSubmenu, pointerMoved, shouldDropStart, useMenu } from "./menu_context";
+import { isRightToLeft, MenuContext, type MenuContextValue, MenuFilterContext, MenuLevelContext, type OpenSubmenu, pointerMoved, shouldDropStart, useMenu } from "./menu_context";
import { placeFloating } from "./Popup";
import { joinElements } from "./react_utils";
import { renderShortcutKbds } from "./shortcut_kbd";
@@ -381,6 +381,8 @@ export interface FormDropdownSubmenuProps {
onDropdownToggleClicked?: (e: MouseEvent) => void;
disabled?: boolean;
className?: string;
+ /** Inside a menu, whether typing while the submenu is open filters it. See `MenuCommandItem.filterable`. */
+ filterable?: boolean;
}
/**
@@ -394,12 +396,13 @@ export function FormDropdownSubmenu(props: FormDropdownSubmenuProps) {
return <MenuSubmenu {...props} menu={menu} />;
}
-function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleClicked, disabled, className }: FormDropdownSubmenuProps & { menu: MenuContextValue }) {
+function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleClicked, disabled, className, filterable }: FormDropdownSubmenuProps & { menu: MenuContextValue }) {
const level = useContext(MenuLevelContext);
const id = useUniqueName("menu-row");
const openSubmenu = menu.open[level];
const open = openSubmenu?.id === id;
const isActive = menu.active?.id === id;
+ const filter = filterable ? { rowId: id, level, text: menu.filter?.rowId === id ? menu.filter.text : "" } : undefined;
/** Runs the row's own action for the keys, with the modifiers of the key that ran it. */
function select(e: MouseEvent | KeyboardEvent) {
@@ -417,7 +420,7 @@ function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleCli
<li
id={id}
ref={(element) => {
- menu.registerRow(id, element ? { level, element, custom: false, disabled: !!disabled, hasSubmenu: true, select } : undefined);
+ menu.registerRow(id, element ? { level, element, custom: false, disabled: !!disabled, hasSubmenu: true, filterable, select } : undefined);
}}
className={clsx("dropdown-item dropdown-submenu", open && "submenu-open", isActive && "tn-menu-active",
disabled && "disabled", className)}
@@ -465,11 +468,15 @@ function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleCli
// A phone has no room beside the menu, so an open submenu unfolds under its row.
? (
<ul className={clsx("dropdown-menu", open && "show")} role="menu" aria-labelledby={titleId(id)}>
- <MenuLevelContext.Provider value={level + 1}>{open && children}</MenuLevelContext.Provider>
+ <MenuLevelContext.Provider value={level + 1}>
+ <MenuFilterContext.Provider value={filter}>{open && children}</MenuFilterContext.Provider>
+ </MenuLevelContext.Provider>
</ul>
)
: open && openSubmenu && menu.layerHost && createPortal((
- <SubmenuLayer level={level + 1} submenu={openSubmenu}>{children}</SubmenuLayer>
+ <SubmenuLayer level={level + 1} submenu={openSubmenu}>
+ <MenuFilterContext.Provider value={filter}>{children}</MenuFilterContext.Provider>
+ </SubmenuLayer>
), menu.layerHost)}
</li>
);
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.css
index c0c8c9b052..1072d5c6a4 100644
--- a/apps/client/src/widgets/react/Menu.css
+++ b/apps/client/src/widgets/react/Menu.css
@@ -78,3 +78,46 @@ body.desktop .dropdown-item.dropdown-submenu.submenu-open,
background-color: transparent !important;
border-color: transparent !important;
}
+
+/* The input at the top of a filterable submenu, above its rows or its matches. */
+.tn-menu-filter-row {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ margin: 0 0.25rem 0.25rem;
+ padding: 0 0.5rem 0.25rem;
+ border-bottom: 1px solid var(--dropdown-border-color);
+ color: var(--muted-text-color);
+
+ /* Bootstrap draws `.form-control` and its focus as a field; in a menu the row is the field. */
+ .tn-menu-filter-input,
+ .tn-menu-filter-input:focus {
+ flex: 1;
+ min-width: 10em;
+ padding: 0.125rem 0;
+ border: none;
+ background: transparent;
+ box-shadow: none;
+ color: var(--menu-text-color);
+ }
+}
+
+.tn-menu-filter-empty {
+ padding: 0.25rem 0.75rem;
+ color: var(--muted-text-color);
+ font-style: italic;
+}
+
+.tn-menu-filter-title mark {
+ padding: 0;
+ color: inherit;
+ background-color: transparent;
+ font-weight: bold;
+}
+
+/* The submenus a match stands in, after its title. */
+.tn-menu-filter-path {
+ margin-inline-start: 0.75em;
+ color: var(--muted-text-color);
+ font-size: 0.9em;
+}
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 4a616f2923..39a3934797 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -2,11 +2,13 @@ import "./Menu.css";
import clsx from "clsx";
import type { ComponentChildren } from "preact";
-import { useCallback, useLayoutEffect, useRef, useState } from "preact/hooks";
+import { useCallback, useContext, useLayoutEffect, useRef, useState } from "preact/hooks";
import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";
+import { t } from "../../services/i18n";
import { FormDropdownDivider, FormDropdownSubmenu, FormListCustomItem, FormListHeader, FormListItem } from "./FormList";
-import { type ActiveRow, isRightToLeft, MenuContext, type MenuContextValue, type OpenSubmenu, pointerMoved, type RowEntry, shouldDropStart } from "./menu_context";
+import FormTextBox from "./FormTextBox";
+import { type ActiveRow, isRightToLeft, MenuContext, type MenuContextValue, type MenuFilter, MenuFilterContext, type OpenSubmenu, pointerMoved, type RowEntry, shouldDropStart, useMenu } from "./menu_context";
import Popup, { type PopupProps } from "./Popup";
/**
@@ -49,6 +51,9 @@ export interface MenuProps<T> extends Pick<PopupProps, "anchor" | "offset" | "co
/** The keys the menu keeps while focus is inside a custom row: those that leave it. */
const KEYS_LEAVING_CUSTOM_ROW = new Set([ "ArrowUp", "ArrowDown", "Escape", "Tab" ]);
+/** The keys the menu keeps while focus is in a submenu's filter input; the input edits with the rest. */
+const KEYS_OF_FILTER = new Set([ "ArrowUp", "ArrowDown", "Enter", "Escape", "Tab" ]);
+const FILTER_INPUT = "input.tn-menu-filter-input";
/** How long typed letters keep adding to the text a row is looked up by. */
const TYPEAHEAD_TIMEOUT = 500;
@@ -87,6 +92,13 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
/** The level whose first row becomes active once it has rendered, for a submenu a key opened. */
const pendingFirstRow = useRef<number | undefined>(undefined);
const typeahead = useRef({ text: "", timeout: 0 });
+ const [ filter, setFilterState ] = useState<MenuFilter>();
+ /** The filter as the keys last left it, ahead of the render that shows it: keys come faster. */
+ const filterRef = useRef<MenuFilter | undefined>(undefined);
+ const setFilter = useCallback((next: MenuFilter | undefined) => {
+ filterRef.current = next;
+ setFilterState(next);
+ }, []);
/** Whether the keys moved the menu since the pointer last did. See `Menu.css`. */
const [ keyboardDriven, setKeyboardDriven ] = useState(false);
/** Whether the menu has asked to close, which it does once. */
@@ -116,7 +128,7 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
});
}, [ rows ]);
const context: MenuContextValue = {
- open, openSubmenu, active, setActive, rows, registerRow, keyboardDriven, dropStart, setDropStart, close, layerHost
+ open, openSubmenu, active, setActive, rows, registerRow, keyboardDriven, dropStart, setDropStart, close, filter, setFilter, layerHost
};
/** The ids of the rows the keys can stand on at `level`, in the order they stand in. */
@@ -140,13 +152,39 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
const activateFirstRowRef = useRef(activateFirstRow);
activateFirstRowRef.current = activateFirstRow;
- // After the commit: a submenu's rows register their elements only as they mount.
+ // After the commit: a submenu's rows register their elements only as they mount. A filter
+ // input with focus names the row too, as the keys pick it from there.
useLayoutEffect(() => {
const row = active && rows.get(active.id);
const rowId = row && !row.custom ? row.element.id : undefined;
- if (rowId) menuRef.current?.setAttribute("aria-activedescendant", rowId);
- else menuRef.current?.removeAttribute("aria-activedescendant");
- }, [ active, open, rows ]);
+ for (const element of [ menuRef.current, filterInputIn(menuRef.current) ]) {
+ if (!element) continue;
+ if (rowId) element.setAttribute("aria-activedescendant", rowId);
+ else element.removeAttribute("aria-activedescendant");
+ }
+ }, [ active, open, rows, filter ]);
+
+ // A filter ends with the submenu it filters, as the pointer or the keys close it.
+ useLayoutEffect(() => {
+ const current = filterRef.current;
+ if (current && open[current.level]?.id !== current.rowId) setFilter(undefined);
+ }, [ open, setFilter ]);
+
+ // The first match, or the first row once the input is emptied, is the one Enter runs. Typing
+ // that began in the menu goes on in the input.
+ const lastFilter = useRef<MenuFilter | undefined>(undefined);
+ useLayoutEffect(() => {
+ const level = (filter ?? lastFilter.current)?.level;
+ lastFilter.current = filter;
+ if (level === undefined) return;
+ if (!activateFirstRow(level + 1)) pendingFirstRow.current = level + 1;
+
+ const input = filterInputIn(menuRef.current);
+ if (filter && input && document.activeElement !== input) {
+ input.focus({ preventScroll: true });
+ input.setSelectionRange(input.value.length, input.value.length);
+ }
+ }, [ filter ]); // eslint-disable-line react-hooks/exhaustive-deps
// A custom row takes focus in itself, for its own keys; any other row hands it back to the menu.
useLayoutEffect(() => {
@@ -155,7 +193,8 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
if (!menu || !row) return;
if (row.custom) {
focusTarget(row.element)?.focus({ preventScroll: true });
- } else if (document.activeElement !== menu && menu.contains(document.activeElement)) {
+ } else if (document.activeElement !== menu && menu.contains(document.activeElement)
+ && !document.activeElement?.matches(FILTER_INPUT)) {
menu.focus({ preventScroll: true });
}
}, [ active, rows ]);
@@ -164,12 +203,13 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
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. Inside a custom row, only the
- // keys that leave it, so the control there keeps its own.
+ // `.dropdown-menu`, and takes them for a dropdown of its own. Inside a custom row or a
+ // filter input, only the keys that are the menu's, so the control there keeps its own.
const listener = (e: KeyboardEvent) => {
const menu = menuRef.current;
- if (e.target === menu
- || (menu?.contains(e.target as Node) && KEYS_LEAVING_CUSTOM_ROW.has(e.key))) {
+ const inFilter = e.target instanceof Element && e.target.matches(FILTER_INPUT);
+ const keys = inFilter ? KEYS_OF_FILTER : KEYS_LEAVING_CUSTOM_ROW;
+ if (e.target === menu || (menu?.contains(e.target as Node) && keys.has(e.key))) {
keyHandler.current(e);
}
};
@@ -178,11 +218,14 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
}, []);
function onKeyDown(e: KeyboardEvent) {
- const level = active?.level ?? 0;
+ // From a filter input, the keys act on the rows of the submenu it filters.
+ const filterInput = e.target instanceof HTMLInputElement && e.target.matches(FILTER_INPUT) ? e.target : undefined;
+ const level = filterInput ? Number(filterInput.dataset.level) : active?.level ?? 0;
const levelRows = navigableRows(level);
- const index = active ? levelRows.indexOf(active.id) : -1;
+ const activeHere = active?.level === level ? active : undefined;
+ const index = activeHere ? levelRows.indexOf(activeHere.id) : -1;
const count = levelRows.length;
- const activeRow = active && rows.get(active.id);
+ const activeRow = activeHere && rows.get(activeHere.id);
// A submenu goes with its row's highlight, as in a native menu, until Right opens it again.
const moveTo = (rowId: string) => {
if (open[level]?.id !== rowId) openSubmenu(level);
@@ -193,8 +236,8 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
if (rowId) moveTo(rowId);
};
const openActive = () => {
- if (!active || !activeRow?.hasSubmenu || activeRow.custom) return;
- openSubmenu(level, active.id, activeRow.element, true);
+ if (!activeHere || !activeRow?.hasSubmenu || activeRow.custom) return;
+ openSubmenu(level, activeHere.id, activeRow.element, true);
// A submenu already open has its rows; one opening now has them once it renders.
if (!activateFirstRow(level + 1)) pendingFirstRow.current = level + 1;
};
@@ -206,45 +249,55 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
};
const rtl = isRightToLeft();
- 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;
- // Into the active row's submenu.
- case rtl ? "ArrowLeft" : "ArrowRight":
- openActive();
- break;
- // Out of the submenu.
- case rtl ? "ArrowRight" : "ArrowLeft":
- if (level > 0) closeLevel(level);
- break;
- case "Enter":
- case " ":
- if (!activeRow || activeRow.custom) break;
- openActive();
- activeRow.select(e);
- break;
- case "Escape":
- // One level at a time, then the menu itself.
- if (open.length) closeLevel(open.length);
- else close();
- 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 rowId = levelRows[(index + step + count) % count];
- if (rowId && rows.get(rowId)?.element.textContent?.trim().toLowerCase().startsWith(typed.text)) {
- moveTo(rowId);
- break;
+ if (filterInput && e.key === "Escape") {
+ // Emptied first; empty, it closes the submenu and gives the menu its keys back.
+ if (filterInput.value) {
+ setFilter(undefined);
+ } else {
+ closeLevel(level);
+ menuRef.current?.focus({ preventScroll: true });
+ }
+ } else if (filterInput || !filterKey(e, level, activeRow)) {
+ 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;
+ // Into the active row's submenu.
+ case rtl ? "ArrowLeft" : "ArrowRight":
+ openActive();
+ break;
+ // Out of the submenu.
+ case rtl ? "ArrowRight" : "ArrowLeft":
+ if (level > 0) closeLevel(level);
+ break;
+ case "Enter":
+ case " ":
+ if (!activeRow || activeRow.custom) break;
+ openActive();
+ activeRow.select(e);
+ break;
+ case "Escape":
+ // One level at a time, then the menu itself.
+ if (open.length) closeLevel(open.length);
+ else close();
+ 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 rowId = levelRows[(index + step + count) % count];
+ if (rowId && rows.get(rowId)?.element.textContent?.trim().toLowerCase().startsWith(typed.text)) {
+ moveTo(rowId);
+ break;
+ }
}
}
}
@@ -254,6 +307,35 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
e.stopPropagation();
}
+ /**
+ * A letter typed while the menu has focus, into a filterable submenu: the one the active row
+ * opened, or the nearest one the keys stand in. It goes into that submenu's filter input, which
+ * takes focus for the rest. Returns whether the key went there.
+ */
+ function filterKey(e: KeyboardEvent, level: number, activeRow: RowEntry | undefined) {
+ if (e.key.length !== 1 || e.key === " " || e.ctrlKey || e.metaKey || e.altKey) return false;
+ const current = filterRef.current;
+ if (current) {
+ // Typed before the input took focus, as fast typing can.
+ setFilter({ ...current, text: current.text + e.key });
+ return true;
+ }
+
+ let target: Omit<MenuFilter, "text"> | undefined;
+ if (active && activeRow?.filterable && open[level]?.id === active.id) {
+ target = { rowId: active.id, level };
+ }
+ for (let parent = level - 1; !target && parent >= 0; parent--) {
+ const rowId = open[parent]?.id;
+ if (rowId && rows.get(rowId)?.filterable) target = { rowId, level: parent };
+ }
+ if (!target) return false;
+ // The submenus open inside it give way to the list of matches.
+ openSubmenu(target.level + 1);
+ setFilter({ ...target, text: e.key });
+ return true;
+ }
+
// 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.
@@ -315,7 +397,64 @@ function MenuItems<T>({ items, onSelect }: {
items: MenuItem<T>[],
onSelect: MenuProps<T>["onSelect"]
}) {
- return <>{menuRows(items).map((row, index) => <MenuItemRow key={index} row={row} onSelect={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">
+ <span className="bx bx-search" aria-hidden="true" />
+ <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)}
+ />
+ </li>
+ );
+}
+
+/**
+ * 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 }: {
+ items: MenuItem<T>[],
+ text: string,
+ onSelect: MenuProps<T>["onSelect"]
+}) {
+ const matches = filterMenuItems(items, text);
+ return <>
+ {matches.length === 0 && <li className="tn-menu-filter-empty" role="none">{t("menu.no_matches")}</li>}
+ {matches.map(({ item, title, path }, index) => (
+ <FormListItem
+ key={index}
+ icon={item.uiIcon ?? "bx bx-empty"} iconClassName={item.iconColorClass}
+ badges={item.badges?.map((badge) => ({ className: badge.className, text: badge.title }))}
+ closeOnSelect={false} onClick={(e) => onSelect?.(item, e)}
+ >
+ <span className="tn-menu-filter-title">{highlightMatch(title, text)}</span>
+ {path.length > 0 && <span className="tn-menu-filter-path">{path.join(" › ")}</span>}
+ </FormListItem>
+ ))}
+ </>;
}
function MenuItemRow<T>({ row, onSelect }: { row: MenuItem<T>, onSelect: MenuProps<T>["onSelect"] }) {
@@ -336,7 +475,7 @@ function MenuItemRow<T>({ row, onSelect }: { row: MenuItem<T>, onSelect: MenuPro
return (
<FormDropdownSubmenu
icon={uiIcon ?? "bx bx-empty"} title={label} disabled={enabled === false}
- className={className} onDropdownToggleClicked={select}
+ className={className} onDropdownToggleClicked={select} filterable={row.filterable}
>
<MenuItems items={items} onSelect={onSelect} />
</FormDropdownSubmenu>
@@ -357,6 +496,73 @@ function MenuItemRow<T>({ row, onSelect }: { row: MenuItem<T>, onSelect: MenuPro
);
}
+interface MenuMatch<T> {
+ item: MenuCommandItem<T>;
+ /** The title as text. */
+ title: string;
+ /** The titles of the submenus the item stands in, outermost first. */
+ path: string[];
+}
+
+/**
+ * The items, at any depth, that run something and match `text`: every word of it is in the
+ * item's title or in those of the submenus it stands in. Those whose title starts with the text
+ * come first, then those whose title holds it, each group in menu order.
+ */
+function filterMenuItems<T>(items: MenuItem<T>[], text: string): MenuMatch<T>[] {
+ const query = text.trim().toLowerCase();
+ const words = query.split(/\s+/).filter(Boolean);
+ const found: (MenuMatch<T> & { rank: number })[] = [];
+
+ function collect(level: MenuItem<T>[], path: string[]) {
+ for (const item of level) {
+ if ("kind" in item) continue;
+ const title = textOf(item.title);
+ if (item.items) {
+ collect(item.items, [ ...path, title ]);
+ continue;
+ }
+ if (item.enabled === false) continue;
+ const lowerTitle = title.toLowerCase();
+ const haystack = [ ...path, title ].join(" ").toLowerCase();
+ if (!words.every((word) => haystack.includes(word))) continue;
+ const rank = lowerTitle.startsWith(query) ? 0 : lowerTitle.includes(query) ? 1 : 2;
+ found.push({ item, title, path, rank });
+ }
+ }
+
+ collect(items, []);
+ return found.sort((a, b) => a.rank - b.rank);
+}
+
+/**
+ * The text an item's title shows. Titles are HTML, read through a `<template>`, whose content is
+ * inert: an `<img>` in it neither loads nor runs its handlers, as one in a detached `<div>` would.
+ */
+function textOf(html: string) {
+ const template = document.createElement("template");
+ template.innerHTML = html;
+ return template.content.textContent ?? "";
+}
+
+/** `title` with the first place the typed text, or else one of its words, occurs in it marked. */
+function highlightMatch(title: string, text: string) {
+ const lowerTitle = title.toLowerCase();
+ const query = text.trim().toLowerCase();
+ for (const candidate of [ query, ...query.split(/\s+/) ].filter(Boolean)) {
+ const start = lowerTitle.indexOf(candidate);
+ if (start < 0) continue;
+ const end = start + candidate.length;
+ return <>{title.slice(0, start)}<mark>{title.slice(start, end)}</mark>{title.slice(end)}</>;
+ }
+ return title;
+}
+
+/** The filter input of the submenu open in `menu`, if one is. */
+function filterInputIn(menu: HTMLElement | null) {
+ return menu?.querySelector<HTMLInputElement>(FILTER_INPUT) ?? null;
+}
+
/** Where a custom row takes focus: the element its content marks as its way in with `tabindex="0"`. */
function focusTarget(row: HTMLElement | undefined) {
return row?.querySelector<HTMLElement>("[tabindex='0']") ?? null;
diff --git a/apps/client/src/widgets/react/menu_context.ts b/apps/client/src/widgets/react/menu_context.ts
index 985851c9a4..98435c2ddf 100644
--- a/apps/client/src/widgets/react/menu_context.ts
+++ b/apps/client/src/widgets/react/menu_context.ts
@@ -28,6 +28,8 @@ export interface RowEntry {
custom: boolean;
disabled: boolean;
hasSubmenu: boolean;
+ /** Whether typing while its submenu is open filters it. */
+ filterable?: boolean;
/** Runs the row, as a press or Enter does, once its submenu, if it has one, is open. */
select(e: MouseEvent | KeyboardEvent): void;
}
@@ -38,6 +40,15 @@ export interface ActiveRow {
id: string;
}
+/** What was typed into a filterable submenu, and the row it opened from. */
+export interface MenuFilter {
+ /** The id of the row the filtered submenu opened from. */
+ rowId: string;
+ /** The level that row stands at; the submenu is one deeper. */
+ level: number;
+ text: string;
+}
+
/** What every row of a menu shares, at every level. */
export interface MenuContextValue {
/** The submenu standing open at each level, the top level's first. */
@@ -63,6 +74,10 @@ export interface MenuContextValue {
/** Records the side the submenus of `level`'s rows open on. */
setDropStart(level: number, dropStart: boolean): void;
close(): void;
+ /** What is typed into a filterable submenu, while anything is. */
+ filter?: MenuFilter;
+ /** Sets what is typed into a filterable submenu, or with `undefined` empties it. */
+ setFilter(filter: MenuFilter | undefined): void;
/**
* Where a row renders its submenu's layer: the top level's element, so the rules scoped to the
* menu apply, but outside its scroller and any other layer, as a fixed layer escapes a
@@ -72,6 +87,11 @@ export interface MenuContextValue {
}
export const MenuContext = createContext<MenuContextValue | null>(null);
+/**
+ * The filterable submenu the rows rendered here stand in, with what is typed into it, which is
+ * empty until something is. `undefined` in a submenu that does not filter.
+ */
+export const MenuFilterContext = createContext<MenuFilter | undefined>(undefined);
/** How deep the rows rendered here stand: 0 at the top level, 1 in its submenus, and so on. */
export const MenuLevelContext = createContext(0);
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.html
index 617705857a..9e21042527 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.html
@@ -50,6 +50,12 @@
types created less often in the <em>More</em> submenu.</li>
<li><a class="reference-link" href="#root/_help_KC1HB96bqqHX">Templates</a>&nbsp;will
also be present (if any) at the end of the list.</li>
+ <li>To find an entry quickly, type into the search box at the top of the submenu,
+ or just start typing while the submenu is open. The submenu then lists
+ every matching entry, including those inside its own submenus (such as
+ a code language or a collection), each with the submenu it comes from.
+ Use <kbd>↑</kbd> and <kbd>↓</kbd> to pick a match, <kbd>Enter</kbd> to create
+ it, and <kbd>Esc</kbd> to clear the search.</li>
<li>The note will be added on the same level of hierarchy as the note selected.</li>
</ul>
</li>
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.md b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.md
index 4545cfd978..e4d4841e0c 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.md
@@ -26,6 +26,7 @@ The contextual menu can operate:
* Allows easy creation of a note with a specified [note type](../../../Note%20Types.md).
* <a class="reference-link" href="../../../Advanced%20Usage/Snippets.md">Snippets</a> and <a class="reference-link" href="../../../Collections.md">Collections</a> are grouped in the _Snippet_ and _Collection_ submenus, and the note types created less often in the _More_ submenu.
* <a class="reference-link" href="../../../Advanced%20Usage/Templates.md">Templates</a> will also be present (if any) at the end of the list.
+ * To find an entry quickly, type into the search box at the top of the submenu, or just start typing while the submenu is open. The submenu then lists every matching entry, including those inside its own submenus (such as a code language or a collection), each with the submenu it comes from. Use <kbd>↑</kbd> and <kbd>↓</kbd> to pick a match, <kbd>Enter</kbd> to create it, and <kbd>Esc</kbd> to clear the search.
* The note will be added on the same level of hierarchy as the note selected.
* **Insert child note**
* Same as _Insert note after_, but the note will be created as a child of the selected note.