An open source design system that's fully customizable and agent ready
TypeScript
fix(Typeahead): an empty or failed focus list closes instead of staying open and empty (#9532)
Cindy Zhang6a591d932903
diff --git a/.changeset/typeahead-empty-focus-list-closes.md b/.changeset/typeahead-empty-focus-list-closes.mdnew file mode 100644index 0000000000..7ed49b07cc--- /dev/null+++ b/.changeset/typeahead-empty-focus-list-closes.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Typeahead`: with focus entries on, an open list whose focus entries come back empty, or fail to load (for example after the query is cleared), now closes instead of staying open and empty. A typed search with no results still shows its message.++@cixzhangdiff --git a/docs/specs/components/Typeahead/BaseTypeahead.spec.md b/docs/specs/components/Typeahead/BaseTypeahead.spec.mdindex fd0242034b..6729a5ef3e 100644--- a/docs/specs/components/Typeahead/BaseTypeahead.spec.md+++ b/docs/specs/components/Typeahead/BaseTypeahead.spec.md@@ -108,7 +108,7 @@ Consumer migration instructions belong in consumer docs and release notes.| ID | Invariant | Basis || ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ || 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 |-| 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. | Current source and tests |+| 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. A focus bootstrap or reload that yields no eligible choice, or fails, closes the list; a completed empty search for a typed query still shows FR4's message. | Current source and tests || FR3 | A newer query, selection, clear, source replacement, or unmount invalidates stale asynchronous work. Escape hides the current popup without invalidating pending work, so a late response reopens it. Lists for a query that is no longer current, including partial lists, are dropped (`spec:AST-092` FR4). ArrowDown on a closed field after the source was replaced searches the replacement instead of showing the old list. | Current source and tests; `spec:AST-092` FR4 || FR4 | The popup is a named listbox whose result rows are options, and no active descendant is set while no option shows. A completed empty search's message MUST be presentational and announced as `spec:AST-056` AR1 requires (`spec:AST-058` FR7). Implementation gap: the message renders as one disabled option. | APG combobox pattern; `spec:AST-058` FR7; current source and tests || FR5 | Arrow keys wrap the highlight; Home/End move to the first/last option; Enter selects; Escape and Tab hide the current popup, Tab moving focus on; IME-owned key events do not activate combobox commands. Escape dismissal is not durable while source work remains pending (FR3). | `spec:AST-020` FR15; current source and tests |@@ -133,7 +133,7 @@ Consumer migration instructions belong in consumer docs and release notes.| 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 |+| focused bootstrap | popup opens only when enabled and results exist, and closes when a bootstrap or reload yields none or fails | 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 | a presentational message and no active descendant; today one disabled option, the FR4 gap | caller-supplied empty text |@@ -258,7 +258,7 @@ Consumer migration instructions belong in consumer docs and release notes.| 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` |+| FR2 | `BaseTypeahead.test.tsx` "counts grapheme clusters when enforcing minQueryLength"; `Typeahead.test.tsx` minQueryLength and paste cases; `BaseTypeahead.test.tsx` "focus list with no choices" cases and "closes an open focus list when the reload fails" | 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` |diff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.jsonindex f926d7d2c0..fe144e838c 100644--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json@@ -1446,7 +1446,6 @@"FR15","FR15","FR15",- "FR15","FR2","FR2","FR2",@@ -1476,7 +1475,6 @@"component:BaseTypeahead","component:Tokenizer","component:Tokenizer",- "component:Tokenizer","family:input-fields","spec quote","spec quote",diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsxindex 3fe4e08a90..7c762b32aa 100644--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx@@ -1288,7 +1288,7 @@ describe('Tokenizer', () => {maxEntries?: number;source?: () => SearchSource;steps: string[];- expanded: boolean;+ expanded?: boolean;listed?: string[];notListed?: string[];};@@ -1322,10 +1322,11 @@ describe('Tokenizer', () => {expanded: false,},{- situation: 'token picked from the list (inside add): closes, no reopen',+ // Whether a pick keeps the list open is FR14's, not this table's.+ situation: 'token picked from the list (inside add): not offered again',initial: [users[0]],steps: ['open', 'listed:Charlie', 'pick:Charlie'],- expanded: false,+ notListed: ['Charlie'],},{situation: 'focus list open, slow reload: new token never listed',@@ -1456,10 +1457,12 @@ describe('Tokenizer', () => {await new Promise(resolve => setTimeout(resolve, 300));});- expect(input).toHaveAttribute(- 'aria-expanded',- row.expanded ? 'true' : 'false',- );+ if (row.expanded != null) {+ expect(input).toHaveAttribute(+ 'aria-expanded',+ row.expanded ? 'true' : 'false',+ );+ }for (const name of row.listed ?? []) {expect(option(name)).toBeInTheDocument();}diff --git a/packages/core/src/Typeahead/BaseTypeahead.test.tsx b/packages/core/src/Typeahead/BaseTypeahead.test.tsxindex e51aa558b4..217fcdd93b 100644--- a/packages/core/src/Typeahead/BaseTypeahead.test.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.test.tsx@@ -383,6 +383,90 @@ describe('BaseTypeahead', () => {).not.toBeInTheDocument();});+ // FR2: a focus load that yields no choice, or fails, closes the list; a+ // completed empty search for a typed query still shows FR4's message.+ describe('focus list with no choices', () => {+ const renderField = (searchSource: SearchSource<SearchableItem>) =>+ render(+ <BaseTypeahead+ searchSource={searchSource}+ value={null}+ onChange={() => {}}+ hasEntriesOnFocus+ />,+ );++ it('closes when a cleared query loads an empty focus list', async () => {+ const user = userEvent.setup();+ renderField({search: () => [resultItem], bootstrap: () => []});+ const input = screen.getByRole('combobox');++ await user.type(input, 're');+ await waitFor(() => {+ expect(+ screen.getByRole('option', {name: 'Result', hidden: true}),+ ).toBeInTheDocument();+ });+ await user.clear(input);++ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'false');+ });+ });++ it('closes when a cleared query leaves the empty-search message for an empty focus list', async () => {+ const user = userEvent.setup();+ renderField({search: () => [], bootstrap: () => []});+ const input = screen.getByRole('combobox');++ await user.type(input, 'zz');+ await waitFor(() => {+ expect(screen.getByText('No results found')).toBeInTheDocument();+ });+ await user.clear(input);++ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'false');+ });+ });++ it('closes when a cleared query fails to load the focus list', async () => {+ const user = userEvent.setup();+ renderField({+ search: () => [resultItem],+ bootstrap: async () => {+ throw new Error('offline');+ },+ });+ const input = screen.getByRole('combobox');++ await user.type(input, 're');+ await waitFor(() => {+ expect(+ screen.getByRole('option', {name: 'Result', hidden: true}),+ ).toBeInTheDocument();+ });+ await user.clear(input);++ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'false');+ });+ });++ it('still shows the empty-search message for a typed query with no results', async () => {+ const user = userEvent.setup();+ renderField({search: () => [], bootstrap: () => [resultItem]});+ const input = screen.getByRole('combobox');++ await user.type(input, 'zz');++ await waitFor(() => {+ expect(screen.getByText('No results found')).toBeInTheDocument();+ });+ expect(input).toHaveAttribute('aria-expanded', 'true');+ });+ });+// component:Tokenizer FR13, spec:AST-092 FR4: when the caller's committed// values change, an open list reloads from the source they now filter.describe('committed values change', () => {diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex 92b22caa5f..17ba968f05 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -607,8 +607,9 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({);// Committed values (Tokenizer's tokens) leave the shown rows in the same// render that commits them, before any reload answers, so a list never- // offers a token (component:Tokenizer FR13). The highlight stays on its item- // when that item remains. The previous key is remembered in state, like+ // offers a token (component:Tokenizer FR13). Until the reload answers, the+ // highlight stays on its item when that item remains; the reloaded list+ // highlights its first row. The previous key is remembered in state, like// `sourceOfState` below.const committedChoices = useCommittedChoices();const committedChoicesKey = committedChoices?.key;@@ -1119,11 +1120,16 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({resultsGenRef.current = gen;const shown = bootstrapResults.slice(0, maxMenuItems);const nextHighlightedIndex = shown.length > 0 ? 0 : -1;+ // A focus load that yields no choice, or fails (it arrives here empty),+ // closes the list rather than leaving it open and empty. A typed+ // query's empty search is not a focus load and keeps its empty-search+ // message.if (results.length === 0 &&shown.length === 0 &&highlightedIndex === -1) {+ popover.hide();return;}setHeldHeight(null);@@ -1131,11 +1137,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({setHighlightedIndex(nextHighlightedIndex);if (bootstrapResults.length > 0) {showLayer();- } else if (committedChoices != null) {- // A Tokenizer list left with no eligible choice (its focus entries- // all committed, or the request failed) closes rather than staying- // open and empty (component:Tokenizer FR15). A plain Typeahead- // provides no committed choices and keeps its current behavior.+ } else {popover.hide();}},@@ -1146,7 +1148,6 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({showLayer,replaceResults,popover,- committedChoices,],);