diff --git a/app/components/Menu/ContextMenu.tsx b/app/components/Menu/ContextMenu.tsx
index e9f734b4be..8c209b8996 100644
--- a/app/components/Menu/ContextMenu.tsx
+++ b/app/components/Menu/ContextMenu.tsx
@@ -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 (
@@ -97,8 +106,11 @@ export const ContextMenu = observer(
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
onCloseAutoFocus={preventDefault}
+ onEscapeKeyDown={handleEscapeKeyDown}
+ onKeyDownCapture={handleKeyDownCapture}
>
- {content}
+
+ {content ?? (query ? : null)}
diff --git a/app/components/Menu/DropdownMenu.tsx b/app/components/Menu/DropdownMenu.tsx
index 313e1629b0..9a5036c772 100644
--- a/app/components/Menu/DropdownMenu.tsx
+++ b/app/components/Menu/DropdownMenu.tsx
@@ -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 (
@@ -144,9 +153,12 @@ export const DropdownMenu = observer(function DropdownMenu({
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
onCloseAutoFocus={preventDefault}
+ onEscapeKeyDown={handleEscapeKeyDown}
+ onKeyDownCapture={handleKeyDownCapture}
>
- {content}
- {append}
+
+ {content ?? (query ? : null)}
+ {query ? null : append}
diff --git a/app/components/Menu/MenuFilter.tsx b/app/components/Menu/MenuFilter.tsx
new file mode 100644
index 0000000000..6fae2db542
--- /dev/null
+++ b/app/components/Menu/MenuFilter.tsx
@@ -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) => 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();
+ const contentRef = React.useRef(null);
+ const highlightRef = React.useRef(null);
+
+ const reset = React.useCallback(() => {
+ contentRef.current = null;
+ highlightRef.current = null;
+ setQuery(undefined);
+ }, []);
+
+ const handleKeyDownCapture = React.useCallback(
+ (event: React.KeyboardEvent) => {
+ 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(
+ `[${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(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) => {
+ onChange(event.target.value);
+ },
+ [onChange]
+ );
+
+ const handleKeyDown = React.useCallback(
+ (event: React.KeyboardEvent) => {
+ // 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(ITEM_SELECTOR))
+ : [];
+ const highlighted =
+ content?.querySelector(`[${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 (
+
+
+
+ );
+}
+
+/**
+ * Displays a message when no menu items match the filter query.
+ */
+export function MenuFilterEmpty() {
+ const { t } = useTranslation();
+ return {t("No results")};
+}
+
+/**
+ * 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(
+ "[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(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")};
+`;
diff --git a/app/components/Menu/transformer.test.tsx b/app/components/Menu/transformer.test.tsx
new file mode 100644
index 0000000000..379aca1681
--- /dev/null
+++ b/app/components/Menu/transformer.test.tsx
@@ -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();
+ });
+});
diff --git a/app/components/Menu/transformer.tsx b/app/components/Menu/transformer.tsx
index 2ac0c4bf97..2dadb495ae 100644
--- a/app/components/Menu/transformer.tsx
+++ b/app/components/Menu/transformer.tsx
@@ -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();
+ 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 ? (
{"icon" in item ? item.icon : null}
) : 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)
diff --git a/app/components/primitives/components/Menu.tsx b/app/components/primitives/components/Menu.tsx
index eb41ac9314..82cc2b1a52 100644
--- a/app/components/primitives/components/Menu.tsx
+++ b/app/components/primitives/components/Menu.tsx
@@ -68,7 +68,9 @@ const BaseMenuItemCSS = css`
`
&[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: ${
diff --git a/app/editor/components/ToolbarMenu.tsx b/app/editor/components/ToolbarMenu.tsx
index 48942118b1..fa67f235d0 100644
--- a/app/editor/components/ToolbarMenu.tsx
+++ b/app/editor/components/ToolbarMenu.tsx
@@ -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(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}
>
- {toMenuItems(items)}
+
+
+ {toMenuItems(items, query) ??
+ (query ? : null)}
+