An open source design system that's fully customizable and agent ready
TypeScript
fix(core): select by typing on a focused Selector (#3764) (#3797)
AK4c528d08f7b3
diff --git a/.changeset/selector-typeahead-select.md b/.changeset/selector-typeahead-select.mdnew file mode 100644index 0000000000..5f0387e7ce--- /dev/null+++ b/.changeset/selector-typeahead-select.md@@ -0,0 +1,15 @@+---+'@astryxdesign/core': patch+---++[fix] Selector selects by typing, matching a native select (#3764)++Typing a printable character on a focused, closed Selector now selects the matching option — tab to a state picker, press "C", get "CA" — instead of doing nothing until the menu is opened. Repeated presses cycle through options sharing a first letter, and spaces count as match characters ("new y" reaches "New York"). With the menu open, typing moves the highlight and Enter commits, as before. With `hasSearch`, typing on the closed trigger opens the popup and seeds the search input.++Matching reuses the shared `useTypeahead` hook, so Selector behaves like the other collections (menus, listboxes). Because a match committed from the closed trigger changes the value without opening the popup or moving focus, the new selection is announced through `useAnnounce`.++`useCombobox` no longer implements typeahead itself; callers that want it compose `useTypeahead` and run it ahead of the combobox key handler.++Adopting the shared hook exposed two matching bugs in it, fixed here — so `DropdownMenu`, `ContextMenu` and `NavHeadingMenu` improve too. A single-character search now starts _after_ the current item, as native `<select>` and the APG pattern do, instead of only advancing on a repeated press: pressing a letter that the focused item already begins with used to do nothing at all. And with nothing focused the search now genuinely starts at the top, rather than wrapping onto the last item first. Characters composed with Option/Alt (`Option+a` → "å") count as typeahead again, so accented labels stay reachable.++@AKnassadiff --git a/packages/core/src/CommandPalette/CommandPalette.test.tsx b/packages/core/src/CommandPalette/CommandPalette.test.tsxindex 9231dd236a..06a548b102 100644--- a/packages/core/src/CommandPalette/CommandPalette.test.tsx+++ b/packages/core/src/CommandPalette/CommandPalette.test.tsx@@ -274,6 +274,35 @@ describe('CommandPalette', () => {);});+ it('does not move the highlight while typing in the search input', async () => {+ // The palette's input already filters; letting the shared combobox+ // typeahead also chase prefixes would drag the highlight — and Enter —+ // onto a command the user never picked.+ const gitSource = createStaticSource([+ {id: 'git-add', label: 'git add'},+ {id: 'git-commit', label: 'git commit'},+ {id: 'git-push', label: 'git push'},+ ]);+ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={gitSource}+ />,+ );++ const input = screen.getByRole('combobox');+ await waitFor(() =>+ expect(screen.getByText('git add')).toBeInTheDocument(),+ );++ fireEvent.keyDown(input, {key: 'g'});+ fireEvent.keyDown(input, {key: 'i'});+ fireEvent.keyDown(input, {key: 't'});++ expect(input).not.toHaveAttribute('aria-activedescendant');+ });+describe('screen reader announcements', () => {const politeRegion = () =>document.querySelector('[data-astryx-live-region="polite"]');diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex b2b9091f1f..225d8e4e09 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -265,6 +265,27 @@ describe('DropdownMenu', () => {).toHaveFocus();});+ it('typeahead advances past an item that already starts with the letter', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ items={[{label: 'Copy'}, {label: 'Copy link'}, {label: 'Delete'}]}+ />,+ );+ await user.click(screen.getByRole('button', {name: /Actions/}));+ const menu = screen.getByRole('menu', {hidden: true});+ screen.getByRole('menuitem', {name: 'Copy', hidden: true}).focus();++ fireEvent.keyDown(menu, {key: 'c'});++ // APG: a printable character moves focus to the NEXT item starting with+ // it. Anchoring at the focused item instead makes the press a dead key.+ expect(+ screen.getByRole('menuitem', {name: 'Copy link', 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/Selector/Selector.doc.mjs b/packages/core/src/Selector/Selector.doc.mjsindex 99be8fc423..6183503bab 100644--- a/packages/core/src/Selector/Selector.doc.mjs+++ b/packages/core/src/Selector/Selector.doc.mjs@@ -172,7 +172,7 @@ export const docs = {components: [{name: 'SelectorOption'}],usage: {description:- 'A dropdown selector for choosing a single value from a list of options. Supports labels, validation, descriptions, and required/optional states. Use it in forms and settings when presenting a moderate number of options.',+ 'A dropdown selector for choosing a single value from a list of options. Supports labels, validation, descriptions, and required/optional states. Use it in forms and settings when presenting a moderate number of options. Keyboard typeahead matches a native select: typing on the focused closed trigger selects the matching option directly, repeated presses cycle through options sharing a first letter, and spaces count as match characters ("new y" reaches "New York"). With the menu open, typing moves the highlight and Enter commits. With hasSearch, typing on the closed trigger opens the popup and seeds the search input.',bestPractices: [{guidance: true,@@ -274,7 +274,7 @@ export const docs = {export const docsZh = {usage: {description:- 'A dropdown selector for choosing a single value from a list of options. Supports labels, validation, descriptions, and required/optional states. Use it in forms and settings when presenting a moderate number of options.',+ 'A dropdown selector for choosing a single value from a list of options. Supports labels, validation, descriptions, and required/optional states. Use it in forms and settings when presenting a moderate number of options. Keyboard typeahead matches a native select: typing on the focused closed trigger selects the matching option directly, repeated presses cycle through options sharing a first letter, and spaces count as match characters ("new y" reaches "New York"). With the menu open, typing moves the highlight and Enter commits. With hasSearch, typing on the closed trigger opens the popup and seeds the search input.',bestPractices: [{guidance: true,@@ -366,7 +366,7 @@ export const docsZh = {export const docsDense = {usage: {description:- 'A dropdown selector for choosing a single value from a list of options. Supports labels, validation, descriptions, and required/optional states. Use it in forms and settings when presenting a moderate number of options.',+ 'A dropdown selector for choosing a single value from a list of options. Supports labels, validation, descriptions, and required/optional states. Use it in forms and settings when presenting a moderate number of options. Keyboard typeahead matches a native select: typing on the focused closed trigger selects the matching option directly, repeated presses cycle through options sharing a first letter, and spaces count as match characters ("new y" reaches "New York"). With the menu open, typing moves the highlight and Enter commits. With hasSearch, typing on the closed trigger opens the popup and seeds the search input.',bestPractices: [{guidance: true,diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsxindex 2d9f5f1dc6..476e0b9b3e 100644--- a/packages/core/src/Selector/Selector.test.tsx+++ b/packages/core/src/Selector/Selector.test.tsx@@ -18,6 +18,7 @@ import {within,} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import {useState} from 'react';import {Selector} from './Selector';import {SelectorOption} from './SelectorOption';import {Icon} from '../Icon';@@ -30,12 +31,11 @@ function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {const {prose, component} = generateThemeCSS(theme);return [prose, component].filter(Boolean).join('\n\n');}-function politeRegion(): HTMLElement | null {- return document.querySelector('[data-astryx-live-region="polite"]');-}// Mock showPopover and hidePopover methods since they're not implemented in jsdombeforeEach(() => {+ // The live regions are a document-level singleton; start each test clean.+ __resetLiveRegionsForTest();HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {this.setAttribute('popover-open', '');const event = new Event('toggle', {bubbles: false});@@ -70,6 +70,23 @@ const h = {hidden: true} as const;const OPTIONS = ['Apple', 'Banana', 'Cherry'];+// Mirrors useTypeahead's default resetMs — how long the typed buffer survives.+const TYPEAHEAD_RESET_MS = 750;++const politeRegion = () =>+ document.querySelector('[data-astryx-live-region="polite"]');++/**+ * Type onto an element with no awaits between keystrokes. Typeahead only+ * accumulates while keys land inside the reset window, so an awaited+ * `user.keyboard` per character would put CI stalls on the critical path.+ */+function type(text: string, element: HTMLElement) {+ for (const key of text) {+ fireEvent.keyDown(element, {key});+ }+}+function rect({top,bottom,@@ -1130,6 +1147,532 @@ describe('Selector', () => {});});+ describe('typeahead', () => {+ it('selects the matching option by typing on the closed trigger', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(<Selector label="Fruit" options={OPTIONS} onChange={onChange} />);++ await user.tab();+ await user.keyboard('c');++ expect(onChange).toHaveBeenCalledWith('Cherry');+ // Native select parity: the value changes without opening the menu.+ expect(screen.getByRole('combobox')).toHaveAttribute(+ 'aria-expanded',+ 'false',+ );+ });++ it('cycles through options sharing a first letter on repeated presses', async () => {+ const user = userEvent.setup();+ function Harness() {+ const [value, setValue] = useState<string | undefined>(undefined);+ return (+ <Selector+ label="City"+ options={['Austin', 'Chicago', 'Cleveland', 'Columbus']}+ value={value}+ onChange={setValue}+ />+ );+ }+ render(<Harness />);++ await user.tab();+ await user.keyboard('c');+ expect(screen.getByRole('combobox')).toHaveTextContent('Chicago');+ await user.keyboard('c');+ expect(screen.getByRole('combobox')).toHaveTextContent('Cleveland');+ await user.keyboard('c');+ expect(screen.getByRole('combobox')).toHaveTextContent('Columbus');+ // Wraps back around past non-matching options.+ await user.keyboard('c');+ expect(screen.getByRole('combobox')).toHaveTextContent('Chicago');+ });++ it('advances past the current selection on a fresh single-letter press', async () => {+ const user = userEvent.setup();+ function Harness() {+ const [value, setValue] = useState<string | undefined>('Chicago');+ return (+ <Selector+ label="City"+ options={['Austin', 'Chicago', 'Cleveland', 'Columbus']}+ value={value}+ onChange={setValue}+ />+ );+ }+ render(<Harness />);++ const trigger = screen.getByRole('combobox');+ await user.tab();+ // Native select parity: the selected option's own initial moves on to+ // the next match. Anchoring the search AT the selection instead of after+ // it re-matches the current value, and the duplicate-select guard then+ // swallows the keystroke entirely.+ type('c', trigger);++ expect(trigger).toHaveTextContent('Cleveland');+ });++ it('advances the highlight past the current one with the menu open', async () => {+ const user = userEvent.setup();+ render(+ <Selector+ label="City"+ options={['Austin', 'Chicago', 'Cleveland', 'Columbus']}+ value="Chicago"+ onChange={() => {}}+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.tab();+ await user.keyboard('{Enter}'); // opens with the highlight on Chicago+ type('c', trigger);++ const activeId = trigger.getAttribute('aria-activedescendant');+ expect(document.getElementById(activeId ?? '')).toHaveTextContent(+ 'Cleveland',+ );+ });++ it('treats a space mid-buffer as part of the match, not as open', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <Selector+ label="State"+ options={['New Jersey', 'New York']}+ onChange={onChange}+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.tab();+ // Synchronous keydowns: the buffer only accumulates while keystrokes+ // land inside the TYPEAHEAD_RESET_MS window, and awaiting between them+ // would put a CI stall on the critical path.+ type('new y', trigger);++ expect(onChange).toHaveBeenLastCalledWith('New York');+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });++ it('opens and seeds the search input when typing on a closed hasSearch trigger', async () => {+ const user = userEvent.setup();+ render(<Selector label="Fruit" options={OPTIONS} hasSearch />);++ await user.tab();+ await user.keyboard('c');++ const search = screen.getByPlaceholderText('Search…');+ expect(search).toHaveValue('c');+ await waitFor(() => expect(search).toHaveFocus());+ });++ it('accumulates a multi-character prefix and resets it after the timeout', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ // Controlled: the committed value has to feed back in, or the match+ // anchor stays -1 for the whole test and never gets exercised.+ function Harness() {+ const [value, setValue] = useState<string | undefined>(undefined);+ return (+ <Selector+ label="Fruit"+ options={['Apple', 'Banana', 'Blueberry']}+ value={value}+ onChange={next => {+ setValue(next);+ onChange(next);+ }}+ />+ );+ }+ render(<Harness />);++ const trigger = screen.getByRole('combobox');+ await user.tab();+ type('b', trigger);+ expect(trigger).toHaveTextContent('Banana');+ // Within the window the buffer accumulates: "bl" → Blueberry. A+ // multi-character buffer refines, so it may keep the current match.+ type('l', trigger);+ expect(trigger).toHaveTextContent('Blueberry');++ // Past the window the buffer starts fresh: "a" → Apple. A surviving+ // buffer would search "bla" and match nothing, so only a real reset+ // gets here — worth the one real wait in the suite.+ await new Promise(resolve =>+ setTimeout(resolve, TYPEAHEAD_RESET_MS + 100),+ );+ type('a', trigger);+ expect(trigger).toHaveTextContent('Apple');+ });++ it('skips disabled options when matching', async () => {+ const user = userEvent.setup();+ function Harness() {+ const [value, setValue] = useState<string | undefined>(undefined);+ return (+ <Selector+ label="Fruit"+ options={[{value: 'Cherry', disabled: true}, 'Coconut']}+ value={value}+ onChange={setValue}+ />+ );+ }+ render(<Harness />);++ const trigger = screen.getByRole('combobox');+ await user.tab();+ type('c', trigger);+ expect(trigger).toHaveTextContent('Coconut');++ // The skip has to survive cycling too: with Coconut current, the next+ // press wraps onto the disabled Cherry and must pass over it.+ type('c', trigger);+ expect(trigger).toHaveTextContent('Coconut');+ expect(trigger).not.toHaveTextContent('Cherry');+ });++ it('moves the highlight without committing when typing with the menu open', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <Selector+ label="City"+ options={['Austin', 'Chicago', 'Cleveland']}+ onChange={onChange}+ />,+ );++ await user.tab();+ await user.keyboard('{Enter}'); // open+ const trigger = screen.getByRole('combobox');++ await user.keyboard('c');+ let activeId = trigger.getAttribute('aria-activedescendant');+ expect(document.getElementById(activeId ?? '')).toHaveTextContent(+ 'Chicago',+ );++ // Repeated press cycles the highlight, still without committing.+ await user.keyboard('c');+ activeId = trigger.getAttribute('aria-activedescendant');+ expect(document.getElementById(activeId ?? '')).toHaveTextContent(+ 'Cleveland',+ );+ expect(onChange).not.toHaveBeenCalled();+ // aria-activedescendant already announces each match, so announcing+ // again here would make a screen reader say every match twice.+ // useAnnounce writes its text in a rAF callback, so let a frame pass —+ // asserting before it runs would pass no matter what the code does.+ await new Promise(resolve => requestAnimationFrame(() => resolve(null)));+ expect(politeRegion()?.textContent ?? '').toBe('');++ await user.keyboard('{Enter}');+ expect(onChange).toHaveBeenCalledWith('Cleveland');+ });++ it('does not fire onChange when the only match is already selected', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <Selector+ label="Fruit"+ options={OPTIONS}+ value="Cherry"+ onChange={onChange}+ />,+ );++ await user.tab();+ await user.keyboard('c');++ expect(onChange).not.toHaveBeenCalled();+ });++ it('ignores printable keys pressed with ctrl or meta modifiers', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(<Selector label="Fruit" options={OPTIONS} onChange={onChange} />);++ await user.tab();+ await user.keyboard('{Control>}c{/Control}{Meta>}b{/Meta}');++ expect(onChange).not.toHaveBeenCalled();+ });++ it('announces the committed option to screen readers', async () => {+ const user = userEvent.setup();+ render(<Selector label="Fruit" options={OPTIONS} onChange={() => {}} />);++ await user.tab();+ await user.keyboard('c');++ // The trigger keeps focus and the menu never opens, so nothing else+ // prompts a re-read. The polite live region carries the new value.+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Cherry');+ });+ });++ it('does not select while focusable-disabled', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <Selector+ label="Fruit"+ options={OPTIONS}+ onChange={onChange}+ isDisabled+ disabledMessage="Ask an admin"+ />,+ );++ // aria-disabled keeps the trigger focusable, so keydowns still arrive.+ screen.getByRole('combobox').focus();+ await user.keyboard('c');++ expect(onChange).not.toHaveBeenCalled();+ });++ it('cycles without duplicating changeAction while an action is pending', async () => {+ const user = userEvent.setup();+ const calls: string[] = [];+ render(+ <Selector+ label="City"+ options={['Chicago', 'Cleveland', 'Columbus']}+ value={undefined}+ changeAction={async value => {+ calls.push(value);+ // Never settles, so the value prop never catches up to what the+ // trigger already shows.+ await new Promise<void>(() => {});+ }}+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.tab();+ type('ccc', trigger);++ // The anchor must come from the optimistic value, not the stale prop.+ // Three options make that observable: with a stale anchor every press+ // re-matches Chicago, which the duplicate guard then swallows.+ expect(calls).toEqual(['Chicago', 'Cleveland', 'Columbus']);+ });++ it('starts a fresh buffer after selecting from the open menu', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <Selector+ label="Animal"+ options={['Cat', 'Dog']}+ onChange={onChange}+ />,+ );++ await user.tab();+ await user.keyboard('{Enter}'); // open+ await user.keyboard('d'); // highlight Dog+ await user.keyboard('{Enter}'); // commit Dog, closes+ onChange.mockClear();++ // The stale 'd' must not linger: 'c' is a fresh buffer, not "dc".+ await user.keyboard('c');+ expect(onChange).toHaveBeenCalledWith('Cat');+ });++ it('starts a fresh buffer after the value is cleared', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ function Harness() {+ const [value, setValue] = useState<string | null>('Dog');+ return (+ <Selector+ label="Animal"+ options={['Cat', 'Dog']}+ hasClear+ value={value}+ onChange={next => {+ setValue(next);+ onChange(next);+ }}+ />+ );+ }+ render(<Harness />);++ const trigger = screen.getByRole('combobox');+ await user.tab();+ // Fills the buffer with 'd' without committing — Dog is already current.+ type('d', trigger);+ fireEvent.keyDown(trigger, {key: 'Delete'});+ expect(onChange).toHaveBeenLastCalledWith(null);++ // The stale 'd' must not survive the clear: 'c' is a fresh buffer, not+ // "dc", which would match nothing and leave the value cleared.+ type('c', trigger);+ expect(onChange).toHaveBeenLastCalledWith('Cat');+ });++ it('matches on the label and commits the value', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ // Values deliberately crossed against labels: a native select matches+ // the rendered text and reports the value.+ function Harness() {+ const [value, setValue] = useState<string | undefined>(undefined);+ return (+ <Selector+ label="Fruit"+ options={[+ {value: 'zzz', label: 'Apple'},+ {value: 'apple', label: 'Zebra'},+ ]}+ value={value}+ onChange={next => {+ setValue(next);+ onChange(next);+ }}+ />+ );+ }+ render(<Harness />);++ const trigger = screen.getByRole('combobox');+ await user.tab();+ type('a', trigger);++ expect(onChange).toHaveBeenCalledWith('zzz');+ expect(trigger).toHaveTextContent('Apple');++ // No other label starts with "a" — the option whose *value* is 'apple'+ // is labelled Zebra — so a second press stays put and commits nothing.+ type('a', trigger);+ expect(onChange).toHaveBeenCalledTimes(1);+ });++ it('matches across sections, ignoring dividers and group titles', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <Selector+ label="Fruit"+ options={[+ 'Almond',+ {type: 'divider'},+ {+ type: 'section',+ title: 'Tropical',+ options: [+ {value: 'mango', label: 'Mango'},+ {value: 'papaya', label: 'Papaya'},+ ],+ },+ ]}+ onChange={onChange}+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.tab();+ type('p', trigger);+ expect(onChange).toHaveBeenCalledWith('papaya');++ // The section title "Tropical" is decoration, not an option.+ onChange.mockClear();+ type('t', trigger);+ expect(onChange).not.toHaveBeenCalled();+ });++ it('keeps aria-activedescendant on the matched option across a section', async () => {+ const user = userEvent.setup();+ render(+ <Selector+ label="Fruit"+ options={[+ 'Almond',+ {type: 'divider'},+ {+ type: 'section',+ title: 'Berries',+ options: [{value: 'blueberry', label: 'Blueberry'}],+ },+ ]}+ value="Almond"+ onChange={() => {}}+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.tab();+ await user.keyboard('{Enter}'); // opens on Almond+ type('b', trigger);++ const activeId = trigger.getAttribute('aria-activedescendant');+ expect(document.getElementById(activeId ?? '')).toHaveTextContent(+ 'Blueberry',+ );+ });++ it('anchors at the top when the value matches no option', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <Selector+ label="Fruit"+ options={['Apple', 'Apricot']}+ value="Durian"+ onChange={onChange}+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.tab();+ type('a', trigger);++ // Nothing is really selected, so the first match must stay reachable.+ expect(onChange).toHaveBeenCalledWith('Apple');+ });++ it('lets Space open the menu after an abandoned typeahead', async () => {+ const user = userEvent.setup();+ render(<Selector label="Fruit" options={OPTIONS} />);++ const trigger = screen.getByRole('combobox');+ await user.tab();+ await user.keyboard('{Enter}'); // open+ await user.keyboard('z'); // no match; buffer holds "z"+ await user.keyboard('{Escape}'); // close, abandoning the buffer++ // A live "z" buffer would swallow Space as a match character.+ await user.keyboard(' ');+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ });++ it('seeds every character typed before the search input takes focus', async () => {+ const user = userEvent.setup();+ render(<Selector label="Fruit" options={OPTIONS} hasSearch />);++ await user.tab();+ // The popup opens on the first key, but focus only moves to the search+ // input on the next frame — the second key still lands on the trigger.+ await user.keyboard('ch');++ const search = screen.getByPlaceholderText('Search…');+ await waitFor(() => expect(search).toHaveValue('ch'));+ });+ });+describe('InputGroup integration', () => {it('uses the group Field chrome and composes group and selector labels', () => {render(diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex 7fa88d06a5..1acafe2f4a 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -67,6 +67,7 @@ import {getSelectableOptions,} from './utils';import {useCombobox, useSelectedItemOffset} from './hooks';+import {useTypeahead} from '../hooks/useTypeahead';import {SelectorOption} from './SelectorOption';import {getInputARIA, mergeProps} from '../utils';import {useSize} from '../SizeContext/SizeContext';@@ -726,6 +727,7 @@ export function Selector<T extends SelectorOptionType>(const [, startTransition] = useTransition();const [optimisticValue, setOptimisticValue] = useOptimistic(normalizedValue);const isBusy = isLoading || optimisticValue !== normalizedValue;+ const announce = useAnnounce();// Disabled-reason tooltip. Disabled controls swallow pointer events, so the// tooltip listeners attach to the trigger container (which already exists)@@ -786,15 +788,15 @@ export function Selector<T extends SelectorOptionType>(// Ref for listbox to measure selected item positionconst listboxRef = useRef<HTMLDivElement>(null);- // Announce match counts / "No results found" politely as the user types, so- // screen-reader users hear how many options remain. Filtering was previously- // silent (comboboxes-7). Mirrors BaseTypeahead, which announces from its- // query-change callback (not a reactive effect) via the same useAnnounce hook.- const announce = useAnnounce();+ // Typeahead is defined below (it needs the popover), but closing and clearing+ // must drop its pending buffer — otherwise a stale prefix survives the reset+ // window and poisons the next keystroke ("Dog" then "c" would search "dc").+ const resetTypeaheadRef = useRef<() => void>(() => {});// Layer for dropdown positioningconst handleLayerHide = useCallback(() => {setSearchQuery('');+ resetTypeaheadRef.current();// Clear any lingering result count when the popover closes so stale status// text does not linger in the a11y tree.announce('');@@ -865,6 +867,7 @@ export function Selector<T extends SelectorOptionType>(// Clear the current value. Shared by the clear button and the keyboard// Delete/Backspace path so clearing is reachable without a mouse.const clearValue = useCallback(() => {+ resetTypeaheadRef.current();onChange?.(null);if (changeAction) {startTransition(async () => {@@ -874,10 +877,29 @@ export function Selector<T extends SelectorOptionType>(}}, [onChange, changeAction, startTransition, setOptimisticValue]);- // Selector behavior (keyboard nav, typeahead, selection)+ // Type-to-find appends to the query rather than replacing it: characters+ // typed before focus reaches the search input must not be dropped.+ const appendSearchQuery = useCallback((char: string) => {+ setSearchQuery(query => query + char);+ }, []);++ const commitValue = useCallback(+ (newValue: string) => {+ onChange?.(newValue);+ if (changeAction) {+ startTransition(async () => {+ setOptimisticValue(newValue);+ await changeAction(newValue);+ });+ }+ },+ [onChange, changeAction, startTransition, setOptimisticValue],+ );++ // Selector behavior (keyboard nav, selection)const {highlightedIndex,- setHighlightedIndex: _setHighlightedIndex,+ setHighlightedIndex,getItemId,onTriggerClick,onKeyDown,@@ -885,7 +907,11 @@ export function Selector<T extends SelectorOptionType>(onItemMouseEnter,} = useCombobox({selectableItems: filteredItems,- value: normalizedValue,+ // The optimistic value, not the raw prop: with a pending changeAction the+ // prop still holds the old selection, so the popup would open with the+ // highlight on it and Delete/Backspace could clear a value the action has+ // already replaced.+ value: optimisticValue,isDisabled,isOpen: popover.isOpen,hasSearch,@@ -893,27 +919,61 @@ export function Selector<T extends SelectorOptionType>(popover.show();if (hasSearch) {requestAnimationFrame(() => {- searchRef.current?.focus();+ const input = searchRef.current;+ if (input) {+ input.focus();+ // When typing seeded the query, place the caret after it so the+ // user keeps typing where they left off.+ input.setSelectionRange(input.value.length, input.value.length);+ }});}}, [popover, hasSearch]),onClose: popover.hide,- onSelect: useCallback(- (newValue: string) => {- onChange?.(newValue);- if (changeAction) {- startTransition(async () => {- setOptimisticValue(newValue);- await changeAction(newValue);- });- }- },- [onChange, changeAction, startTransition, setOptimisticValue],- ),+ onSelect: commitValue,onClear: hasClear ? clearValue : undefined,+ onSearchSeed: appendSearchQuery,listboxId,});+ // Type-to-select, shared with the other collections (menus, listboxes).+ // Open, it walks the highlight — aria-activedescendant announces each match.+ // Closed, it commits the match like a native select, which changes the value+ // without opening the popup or moving focus, so nothing else would prompt+ // assistive tech to re-read the trigger: announce it explicitly.+ const typeahead = useTypeahead({+ getItemLabels: () => selectableItems.map(item => item.label ?? item.value),+ isDisabled: index => selectableItems[index]?.disabled === true,+ // Cycle onward from the highlight when open, from the committed selection+ // when closed — the optimistic one, so a pending changeAction cannot strand+ // cycling on the first match. -1 means nothing is selected or highlighted,+ // which the hook reads as "search from the top".+ getCurrentIndex: () =>+ popover.isOpen ? highlightedIndex : selectedItemIndex,+ onMatch: index => {+ const item = selectableItems[index];+ if (popover.isOpen) {+ setHighlightedIndex(index);+ } else if (item.value !== optimisticValue) {+ commitValue(item.value);+ announce(item.label ?? item.value);+ }+ },+ });+ resetTypeaheadRef.current = typeahead.reset;++ const handleTriggerKeyDown = useCallback(+ (e: React.KeyboardEvent) => {+ // With hasSearch the query input owns typing, so type-to-select is off.+ if (!isDisabled && !hasSearch && typeahead.onKeyDown(e)) {+ e.preventDefault();+ return;+ }+ onKeyDown(e);+ },+ [isDisabled, hasSearch, typeahead, onKeyDown],+ );+// Keep the highlighted option visible during keyboard navigation. The// listbox is a fixed-height scroll container, so without this the virtual// cursor walks off-screen once navigation passes the visible window. Mirrors@@ -1243,7 +1303,7 @@ export function Selector<T extends SelectorOptionType>(// still blocked by the isDisabled guards in useCombobox.disabled={isDisabled && !showsDisabledMessage}aria-disabled={showsDisabledMessage ? 'true' : undefined}- onKeyDown={onKeyDown}+ onKeyDown={handleTriggerKeyDown}tabIndex={isDisabled && !showsDisabledMessage ? -1 : 0}{...stylex.props(styles.trigger)}><span {...stylex.props(styles.triggerLabel)}>diff --git a/packages/core/src/Selector/hooks.ts b/packages/core/src/Selector/hooks.tsindex c5aab582fe..f5f467c489 100644--- a/packages/core/src/Selector/hooks.ts+++ b/packages/core/src/Selector/hooks.ts@@ -10,7 +10,7 @@* @position Internal hooks; used by Selector.tsx*/-import {useCallback, useRef, useState} from 'react';+import {useCallback, useState} from 'react';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import type {RefObject} from 'react';import type {SelectorOptionData} from './types';@@ -150,7 +150,7 @@ export function useSelectedItemOffset({}// =============================================================================-// useCombobox - Keyboard navigation, typeahead, and selection+// useCombobox - Keyboard navigation and selection// =============================================================================interface UseComboboxOptions {@@ -169,6 +169,13 @@ interface UseComboboxOptions {* navigation owns those keys there) or when there is no value.*/onClear?: () => void;+ /**+ * With `hasSearch`, printable characters typed on the trigger are appended to+ * the search query (opening the popup if needed), so type-to-find works+ * without a separate open step. Characters keep arriving here until focus+ * lands in the search input, which then owns its own typing.+ */+ onSearchSeed?: (char: string) => void;listboxId: string;}@@ -183,7 +190,12 @@ interface UseComboboxResult {}/**- * Handles keyboard navigation, typeahead search, and selection for combobox/listbox patterns.+ * Handles keyboard navigation and selection for combobox/listbox patterns.+ *+ * Type-to-select is not handled here: callers that want it compose the shared+ * `useTypeahead` hook and run it ahead of this handler (see Selector). That+ * keeps matching consistent with the other collections and leaves consumers+ * whose own input already filters the items (CommandPalette) untouched.*/export function useCombobox({selectableItems,@@ -195,13 +207,10 @@ export function useCombobox({onClose,onSelect,onClear,+ onSearchSeed,listboxId,}: UseComboboxOptions): UseComboboxResult {const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);- const [typeahead, setTypeahead] = useState('');- const typeaheadTimeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(- undefined,- );const getItemId = useCallback((index: number) => `${listboxId}-item-${index}`,@@ -298,6 +307,8 @@ export function useCombobox({if (hasSearch) {break;}+ // A space mid-typeahead extends the query instead of activating; the+ // caller's useTypeahead claims it before this handler ever runs.// falls throughcase 'Enter':e.preventDefault();@@ -373,28 +384,20 @@ export function useCombobox({break;default:- if (!hasSearch && e.key.length === 1 && !e.ctrlKey && !e.metaKey) {- const newTypeahead = typeahead + e.key.toLowerCase();- setTypeahead(newTypeahead);-- if (typeaheadTimeoutRef.current) {- clearTimeout(typeaheadTimeoutRef.current);- }- typeaheadTimeoutRef.current = setTimeout(() => {- setTypeahead('');- }, 500);-- const matchIndex = selectableItems.findIndex(- item =>- !item.disabled &&- item.label?.toLowerCase().startsWith(newTypeahead),- );- if (matchIndex >= 0) {- if (!isOpen) {- onOpen();- }- setHighlightedIndex(matchIndex);+ // Keys land here only while the trigger holds focus — once the search+ // input takes over it handles its own typing — so they belong in the+ // query, including the ones racing the open.+ if (+ hasSearch &&+ onSearchSeed &&+ e.key.length === 1 &&+ !e.ctrlKey &&+ !e.metaKey+ ) {+ if (!isOpen) {+ onOpen();}+ onSearchSeed(e.key);}break;}@@ -409,9 +412,9 @@ export function useCombobox({selectItem,findSelectedIndex,getEnabledIndices,- typeahead,hasSearch,onClear,+ onSearchSeed,value,],);diff --git a/packages/core/src/hooks/useTypeahead.test.tsx b/packages/core/src/hooks/useTypeahead.test.tsxindex f8ed187f1c..51c527d87f 100644--- a/packages/core/src/hooks/useTypeahead.test.tsx+++ b/packages/core/src/hooks/useTypeahead.test.tsx@@ -106,4 +106,154 @@ describe('useTypeahead', () => {expect(api.onKeyDown(key(' '))).toBe(false);expect(onMatch).not.toHaveBeenCalled();});++ it('extends a live buffer with a space', () => {+ const onMatch = vi.fn();+ const {result} = renderHook(() =>+ useTypeahead({+ getItemLabels: () => ['Newark', 'New York'],+ onMatch,+ }),+ );+ for (const k of 'new ') {+ result.current.onKeyDown(key(k));+ }+ result.current.onKeyDown(key('y'));+ // "new y" reaches New York; a space that ended the buffer instead would+ // leave "newy", which matches nothing.+ expect(onMatch).toHaveBeenLastCalledWith(1);+ });++ it('ignores a Space chorded with ctrl or meta even mid-buffer', () => {+ const onMatch = vi.fn();+ const {result} = renderHook(() =>+ useTypeahead({+ getItemLabels: () => ['Melon', 'New York'],+ onMatch,+ }),+ );+ expect(result.current.onKeyDown(key('n'))).toBe(true);+ expect(onMatch).toHaveBeenLastCalledWith(1);++ // A chord is not typing. Consuming it would append a raw space and leave+ // the buffer as "n ", poisoning every keystroke until the reset window.+ expect(+ result.current.onKeyDown(+ new KeyboardEvent('keydown', {key: ' ', ctrlKey: true}),+ ),+ ).toBe(false);+ expect(+ result.current.onKeyDown(+ new KeyboardEvent('keydown', {key: ' ', metaKey: true}),+ ),+ ).toBe(false);++ result.current.onKeyDown(key('e'));+ expect(onMatch).toHaveBeenCalledTimes(2);+ expect(onMatch).toHaveBeenLastCalledWith(1);+ });++ it('starts a fresh single-character search after the current item', () => {+ const {onMatch, api} = setup({current: 0}); // Apple is current+ api.onKeyDown(key('a'));+ // A single-character search begins at current + 1, so pressing the current+ // item's own initial advances instead of re-matching it into a dead key.+ expect(onMatch).toHaveBeenCalledWith(1); // Apricot+ });++ it('searches from the top when there is no current item', () => {+ // The last item also matches, so this distinguishes "from the top" from+ // wrapping backwards off -1 and hitting the bottom of the list first.+ const onMatch = vi.fn();+ const {result} = renderHook(() =>+ useTypeahead({+ getItemLabels: () => ['Apple', 'Berry', 'Avocado'],+ onMatch,+ getCurrentIndex: () => -1,+ }),+ );+ result.current.onKeyDown(key('a'));+ expect(onMatch).toHaveBeenCalledWith(0); // Apple, not Avocado+ });++ it('keeps the current item in range once the buffer is multi-character', () => {+ const {onMatch, api} = setup({current: 0});+ api.onKeyDown(key('a')); // single char: advances to Apricot+ expect(onMatch).toHaveBeenLastCalledWith(1);+ api.onKeyDown(key('p')); // "ap" refines, so Apple is a candidate again+ expect(onMatch).toHaveBeenLastCalledWith(0);+ });++ it('skips unmatchable label slots without shifting the reported index', () => {+ // Callers may pass null/empty entries to keep the index mapping 1:1 with+ // their own items — menus pass el.textContent, which can be null.+ const onMatch = vi.fn();+ const {result} = renderHook(() =>+ useTypeahead({+ getItemLabels: () => [null, '', ' ', undefined, 'Apple'],+ onMatch,+ }),+ );+ result.current.onKeyDown(key('a'));+ expect(onMatch).toHaveBeenCalledWith(4);+ });++ it('treats any negative or stale current index safely', () => {+ // A sentinel other than -1, and an index left over from a longer list:+ // neither may search backwards or report an index outside the list.+ const fromBelowZero = vi.fn();+ const {result: below} = renderHook(() =>+ useTypeahead({+ getItemLabels: () => LABELS,+ onMatch: fromBelowZero,+ getCurrentIndex: () => -5,+ }),+ );+ below.current.onKeyDown(key('a'));+ expect(fromBelowZero).toHaveBeenCalledWith(0); // Apple, from the top++ const fromStale = vi.fn();+ const {result: stale} = renderHook(() =>+ useTypeahead({+ getItemLabels: () => LABELS,+ onMatch: fromStale,+ getCurrentIndex: () => 7,+ }),+ );+ stale.current.onKeyDown(key('b'));+ expect(fromStale).toHaveBeenCalledWith(2); // Banana, in range+ });++ it('wraps onto the only item when the list has one entry', () => {+ // "Advance past the current item" is about cycling; with one item the+ // cycle is itself. The caller decides whether that is a no-op.+ const onMatch = vi.fn();+ const {result} = renderHook(() =>+ useTypeahead({+ getItemLabels: () => ['Apple'],+ onMatch,+ getCurrentIndex: () => 0,+ }),+ );+ expect(result.current.onKeyDown(key('a'))).toBe(true);+ expect(onMatch).toHaveBeenCalledWith(0);+ });++ it('matches characters composed with Option/Alt', () => {+ const onMatch = vi.fn();+ const {result} = renderHook(() =>+ useTypeahead({+ getItemLabels: () => ['Ångström', 'Berlin'],+ onMatch,+ getCurrentIndex: () => -1,+ }),+ );+ // Option+a on macOS emits a printable 'å' with altKey set. Excluding it+ // makes accented labels untypeable; real chords still carry ctrl/meta.+ const handled = result.current.onKeyDown(+ new KeyboardEvent('keydown', {key: 'å', altKey: true}),+ );+ expect(handled).toBe(true);+ expect(onMatch).toHaveBeenCalledWith(0);+ });});diff --git a/packages/core/src/hooks/useTypeahead.ts b/packages/core/src/hooks/useTypeahead.tsindex 138cf9b0eb..0e40d6e26f 100644--- a/packages/core/src/hooks/useTypeahead.ts+++ b/packages/core/src/hooks/useTypeahead.ts@@ -32,8 +32,9 @@ export interface UseTypeaheadOptions {/*** 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).+ * so repeated presses of the same letter cycle through matches. Any negative+ * value (the default) means nothing is current: the search runs from the top+ * and never skips the first item.*/getCurrentIndex?: () => number;@@ -67,9 +68,12 @@ export interface UseTypeaheadReturn {function isPrintableCharacter(e: React.KeyboardEvent | KeyboardEvent): boolean {return (e.key.length === 1 &&+ // Alt alone is not excluded: Option+letter on macOS composes a printable+ // character (Option+a → "å"), and dropping those makes accented labels+ // untypeable. Real chords still carry ctrl or meta — including AltGr,+ // which sets ctrlKey on Windows and Linux.!e.ctrlKey &&!e.metaKey &&- !e.altKey &&// A lone space is used for activation in menus, not typeahead-from-empty.e.key !== ' ');@@ -133,8 +137,14 @@ export function useTypeahead(options: UseTypeaheadOptions): UseTypeaheadReturn {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;+ // Space); once the user is mid-typing, Space extends the query. Chorded+ // with ctrl or meta it is neither — that is an OS or IME shortcut, and+ // consuming it would append a raw space that poisons the whole buffer.+ const isSpaceMidType =+ e.key === ' ' &&+ !e.ctrlKey &&+ !e.metaKey &&+ bufferRef.current.length > 0;if (!isPrintableCharacter(e) && !isSpaceMidType) {return false;}@@ -154,11 +164,16 @@ export function useTypeahead(options: UseTypeaheadOptions): UseTypeaheadReturn {bufferRef.current = nextBuffer;scheduleReset();- const start = getCurrentIndex?.() ?? -1;+ const current = 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;+ const hasCurrent = current >= 0;+ const start = hasCurrent ? current : 0;+ // A single-character search starts AFTER the current item, so pressing a+ // letter walks to the next item beginning with it instead of re-matching+ // the one already selected (native <select> and APG getIndexByLetter).+ // Once the buffer is longer it is refining a match, so the current item+ // stays in range. With nothing current there is nothing to advance past.+ const offset = hasCurrent && nextBuffer.length === 1 ? 1 : 0;for (let i = 0; i < count; i++) {const index = (start + offset + i + count) % count;