Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(Typeahead, Tokenizer): a press in the field's own input or buttons keeps the list open (#9367)

Cindy Zhanga4226c9a22cc
diff --git a/.changeset/typeahead-input-press-keeps-list.md b/.changeset/typeahead-input-press-keeps-list.md
new file mode 100644
index 0000000000..8c0d526be1
--- /dev/null
+++ b/.changeset/typeahead-input-press-keeps-list.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A press in a Typeahead's or Tokenizer's own text input, or on its buttons, no longer closes its open list. Clicking between two letters to fix a typo moves the caret and keeps the matches showing; a press anywhere else on the page still closes the list, and Escape still does.
+
+@duytbp
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 93d91fcded..1daad1a5c6 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -297,6 +297,15 @@ during a press so native light dismissal does not mistake them for outside
interaction. Their click action is cancelled as an invoker toggle so the control
can perform its own action without closing the layer.
+A text input cannot be an invoker, so BaseTypeahead's list, which its text field
+owns, is a manual popover. A press that starts and ends on the field's input or
+its buttons, or in the list, is inside, judged across open shadow roots; a press
+that starts and ends anywhere else closes the list, a scroll or pinch that
+starts outside does not, and Escape stays on the shared stack. Implementation
+gap: DateTimeInput's time list, DateInput's calendar and ChatComposerInput's
+trigger menu are still auto popovers with native light dismiss, so a press in
+their own text input closes them.
+
### Current dismissal plumbing
`family:overlay-dismissal` owns the shipped Escape/platform-close membership
@@ -321,6 +330,9 @@ Outside interaction is not coordinated by the shared stack. Current paths are
independent:
- auto popovers use native light dismiss;
+- BaseTypeahead's list, a manual popover, uses Layer's outside-press watch,
+ which closes on a press that starts and ends outside the field and the list
+ and forgets a cancelled press (a scroll);
- native dialogs handle backdrop clicks locally;
- ContextMenu uses a local outside `mousedown` listener, which skips the
compatibility mouse events of the finger press that opened the menu;
@@ -603,6 +615,8 @@ above are the stack's, the mounting under them is this gap's.
menu focus, and exposure-induced re-hover suppression.
- `Layer/useTouchTrigger.ts` owns touch trigger classification and the current
touch-only outside listener for Tooltip/HoverCard.
+- `Layer/outsidePress.ts` owns the outside-press watch for a text field's
+ manual layer, used by BaseTypeahead.
- `DropdownMenuContext` and `DropdownMenuSubMenu` own the current local
menu-cascade parent-close chain.
- Dialog families own native modal/backdrop presentation and their local channel
diff --git a/docs/specs/components/Tokenizer/Tokenizer.spec.md b/docs/specs/components/Tokenizer/Tokenizer.spec.md
index 7297ea5209..a8484c39d0 100644
--- a/docs/specs/components/Tokenizer/Tokenizer.spec.md
+++ b/docs/specs/components/Tokenizer/Tokenizer.spec.md
@@ -193,7 +193,7 @@ it does not become an element or geometry escape hatch.
Each requirement identifies its basis. This current record defines the approved
package-internal contract while implementation and focused verification remain
-pending. FR1–FR15 describe the `popover` presentation, the inline combobox;
+pending. FR1–FR15 and FR25 describe the `popover` presentation, the inline combobox;
FR16–FR24 describe the `experimental.presentation` option and its sheet
presentation, which has no inline combobox, suggestion menu, or end lane.
@@ -223,6 +223,7 @@ presentation, which has no inline combobox, suggestion menu, or end lane.
| FR22 | With `hasCreate`, a non-empty trimmed query that matches no selected id, no selected label, and no result label (case-insensitive) adds a create row above the list showing `Create "{text}"` with a trailing Add action named `Add {text}`. Activating it commits a `create` change whose item has the text as both id and label, clears the query, and moves focus to the sheet's search field, since the row it was on is gone. The create row is absent at `maxEntries`. | DEC-3; Lab touch-flow evidence; `hasCreate` contract of the inline field | Verified current behavior through the internal entry. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |
| FR23 | At `maxEntries`, unchecked rows carry `aria-disabled="true"`, stay focusable, and ignore activation; checked rows remain toggleable so the person can make room (`spec:AST-085/FR1`). | DEC-3; Lab touch-flow evidence; `spec:AST-085` | Verified current behavior through the internal entry. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |
| FR24 | Clear all is disabled while `value` is empty: `aria-disabled`, still in the focus order, with a tooltip saying nothing is selected, and a click opens nothing (`spec:AST-085/FR1`). Otherwise it opens an AlertDialog confirmation naming the field; confirming commits `[]` with a `remove` change naming the last selected item, closes the confirmation, and — once the confirmation has closed — moves focus to the sheet's search field, the destination this record names (`spec:AST-085/FR4`): the clear is spent, and the search field is where the next selection starts (WCAG 2.2 SC 2.4.3 through `spec:AST-020/FR1`), and announces "All items removed" inside the sheet (AR6); cancelling changes nothing and focus returns to Clear all. | DEC-3; Lab touch-flow evidence | Verified current behavior through the internal entry. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |
+| FR25 | The result list follows `component:BaseTypeahead` FR12: a press on the field's input or its buttons, or in the list, keeps it open, and a press anywhere else closes it. | `component:BaseTypeahead` FR12 | Verified current behavior |
### Allowed variation
@@ -475,6 +476,7 @@ become Tokenizer policy.
| AR1–AR5 | Existing interaction suites plus focused pointer/keyboard/browser checks; native-disabled assertions pending conformance (`spec:AST-085`) | add/edit, focus/refocus, overflow, disabled, dismissal, retained bootstrap selection | Modality changes placement, semantics/focus regress, active descendant becomes invalid, or visible placement is wrong before fallback. | `audit:Tokenizer/accessibility` |
| AR7 | Focused Tokenizer tests, inline and sheet, and the PowerSearch test | inline Clear all; a localized catalog; a Clear all confirmed in the sheet counted across every live region; PowerSearch's own words | The inline Clear all is silent, speaks words other than its catalog message, a sheet Clear all is announced twice, or PowerSearch speaks Tokenizer's words. | `audit:Tokenizer/accessibility` |
| FR16–FR24, AR6, PR6 | Focused Tokenizer sheet tests with the compact-touch query stubbed both ways, a server-render-then-hydrate test, plus real-engine touch evidence | default popover, forced sheet, adaptive both ways, `adaptive` server-rendered as the combobox and hydrated without a recoverable error, then the trigger on a coarse-pointer client with the body still active, with `hasAutoFocus` the autofocused input's focus on the trigger after the swap and no `onBlur`/`onFocus` reported, the trigger's box against the hydrating field's at 390 and 414px, base props and ref on the trigger, the trigger's description in the inline input's order — a disabled trigger with `disabledMessage`, `description` and a status exposing the caller's ids, the description, the status message and the reason before the count and the tokens —, inert-prop warning, pending search, in-sheet announcements of toggles, busy start, result count and the rendered empty outcome, the confirmed Clear all announced once the confirmation has closed, a below-threshold query, a rejecting source, focus on the panel at open, the query cleared by a swipe, scrim, or Escape close, focus after a presentation change with the sheet closed, focus after the create row, focus after a confirmed Clear all, a spent Clear all focusable with `aria-disabled` and no action, focus after a settled search removes the focused row, no busy feedback or busy-start announcement on open with an instant source, only the search field — no list, no message, no announcement — for an empty query with nothing to list (a search-only source, nothing selected), and the list once a query finds items, element counts under a fine and a coarse pointer at rest and open (Chromium, Experimental stories: adaptive 154/120 at rest — the closed trigger in place of the inline field, a different element that stays under the fine count — and 157/165 open at the query "e" with no footer, the coarse total reconciled as rest − the re-hosted surfaces host + the dialog of 47 by part, forced sheet 114/114 and 165/165; the two owner exceptions DEC-3 records beyond the FR60 allowance, with before and after counts), no confirmation dialog in the DOM while none is pending, the query kept across a disabled-forced close, `aria-setsize`/`aria-posinset` on each row's `listitem` and the next batch on focus reaching the last rendered row, open/toggle/reopen order, create, batches, limit, Clear all, disabled while open, focus return | A field without `experimental` changes, a toggle moves a row, Clear all skips confirmation, the limit disables checked rows, or the popover bundle carries the sheet. | `audit:Tokenizer/sheet` |
+| FR25 | `Tokenizer.test.tsx` press-inside case; `component:BaseTypeahead` FR12's verification | Press in the input, press elsewhere | A press in the input that closes the list, or a press elsewhere that leaves it open, fails. | — |
| Record structure | `scripts/check-knowledge.mjs` | Template-v3 current record and current-only frontmatter links | Invalid metadata, authority, or relationship references fail repository validation. | `audit:Tokenizer/knowledge` |
## Decision log
diff --git a/docs/specs/components/Typeahead/BaseTypeahead.spec.md b/docs/specs/components/Typeahead/BaseTypeahead.spec.md
index 4d8c2bb250..fd0242034b 100644
--- a/docs/specs/components/Typeahead/BaseTypeahead.spec.md
+++ b/docs/specs/components/Typeahead/BaseTypeahead.spec.md
@@ -118,6 +118,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR9 | A disabled input MUST stay focusable with `aria-disabled` (`spec:AST-085` FR1), and caller handlers other than focus and blur MUST NOT run while disabled (FR2). Focusable-disabled uses `aria-disabled` plus `readOnly` and blocks text and query mutation, opening the list, and selection by Enter or a press, including from a list that was open before it applied; that list can still close, and search work in flight when it applies is dropped. Typeahead always uses focusable-disabled, and Tokenizer does except in `unfocusedLayer` mode without a `disabledMessage`, where the input is still natively `disabled`. Implementation gap: the default disabled mode is native `disabled`, which removes the Tab stop, and a focusable-disabled input still runs caller `onClick`, `onPointerDown`, and key handlers. | `spec:AST-085` FR1, FR2; current source and tests |
| FR10 | A search source may show partial lists for a query through `context.update` before `search()` settles; the typeahead follows `spec:AST-092` FR1–FR10: it shows a partial list at once and stays busy until the final list, keeps shown rows and the highlight in place as later lists append, keeps an option's id while its item stays, announces once per query when it settles, keeps the last non-empty list when the answer fails, and warns in development when a later list moves shown rows. | `spec:AST-092` |
| FR11 | The typeahead panel has not adopted the option-action grid: a result's `action` is not rendered, the row shows without it, and a development warning reports it once (`spec:AST-058` FR9). | `spec:AST-058` FR9; current source |
+| FR12 | While the list is open, a press that starts and ends on the field's input or its buttons, or in the list, keeps the list open; a press that starts and ends anywhere else closes it, and a scroll or pinch that starts outside does not. A press on the field's label or a Tokenizer token moves focus out of the input and back, so the list closes and reopens on that press and ends open. A field inside an open shadow root counts the same. The list is a manual popover, because the browser's light dismiss counts a press in a text input as outside (`architecture:layer-runtime`). | `architecture:layer-runtime`; current source and tests |
### Allowed variation
@@ -244,7 +245,7 @@ Consumer migration instructions belong in consumer docs and release notes.
- `family:overlay-dismissal` owns Escape and platform-close ordering while the
popup is present.
- `architecture:layer-runtime` owns top-layer hosting, anchoring, viewport
- positioning, and native light dismissal.
+ positioning, and outside-press dismissal for a text field's layer (FR12).
- `spec:AST-092` owns incremental search results (FR10).
- `spec:AST-058` owns the empty-search message and option actions (FR4, FR11).
- `architecture:public-component-api` owns reachable exports and BaseProps
@@ -254,22 +255,23 @@ Consumer migration instructions belong in consumer docs and release notes.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
-| FR1 | `Typeahead.test.tsx` "shows results on input change", "does not select every result when items lack ids", popover-after-selection and hasSearched-reset cases | Search, select, re-enter | A selection that keeps the query or results open, or selects several rows, fails. Evidence gap: no test asserts focus returning to the input after a selection. | `audit:BaseTypeahead/behavior` |
-| FR2 | `BaseTypeahead.test.tsx` "counts grapheme clusters when enforcing minQueryLength"; `Typeahead.test.tsx` minQueryLength and paste cases | Threshold, fallback below it, paste | A search below the threshold or an empty result for an unsearched query fails. Evidence gap: no test asserts the debounce delay. | `audit:BaseTypeahead/behavior` |
-| FR3, PR1 | `Typeahead.test.tsx` out-of-order async results cases ("discards a stale response that resolves after a newer query", "discards a response from a source that was replaced while it was in flight"); `BaseTypeahead.test.tsx` source-replacement cases; `BaseTypeahead.test.tsx` "loads the replacement source when ArrowDown opens the closed field", "searches the replacement source for the typed query when ArrowDown opens the closed field"; `BaseTypeahead.incremental.test.tsx` "drops lists for a query that is no longer current (FR4)", "drops lists and rejections that arrive after unmount (FR4)" | Newer query; replaced source | A stale response or partial list that replaces newer results, a list after unmount, or an old list on ArrowDown after a source replacement fails. Evidence gap: no test asserts timer cleanup or the Escape reopen. | `audit:BaseTypeahead/behavior` |
-| FR4, AR1, AR3 | `BaseTypeahead.test.tsx` "exposes a completed empty search as a disabled listbox option"; `Typeahead.test.tsx` "renders input with combobox role", "sets aria-expanded=false initially", "does not set aria-activedescendant when search has 0 results"; `BaseTypeahead.emptyState.a11y.chromium.spec.ts` | Results; completed empty | An invalid listbox, an empty search with no message, or an active descendant on the message fails. Evidence gap: no test asserts `aria-selected` on the selected option. The disabled-option cases assert the current FR4 gap pending conformance. | `audit:BaseTypeahead/accessibility` |
-| FR5, AR5 | `Typeahead.test.tsx` IME, focus-out, and arrow-scroll cases ("does not select the highlighted result on a composing Enter", "closes the list on the Tab keydown, before the blur it produces", "Tab from the input with the list open moves focus to the next control", "scrolls the highlighted option into view during arrow navigation", "reopens on click when the input was already focused and the dropdown closed without a blur", "picks nothing from a list opened before the field became disabled, and lets it close") | Arrows, Enter, Tab, IME | A composing Enter that selects, a Tab that keeps the list open or traps focus, or an Escape that leaves the list open or moves focus fails. Evidence gap: no test asserts the wrap, or Home and End. | `audit:BaseTypeahead/accessibility` |
-| FR6 | `Typeahead.test.tsx` busy-indicator-ownership and hasEntriesOnFocus loading cases | Direct and composed busy; bootstrap | A duplicate or missing Spinner, a stale busy state, or a repeated transition report fails. | `audit:BaseTypeahead/behavior` |
-| FR7, ORD2 | `BaseTypeahead.test.tsx` "forwards supported DOM, styling, and event props to the combobox input", "preserves native input attributes when legacy aliases are undefined", "lets defined legacy aliases override their native equivalents" | DOM, style, events; legacy aliases | A dropped prop, a replaced owned semantic, or a wrong alias precedence fails. Evidence gap: no test asserts that a direct caller's `onKeyDown` runs first and that `preventDefault()` in it skips the built-in handling. | `audit:BaseTypeahead/api` |
-| FR8 | Evidence gap: no test asserts the popup inside the viewport at 320 CSS px | — | — | `audit:BaseTypeahead/layout` |
-| FR9 | `Typeahead.test.tsx` "disables input when isDisabled" (a bare BaseTypeahead, asserting the current native-disabled gap pending conformance), "blocks typing and selection while focusable-disabled", "opens no list and picks nothing while focusable-disabled (spec:AST-085 FR2)", "does not reopen on a click into the still-focused input once disabled", "picks nothing from a list opened before the field became disabled, and lets it close", "does not open a list for a search that settles after the field became disabled", "drops a search answer that arrives after the field became disabled" | Native disabled; focusable-disabled before and after open | Typing, opening, or selecting while focusable-disabled, a list that cannot close, or a search answer that lands after disabling fails. Evidence gap: no test asserts that caller handlers are skipped while disabled. | `audit:BaseTypeahead/accessibility` |
-| FR10 | `BaseTypeahead.incremental.test.tsx` cases | Partial, appended, failed, and replaced lists; groups; popup above and below; StrictMode | A partial list not shown at once, a moved row or highlight, a changed option id, a second announcement, a lost list on failure, or a missing development warning fails. | `audit:BaseTypeahead/behavior` |
-| FR11 | Evidence gap: no test, matching the source's development warning | Result with `action` | A rendered action or a missing warning fails. | `audit:BaseTypeahead/behavior` |
-| AR2, AR4 | `Typeahead.test.tsx` result-announcement cases ("announces the result count to a live region (comboboxes-6)", "announces the plural result count", "speaks the result count from a provider catalog", "announces \"no results found\" when the search is empty (comboboxes-6)"); `BaseTypeahead.incremental.test.tsx` "announces the result count once per query, when it settles (FR8)" | Counts, empty, provider catalog | A missing or wrong announcement fails. Evidence gap: no test asserts a direct caller's accessible name. | `audit:BaseTypeahead/accessibility` |
-| ORD1 | `TypeaheadItem.test.tsx` "renders item.element raw in place of the label layout" | `item.element` | `item.element` that does not replace the default content fails. Evidence gap: no test asserts `renderItem` precedence below `item.element`. | `audit:BaseTypeahead/behavior` |
-| Theming anatomy | `themingTargets.test.ts`; `scripts/check-knowledge.mjs` | Mapped parts | A rendered class absent from the documented targets, or a stale disposition, fails. | `audit:BaseTypeahead/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
+| FR1 | `Typeahead.test.tsx` "shows results on input change", "does not select every result when items lack ids", popover-after-selection and hasSearched-reset cases | Search, select, re-enter | A selection that keeps the query or results open, or selects several rows, fails. Evidence gap: no test asserts focus returning to the input after a selection. | `audit:BaseTypeahead/behavior` |
+| FR2 | `BaseTypeahead.test.tsx` "counts grapheme clusters when enforcing minQueryLength"; `Typeahead.test.tsx` minQueryLength and paste cases | Threshold, fallback below it, paste | A search below the threshold or an empty result for an unsearched query fails. Evidence gap: no test asserts the debounce delay. | `audit:BaseTypeahead/behavior` |
+| FR3, PR1 | `Typeahead.test.tsx` out-of-order async results cases ("discards a stale response that resolves after a newer query", "discards a response from a source that was replaced while it was in flight"); `BaseTypeahead.test.tsx` source-replacement cases; `BaseTypeahead.test.tsx` "loads the replacement source when ArrowDown opens the closed field", "searches the replacement source for the typed query when ArrowDown opens the closed field"; `BaseTypeahead.incremental.test.tsx` "drops lists for a query that is no longer current (FR4)", "drops lists and rejections that arrive after unmount (FR4)" | Newer query; replaced source | A stale response or partial list that replaces newer results, a list after unmount, or an old list on ArrowDown after a source replacement fails. Evidence gap: no test asserts timer cleanup or the Escape reopen. | `audit:BaseTypeahead/behavior` |
+| FR4, AR1, AR3 | `BaseTypeahead.test.tsx` "exposes a completed empty search as a disabled listbox option"; `Typeahead.test.tsx` "renders input with combobox role", "sets aria-expanded=false initially", "does not set aria-activedescendant when search has 0 results"; `BaseTypeahead.emptyState.a11y.chromium.spec.ts` | Results; completed empty | An invalid listbox, an empty search with no message, or an active descendant on the message fails. Evidence gap: no test asserts `aria-selected` on the selected option. The disabled-option cases assert the current FR4 gap pending conformance. | `audit:BaseTypeahead/accessibility` |
+| FR5, AR5 | `Typeahead.test.tsx` IME, focus-out, and arrow-scroll cases ("does not select the highlighted result on a composing Enter", "closes the list on the Tab keydown, before the blur it produces", "Tab from the input with the list open moves focus to the next control", "scrolls the highlighted option into view during arrow navigation", "reopens on click when the input was already focused and the dropdown closed without a blur", "picks nothing from a list opened before the field became disabled, and lets it close") | Arrows, Enter, Tab, IME | A composing Enter that selects, a Tab that keeps the list open or traps focus, or an Escape that leaves the list open or moves focus fails. Evidence gap: no test asserts the wrap, or Home and End. | `audit:BaseTypeahead/accessibility` |
+| FR6 | `Typeahead.test.tsx` busy-indicator-ownership and hasEntriesOnFocus loading cases | Direct and composed busy; bootstrap | A duplicate or missing Spinner, a stale busy state, or a repeated transition report fails. | `audit:BaseTypeahead/behavior` |
+| FR7, ORD2 | `BaseTypeahead.test.tsx` "forwards supported DOM, styling, and event props to the combobox input", "preserves native input attributes when legacy aliases are undefined", "lets defined legacy aliases override their native equivalents" | DOM, style, events; legacy aliases | A dropped prop, a replaced owned semantic, or a wrong alias precedence fails. Evidence gap: no test asserts that a direct caller's `onKeyDown` runs first and that `preventDefault()` in it skips the built-in handling. | `audit:BaseTypeahead/api` |
+| FR8 | Evidence gap: no test asserts the popup inside the viewport at 320 CSS px | — | — | `audit:BaseTypeahead/layout` |
+| FR9 | `Typeahead.test.tsx` "disables input when isDisabled" (a bare BaseTypeahead, asserting the current native-disabled gap pending conformance), "blocks typing and selection while focusable-disabled", "opens no list and picks nothing while focusable-disabled (spec:AST-085 FR2)", "does not reopen on a click into the still-focused input once disabled", "picks nothing from a list opened before the field became disabled, and lets it close", "does not open a list for a search that settles after the field became disabled", "drops a search answer that arrives after the field became disabled" | Native disabled; focusable-disabled before and after open | Typing, opening, or selecting while focusable-disabled, a list that cannot close, or a search answer that lands after disabling fails. Evidence gap: no test asserts that caller handlers are skipped while disabled. | `audit:BaseTypeahead/accessibility` |
+| FR10 | `BaseTypeahead.incremental.test.tsx` cases | Partial, appended, failed, and replaced lists; groups; popup above and below; StrictMode | A partial list not shown at once, a moved row or highlight, a changed option id, a second announcement, a lost list on failure, or a missing development warning fails. | `audit:BaseTypeahead/behavior` |
+| FR11 | Evidence gap: no test, matching the source's development warning | Result with `action` | A rendered action or a missing warning fails. | `audit:BaseTypeahead/behavior` |
+| FR12 | `Typeahead.test.tsx` press inside and outside suite; `Tokenizer.test.tsx` press-inside case; `TypeaheadInputPress.a11y.chromium.spec.ts` | Press in the input, in the list, elsewhere; a scroll that starts elsewhere; a field in a shadow root | A press on the field or in the list that closes the list, a press elsewhere that leaves it open, or a scroll that closes it fails. | — |
+| AR2, AR4 | `Typeahead.test.tsx` result-announcement cases ("announces the result count to a live region (comboboxes-6)", "announces the plural result count", "speaks the result count from a provider catalog", "announces \"no results found\" when the search is empty (comboboxes-6)"); `BaseTypeahead.incremental.test.tsx` "announces the result count once per query, when it settles (FR8)" | Counts, empty, provider catalog | A missing or wrong announcement fails. Evidence gap: no test asserts a direct caller's accessible name. | `audit:BaseTypeahead/accessibility` |
+| ORD1 | `TypeaheadItem.test.tsx` "renders item.element raw in place of the label layout" | `item.element` | `item.element` that does not replace the default content fails. Evidence gap: no test asserts `renderItem` precedence below `item.element`. | `audit:BaseTypeahead/behavior` |
+| Theming anatomy | `themingTargets.test.ts`; `scripts/check-knowledge.mjs` | Mapped parts | A rendered class absent from the documented targets, or a stale disposition, fails. | `audit:BaseTypeahead/theming` |
## Current-state impact
diff --git a/docs/specs/components/Typeahead/Typeahead.spec.md b/docs/specs/components/Typeahead/Typeahead.spec.md
index a9dde61009..cd0cc6c289 100644
--- a/docs/specs/components/Typeahead/Typeahead.spec.md
+++ b/docs/specs/components/Typeahead/Typeahead.spec.md
@@ -97,17 +97,18 @@ BaseTypeahead and TypeaheadItem keep their own records.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
-| FR1 | The current standalone presentation contains a Field and painted Input surface; the supported InputGroup path renders the same Input surface without a Field. The surface contains an editable input when unselected or editing, and a Selected token plus collapsed input when selected and not editing. | Current source, docs, and tests |
-| FR2 | Input surface, Dropdown, Empty state, and Default item content carry the four Typeahead targets documented in `Typeahead.doc.mjs`. | Current source, docs, and tests |
-| FR3 | Every result, whether default or caller-rendered, sits inside the same stable outer Result row that owns option semantics, highlight, selected styling, pointer interaction, and keyboard indexing. | Current source and tests |
-| FR4 | `typeahead-item` reaches only the standard TypeaheadItem label/supporting-content branch inside a Result row. A custom `renderItem` branch or caller-provided `item.element` does not receive that target, and no branch gives the outer Result row a Typeahead target. | Current source and owner tests |
-| FR5 | Result group heading and Selected result state are stable visible concepts but no Typeahead target reaches them (OQ1). The selected check uses a generic Icon, which exposes no Typeahead-specific selected-row selector. | Current source |
-| FR6 | When present, Field, Selected token, Clear button, Spinner, and Icon-rendered start icon retain their Field, Token, Spinner, and Icon theming owners; arbitrary ReactNode start and item content stays caller-owned. | Current composition and owners |
-| FR7 | A disabled Typeahead keeps the input's Tab stop with `aria-disabled` and `readOnly` (`spec:AST-085` FR1), opens and picks nothing, and drops search work in flight when it becomes disabled; with a `disabledMessage` it links the reason Tooltip through `aria-describedby`. Caller handlers other than focus and blur MUST NOT run while disabled (FR2). Implementation gap: a disabled input still runs caller click, pointer, and key handlers (`component:BaseTypeahead` FR9). | `spec:AST-085` FR1, FR2; current tests |
-| FR8 | With a selected value and not editing, the Token paints over the collapsed input, which leaves the Tab order, and the Token's button, named by the field label and the value, is the Tab stop; clicking the Token enters edit mode, which searches the value's label and restores the input to the Tab order; blur without an action restores the Token; a composing Escape does not leave edit mode. With `hasClear`, the clear button calls `onChange(null)`, and clearing while editing empties the input. | Current tests |
-| FR9 | The field has no root styling props: `control*` reaches the input surface and `container*` the Field box (`family:input-fields` FR10); DOM props and the ref reach the combobox input in both paths; a caller `onKeyDown` runs after built-in key handling, once per key, and also for keys on the clear button; a caller `aria-labelledby` follows the field's own name. The surface keeps one row with the end controls in flow at the inline end, and its height is the shared element size as a minimum. | `family:input-fields` FR10; current tests |
+| ID | Invariant | Basis |
+| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
+| FR1 | The current standalone presentation contains a Field and painted Input surface; the supported InputGroup path renders the same Input surface without a Field. The surface contains an editable input when unselected or editing, and a Selected token plus collapsed input when selected and not editing. | Current source, docs, and tests |
+| FR2 | Input surface, Dropdown, Empty state, and Default item content carry the four Typeahead targets documented in `Typeahead.doc.mjs`. | Current source, docs, and tests |
+| FR3 | Every result, whether default or caller-rendered, sits inside the same stable outer Result row that owns option semantics, highlight, selected styling, pointer interaction, and keyboard indexing. | Current source and tests |
+| FR4 | `typeahead-item` reaches only the standard TypeaheadItem label/supporting-content branch inside a Result row. A custom `renderItem` branch or caller-provided `item.element` does not receive that target, and no branch gives the outer Result row a Typeahead target. | Current source and owner tests |
+| FR5 | Result group heading and Selected result state are stable visible concepts but no Typeahead target reaches them (OQ1). The selected check uses a generic Icon, which exposes no Typeahead-specific selected-row selector. | Current source |
+| FR6 | When present, Field, Selected token, Clear button, Spinner, and Icon-rendered start icon retain their Field, Token, Spinner, and Icon theming owners; arbitrary ReactNode start and item content stays caller-owned. | Current composition and owners |
+| FR7 | A disabled Typeahead keeps the input's Tab stop with `aria-disabled` and `readOnly` (`spec:AST-085` FR1), opens and picks nothing, and drops search work in flight when it becomes disabled; with a `disabledMessage` it links the reason Tooltip through `aria-describedby`. Caller handlers other than focus and blur MUST NOT run while disabled (FR2). Implementation gap: a disabled input still runs caller click, pointer, and key handlers (`component:BaseTypeahead` FR9). | `spec:AST-085` FR1, FR2; current tests |
+| FR8 | With a selected value and not editing, the Token paints over the collapsed input, which leaves the Tab order, and the Token's button, named by the field label and the value, is the Tab stop; clicking the Token enters edit mode, which searches the value's label and restores the input to the Tab order; blur without an action restores the Token; a composing Escape does not leave edit mode. With `hasClear`, the clear button calls `onChange(null)`, and clearing while editing empties the input. | Current tests |
+| FR9 | The field has no root styling props: `control*` reaches the input surface and `container*` the Field box (`family:input-fields` FR10); DOM props and the ref reach the combobox input in both paths; a caller `onKeyDown` runs after built-in key handling, once per key, and also for keys on the clear button; a caller `aria-labelledby` follows the field's own name. The surface keeps one row with the end controls in flow at the inline end, and its height is the shared element size as a minimum. | `family:input-fields` FR10; current tests |
+| FR10 | The result list follows `component:BaseTypeahead` FR12: a press on the field's input or its buttons, or in the list, keeps it open, and a press anywhere else closes it. | `component:BaseTypeahead` FR12 |
### Allowed variation
@@ -248,8 +249,8 @@ normalize targets.
BaseTypeahead; Typeahead adds no props for them.
- `architecture:component-theming-surface` owns anatomy qualification, local
target mapping, delegation, and factual `none` dispositions.
-- `architecture:layer-runtime` owns the current Popover host, positioning, native
- light-dismiss, and visibility reconciliation used by the Dropdown.
+- `architecture:layer-runtime` owns the current Popover host, positioning,
+ outside-press dismissal, and visibility reconciliation used by the Dropdown.
- `family:overlay-dismissal` owns shared Escape and platform-close ordering;
Typeahead participates through its composed Popover owner.
- Field, Token, and Icon retain ownership of their delegated targets and
@@ -265,6 +266,7 @@ normalize targets.
| FR7 | `Typeahead.test.tsx` disabledMessage cases, including "keeps its tab stop when disabled without a reason" and "drops a search answer that arrives after the field became disabled"; `Typeahead.disabled.a11y.chromium.spec.ts` "Tab reaches the disabled field, which rings and stays read-only" | Disabled with and without a reason | A reason not linked from the input, a disabled input without a Tab stop, typing or selecting while disabled, or a search answer that lands after disabling fails. Evidence gap: no test asserts that caller handlers are skipped while disabled. | `audit:Typeahead/accessibility` |
| FR8, ORD1, AR2, AR3 | `Typeahead.test.tsx` edit-mode and collapsed-input tab-order cases; "calls onChange with null when clear button is clicked"; "does not show clear button when hasClear is false"; "names the token button, the Tab stop while a value shows, by the field label and the value", "names the token button with a caller aria-labelledby as the input is named" | Token, edit, blur, clear; Tab order | A Token that does not enter edit mode, an input left in the Tab order behind a Token, a composing Escape that leaves edit mode, a clear that does not send `null`, or a token button not named by the label and value fails. | `audit:Typeahead/behavior` |
| FR9, AR1 | `Typeahead.fr10.test.tsx` props-type case; `Typeahead.test.tsx` "forwards DOM props and ref to the combobox input while preserving edit and blur behavior", "forwards DOM props and ref to the input inside InputGroup, with control* on the surface", consumer key-handler cases, caller aria-labelledby cases, and end-controls cases; "exposes the resolved required state on the combobox (FormLayout FR5, AR2)", "marks the combobox invalid for an error status only (WCAG 4.1.2)", "keeps a caller's own aria-invalid and aria-required when the field's own state is off" | Standalone and grouped; key handlers; caller name | A root styling prop, a dropped DOM prop or ref, a caller key handler that runs first or twice, a lost caller name, a missing `aria-required` or error `aria-invalid`, or end controls out of flow fails. Evidence gap: no test asserts the minimum height. | `audit:Typeahead/layout` |
+| FR10 | `component:BaseTypeahead` FR12's verification | — | — | — |
| PR1 | Covered by `component:BaseTypeahead`'s rows; no test asserts the absence of Typeahead listeners (evidence gap) | — | — | `audit:Typeahead/behavior` |
| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and targets | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:Typeahead/theming` |
diff --git a/packages/core/src/Layer/outsidePress.ts b/packages/core/src/Layer/outsidePress.ts
new file mode 100644
index 0000000000..e59b9714da
--- /dev/null
+++ b/packages/core/src/Layer/outsidePress.ts
@@ -0,0 +1,99 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file outsidePress.ts
+ * @input Listens for pointerdown, pointerup and pointercancel on a document
+ * @output Exports watchOutsidePress and useOutsidePress, which owns one watch
+ * for a component: start on show, stop on hide, stop on unmount
+ * @position Internal to Layer; the outside-press dismissal for a manual
+ * popover whose owner decides what counts as inside (a combobox's field
+ * and its list). Not exported from the package.
+ *
+ * A press closes the layer only when it starts and ends outside, as native
+ * light dismiss does: a pointerdown outside is remembered, the pointerup that
+ * follows closes the layer if it is outside too, and a pointercancel (the
+ * browser took the gesture for a scroll or a pinch) forgets it. Inside is
+ * judged on the event's composed path, so a field or list inside an open
+ * shadow root, which the document sees as its shadow host, is still inside.
+ */
+
+import {useCallback, useEffect, useMemo, useRef} from 'react';
+
+/**
+ * Watch the owner's document for a press outside, until the returned function
+ * is called. The caller stops it when its layer hides and when it unmounts.
+ *
+ * @param owner - The element that owns the layer (the field); its document is
+ * watched.
+ * @param isInside - Whether a press with this composed path is inside.
+ * @param onOutside - Called once for each press that starts and ends outside.
+ * @returns Stops watching.
+ */
+export function watchOutsidePress(
+ owner: Element,
+ isInside: (path: ReadonlyArray<EventTarget>) => boolean,
+ onOutside: () => void,
+): () => void {
+ const doc = owner.ownerDocument;
+ let startedOutside = false;
+
+ // Capture phase, so a press whose target stops propagation is still seen.
+ const handleDown = (event: PointerEvent) => {
+ startedOutside = !isInside(event.composedPath());
+ };
+ const handleUp = (event: PointerEvent) => {
+ const wasOutside = startedOutside;
+ startedOutside = false;
+ if (wasOutside && !isInside(event.composedPath())) {
+ onOutside();
+ }
+ };
+ const handleCancel = () => {
+ startedOutside = false;
+ };
+
+ doc.addEventListener('pointerdown', handleDown, true);
+ doc.addEventListener('pointerup', handleUp, true);
+ doc.addEventListener('pointercancel', handleCancel, true);
+ return () => {
+ doc.removeEventListener('pointerdown', handleDown, true);
+ doc.removeEventListener('pointerup', handleUp, true);
+ doc.removeEventListener('pointercancel', handleCancel, true);
+ };
+}
+
+export interface OutsidePressWatch {
+ /** Start watching, replacing any watch already running. */
+ start: (
+ owner: Element,
+ isInside: (path: ReadonlyArray<EventTarget>) => boolean,
+ onOutside: () => void,
+ ) => void;
+ /** Stop watching; does nothing when no watch is running. */
+ stop: () => void;
+}
+
+/**
+ * One outside-press watch for a component: it calls `start` when its layer
+ * shows and `stop` when it hides, and the watch's document listeners (an
+ * external system) are removed when the component unmounts with it running.
+ * Both functions are stable.
+ */
+export function useOutsidePress(): OutsidePressWatch {
+ const stopRef = useRef<(() => void) | null>(null);
+ const stop = useCallback(() => {
+ stopRef.current?.();
+ stopRef.current = null;
+ }, []);
+ const start = useCallback<OutsidePressWatch['start']>(
+ (owner, isInside, onOutside) => {
+ stopRef.current?.();
+ stopRef.current = watchOutsidePress(owner, isInside, onOutside);
+ },
+ [],
+ );
+ useEffect(() => stop, [stop]);
+ return useMemo(() => ({start, stop}), [start, stop]);
+}
diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsx
index e9f93b749c..14b6704d5c 100644
--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx
@@ -165,6 +165,40 @@ describe('Tokenizer minQueryLength', () => {
});
});
+// component:BaseTypeahead FR12 through Tokenizer: a press in the field keeps the list open.
+describe('Tokenizer press inside and outside', () => {
+ it('keeps the list open on a press in its input and closes it on a press elsewhere', async () => {
+ render(
+ <>
+ <Tokenizer
+ label="People"
+ searchSource={userSource}
+ value={[]}
+ onChange={() => {}}
+ debounceMs={0}
+ />
+ <p>Elsewhere</p>
+ </>,
+ );
+ const input = screen.getByRole('combobox');
+ input.focus();
+ fireEvent.change(input, {target: {value: 'Ali'}});
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ fireEvent.pointerDown(input);
+ fireEvent.pointerUp(input);
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+
+ fireEvent.pointerDown(screen.getByText('Elsewhere'));
+ fireEvent.pointerUp(screen.getByText('Elsewhere'));
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ });
+ });
+});
+
describe('Tokenizer', () => {
it('forwards DOM props and ref to the combobox input while preserving focus callbacks', () => {
const ref = createRef<HTMLInputElement>();
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index fe7737469b..a2927cdafd 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -39,6 +39,7 @@ import {useAnnounce} from '../hooks/useAnnounce';
import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {useOutsidePress} from '../Layer/outsidePress';
import {isImeKeyEvent} from '../utils/ime';
import {TypeaheadItem} from './TypeaheadItem';
import {Icon} from '../Icon';
@@ -692,10 +693,9 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
onLoadingChangeRef.current?.(next);
}, []);
- // Track active pointer to defer popover.show() past click events.
- // With popover="auto", showing the popover between pointerdown and
- // pointerup/click causes the browser's light-dismiss to immediately
- // close it (the click is seen as "outside" the newly-opened popover).
+ // Track active pointer to defer popover.show() past click events, so a
+ // list that opens during a press starts its outside-press watch after that
+ // press ends and never judges it.
const pointerActiveRef = useRef(false);
// Whether the input was ALREADY the active element the moment the current
@@ -778,23 +778,56 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
}
}, [searchSource]);
- // Layer for dropdown
+ // Layer for dropdown. The list is a manual popover (see usePopover below):
+ // while it is open, a press on the combobox itself (its input or its
+ // buttons) or in the list is inside, and a press anywhere else closes it
+ // (component:BaseTypeahead FR12). The watch starts when the list shows and
+ // stops when it hides or the field unmounts (useOutsidePress owns that).
+ // An outside press hides the
+ // popover element directly, which useLayer reconciles like the browser's
+ // own light dismiss.
+ const outsidePress = useOutsidePress();
const handleLayerShow = useCallback(() => {
onOpenChange?.(true);
- }, [onOpenChange]);
+ const anchorEl = anchorRef?.current ?? fallbackAnchorRef.current;
+ if (anchorEl == null) {
+ outsidePress.stop();
+ return;
+ }
+ // The list's own element sits inside the popover element.
+ const findLayer = () =>
+ dropdownRef.current?.closest<HTMLElement>('[popover]') ?? null;
+ outsidePress.start(
+ anchorEl,
+ path => {
+ const anchor = anchorRef?.current ?? fallbackAnchorRef.current;
+ const layer = findLayer();
+ return path.some(
+ target => target === anchor || (layer != null && target === layer),
+ );
+ },
+ () => findLayer()?.hidePopover(),
+ );
+ }, [onOpenChange, anchorRef, outsidePress]);
const handleLayerHide = useCallback(() => {
+ outsidePress.stop();
onOpenChange?.(false);
setHighlightedIndex(-1);
closedGenRef.current = searchGenRef.current;
setHeldHeight(null);
searchSource.cancel?.();
- }, [onOpenChange, searchSource]);
+ }, [onOpenChange, searchSource, outsidePress]);
const popover = usePopover({
onShow: handleLayerShow,
onHide: handleLayerHide,
- hasLightDismiss: true,
+ // A manual popover: the browser's light dismiss counts a press in the
+ // input as outside (a text input cannot be an invoker), so it would close
+ // the list on every press in the field. handleLayerShow watches for a
+ // press outside instead (architecture:layer-runtime); Escape stays on the
+ // shared layer stack.
+ hasLightDismiss: false,
hasCloseButton: false,
hasAutoFocus: false,
// The popup's own role="listbox" is the exposed semantics; the input keeps
@@ -802,9 +835,8 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
role: 'none',
});
- // Show the layer, deferring past the active click if a pointer is down.
- // Without this, popover="auto" light-dismiss immediately closes the
- // dropdown when it opens between pointerdown and pointerup/click.
+ // Show the layer, deferring past the active click if a pointer is down
+ // (see pointerActiveRef).
// Read at show time, so a search or bootstrap that settles after the field
// became disabled does not open the list (spec:AST-085 FR2).
const isDisabledRef = useRef(isDisabled);
@@ -1273,10 +1305,10 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
// Handle blur — close the dropdown when focus leaves the input for an
// element that is neither inside the field wrapper (anchor) nor inside the
- // dropdown popover. The native popover="auto" light-dismiss only fires on
- // outside pointer clicks and Escape; it does not close when focus moves away
- // via the keyboard (Tab) or programmatically, which would otherwise leave an
- // orphaned open menu. Clicking a result moves focus onto the option (it is
+ // dropdown popover. The outside-press watch only answers pointer presses
+ // and Escape stays on the layer stack; neither closes the list when focus
+ // moves away via the keyboard (Tab) or programmatically, which would
+ // otherwise leave an orphaned open menu. Clicking a result moves focus onto the option (it is
// tabIndex={-1}, so it lives inside the popover) and selection re-focuses the
// input, so this only closes on a genuine focus-out of the whole field.
const handleBlur = useCallback(
diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsx
index b4d7f6b9cc..ef93057ebe 100644
--- a/packages/core/src/Typeahead/Typeahead.test.tsx
+++ b/packages/core/src/Typeahead/Typeahead.test.tsx
@@ -18,8 +18,16 @@ import {
afterAll,
beforeEach,
afterEach,
+ onTestFinished,
} from 'vitest';
-import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';
+import {
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+ act,
+ cleanup,
+} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import * as stylex from '@stylexjs/stylex';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
@@ -34,6 +42,7 @@ import {
type ProfilerOnRenderCallback,
} from 'react';
import {FormLayout} from '../FormLayout/FormLayout';
+import {Dialog} from '../Dialog/Dialog';
import {Typeahead} from './Typeahead';
import {readFile} from 'node:fs/promises';
import {resolve} from 'node:path';
@@ -445,6 +454,138 @@ describe('BaseTypeahead', () => {
});
});
+// component:BaseTypeahead FR12: a press on the field or in the list is inside.
+describe('BaseTypeahead press inside and outside', () => {
+ function press(target: Element) {
+ fireEvent.pointerDown(target, {composed: true});
+ fireEvent.pointerUp(target, {composed: true});
+ }
+
+ async function openList(container?: HTMLElement) {
+ render(
+ <>
+ <BaseTypeahead
+ searchSource={fruitSource}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />
+ <p>Elsewhere</p>
+ </>,
+ container ? {container} : undefined,
+ );
+ const root = container ?? document.body;
+ const input = root.querySelector('[role="combobox"]') as HTMLInputElement;
+ input.focus();
+ fireEvent.change(input, {target: {value: 'App'}});
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+ return input;
+ }
+
+ it('keeps the list open on a press in its own input', async () => {
+ const input = await openList();
+ press(input);
+ fireEvent.click(input);
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ // The list is a manual popover, so the browser does not light-dismiss it.
+ const list = document.getElementById(input.getAttribute('aria-controls')!);
+ expect(list?.closest('[popover]')).toHaveAttribute('popover', 'manual');
+ });
+
+ it('keeps the list open on a press in the list', async () => {
+ const input = await openList();
+ press(screen.getAllByRole('option', {hidden: true})[0]);
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('closes the list on a press outside the field and the list', async () => {
+ const input = await openList();
+ press(screen.getByText('Elsewhere'));
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ });
+ });
+
+ it('keeps the list open when a scroll starts outside (pointercancel)', async () => {
+ const input = await openList();
+ const elsewhere = screen.getByText('Elsewhere');
+ fireEvent.pointerDown(elsewhere, {composed: true});
+ fireEvent.pointerCancel(elsewhere, {composed: true});
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('inside a Dialog, keeps the list on an input press and closes only the list on a press elsewhere in the dialog', async () => {
+ // jsdom has no showModal/close; stand-ins like Dialog's own tests use.
+ const {showModal, close} = HTMLDialogElement.prototype;
+ HTMLDialogElement.prototype.showModal = function (this: HTMLDialogElement) {
+ this.setAttribute('open', '');
+ };
+ HTMLDialogElement.prototype.close = function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ };
+ onTestFinished(() => {
+ HTMLDialogElement.prototype.showModal = showModal;
+ HTMLDialogElement.prototype.close = close;
+ });
+ const onDialogChange = vi.fn();
+ render(
+ <Dialog isOpen={true} onOpenChange={onDialogChange}>
+ <BaseTypeahead
+ searchSource={fruitSource}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />
+ <p>Dialog text</p>
+ </Dialog>,
+ );
+ const input = screen.getByRole('combobox');
+ input.focus();
+ fireEvent.change(input, {target: {value: 'App'}});
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+ press(input);
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ press(screen.getByText('Dialog text'));
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(onDialogChange).not.toHaveBeenCalled();
+ });
+
+ it('removes its document listeners when the field unmounts with the list open', async () => {
+ const input = await openList();
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ const remove = vi.spyOn(document, 'removeEventListener');
+ cleanup();
+ for (const type of ['pointerdown', 'pointerup', 'pointercancel']) {
+ expect(remove).toHaveBeenCalledWith(type, expect.any(Function), true);
+ }
+ remove.mockRestore();
+ });
+
+ it('keeps the list open on a press in its input inside a shadow root', async () => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const container = document.createElement('div');
+ host.attachShadow({mode: 'open'}).appendChild(container);
+ try {
+ const input = await openList(container);
+ press(input);
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ press(container.querySelector('p')!);
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ });
+ } finally {
+ host.remove();
+ }
+ });
+});
+
describe('BaseTypeahead focus-out', () => {
it('closes the dropdown when focus leaves the input', async () => {
render(
diff --git a/packages/core/src/Typeahead/__tests__/TypeaheadInputPress.a11y.chromium.spec.ts b/packages/core/src/Typeahead/__tests__/TypeaheadInputPress.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..0c38102f83
--- /dev/null
+++ b/packages/core/src/Typeahead/__tests__/TypeaheadInputPress.a11y.chromium.spec.ts
@@ -0,0 +1,60 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope ^(packages/core/src/Typeahead/|packages/core/src/Tokenizer/|packages/core/src/Popover/|apps/storybook/stories/Typeahead)
+
+/**
+ * @file TypeaheadInputPress.a11y.chromium.spec.ts
+ * @input The `Core/Typeahead` Default story in a built Storybook, in Chromium.
+ * @output Real-browser proof of component:BaseTypeahead FR12: with the list open,
+ * a press in the field's own input keeps it open (native light dismiss used
+ * to close it), and a press elsewhere on the page closes it.
+ * @position Runs in pr-a11y when Typeahead, Tokenizer, Popover or this spec
+ * changes. jsdom has no light dismiss, so only a browser shows the defect.
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const STORY = 'core-typeahead--default';
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(DEFAULT_STORYBOOK_DIR);
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+async function openList(page: Page) {
+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);
+ const input = page.getByRole('combobox');
+ await input.click();
+ await input.pressSequentially('ap');
+ await expect(input).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.getByRole('listbox')).toBeVisible();
+ return input;
+}
+
+test('a press in the input keeps the list open', async ({page}) => {
+ const input = await openList(page);
+ // Click between the two letters, as a person fixing a typo would.
+ const box = await input.boundingBox();
+ if (box == null) {
+ throw new Error('the input has no layout box');
+ }
+ await page.mouse.click(box.x + 12, box.y + box.height / 2);
+ await expect(input).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.getByRole('listbox')).toBeVisible();
+});
+
+test('a press elsewhere closes the list', async ({page}) => {
+ const input = await openList(page);
+ await page.mouse.click(5, 5);
+ await expect(input).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.getByRole('listbox')).toBeHidden();
+});