An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add useTypeahead hook + wire into DropdownMenu (menus-11) (#3431)
Cindy Zhangc891bf886254
diff --git a/.changeset/typeahead-context-nav-menus.md b/.changeset/typeahead-context-nav-menus.mdnew file mode 100644index 0000000000..13a9b01a48--- /dev/null+++ b/.changeset/typeahead-context-nav-menus.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] ContextMenu and NavMenu heading menus now support first-character typeahead (type a letter to jump to the matching item), via the shared `useTypeahead` hook — matching DropdownMenu. MoreMenu inherits it through DropdownMenu (#3343).+@cixzhangdiff --git a/.changeset/use-typeahead.md b/.changeset/use-typeahead.mdnew file mode 100644index 0000000000..ac83fcdf6b--- /dev/null+++ b/.changeset/use-typeahead.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[feat] Add `useTypeahead` — a first-character (type-to-focus) search hook, and wire it into `DropdownMenu`. Typing a letter jumps to the next menu item whose label starts with it; repeated presses of the same letter cycle through matches; the buffer resets after 750ms; disabled items are skipped. The hook is additive and collection-agnostic (composes with `useListFocus`/`useGridFocus` via `onMatch`), so menus/listboxes gain APG typeahead which astryx previously lacked (menus-11, infra-14) (#3343).+@cixzhangdiff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsxindex e11cac49ec..6bdd358afe 100644--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx@@ -60,6 +60,22 @@ describe('ContextMenu', () => {expect(screen.getByRole('menu', {hidden: true})).toBeInTheDocument();});+ it('typeahead focuses the matching menu item (menus-11)', () => {+ render(+ <ContextMenu+ items={[{label: 'Cut'}, {label: 'Copy'}, {label: 'Paste'}]}+ hasAutoFocus={false}>+ <div>Right-click me</div>+ </ContextMenu>,+ );+ fireEvent.contextMenu(screen.getByText('Right-click me'));+ const menu = screen.getByRole('menu', {hidden: true});+ fireEvent.keyDown(menu, {key: 'p'});+ expect(+ screen.getByRole('menuitem', {name: 'Paste', hidden: true}),+ ).toHaveFocus();+ });+it('opens menu on right-click', () => {render(<ContextMenu items={[{label: 'Item 1'}]}>diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex e55407c285..85445acdfb 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -42,6 +42,7 @@ import {type DropdownMenuContextValue,} from '../DropdownMenu/DropdownMenuContext';import {useListFocus} from '../hooks/useListFocus';+import {useTypeahead} from '../hooks/useTypeahead';import {layerAnimations} from '../Layer/layerAnimations.stylex';import {colorVars,@@ -219,12 +220,35 @@ export function ContextMenu({listRef,handleKeyDown: listNavKeyDown,focusFirst,+ focusItem,} = useListFocus<HTMLDivElement>({itemSelector: '[role="menuitem"]:not([aria-disabled="true"])',wrap: false,onEscape: closeMenu,});+ // First-character typeahead over the enabled menu items (menus-11).+ const getMenuItems = useCallback(+ (): HTMLElement[] =>+ listRef.current+ ? Array.from(+ listRef.current.querySelectorAll<HTMLElement>(+ '[role="menuitem"]:not([aria-disabled="true"])',+ ),+ )+ : [],+ [listRef],+ );+ const typeahead = useTypeahead({+ getItemLabels: () => getMenuItems().map(el => el.textContent),+ onMatch: focusItem,+ getCurrentIndex: () =>+ getMenuItems().findIndex(+ el =>+ el === document.activeElement || el.contains(document.activeElement),+ ),+ });+// Dismiss on any click outside the menu. We use popover="manual" (not// "auto") because the native light-dismiss treats the mouseup from the// opening right-click as a dismiss event. Handling it ourselves via@@ -280,9 +304,13 @@ export function ContextMenu({}return;}+ if (typeahead.onKeyDown(e)) {+ e.preventDefault();+ return;+ }listNavKeyDown(e);},- [listNavKeyDown],+ [listNavKeyDown, typeahead],);const handleContextMenu = useCallback(diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex 468c48775a..f31c3af691 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -59,10 +59,7 @@ describe('DropdownMenu', () => {it('does not wrap the menu in a role="dialog" aria-modal element', () => {render(- <DropdownMenu- button={{label: 'Actions'}}- items={[{label: 'Item 1'}]}- />,+ <DropdownMenu button={{label: 'Actions'}} items={[{label: 'Item 1'}]} />,);// The popup exposes its own role="menu"; it must not be nested inside a// modal dialog, which would announce an unnamed dialog around the menu@@ -134,6 +131,22 @@ describe('DropdownMenu', () => {expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled();});+ it('typeahead focuses the item matching the typed character (menus-11)', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ items={[{label: 'Cut'}, {label: 'Copy'}, {label: 'Delete'}]}+ />,+ );+ await user.click(screen.getByRole('button', {name: /Actions/}));+ const menu = screen.getByRole('menu', {hidden: true});+ fireEvent.keyDown(menu, {key: 'd'});+ expect(+ screen.getByRole('menuitem', {name: 'Delete', hidden: true}),+ ).toHaveFocus();+ });+it('calls onClick callback when button is clicked', async () => {const user = userEvent.setup();const handleClick = vi.fn();diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex 995f772069..6ea01ddc36 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -43,6 +43,7 @@ import {type DropdownMenuContextValue,} from './DropdownMenuContext';import {useListFocus} from '../hooks/useListFocus';+import {useTypeahead} from '../hooks/useTypeahead';import {layerAnimations} from '../Layer/layerAnimations.stylex';import type {LayerPlacement} from '../Layer/useLayer';import {@@ -263,12 +264,36 @@ export function DropdownMenu({listRef,handleKeyDown: listNavKeyDown,focusFirst,+ focusItem,} = useListFocus<HTMLDivElement>({itemSelector: '[role="menuitem"]:not([aria-disabled="true"])',wrap: false,onEscape: closeMenu,});+ // First-character typeahead over the (enabled) menu items — jump to the next+ // item whose label starts with the typed text (menus-11).+ const getMenuItems = useCallback(+ (): HTMLElement[] =>+ listRef.current+ ? Array.from(+ listRef.current.querySelectorAll<HTMLElement>(+ '[role="menuitem"]:not([aria-disabled="true"])',+ ),+ )+ : [],+ [listRef],+ );+ const typeahead = useTypeahead({+ getItemLabels: () => getMenuItems().map(el => el.textContent),+ onMatch: focusItem,+ getCurrentIndex: () =>+ getMenuItems().findIndex(+ el =>+ el === document.activeElement || el.contains(document.activeElement),+ ),+ });+// Sync controlled open state → popover, and focus first item on openuseEffect(() => {if (isControlled) {@@ -283,7 +308,7 @@ export function DropdownMenu({}}, [controlledIsOpen, isControlled, popover, hasAutoFocus, focusFirst]);- // Extend useListFocus with Enter/Space activation+ // Extend useListFocus with Enter/Space activation + typeaheadconst listKeyDown = useCallback((e: React.KeyboardEvent) => {if (e.key === 'Enter' || e.key === ' ') {@@ -303,9 +328,14 @@ export function DropdownMenu({closeMenu();return;}+ // Type-to-focus next; if it consumed a printable key, stop here.+ if (typeahead.onKeyDown(e)) {+ e.preventDefault();+ return;+ }listNavKeyDown(e);},- [listNavKeyDown, closeMenu],+ [listNavKeyDown, closeMenu, typeahead],);const openAndFocus = useCallback(() => {diff --git a/packages/core/src/NavMenu/NavHeadingMenu.tsx b/packages/core/src/NavMenu/NavHeadingMenu.tsxindex 154d277fb1..98235ce08a 100644--- a/packages/core/src/NavMenu/NavHeadingMenu.tsx+++ b/packages/core/src/NavMenu/NavHeadingMenu.tsx@@ -18,6 +18,7 @@ import {spacingVars} from '../theme/tokens.stylex';import {mergeProps, mergeRefs} from '../utils';import type {BaseProps} from '../BaseProps';import {useListFocus} from '../hooks/useListFocus';+import {useTypeahead} from '../hooks/useTypeahead';import {themeProps} from '../utils/themeProps';import {NavHeadingMenuContext,@@ -98,10 +99,32 @@ export function NavHeadingMenu({const closeCtx = useNavHeadingCloseContext();const closeMenu = closeCtx?.closeMenu;- const {listRef, handleKeyDown} = useListFocus({+ const {listRef, handleKeyDown, focusItem} = useListFocus({onEscape: closeMenu,});+ // First-character typeahead over the menu items (menus-11).+ const getMenuItems = useCallback(+ (): HTMLElement[] =>+ listRef.current+ ? Array.from(+ listRef.current.querySelectorAll<HTMLElement>('[role="menuitem"]'),+ )+ : [],+ [listRef],+ );+ const typeahead = useTypeahead({+ getItemLabels: () => getMenuItems().map(el => el.textContent),+ onMatch: focusItem,+ getCurrentIndex: () =>+ getMenuItems().findIndex(+ el =>+ el === document.activeElement || el.contains(document.activeElement),+ ),+ isDisabled: index =>+ getMenuItems()[index]?.getAttribute('aria-disabled') === 'true',+ });+// Extend useListFocus with Enter/Space activation. Items rendered without an// `href` are `<div role="menuitem">` elements, which have no native keyboard// activation — without this, Enter/Space on a focused onClick-only item does@@ -116,9 +139,13 @@ export function NavHeadingMenu({return;}}+ if (typeahead.onKeyDown(e)) {+ e.preventDefault();+ return;+ }handleKeyDown(e);},- [handleKeyDown],+ [handleKeyDown, typeahead],);const ctx = useMemo(diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 6d1506a21c..bd2cdc3578 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -23,6 +23,9 @@ export type {UseGridFocusOptions, UseGridFocusReturn} from './useGridFocus';export {useListFocus} from './useListFocus';export type {UseListFocusOptions, UseListFocusReturn} from './useListFocus';+export {useTypeahead} from './useTypeahead';+export type {UseTypeaheadOptions, UseTypeaheadReturn} from './useTypeahead';+export {useMediaQuery} from './useMediaQuery';export {useOverflow} from './useOverflow';diff --git a/packages/core/src/hooks/useTypeahead.test.tsx b/packages/core/src/hooks/useTypeahead.test.tsxnew file mode 100644index 0000000000..f8ed187f1c--- /dev/null+++ b/packages/core/src/hooks/useTypeahead.test.tsx@@ -0,0 +1,109 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useTypeahead.test.tsx+ * @input Uses vitest, @testing-library/react, useTypeahead hook+ * @output Unit tests for useTypeahead first-character search+ * @position Testing; validates useTypeahead.ts+ *+ * SYNC: When useTypeahead.ts changes, update tests to match new behavior+ */++import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {renderHook} from '@testing-library/react';+import {useTypeahead} from './useTypeahead';++const LABELS = ['Apple', 'Apricot', 'Banana', 'Cherry'] as const;+const NO_DISABLED: number[] = [];++function setup(opts?: {current?: number; disabledIndices?: number[]}) {+ const onMatch = vi.fn();+ const disabled = opts?.disabledIndices ?? NO_DISABLED;+ const {result} = renderHook(() =>+ useTypeahead({+ getItemLabels: () => LABELS,+ onMatch,+ getCurrentIndex: () => opts?.current ?? -1,+ isDisabled: (i: number) => disabled.includes(i),+ }),+ );+ return {onMatch, api: result.current};+}++function key(k: string): KeyboardEvent {+ return new KeyboardEvent('keydown', {key: k});+}++describe('useTypeahead', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('matches the first item whose label starts with the typed character', () => {+ const {onMatch, api} = setup();+ const handled = api.onKeyDown(key('b'));+ expect(handled).toBe(true);+ expect(onMatch).toHaveBeenCalledWith(2); // Banana+ });++ it('accumulates the buffer to disambiguate (a → ap → apr)', () => {+ const {onMatch, api} = setup();+ api.onKeyDown(key('a')); // Apple (first "a")+ expect(onMatch).toHaveBeenLastCalledWith(0);+ api.onKeyDown(key('p')); // "ap" still Apple+ expect(onMatch).toHaveBeenLastCalledWith(0);+ api.onKeyDown(key('r')); // "apr" → Apricot+ expect(onMatch).toHaveBeenLastCalledWith(1);+ });++ it('cycles through same-letter matches on repeated presses', () => {+ // Start with nothing focused; repeated "a" walks Apple → Apricot → wrap.+ const onMatch = vi.fn();+ let current = -1;+ const {result} = renderHook(() =>+ useTypeahead({+ getItemLabels: () => LABELS,+ onMatch: (i: number) => {+ current = i;+ onMatch(i);+ },+ getCurrentIndex: () => current,+ }),+ );+ result.current.onKeyDown(key('a'));+ expect(onMatch).toHaveBeenLastCalledWith(0); // Apple (first match)+ result.current.onKeyDown(key('a'));+ expect(onMatch).toHaveBeenLastCalledWith(1); // advance to Apricot+ result.current.onKeyDown(key('a'));+ expect(onMatch).toHaveBeenLastCalledWith(0); // wrap back to Apple+ });++ it('resets the buffer after the timeout', () => {+ const {onMatch, api} = setup();+ api.onKeyDown(key('a')); // Apple+ api.onKeyDown(key('p')); // Apple ("ap")+ vi.advanceTimersByTime(800);+ api.onKeyDown(key('b')); // fresh buffer → Banana+ expect(onMatch).toHaveBeenLastCalledWith(2);+ });++ it('skips disabled items', () => {+ const {onMatch, api} = setup({disabledIndices: [0]}); // Apple disabled+ api.onKeyDown(key('a'));+ expect(onMatch).toHaveBeenCalledWith(1); // Apricot+ });++ it('ignores control keys and modifier chords', () => {+ const {onMatch, api} = setup();+ expect(api.onKeyDown(key('ArrowDown'))).toBe(false);+ expect(+ api.onKeyDown(new KeyboardEvent('keydown', {key: 'a', metaKey: true})),+ ).toBe(false);+ expect(onMatch).not.toHaveBeenCalled();+ });++ it('does not treat a bare Space as typeahead', () => {+ const {onMatch, api} = setup();+ expect(api.onKeyDown(key(' '))).toBe(false);+ expect(onMatch).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/hooks/useTypeahead.ts b/packages/core/src/hooks/useTypeahead.tsnew file mode 100644index 0000000000..138cf9b0eb--- /dev/null+++ b/packages/core/src/hooks/useTypeahead.ts@@ -0,0 +1,183 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useTypeahead.ts+ * @input Uses React useCallback/useRef+ * @output Exports useTypeahead hook for first-character (type-to-focus) search+ * @position Core hook; adds APG typeahead to menus, listboxes, and other+ * collections. Composes with useListFocus/useGridFocus (or any collection)+ * via a caller-supplied getItemLabels + onMatch.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/hooks/index.ts+ */++import {useCallback, useRef} from 'react';++export interface UseTypeaheadOptions {+ /**+ * Returns the current, in-DOM-order list of item labels to match against.+ * An entry may be `null`/empty to mark a non-matchable slot (its index is+ * preserved so it maps 1:1 to the caller's items).+ */+ getItemLabels: () => ReadonlyArray<string | null | undefined>;++ /**+ * Called with the index of the matched item so the caller can focus/select+ * it (e.g. `useListFocus`'s `focusItem`).+ */+ onMatch: (index: number) => void;++ /**+ * The index to start searching from — typically the currently focused item,+ * so repeated presses of the same letter cycle through matches. Defaults to+ * -1 (search from the top).+ */+ getCurrentIndex?: () => number;++ /**+ * Milliseconds of inactivity after which the typed buffer resets.+ * @default 750+ */+ resetMs?: number;++ /**+ * Whether an index should be skipped (e.g. disabled items).+ */+ isDisabled?: (index: number) => boolean;+}++export interface UseTypeaheadReturn {+ /**+ * Keydown handler. Call it (or let it fall through) from the collection's+ * own key handler. Returns `true` when it handled a printable character (so+ * the caller can `preventDefault`/stop further handling), `false` otherwise.+ */+ onKeyDown: (e: React.KeyboardEvent | KeyboardEvent) => boolean;+ /** Clear the pending buffer (e.g. on close). */+ reset: () => void;+}++/**+ * Whether a key event represents a single printable character (a type-to-focus+ * candidate) rather than a control/navigation key or a shortcut chord.+ */+function isPrintableCharacter(e: React.KeyboardEvent | KeyboardEvent): boolean {+ return (+ e.key.length === 1 &&+ !e.ctrlKey &&+ !e.metaKey &&+ !e.altKey &&+ // A lone space is used for activation in menus, not typeahead-from-empty.+ e.key !== ' '+ );+}++/**+ * First-character ("type-ahead") search for a collection.+ *+ * Buffers printable keystrokes (resetting after `resetMs` of inactivity),+ * matches items whose label starts with the buffer, and cycles from the+ * current index — so pressing "s" repeatedly walks through the "s" items+ * instead of sticking on the first. Space is reserved for activation and is+ * only treated as typeahead while a buffer is already active.+ *+ * Additive and collection-agnostic: it does not move focus itself; the caller+ * wires `onMatch` to its own focus/selection (e.g. `useListFocus.focusItem`).+ *+ * @example+ * ```+ * const {listRef, handleKeyDown, focusItem, getItems} = useListFocus(...);+ * const typeahead = useTypeahead({+ * getItemLabels: () => getItems().map(el => el.textContent),+ * onMatch: focusItem,+ * getCurrentIndex: () => getItems().findIndex(el => el === document.activeElement),+ * });+ * const onKeyDown = (e) => { if (!typeahead.onKeyDown(e)) handleKeyDown(e); };+ * ```+ */+export function useTypeahead(options: UseTypeaheadOptions): UseTypeaheadReturn {+ const {+ getItemLabels,+ onMatch,+ getCurrentIndex,+ resetMs = 750,+ isDisabled,+ } = options;++ const bufferRef = useRef('');+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(+ undefined,+ );++ const reset = useCallback(() => {+ bufferRef.current = '';+ if (timeoutRef.current) {+ clearTimeout(timeoutRef.current);+ timeoutRef.current = undefined;+ }+ }, []);++ const scheduleReset = useCallback(() => {+ if (timeoutRef.current) {+ clearTimeout(timeoutRef.current);+ }+ timeoutRef.current = setTimeout(() => {+ bufferRef.current = '';+ timeoutRef.current = undefined;+ }, resetMs);+ }, [resetMs]);++ const onKeyDown = useCallback(+ (e: React.KeyboardEvent | KeyboardEvent): boolean => {+ // A bare Space with no active buffer is not typeahead (menus activate on+ // Space); once the user is mid-typing, Space extends the query.+ const isSpaceMidType = e.key === ' ' && bufferRef.current.length > 0;+ if (!isPrintableCharacter(e) && !isSpaceMidType) {+ return false;+ }++ const labels = getItemLabels();+ if (labels.length === 0) {+ return false;+ }++ // Pressing the SAME single character repeatedly cycles to the next match+ // rather than filtering deeper (APG behavior).+ const char = e.key.toLowerCase();+ const isRepeatSameChar =+ bufferRef.current.length > 0 &&+ bufferRef.current.split('').every(c => c === char);+ const nextBuffer = isRepeatSameChar ? char : bufferRef.current + char;+ bufferRef.current = nextBuffer;+ scheduleReset();++ const start = getCurrentIndex?.() ?? -1;+ const count = labels.length;+ // When repeating a single char, start the search AFTER the current item+ // so we advance; otherwise include the current item.+ const offset = isRepeatSameChar ? 1 : 0;++ for (let i = 0; i < count; i++) {+ const index = (start + offset + i + count) % count;+ if (isDisabled?.(index)) {+ continue;+ }+ const label = labels[index];+ if (+ label != null &&+ label.trim().toLowerCase().startsWith(nextBuffer)+ ) {+ onMatch(index);+ return true;+ }+ }+ return true;+ },+ [getItemLabels, onMatch, getCurrentIndex, scheduleReset, isDisabled],+ );++ return {onKeyDown, reset};+}