Skip to content

fix(core): select by typing on a focused Selector (#3764) - #3797

Merged
cixzhang merged 5 commits into
meta:mainfrom
AKnassa:fix/3764-selector-typeahead
Aug 11, 2026
Merged

cixzhang merged 5 commits into
meta:mainfrom
AKnassa:fix/3764-selector-typeahead

Conversation

@AKnassa

@AKnassa AKnassa commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #3764

What this does

You can now pick an option in a Selector just by typing. Focus the dropdown with Tab, press "C", and it selects "CA" — no need to open the menu and hunt for the option first. This is how the browser's own dropdowns have always worked, and Selector now matches that, so it can genuinely replace them.

Why

The person who reported this was building a state picker. They could tab to it, but then had to stop and interact with the menu to choose anything — which makes a form slow to fill in by keyboard and made Selector a poor swap for a native dropdown.

What changed

  • Type to pick. Typing a letter on a closed Selector selects the first matching option. The menu stays shut, just like a native dropdown.
  • Press again to cycle. If several options start with the same letter, pressing it again moves to the next one — Chicago, then Cleveland, then Columbus, then back around.
  • Spaces work. Typing "new y" gets you to "New York" instead of the space opening the menu. The typed text is forgotten after a short pause, so the next thing you type starts fresh.
  • Screen readers hear it. Because the value changes without the menu opening or focus moving, nothing would otherwise announce the new choice — so it's now announced politely.
  • Searchable Selectors too. With a search box enabled, typing on the closed dropdown opens it and drops what you typed straight into the search field, without losing any characters.
  • Selector-only by design. The matching lives in Selector's own use of the shared useTypeahead hook, not in the shared combobox. CommandPalette and MultiSelector get nothing extra, and the palette is already a search input, so it needs no opt-out.

Menu-open behavior is unchanged for the user: typing walks the highlight and Enter confirms. The same shared hook now drives it, moving the highlight via aria-activedescendant.

How to see it

In Storybook, open Core → Selector → Default, click once outside the dropdown, then press Tab to focus it and type a letter. The value changes with the menu closed.

Notes for reviewers

  • Typeahead is a Selector-level composition of the shared useTypeahead hook, run ahead of the combobox key handler. Nothing was added to useCombobox, so CommandPalette and MultiSelector are untouched.
  • Announcements use useAnnounce rather than local live-region state.
  • Adopting the shared hook surfaced and fixed three bugs in it: a single-character search now starts after the current item (native <select> / APG getIndexByLetter); a -1 start no longer wraps onto the last item; and a ctrl/meta-chorded Space no longer appends a raw space that poisons the buffer. DropdownMenu, ContextMenu, and NavHeadingMenu share the hook and benefit.
  • The typeahead anchor and the duplicate-select guard read the optimistic value rather than the raw value prop, so a pending changeAction can't strand cycling on the first match or re-fire the action for a value already committed.
  • The typed-text buffer resets on select, close, and clear, so a stale prefix can't poison the next keystroke.
  • Unit tests cover the closed and open paths, cycling, spaces, disabled-skip, sections, and the shared-hook edge cases (chord-Space, null label slots, stale/negative index).
  • Follow-up, not in this PR: useAnnounce mounts its live region on document.body, so a Selector inside a modal Dialog won't announce — a limitation shared by every current useAnnounce consumer, not specific to this change.

Typing a printable character on a focused, closed Selector did nothing —
the keydown only opened the popup and moved a highlight, so a state picker
could not be driven the way a native <select> can ("C" -> "CA"). Typing on
the closed trigger now commits the matching option without opening the menu.

Repeated presses cycle through options sharing a first letter (wrapping past
the current selection), spaces count as match characters so "new y" reaches
"New York", and the buffer resets after 500ms. Menu-open behavior is
unchanged: typing moves the highlight and Enter commits. With hasSearch,
typing on the closed trigger opens the popup and appends to the search query,
so characters racing the focus handoff are not dropped.

The commit path changes the value without opening the popup or moving focus,
so a polite live region announces the new selection.

useCombobox gains hasTypeahead (default true). CommandPalette passes false:
its own input already filters the items and forwards every keystroke to the
hook, so prefix matching on top of that would drag the highlight — and what
Enter commits — onto a command the user never picked.

The typeahead anchor and duplicate-select guard read the optimistic value
rather than the raw prop, so a pending changeAction cannot strand cycling on
the first match or re-fire the action for a value already committed.

Claude-Session: https://claude.ai/code/session_01LvZ7hEU9jDyeZm4YTStXzt
@vercel

vercel Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
astryx Ready Ready Preview, Comment Jul 27, 2026 1:55am

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 11, 2026
@AKnassa
AKnassa marked this pull request as ready for review July 11, 2026 03:20

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for working on this! I left some comments mainly to reuse existing a11y hooks so we're not applying behaviors inconsistently.

// keystroke here. Prefix typeahead on top of that would chase the same
// text and drag the highlight — and what Enter commits — off the user's
// pick, so the input stays the only thing typing drives.
hasTypeahead: false,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This option probably doesn't make sense for the command palette since it's already a search input form of typeahead so it naturally performs this behavior. We'd only really need the behavior on selectors.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hasTypeahead is gone. Typeahead lives in the shared useTypeahead hook now, so CommandPalette gets it as a search input with no opt-out to carry.

Comment thread packages/core/src/Selector/Selector.tsx Outdated
// Announces a value committed by typing on the closed trigger. That path
// changes the selection without opening the popup or moving focus, so no
// other event prompts assistive tech to re-read the trigger.
const [liveMessage, setLiveMessage] = useState('');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm it can be finicky to manage this manually but using state seems odd. Are you able to use useAnnounce instead?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched to useAnnounce. The liveMessage state and the inline VisuallyHidden region are removed.

Comment thread packages/core/src/Selector/Selector.tsx Outdated
onSelect: useCallback(
(newValue: string) => {
onChange?.(newValue);
if (!popover.isOpen) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm it should be possible to have the typeahead behavior when it's open (it should move focus to the item that matches) so we shouldn't need this gate.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gate removed. Open, it walks the highlight via aria-activedescendant; closed, it commits like a native select. It moves the virtual cursor rather than DOM focus, since the trigger keeps focus and the popup is the role="listbox", so that is the combobox pattern here.

Comment thread packages/core/src/Selector/hooks.ts Outdated
// clearing all end the "word" being typed. Without this, a stale prefix
// survives for up to TYPEAHEAD_RESET_MS and poisons the next keystroke:
// selecting Dog then typing "c" would search for "dc" and match nothing.
const resetTypeahead = useCallback(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we able to reuse useTypeahead instead of rolling something separately?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. The separate matcher is deleted and it composes the shared useTypeahead ahead of the combobox key handler; reset fires on close and on clear so no stale prefix survives. Adopting it surfaced a few off-by-one bugs in the shared hook (single-char offset and the -1 start), fixed in this PR, so DropdownMenu/ContextMenu/NavHeadingMenu benefit too. More detail in the PR description.

@github-actions github-actions Bot added the needs:code-review High-risk change (new package/component/API) — needs human code review before merge label Jul 11, 2026
@github-actions
github-actions Bot requested a review from cixzhang July 11, 2026 18:30
@github-actions github-actions Bot added the community Authored by a community contributor (not on the eng/design team) label Jul 11, 2026
@HelloOjasMutreja

Copy link
Copy Markdown
Contributor

Dug into both open review questions against the current diff — concrete answers on both:

useTypeahead reuse (hooks.ts)

packages/core/src/hooks/useTypeahead.ts already implements almost exactly what findTypeaheadMatch/handleTypeahead roll here: buffered printable-char matching, reset-after-inactivity via a ref+timeout, cycling to the next match on a repeated single character (APG getIndexByLetter behavior), and a caller-supplied isDisabled skip — the same four things this PR's custom version does. The composable shape (onMatch(index), caller decides what to do with it) maps directly onto the open/closed branch this PR needs:

const typeahead = useTypeahead({
  getItemLabels: () => selectableItems.map(i => i.label ?? i.value),
  onMatch: (index) => {
    if (isOpen) {
      setHighlightedIndex(index);
    } else {
      const item = selectableItems[index];
      if (item.value !== value) onSelect?.(item.value);
    }
  },
  getCurrentIndex: () => (isOpen ? highlightedIndex : findSelectedIndex()),
  resetMs: 500, // matches TYPEAHEAD_RESET_MS here today (hook defaults to 750)
  isDisabled: (index) => selectableItems[index]?.disabled,
});

useTypeahead.onKeyDown also already handles the "space mid-buffer extends the query" case internally (isSpaceMidType), so the separate space-handling branch in the outer onKeyDown switch could likely delegate to it too instead of calling handleTypeahead(' ') directly. reset() maps onto the existing resetTypeahead() call sites (Escape, clear, close). Net: this should drop findTypeaheadMatch and most of handleTypeahead's bookkeeping (~50 lines) with no behavior change — the existing typeahead test suite here should keep passing unchanged since it's an internal swap, not a behavior change.

useAnnounce reuse (Selector.tsx)

packages/core/src/hooks/useAnnounce.ts is the existing pattern for exactly this — an imperative announce(message) backed by a singleton, persistently-mounted live region. Its own doc comment calls out why that matters: "many screen readers will not announce content injected into a live region that is created together with its content ('born with content')." The <VisuallyHidden role="status" aria-live="polite">{liveMessage}</VisuallyHidden> mounted here is created alongside its content on first render, which is the exact case that hook exists to avoid. Swapping to useAnnounce() + calling announce(committed.label ?? newValue) in the onSelect closed-trigger branch should be a drop-in replacement for the liveMessage state + the inline live region markup.

Happy to leave this as reference if useful — not trying to take over the branch, just wanted to give the open questions a concrete answer since they'd been sitting a while.

AKnassa added 2 commits July 23, 2026 21:10
Answers the four review threads on meta#3797.

useCombobox no longer implements matching at all: findTypeaheadMatch and
handleTypeahead are deleted and Selector composes the shared useTypeahead
ahead of the combobox key handler, so type-to-select behaves like the other
collections. With nothing left to opt out of, CommandPalette's hasTypeahead
flag goes away too — its own input stays the only thing typing drives.

The gate that limited matching to the closed trigger is gone. Typing with the
menu open now walks the highlight; because the trigger keeps focus and owns
aria-activedescendant here, that is the same model arrow-key navigation
already uses. The hand-rolled liveMessage state and its inline VisuallyHidden
live region are replaced by useAnnounce, called only on the closed-trigger
commit — the one path where nothing else prompts a re-read.

Adopting the shared hook surfaced two matching bugs in it, fixed here, so
DropdownMenu, ContextMenu and NavHeadingMenu benefit as well:

  - A single-character search now starts after the current item, matching a
    native <select> and APG getIndexByLetter. It previously advanced only on
    a repeated press, so pressing a letter the current item already begins
    with was a dead keystroke — one per reset window.
  - getCurrentIndex() returning -1 now really searches from the top. The
    modulo was wrapping it onto the last item instead, which every menu
    caller hits whenever nothing is focused; the hook's own JSDoc already
    documented the behavior now implemented. Selector's clamp workaround for
    this is removed.

Characters composed with Option/Alt (Option+a -> "a-ring") count as typeahead
again; real chords still carry ctrl or meta, and AltGr sets ctrlKey.

Test debt from the rework is paid off: the pending-changeAction test was
vacuous on a two-option fixture, and two more tests rendered an uncontrolled
Selector that pinned the match anchor at 0, so none of them could exercise
the anchor. The buffer reset on clear, and the deliberate silence when
matching with the menu open, had no coverage at all. Every fix here is
mutation-verified — reverting each one makes exactly the intended test fail.
…a#3764)

An edge-case pass over the typeahead rework.

One real bug: a Space chorded with ctrl or meta was consumed mid-buffer and
appended a raw space, poisoning the buffer for the rest of the reset window —
the file's own comment already claimed real chords carry ctrl or meta, and
Space was the one character escaping it. isSpaceMidType now excludes both
modifiers. Space is the only character a chord could not already suppress, so
the fix is one line.

New tests pin the edges the rework leans on:

  useTypeahead — chord-Space rejection (ctrl and meta); a Space extending a
    live buffer (the positive path that had no coverage, which is why the
    chord hole survived); null/empty/whitespace label slots keeping their
    index; a negative sentinel and a stale out-of-range current index never
    searching backwards or reporting out of range; a single-item list.
  Selector — matching keys off the label while committing the value; matching
    across sections while ignoring dividers and group titles; aria-active-
    descendant landing on the match after wrapping into a section; a value
    matching no option staying anchored at the top.
  DropdownMenu — pressing the letter the focused item already begins with
    advances to the next match, pinning the shared-hook offset change at the
    consumer level (red on the parent commit).

Mutation-verified: reverting the offset rule fails the DropdownMenu test,
matching on value fails the label test, weakening the null guard fails the
label-slots test.
@AKnassa

AKnassa commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @HelloOjasMutreja. This is the direction the PR landed on, reusing the shared useTypeahead hook. Kept the 750ms reset (the shared default) rather than 500 so typeahead timing stays consistent across menus and selectors.

…ypeahead

# Conflicts:
#	packages/core/src/Selector/Selector.test.tsx
#	packages/core/src/Selector/Selector.tsx
@github-actions

github-actions Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

🧪 Sandbox Preview

View Sandbox for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

Modified Components

CommandPalette (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 1009 -
Complexity N/A Very High (114) -
DropdownMenu (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 1405 -
Complexity N/A Very High (145) -
Selector (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 1491 -
Complexity N/A Very High (150) -

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.7KB 1.2KB

Accessibility Audit

Status: No accessibility violations detected.


Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks this is looking good now

…eahead

Resolved two test-file conflicts by keeping both sides:
- Selector.test.tsx: kept main's generateThemeTestCSS helper; dropped main's
  duplicate politeRegion() (the PR moved the same helper further down the file).
- CommandPalette.test.tsx: kept the PR's 'does not move the highlight while
  typing' test and main's 'screen reader announcements' describe block.
@vercel

vercel Bot commented Aug 11, 2026

Copy link
Copy Markdown

@cixzhang is attempting to deploy a commit to the Meta Open Source Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions github-actions Bot removed the needs:code-review High-risk change (new package/component/API) — needs human code review before merge label Aug 11, 2026
@cixzhang

Copy link
Copy Markdown
Contributor

Hi @AKnassa — this had drifted ~306 commits behind main and was conflicting, so I merged main into your branch on your behalf to clear it (a merge commit, no rebase and no force-push, so your history is untouched).

Both conflicts were in test files only; production code merged clean:

  • packages/core/src/Selector/Selector.test.tsx — main added a generateThemeTestCSS helper next to a politeRegion() helper, while your branch had moved politeRegion further down the file. Kept main's generateThemeTestCSS and your relocated politeRegion, dropping only the duplicate definition.
  • packages/core/src/CommandPalette/CommandPalette.test.tsx — your "does not move the highlight while typing in the search input" test landed at the same spot as main's new screen reader announcements describe block. Kept both.

Verified on the merged tree: no test cases lost (Selector 108, CommandPalette 20 — the exact union of both sides), tsc --noEmit clean, ESLint clean on the touched files, and 400/400 passing across Selector, useTypeahead, DropdownMenu, CommandPalette, ContextMenu, MultiSelector and NavHeading.

Nothing needed from you — just flagging that the branch moved.

@cixzhang
cixzhang enabled auto-merge (squash) August 11, 2026 02:13
@cixzhang
cixzhang merged commit 4c528d0 into meta:main Aug 11, 2026
17 of 18 checks passed
github-actions Bot added a commit that referenced this pull request Aug 11, 2026
@AKnassa

AKnassa commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core CLA Signed This label is managed by the Meta Open Source bot. community Authored by a community contributor (not on the eng/design team) type:fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Selector component doesn't allow keyboard to select by typing

3 participants