Skip to content

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

TypeScript

fix(BaseTypeahead): a focusable-disabled field opens no list and picks nothing (spec:AST-085 FR2) (#9036)

Cindy Zhang19ae6fc298a3
diff --git a/.changeset/typeahead-disabled-inert.md b/.changeset/typeahead-disabled-inert.md
new file mode 100644
index 0000000000..7416665059
--- /dev/null
+++ b/.changeset/typeahead-disabled-inert.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A `Typeahead` or `Tokenizer` disabled with a reason (`isDisabled` with `disabledMessage`) no longer opens its results from ArrowDown or a click. A `Typeahead` disabled this way also no longer accepts a pick by Enter or a press, even from a list that was open before it became disabled (a `Tokenizer` already refused those). Escape or Tab still closes such a list.
+
+@cixzhang @duytbp
diff --git a/packages/core/src/Typeahead/BaseTypeahead.doc.mjs b/packages/core/src/Typeahead/BaseTypeahead.doc.mjs
index af4e93f2c1..4986f71431 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.doc.mjs
+++ b/packages/core/src/Typeahead/BaseTypeahead.doc.mjs
@@ -175,7 +175,7 @@ export const docs = {
name: 'isFocusableDisabled',
type: 'boolean',
description:
- 'Keep a disabled input focusable with aria-disabled and readOnly so a caller-owned disabled reason remains discoverable. It blocks text entry, but when applied after results are already open, Enter can still select the highlighted option.',
+ 'Keep a disabled input focusable with aria-disabled and readOnly so a caller-owned disabled reason remains discoverable. It blocks text entry, opening the results and picking a result, also from results that were open before it applied; Escape or Tab still closes them.',
default: 'false',
},
{
@@ -334,7 +334,7 @@ export const docsZh = {
name: 'isFocusableDisabled',
type: 'boolean',
description:
- '使用 aria-disabled 和只读状态保持禁用输入框可聚焦,以便访问调用方提供的禁用原因。它会阻止文本输入,但如果结果已打开,按 Enter 仍可选择高亮选项。',
+ '使用 aria-disabled 和只读状态保持禁用输入框可聚焦,以便访问调用方提供的禁用原因。它会阻止文本输入、打开结果列表和选择结果,在它生效前已打开的结果中也是如此;Escape 或 Tab 仍可关闭列表。',
default: 'false',
},
{
@@ -467,7 +467,7 @@ export const docsDense = {
emptySearchText: 'Content when the query matched nothing. ReactNode.',
isDisabled: 'Whether input disabled.',
isFocusableDisabled:
- 'Keeps disabled input focusable and blocks text entry; an already-open highlight can still be selected with Enter.',
+ 'Keeps disabled input focusable; blocks text entry, opening and picking, also from an already-open list (Escape/Tab close it).',
hasAutoFocus: 'Auto-focus on mount.',
debounceMs: 'Search debounce ms. 0 for sync.',
size: 'Dropdown option padding size.',
diff --git a/packages/core/src/Typeahead/BaseTypeahead.spec.md b/packages/core/src/Typeahead/BaseTypeahead.spec.md
index 538f555bcb..ffb498b6ac 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.spec.md
+++ b/packages/core/src/Typeahead/BaseTypeahead.spec.md
@@ -77,34 +77,34 @@ Consumer migration instructions belong in consumer docs and release notes.
## Public concepts
-| Concept | Closed values or states | Meaning | Availability by state | Default | Owner | Stability | Invalid-value behavior |
-| --------------- | ---------------------------------------- | ------------------------------------------------------------ | -------------------------- | -------------------------------- | ---------------------------- | --------- | ---------------------------------------------------------------------------------------- |
-| selection | `T` or `null` | Caller-controlled selected result | all states | required | `component:BaseTypeahead` | released | caller retains control |
-| search source | `search`, `bootstrap`, optional `cancel` | Supplies query and focus results | enabled input | required | `component:BaseTypeahead` | released | rejected work clears current results |
-| focus bootstrap | on or off | Offers bootstrap results before query input | empty focused input | off | `component:BaseTypeahead` | released | off keeps the menu closed |
-| query threshold | non-negative number | Minimum visible-character count before search | non-empty query | `1` | `component:BaseTypeahead` | released | below threshold cancels work and closes results |
-| debounce | milliseconds | Delays query search | typed query | `150` | `component:BaseTypeahead` | released | non-positive runs immediately |
-| result cap | number | Limits fetched results shown | completed search/bootstrap | `10` | `component:BaseTypeahead` | released | source order is preserved |
-| result content | default, `renderItem`, or `item.element` | Chooses content inside the stable option row | result present | default TypeaheadItem | caller and component | released | `item.element` takes precedence |
-| disabled state | native or focusable-disabled | Blocks query mutation; native disabled blocks all activation | disabled | native disabled | component and caller wrapper | released | an already-open focusable-disabled list can still select with Enter (retained violation) |
-| popup width | intrinsic or fixed pixels | Sets result popup width before viewport clamping | popup present | intrinsic, at least anchor width | `component:BaseTypeahead` | released | viewport fit wins |
-| size | `sm`, `md`, `lg` | Selects option-row padding | popup options | `md` | `component:BaseTypeahead` | released | TypeScript rejects other values |
+| Concept | Closed values or states | Meaning | Availability by state | Default | Owner | Stability | Invalid-value behavior |
+| --------------- | ---------------------------------------- | ------------------------------------------------------------ | -------------------------- | -------------------------------- | ---------------------------- | --------- | ------------------------------------------------------------------------------- |
+| selection | `T` or `null` | Caller-controlled selected result | all states | required | `component:BaseTypeahead` | released | caller retains control |
+| search source | `search`, `bootstrap`, optional `cancel` | Supplies query and focus results | enabled input | required | `component:BaseTypeahead` | released | rejected work clears current results |
+| focus bootstrap | on or off | Offers bootstrap results before query input | empty focused input | off | `component:BaseTypeahead` | released | off keeps the menu closed |
+| query threshold | non-negative number | Minimum visible-character count before search | non-empty query | `1` | `component:BaseTypeahead` | released | below threshold cancels work and closes results |
+| debounce | milliseconds | Delays query search | typed query | `150` | `component:BaseTypeahead` | released | non-positive runs immediately |
+| result cap | number | Limits fetched results shown | completed search/bootstrap | `10` | `component:BaseTypeahead` | released | source order is preserved |
+| result content | default, `renderItem`, or `item.element` | Chooses content inside the stable option row | result present | default TypeaheadItem | caller and component | released | `item.element` takes precedence |
+| disabled state | native or focusable-disabled | Blocks query mutation; native disabled blocks all activation | disabled | native disabled | component and caller wrapper | released | a list open before focusable-disabled applied picks nothing and can still close |
+| popup width | intrinsic or fixed pixels | Sets result popup width before viewport clamping | popup present | intrinsic, at least anchor width | `component:BaseTypeahead` | released | viewport fit wins |
+| size | `sm`, `md`, `lg` | Selects option-row padding | popup options | `md` | `component:BaseTypeahead` | released | TypeScript rejects other values |
## Behavioral and layout contract
Draft requirements identify their observational or current-authority basis.
-| ID | Candidate invariant | Basis | Draft review state |
-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | ---------------------------------------------- |
-| FR1 | The input is controlled by internal query state while `value` is caller-controlled; selecting a result calls `onChange(item)`, clears query/results, closes the popup, and returns focus to the input. | Current source and tests | verified shipped behavior |
-| FR2 | Search starts only at the grapheme-count threshold, uses the configured debounce, and never presents an empty result for a query that was not searched. | Public API, current i18n character utility, tests | verified audit remediation |
-| FR3 | A newer query, selection, clear, source replacement, or unmount invalidates stale asynchronous work. Escape hides the current popup but does not invalidate pending work, so a late response currently reopens it (retained violation). | Current source, focused retained-red probe, and tests | verified shipped behavior |
-| FR4 | The popup is a named listbox whose result rows are options. A completed empty search renders one disabled option so the listbox retains a valid owned child. | APG combobox pattern, axe, tests | verified audit remediation |
-| FR5 | Arrow keys wrap the highlight; Home/End move to the first/last option; Enter selects; Escape and Tab hide the current popup; IME-owned key events do not activate combobox commands. Escape dismissal is not durable while source work remains pending (FR3). | Current source and tests | verified shipped behavior; Escape gap retained |
-| FR6 | Pending asynchronous source work sets `aria-busy` and renders one named Spinner unless the composed wrapper owns the busy indicator lane. | Current source, input-family FR7, tests | verified shipped behavior |
-| FR7 | Supported BaseProps DOM, ARIA, data, class, style, event, and `xstyle` inputs reach the combobox input while component-owned role, state, value, and behavior remain authoritative. | `architecture:public-component-api/INV5–INV7`, tests | verified audit remediation |
-| FR8 | The popup remains within the inline viewport at 320 CSS px, including long default results and a requested width larger than the available viewport. | WCAG 1.4.10, real Chromium | verified audit remediation |
-| FR9 | Native disabled removes ordinary focus and activation. Focusable-disabled uses `aria-disabled` plus `readOnly` and blocks text/query mutation, but applying it after the popup opens does not currently block Enter selection (retained violation). | Current source, tests, and focused retained-red probe | verified shipped behavior |
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | ---------------------------------------------- |
+| FR1 | The input is controlled by internal query state while `value` is caller-controlled; selecting a result calls `onChange(item)`, clears query/results, closes the popup, and returns focus to the input. | Current source and tests | verified shipped behavior |
+| FR2 | Search starts only at the grapheme-count threshold, uses the configured debounce, and never presents an empty result for a query that was not searched. | Public API, current i18n character utility, tests | verified audit remediation |
+| FR3 | A newer query, selection, clear, source replacement, or unmount invalidates stale asynchronous work. Escape hides the current popup but does not invalidate pending work, so a late response currently reopens it (retained violation). | Current source, focused retained-red probe, and tests | verified shipped behavior |
+| FR4 | The popup is a named listbox whose result rows are options. A completed empty search renders one disabled option so the listbox retains a valid owned child. | APG combobox pattern, axe, tests | verified audit remediation |
+| FR5 | Arrow keys wrap the highlight; Home/End move to the first/last option; Enter selects; Escape and Tab hide the current popup; IME-owned key events do not activate combobox commands. Escape dismissal is not durable while source work remains pending (FR3). | Current source and tests | verified shipped behavior; Escape gap retained |
+| FR6 | Pending asynchronous source work sets `aria-busy` and renders one named Spinner unless the composed wrapper owns the busy indicator lane. | Current source, input-family FR7, tests | verified shipped behavior |
+| FR7 | Supported BaseProps DOM, ARIA, data, class, style, event, and `xstyle` inputs reach the combobox input while component-owned role, state, value, and behavior remain authoritative. | `architecture:public-component-api/INV5–INV7`, tests | verified audit remediation |
+| FR8 | The popup remains within the inline viewport at 320 CSS px, including long default results and a requested width larger than the available viewport. | WCAG 1.4.10, real Chromium | verified audit remediation |
+| FR9 | Native disabled removes ordinary focus and activation. Focusable-disabled uses `aria-disabled` plus `readOnly` and blocks text/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 (`spec:AST-085` FR2). | Current source and tests | verified shipped behavior |
### Allowed variation
@@ -116,17 +116,17 @@ Draft requirements identify their observational or current-authority basis.
### Representative states
-| State | Required invariant | Allowed variation |
-| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
-| rest | named combobox is closed and not busy | caller-owned wrapper and label |
-| focused bootstrap | popup opens only when enabled and results exist | synchronous or asynchronous source |
-| query pending | combobox is busy and duplicate stale work is rejected | direct or wrapper-owned Spinner |
-| results | one highlighted option and valid active descendant | grouped/default/custom content |
-| completed empty | one disabled empty option; no active descendant | caller-supplied empty text |
-| selected result | matching option exposes `aria-selected=true` | generic check presentation |
-| disabled | native disabled blocks activation; focusable-disabled blocks query mutation but can still select an already-open highlight with Enter | native or focusable-disabled semantics |
-| dismissed pending | Escape hides the popup; a late pending response currently reopens it | source completion timing |
-| narrow viewport | popup and result content remain inside two viewport gutters | intrinsic or requested width |
+| State | Required invariant | Allowed variation |
+| ----------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
+| rest | named combobox is closed and not busy | caller-owned wrapper and label |
+| focused bootstrap | popup opens only when enabled and results exist | synchronous or asynchronous source |
+| query pending | combobox is busy and duplicate stale work is rejected | direct or wrapper-owned Spinner |
+| results | one highlighted option and valid active descendant | grouped/default/custom content |
+| completed empty | one disabled empty option; no active descendant | caller-supplied empty text |
+| selected result | matching option exposes `aria-selected=true` | generic check presentation |
+| disabled | native disabled blocks activation; focusable-disabled blocks query mutation, opening and picking, also from an already-open list | native or focusable-disabled semantics |
+| dismissed pending | Escape hides the popup; a late pending response currently reopens it | source completion timing |
+| narrow viewport | popup and result content remain inside two viewport gutters | intrinsic or requested width |
### Transformation and precedence order
@@ -237,17 +237,17 @@ Draft requirements identify their observational or current-authority basis.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| --------------- | ------------------------------------------------------ | ------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------- |
-| FR1–FR2 | BaseTypeahead and Typeahead tests | query, overlap, select, clear | current work replaces newer results or selection does not close | `audit:BaseTypeahead/behavior` |
-| FR3 | shared stale-response tests plus retained-red probe | newer query, clear, unmount, Escape while pending | late work replaces current results or reopens after explicit dismissal | `audit:BaseTypeahead/a11y` |
-| FR4, AR1–AR4 | focused tests, component-scoped axe, live-region tests | results, empty, busy, selected | invalid listbox ownership or state/announcement disappears | `audit:BaseTypeahead/a11y` |
-| FR5, AR5 | keyboard, focus-out, IME, and retained-red tests | arrows, Home/End, Enter, Escape, Tab, composition | command selects or dismisses at the wrong time | `audit:BaseTypeahead/a11y` |
-| FR6 | busy-lane tests | direct and composed pending source | duplicate/missing Spinner or stale busy state | `audit:BaseTypeahead/a11y` |
-| FR7 | focused passthrough tests and strict lint | native-only, alias collisions, DOM/style/events | supported consumer input is dropped or owned semantics are replaced | `audit:BaseTypeahead/api` |
-| FR8 | real-Chromium 320px sensor receipt | long result, wide request, LTR/RTL | popup or its content crosses either viewport gutter | `audit:BaseTypeahead/responsive` |
-| FR9 | shared disabled tests plus retained-red probe | native disabled, focusable-disabled after open | disabled mode mutates query or accepts an already-open selection | `audit:BaseTypeahead/a11y` |
-| Theming anatomy | knowledge and theming-target checks | all mapped parts | target inventory or disposition drifts | `audit:BaseTypeahead/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| --------------- | ------------------------------------------------------ | --------------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------- |
+| FR1–FR2 | BaseTypeahead and Typeahead tests | query, overlap, select, clear | current work replaces newer results or selection does not close | `audit:BaseTypeahead/behavior` |
+| FR3 | shared stale-response tests plus retained-red probe | newer query, clear, unmount, Escape while pending | late work replaces current results or reopens after explicit dismissal | `audit:BaseTypeahead/a11y` |
+| FR4, AR1–AR4 | focused tests, component-scoped axe, live-region tests | results, empty, busy, selected | invalid listbox ownership or state/announcement disappears | `audit:BaseTypeahead/a11y` |
+| FR5, AR5 | keyboard, focus-out, IME, and retained-red tests | arrows, Home/End, Enter, Escape, Tab, composition | command selects or dismisses at the wrong time | `audit:BaseTypeahead/a11y` |
+| FR6 | busy-lane tests | direct and composed pending source | duplicate/missing Spinner or stale busy state | `audit:BaseTypeahead/a11y` |
+| FR7 | focused passthrough tests and strict lint | native-only, alias collisions, DOM/style/events | supported consumer input is dropped or owned semantics are replaced | `audit:BaseTypeahead/api` |
+| FR8 | real-Chromium 320px sensor receipt | long result, wide request, LTR/RTL | popup or its content crosses either viewport gutter | `audit:BaseTypeahead/responsive` |
+| FR9 | shared disabled tests | native disabled; focusable-disabled before and after open | disabled mode mutates query, opens the list, or accepts a selection | `audit:BaseTypeahead/a11y` |
+| Theming anatomy | knowledge and theming-target checks | all mapped parts | target inventory or disposition drifts | `audit:BaseTypeahead/theming` |
## Decision log
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index 7142fc4beb..84991463f0 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -153,10 +153,10 @@ export interface BaseTypeaheadProps<T extends SearchableItem> extends Omit<
* When disabled with a reason, keeps the input focusable via `aria-disabled`
* (instead of the native `disabled` attribute) and `readOnly` so an
* associated disabled-reason tooltip stays discoverable by keyboard and
- * assistive technology. Query and text mutation are blocked, but an
- * already-open highlighted option can still be selected with Enter after a
- * transition into this state. Consumers (Typeahead) own the tooltip and
- * wrapper.
+ * assistive technology. Query and text mutation, opening the list, and a
+ * pick by Enter or a press are blocked, also from a list that was open
+ * before this state applied; Escape or Tab still closes it. Consumers
+ * (Typeahead) own the tooltip and wrapper.
* @default false
*/
isFocusableDisabled?: boolean;
@@ -687,11 +687,25 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
// 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.
+ // 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);
+ useIsomorphicLayoutEffect(() => {
+ isDisabledRef.current = isDisabled;
+ }, [isDisabled]);
const showLayer = useCallback(() => {
+ if (isDisabledRef.current) {
+ return;
+ }
if (pointerActiveRef.current) {
document.addEventListener(
'click',
- () => requestAnimationFrame(() => popover.show()),
+ () =>
+ requestAnimationFrame(() => {
+ if (!isDisabledRef.current) {
+ popover.show();
+ }
+ }),
{once: true},
);
} else {
@@ -915,6 +929,11 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
// Handle item selection
const handleSelect = useCallback(
(item: T) => {
+ // A disabled field changes nothing, also from a list that was open
+ // before it became disabled (spec:AST-085 FR2).
+ if (isDisabled) {
+ return;
+ }
// Bump generation to invalidate any in-flight async searches
searchGenRef.current++;
if (searchTimeoutRef.current) {
@@ -933,7 +952,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
popover.hide();
inputRef.current?.focus();
},
- [onChange, popover, searchSource, setLoading],
+ [isDisabled, onChange, popover, searchSource, setLoading],
);
// Shared by handleFocus and handleClick: bootstrap entries if none are
@@ -984,7 +1003,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
// dropdown never reopens until the user clicks away and back (#6845). See
// wasAlreadyFocusedRef above for how the two cases are told apart.
const handleClick = useCallback(() => {
- if (!wasAlreadyFocusedRef.current || popover.isOpen) {
+ if (isDisabled || !wasAlreadyFocusedRef.current || popover.isOpen) {
return;
}
if (
@@ -997,6 +1016,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
}
openIfEligible();
}, [
+ isDisabled,
popover.isOpen,
hasEntriesOnFocus,
query.length,
@@ -1050,6 +1070,24 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
return;
}
+ // A focusable-disabled field opens no list and picks nothing; it only
+ // lets a list that was open before it became disabled close
+ // (spec:AST-085 FR2).
+ if (isDisabled) {
+ // Enter on a list that is still open picks nothing, and must not
+ // submit an enclosing form either, as it would not while enabled.
+ if (popover.isOpen && e.key === 'Enter') {
+ e.preventDefault();
+ }
+ if (popover.isOpen && (e.key === 'Escape' || e.key === 'Tab')) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ }
+ popover.hide();
+ }
+ return;
+ }
+
if (!popover.isOpen) {
if (e.key === 'ArrowDown' && (hasEntriesOnFocus || query.length > 0)) {
e.preventDefault();
@@ -1123,6 +1161,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
}
},
[
+ isDisabled,
popover,
results,
highlightedIndex,
@@ -1218,8 +1257,8 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
placeholder={placeholder}
// When a disabled-reason tooltip is shown the input keeps focusability
// via aria-disabled + readOnly instead of the native disabled
- // attribute. Query and text mutation are blocked, but an already-open
- // highlighted option can still be selected with Enter after transition.
+ // attribute. Query and text mutation, opening and picking are blocked
+ // by the handlers above (spec:AST-085 FR2).
disabled={isDisabled && !isFocusableDisabled}
readOnly={isFocusableDisabled || undefined}
autoFocus={hasAutoFocus}
diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsx
index df7d7dc5f9..5253c1dad0 100644
--- a/packages/core/src/Typeahead/Typeahead.test.tsx
+++ b/packages/core/src/Typeahead/Typeahead.test.tsx
@@ -2228,6 +2228,126 @@ describe('Typeahead disabledMessage', () => {
expect(onChange).not.toHaveBeenCalled();
});
+ it('opens no list and picks nothing while focusable-disabled (spec:AST-085 FR2)', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <Typeahead
+ label="Assignee"
+ searchSource={fruitSource}
+ value={null}
+ onChange={onChange}
+ hasEntriesOnFocus
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ const input = screen.getByRole('combobox');
+ await user.click(input);
+ await user.click(input);
+ await user.keyboard('{ArrowDown}{Enter}');
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ expect(screen.queryByRole('option', {hidden: true})).toBeNull();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('does not reopen on a click into the still-focused input once disabled', async () => {
+ const user = userEvent.setup();
+ const field = (isDisabled: boolean) => (
+ <Typeahead
+ label="Assignee"
+ searchSource={fruitSource}
+ value={null}
+ onChange={() => {}}
+ hasEntriesOnFocus
+ isDisabled={isDisabled}
+ disabledMessage={isDisabled ? 'You need the Editor role' : undefined}
+ />
+ );
+ const {rerender} = render(field(false));
+ const input = screen.getByRole('combobox');
+ await user.click(input);
+ await waitFor(() => expect(input).toHaveAttribute('aria-expanded', 'true'));
+ // A pick closes the list and leaves focus in the input.
+ await user.click(screen.getAllByRole('option', {hidden: true})[0]);
+ await waitFor(() =>
+ expect(input).toHaveAttribute('aria-expanded', 'false'),
+ );
+ rerender(field(true));
+ const disabled = screen.getByRole('combobox');
+ await user.click(disabled);
+ await user.click(disabled);
+ expect(disabled).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('picks nothing from a list opened before the field became disabled, and lets it close', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const onSubmit = vi.fn((event: React.FormEvent) => event.preventDefault());
+ const field = (isDisabled: boolean) => (
+ <form onSubmit={onSubmit}>
+ <Typeahead
+ label="Assignee"
+ searchSource={fruitSource}
+ value={null}
+ onChange={onChange}
+ hasEntriesOnFocus
+ isDisabled={isDisabled}
+ disabledMessage="You need the Editor role"
+ />
+ </form>
+ );
+ const {rerender} = render(field(false));
+ const input = screen.getByRole('combobox');
+ await user.click(input);
+ await waitFor(() => expect(input).toHaveAttribute('aria-expanded', 'true'));
+ await user.keyboard('{ArrowDown}');
+
+ rerender(field(true));
+ // The open list stays in the DOM (hidden from the accessibility tree).
+ await user.keyboard('{Enter}');
+ fireEvent.click(screen.getAllByRole('option', {hidden: true})[0]);
+ expect(onChange).not.toHaveBeenCalled();
+ // Enter on the still-open list does not submit the form.
+ expect(onSubmit).not.toHaveBeenCalled();
+ await user.keyboard('{Escape}');
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('does not open a list for a search that settles after the field became disabled', async () => {
+ let resolveSearch: (items: SearchableItem[]) => void = () => {};
+ const pendingSource: SearchSource = {
+ search: async () =>
+ new Promise(resolve => {
+ resolveSearch = resolve;
+ }),
+ bootstrap: () => [],
+ };
+ const user = userEvent.setup();
+ const field = (isDisabled: boolean) => (
+ <Typeahead
+ label="Assignee"
+ searchSource={pendingSource}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ isDisabled={isDisabled}
+ disabledMessage={isDisabled ? 'You need the Editor role' : undefined}
+ />
+ );
+ const {rerender} = render(field(false));
+ const input = screen.getByRole('combobox');
+ await user.type(input, 'ap');
+ rerender(field(true));
+ await act(async () => {
+ resolveSearch(fruits);
+ });
+ expect(screen.getByRole('combobox')).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ });
+
it('remains natively disabled when disabled without a reason', () => {
render(
<Typeahead