feat: Filter menu items by typing (#14534)

* feat: Filter menu items by typing

Typing in an open context menu, dropdown menu or editor toolbar dropdown shows a filter row and filters the items. Focus stays on the menu items, so the arrow keys still navigate, and the menu keeps its position and width while filtering.

* fix: Focus first menu item when Escape clears the filter

* fix: Accept AltGr characters and emoji in the menu filter

* refactor: Use isTextInput helper in menu filter

* fix: Text cursor, select all and selection delete in the menu filter

* Refactor to use real input

* fix: Keep the focused menu item highlighted while filtering
This commit is contained in:
Tom Moor authored and GitHub committed 2026-11-11 23:31:46 -05:00
1 parent 7589ce38de
commit acf90fdbf4
7 files changed
+498 -17

No files matched your search

+15 -3
View File
@@ -4,6 +4,7 @@ import useActionContext from "~/hooks/useActionContext";
import useMobile from "~/hooks/useMobile";
import type { ActionFactory, ActionVariant, ActionWithChildren } from "~/types";
import { preventDefault } from "~/utils/events";
import { MenuFilter, MenuFilterEmpty, useMenuFilter } from "./MenuFilter";
import { toMenuItems } from "./transformer";
import { observer } from "mobx-react";
import { useComputed } from "~/hooks/useComputed";
@@ -31,6 +32,13 @@ export const ContextMenu = observer(
const actionContext = useActionContext({
isMenu: true,
});
const {
query,
setQuery,
handleKeyDownCapture,
handleEscapeKeyDown,
reset: resetFilter,
} = useMenuFilter();
// Menu items are only built while the menu is open.
const menuItems = useComputed(() => {
@@ -54,12 +62,13 @@ export const ContextMenu = observer(
(open: boolean) => {
setOpen(open);
if (open) {
resetFilter();
onOpen?.();
} else {
onClose?.();
}
},
[onOpen, onClose]
[onOpen, onClose, resetFilter]
);
const enablePointerEvents = React.useCallback(() => {
@@ -86,7 +95,7 @@ export const ContextMenu = observer(
return <>{children}</>;
}
const content = open ? toMenuItems(menuItems) : null;
const content = open ? toMenuItems(menuItems, query) : null;
return (
<MenuProvider variant="context">
@@ -97,8 +106,11 @@ export const ContextMenu = observer(
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
onCloseAutoFocus={preventDefault}
onEscapeKeyDown={handleEscapeKeyDown}
onKeyDownCapture={handleKeyDownCapture}
>
{content}
<MenuFilter query={query} onChange={setQuery} />
{content ?? (query ? <MenuFilterEmpty /> : null)}
</MenuContent>
</Menu>
</MenuProvider>
+16 -4
View File
@@ -20,6 +20,7 @@ import type {
MenuItem,
MenuItemWithChildren,
} from "~/types";
import { MenuFilter, MenuFilterEmpty, useMenuFilter } from "./MenuFilter";
import { toMenuItems, toMobileMenuItems } from "./transformer";
import { observer } from "mobx-react";
import { useComputed } from "~/hooks/useComputed";
@@ -65,6 +66,13 @@ export const DropdownMenu = observer(function DropdownMenu({
const actionContext = useActionContext({
isMenu: true,
});
const {
query,
setQuery,
handleKeyDownCapture,
handleEscapeKeyDown,
reset: resetFilter,
} = useMenuFilter();
const menuItems = useComputed(() => {
if (!open) {
@@ -93,12 +101,13 @@ export const DropdownMenu = observer(function DropdownMenu({
(open: boolean) => {
setOpen(open);
if (open) {
resetFilter();
onOpen?.();
} else {
onClose?.();
}
},
[onOpen, onClose]
[onOpen, onClose, resetFilter]
);
const enablePointerEvents = React.useCallback(() => {
@@ -130,7 +139,7 @@ export const DropdownMenu = observer(function DropdownMenu({
);
}
const content = toMenuItems(menuItems);
const content = toMenuItems(menuItems, query);
return (
<MenuProvider variant="dropdown">
@@ -144,9 +153,12 @@ export const DropdownMenu = observer(function DropdownMenu({
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
onCloseAutoFocus={preventDefault}
onEscapeKeyDown={handleEscapeKeyDown}
onKeyDownCapture={handleKeyDownCapture}
>
{content}
{append}
<MenuFilter query={query} onChange={setQuery} />
{content ?? (query ? <MenuFilterEmpty /> : null)}
{query ? null : append}
</MenuContent>
</Menu>
</MenuProvider>
+330
View File
@@ -0,0 +1,330 @@
import { VISUALLY_HIDDEN_STYLES } from "@radix-ui/react-visually-hidden";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { s } from "@shared/styles";
import { breakpoint } from "@shared/styles/breakpoint";
import isTextInput from "~/utils/isTextInput";
interface MenuFilterState {
/** The current filter query, or undefined when the filter is hidden. */
query: string | undefined;
/** Sets the filter query. */
setQuery: (query: string) => void;
/** Capture-phase keydown handler to attach to the menu content. */
handleKeyDownCapture: (event: React.KeyboardEvent<HTMLElement>) => void;
/** Escape handler to attach to the menu content. */
handleEscapeKeyDown: (event: KeyboardEvent) => void;
/** Hides the filter and clears the query. */
reset: () => void;
}
/**
* Lets the user filter a menu by typing. When a key that types text is pressed
* on a menu item, focus moves to the filter input, which then receives the
* text.
*
* @returns the filter query and the handlers to attach to the menu content.
*/
export function useMenuFilter(): MenuFilterState {
const [query, setQuery] = React.useState<string>();
const contentRef = React.useRef<HTMLElement | null>(null);
const highlightRef = React.useRef<HTMLElement | null>(null);
const reset = React.useCallback(() => {
contentRef.current = null;
highlightRef.current = null;
setQuery(undefined);
}, []);
const handleKeyDownCapture = React.useCallback(
(event: React.KeyboardEvent<HTMLElement>) => {
const { target, currentTarget } = event;
if (
!(target instanceof HTMLElement) ||
target.closest("[data-radix-menu-content]") !== currentTarget ||
(isTextInput(target) && !target.matches('[role^="menuitem"]')) ||
target.isContentEditable
) {
return;
}
const input = currentTarget.querySelector<HTMLInputElement>(
`[${INPUT_ATTRIBUTE}]`
);
// AltGr is reported as Ctrl+Alt on Windows, but it types a character.
const isShortcut =
(event.ctrlKey || event.metaKey || event.altKey) &&
!event.getModifierState("AltGraph");
if (!input || isShortcut) {
return;
}
// Move up from the first item to the input while the filter is visible.
if (
event.key === "ArrowUp" &&
query !== undefined &&
target === currentTarget.querySelector(ITEM_SELECTOR)
) {
event.preventDefault();
event.stopPropagation();
highlightRef.current = highlightItem(currentTarget, target);
input.focus();
return;
}
const isText =
Array.from(event.key).length === 1 ||
(event.key === "Backspace" && !!query);
if (!isText) {
return;
}
// Space selects the focused item until there is a query to add it to.
if (event.key === " " && !query) {
return;
}
// The default action is kept, so the browser types into the input. Radix
// typeahead, item selection and global shortcuts must not handle the key.
event.stopPropagation();
contentRef.current = currentTarget;
if (target.matches(ITEM_SELECTOR)) {
highlightRef.current = target;
}
if (query === undefined) {
lockLayout(currentTarget);
}
input.focus();
},
[query]
);
const handleEscapeKeyDown = React.useCallback(
(event: KeyboardEvent) => {
if (query === undefined) {
return;
}
event.preventDefault();
setQuery(undefined);
},
[query]
);
// While the input has focus, highlight the item that had focus before, or
// the first match if it was filtered out. Otherwise move focus to the first
// item if the focused item was filtered out, or if the filter was hidden
// while it had focus. A passive effect runs after Radix removes unmounted
// items from its collection.
React.useEffect(() => {
const content = contentRef.current;
if (!content) {
return;
}
const active = document.activeElement;
if (query !== undefined && active?.hasAttribute(INPUT_ATTRIBUTE)) {
highlightRef.current = highlightItem(content, highlightRef.current);
return;
}
if (
active &&
content.contains(active) &&
active.getAttribute("role")?.startsWith("menuitem")
) {
return;
}
const first = content.querySelector<HTMLElement>(ITEM_SELECTOR);
(first ?? content).focus();
}, [query]);
return { query, setQuery, handleKeyDownCapture, handleEscapeKeyDown, reset };
}
interface Props {
/** The current filter query, or undefined when the filter is hidden. */
query: string | undefined;
/** Called when the user changes the query. */
onChange: (query: string) => void;
}
/**
* Displays the filter input at the top of a menu. The input is always
* rendered, so that it can receive focus before the first character is typed,
* but it is only visible while there is a query.
*/
export function MenuFilter({ query, onChange }: Props) {
const { t } = useTranslation();
const isActive = query !== undefined;
const handleChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
onChange(event.target.value);
},
[onChange]
);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
// Radix typeahead must not handle keys typed into the input, but Tab
// must reach the menu so that focus stays in it.
if (event.key !== "Tab") {
event.stopPropagation();
}
if (event.nativeEvent.isComposing) {
return;
}
const content = event.currentTarget.closest("[data-radix-menu-content]");
const items = content
? Array.from(content.querySelectorAll<HTMLElement>(ITEM_SELECTOR))
: [];
const highlighted =
content?.querySelector<HTMLElement>(`[${HIGHLIGHT_ATTRIBUTE}]`) ??
items[0];
if (event.key === "ArrowDown") {
event.preventDefault();
highlighted?.focus();
} else if (event.key === "ArrowUp") {
event.preventDefault();
items[items.length - 1]?.focus();
} else if (event.key === "Enter") {
event.preventDefault();
highlighted?.click();
}
},
[]
);
return (
<Wrapper style={isActive ? undefined : VISUALLY_HIDDEN_STYLES}>
<Input
value={query ?? ""}
onChange={handleChange}
onKeyDown={handleKeyDown}
placeholder={`${t("Filter")}…`}
aria-label={t("Filter")}
tabIndex={-1}
autoComplete="off"
spellCheck={false}
{...{ [INPUT_ATTRIBUTE]: "" }}
/>
</Wrapper>
);
}
/**
* Displays a message when no menu items match the filter query.
*/
export function MenuFilterEmpty() {
const { t } = useTranslation();
return <Empty>{t("No results")}</Empty>;
}
/**
* Records the current width and position of the menu. The filter row applies
* them, so that the menu does not move while the items are filtered.
*/
function lockLayout(content: HTMLElement) {
// The computed width is not changed by the scale of the open animation.
content.style.setProperty(
"--menu-filter-width",
getComputedStyle(content).width
);
content.setAttribute(LOCKED_ATTRIBUTE, "");
const wrapper = content.closest<HTMLElement>(
"[data-radix-popper-content-wrapper]"
);
if (wrapper?.style.transform) {
wrapper.style.setProperty(
"--menu-filter-transform",
wrapper.style.transform
);
wrapper.setAttribute(LOCKED_ATTRIBUTE, "");
}
}
/**
* Marks the item that Enter selects while the filter input has focus.
*
* @param content the menu content.
* @param preferred the item to mark if it is still in the menu.
* @returns the marked item, or null if the menu has no items.
*/
function highlightItem(content: HTMLElement, preferred: HTMLElement | null) {
const item =
preferred?.isConnected &&
content.contains(preferred) &&
preferred.matches(ITEM_SELECTOR)
? preferred
: content.querySelector<HTMLElement>(ITEM_SELECTOR);
content
.querySelectorAll(`[${HIGHLIGHT_ATTRIBUTE}]`)
.forEach((element) => element.removeAttribute(HIGHLIGHT_ATTRIBUTE));
item?.setAttribute(HIGHLIGHT_ATTRIBUTE, "");
return item;
}
const ITEM_SELECTOR = '[role^="menuitem"]:not([data-disabled])';
const HIGHLIGHT_ATTRIBUTE = "data-menu-filter-highlighted";
const LOCKED_ATTRIBUTE = "data-menu-filter-locked";
const INPUT_ATTRIBUTE = "data-menu-filter-input";
const Wrapper = styled.label`
position: sticky;
top: 0;
z-index: 1;
display: flex;
align-items: center;
min-height: 40px;
margin: -6px -6px 6px;
padding: 8px 18px;
cursor: text;
background: ${s("menuBackground")};
border-bottom: 1px solid ${s("divider")};
// Keep the size and position that the menu had before filtering. This rule
// overrides the inline transform that Radix changes when the menu resizes.
[data-radix-menu-content][${LOCKED_ATTRIBUTE}]:has(&) {
width: var(--menu-filter-width);
}
[data-radix-popper-content-wrapper][${LOCKED_ATTRIBUTE}]:has(&) {
transform: var(--menu-filter-transform) !important;
}
`;
const Input = styled.input`
flex: 1;
min-width: 0;
margin: 0;
padding: 0;
border: 0;
outline: none;
background: none;
font: inherit;
font-size: 16px;
color: ${s("text")};
&::placeholder {
color: ${s("placeholder")};
}
${breakpoint("tablet")`
font-size: 14px;
`}
`;
const Empty = styled.div`
padding: 4px 12px;
font-size: 14px;
color: ${s("textTertiary")};
`;
+50
View File
@@ -0,0 +1,50 @@
import type { ReactElement } from "react";
import type { MenuItem } from "~/types";
import { toMenuItems } from "./transformer";
const noop = () => undefined;
const items: MenuItem[] = [
{ type: "button", title: "Team", onClick: noop },
{ type: "button", title: "Due date", onClick: noop },
{ type: "separator" },
{
type: "submenu",
title: "Move to",
items: [
{ type: "button", title: "Engineering", onClick: noop },
{ type: "button", title: "Design", onClick: noop },
],
},
{ type: "button", title: "Hidden date", visible: false, onClick: noop },
];
function render(query?: string) {
return (toMenuItems(items, query) ?? []).filter(
(element): element is ReactElement => !!element
);
}
describe("toMenuItems", () => {
it("returns all visible items without a query", () => {
expect(render().map((element) => element.key)).toEqual([
"button-0",
"button-1",
"separator-2",
"submenu-3",
]);
});
it("returns only matching items and keeps their keys", () => {
expect(render("DATE").map((element) => element.key)).toEqual(["button-1"]);
});
it("keeps a submenu when one of its items matches", () => {
const [submenu] = render("design");
expect(submenu.key).toEqual("submenu-3");
});
it("returns null when nothing matches", () => {
expect(toMenuItems(items, "zzz")).toBeNull();
});
});
+56 -5
View File
@@ -14,11 +14,27 @@ import type { MenuItem } from "~/types";
import { MouseSafeArea } from "~/components/MouseSafeArea";
import { createRef } from "react";
export function toMenuItems(items: MenuItem[]) {
/**
* Converts menu items to menu elements.
*
* @param items the menu items to convert.
* @param query an optional filter query, only matching items are returned.
* @returns the menu elements, or null if there are none.
*/
export function toMenuItems(items: MenuItem[], query?: string) {
const filteredItems = filterMenuItems(items);
const parentRef = createRef<HTMLDivElement>();
const normalizedQuery = query?.toLocaleLowerCase();
if (!filteredItems.length) {
// Keys use the index before the query is applied, so that the focused item
// keeps its element while the query changes.
const entries = filteredItems
.map((item, index) => ({ item, index }))
.filter(
({ item }) => !normalizedQuery || matchesQuery(item, normalizedQuery)
);
if (!entries.length) {
return null;
}
@@ -31,13 +47,19 @@ export function toMenuItems(items: MenuItem[]) {
!!item.icon
);
return filteredItems.map((item, index) => {
return entries.map(({ item, index }) => {
const icon = showIcon ? (
<Components.MenuIconWrapper aria-hidden>
{"icon" in item ? item.icon : null}
</Components.MenuIconWrapper>
) : undefined;
// Children are filtered too, unless the parent title itself matches.
const childQuery =
normalizedQuery && !titleMatches(item, normalizedQuery)
? normalizedQuery
: undefined;
switch (item.type) {
case "button":
return (
@@ -85,7 +107,7 @@ export function toMenuItems(items: MenuItem[]) {
);
case "submenu": {
const submenuItems = toMenuItems(item.items);
const submenuItems = toMenuItems(item.items, childQuery);
if (!submenuItems?.length) {
return null;
@@ -116,7 +138,7 @@ export function toMenuItems(items: MenuItem[]) {
}
case "group": {
const groupItems = toMenuItems(item.items);
const groupItems = toMenuItems(item.items, childQuery);
if (!groupItems?.length) {
return null;
@@ -287,6 +309,35 @@ export function toMobileMenuItems(
});
}
function titleMatches(item: MenuItem, query: string): boolean {
return (
"title" in item &&
typeof item.title === "string" &&
item.title.toLocaleLowerCase().includes(query)
);
}
function matchesQuery(item: MenuItem, query: string): boolean {
if (item.visible === false) {
return false;
}
switch (item.type) {
case "button":
case "route":
case "link":
return titleMatches(item, query);
case "submenu":
case "group":
return (
titleMatches(item, query) ||
item.items.some((child) => matchesQuery(child, query))
);
default:
return false;
}
}
function filterMenuItems(items: MenuItem[]): MenuItem[] {
return items
.filter((item) => item.visible !== false)
@@ -68,7 +68,9 @@ const BaseMenuItemCSS = css<BaseMenuItemProps>`
`
&[data-highlighted],
&[data-state="open"],
&:focus-visible {
&:focus-visible,
[data-radix-menu-content]:has([data-menu-filter-input]:focus)
&[data-menu-filter-highlighted] {
color: ${props.theme.accentText};
background: ${props.$dangerous ? props.theme.danger : props.theme.accent};
outline-color: ${
+28 -4
View File
@@ -16,6 +16,11 @@ import ToolbarButton from "./ToolbarButton";
import ToolbarSeparator from "./ToolbarSeparator";
import Tooltip from "./Tooltip";
import { toMenuItems } from "~/components/Menu/transformer";
import {
MenuFilter,
MenuFilterEmpty,
useMenuFilter,
} from "~/components/Menu/MenuFilter";
import { MenuContent } from "~/components/primitives/Menu";
import { MenuProvider } from "~/components/primitives/Menu/MenuContext";
import { Menu, MenuTrigger } from "~/components/primitives/Menu";
@@ -44,10 +49,23 @@ function ToolbarDropdown(props: ToolbarDropdownProps) {
const { item, shortcut, tooltip } = props;
const { state } = view;
const [isOpen, setIsOpen] = useState<boolean>(false);
const {
query,
setQuery,
handleKeyDownCapture,
handleEscapeKeyDown,
reset: resetFilter,
} = useMenuFilter();
const handleOpenChange = useCallback((open: boolean) => {
setIsOpen(open);
}, []);
const handleOpenChange = useCallback(
(open: boolean) => {
setIsOpen(open);
if (open) {
resetFilter();
}
},
[resetFilter]
);
const items: TMenuItem[] = useMemo(() => {
if (!isOpen) {
@@ -86,8 +104,14 @@ function ToolbarDropdown(props: ToolbarDropdownProps) {
align="end"
aria-label={item.tooltip || t("More options")}
onCloseAutoFocus={handleCloseAutoFocus}
onEscapeKeyDown={handleEscapeKeyDown}
onKeyDownCapture={handleKeyDownCapture}
>
<EventBoundary>{toMenuItems(items)}</EventBoundary>
<MenuFilter query={query} onChange={setQuery} />
<EventBoundary>
{toMenuItems(items, query) ??
(query ? <MenuFilterEmpty /> : null)}
</EventBoundary>
</MenuContent>
</Menu>
</MenuProvider>