Skip to content

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

TypeScript

fix(Typeahead): keep empty feedback with its settled query (#8904)

nynexman4464ad76345bc4c2
diff --git a/.changeset/typeahead-and-tokenizer-show-loading-feedback-in-f8g1.md b/.changeset/typeahead-and-tokenizer-show-loading-feedback-in-f8g1.md
new file mode 100644
index 0000000000..8b45a1f3f4
--- /dev/null
+++ b/.changeset/typeahead-and-tokenizer-show-loading-feedback-in-f8g1.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Typeahead and Tokenizer hide the previous empty-result row while the next query debounces or waits for its answer. The existing input spinner provides loading feedback; no replacement Loading row is added. Settled empty results and their announcements remain unchanged. Fixes #8903.
+@nynexman4464
diff --git a/apps/storybook/stories/BaseTypeahead.stories.tsx b/apps/storybook/stories/BaseTypeahead.stories.tsx
index 32448ee8a7..08a0b9d9ca 100644
--- a/apps/storybook/stories/BaseTypeahead.stories.tsx
+++ b/apps/storybook/stories/BaseTypeahead.stories.tsx
@@ -6,11 +6,13 @@ import {expect, userEvent, waitFor, within} from 'storybook/test';
import * as stylex from '@stylexjs/stylex';
import {
BaseTypeahead,
+ Typeahead,
createStaticSource,
type BaseTypeaheadProps,
type SearchableItem,
type SearchSource,
} from '@astryxdesign/core/Typeahead';
+import {Tokenizer} from '@astryxdesign/core/Tokenizer';
import {
borderVars,
colorVars,
@@ -42,6 +44,14 @@ const pendingSource: SearchSource = {
search: () => new Promise(() => {}),
bootstrap: () => new Promise(() => {}),
};
+// A single-answer remote source with a reproducible pending interval (#8903).
+const delayedSource: SearchSource = {
+ search: async query => {
+ await new Promise<void>(resolve => setTimeout(resolve, 1000));
+ return source.search(query);
+ },
+ bootstrap: () => [],
+};
const styles = stylex.create({
stage: {
@@ -209,6 +219,40 @@ export const EmptyResults: Story = {
},
};
+function EmptyThenPendingDemo() {
+ const [value, setValue] = useState<SearchableItem | null>(null);
+ const [tokens, setTokens] = useState<SearchableItem[]>([]);
+ return (
+ <div {...stylex.props(styles.stage)}>
+ <Demo source={delayedSource} label="Bare framework" />
+ <Typeahead
+ label="Single framework"
+ searchSource={delayedSource}
+ value={value}
+ onChange={setValue}
+ />
+ <Tokenizer
+ label="Framework tokens"
+ searchSource={delayedSource}
+ value={tokens}
+ onChange={setTokens}
+ />
+ </div>
+ );
+}
+
+export const EmptyThenPending: Story = {
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Search for zzz, wait for the empty result, then type react or xxx. Each request takes one second; the previous empty result must not remain during debounce or loading.',
+ },
+ },
+ },
+ render: () => <EmptyThenPendingDemo />,
+};
+
export const CustomRenderer: Story = {
render: () => (
<Demo
diff --git a/packages/core/src/Typeahead/BaseTypeahead.emptyState.a11y.chromium.spec.ts b/packages/core/src/Typeahead/BaseTypeahead.emptyState.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..0127a88316
--- /dev/null
+++ b/packages/core/src/Typeahead/BaseTypeahead.emptyState.a11y.chromium.spec.ts
@@ -0,0 +1,138 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope core/Tokenizer ^apps/storybook/stories/BaseTypeahead
+
+/**
+ * @file BaseTypeahead.emptyState.a11y.chromium.spec.ts
+ * @input Checked-in empty-to-pending Storybook fixture and real Chromium
+ * @output Query/debounce/pending/final row, busy, accessibility-tree and selection evidence
+ * @position Browser regression for AST-092 FR5 and AST-056 AR1 (#8903)
+ */
+
+import {expect, test} from '@playwright/test';
+import {
+ serveStorybook,
+ DEFAULT_STORYBOOK_DIR,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => storybook?.close());
+
+for (const label of [
+ 'Bare framework',
+ 'Single framework',
+ 'Framework tokens',
+]) {
+ for (const query of ['react', 'xxx']) {
+ test(`${label}: empty → debounce → pending → ${query === 'react' ? 'results' : 'empty'}`, async ({
+ page,
+ }, testInfo) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-basetypeahead--empty-then-pending&viewMode=story`,
+ );
+ const input = page.getByRole('combobox', {name: label});
+ await input.waitFor();
+ await page.clock.install();
+ await page.clock.pauseAt(new Date());
+ const listbox = page.locator(
+ `[id="${await input.getAttribute('aria-controls')}"]`,
+ );
+ await input.fill('zzz');
+ await page.clock.runFor(150);
+ await expect(input).toHaveAttribute('aria-busy', 'true');
+ await expect(input).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.getByRole('img', {name: 'Loading'})).toBeVisible();
+ await expect(listbox).not.toBeVisible();
+ await testInfo.attach('first-pending', {
+ body: await page.screenshot({
+ path: testInfo.outputPath('first-pending.png'),
+ }),
+ contentType: 'image/png',
+ });
+ await page.clock.runFor(1000);
+ await expect(listbox).toBeVisible();
+ await expect(listbox.getByRole('option')).toHaveText('No results found');
+ await page.clock.runFor(32);
+ await expect(
+ page.locator('[data-astryx-live-region="polite"]'),
+ ).toHaveText('No results found');
+ // Clear the settled announcement through its normal lifetime.
+ await page.clock.runFor(2000);
+
+ await input.fill(query);
+ await page.clock.runFor(149);
+ await testInfo.attach('debounce', {
+ body: await page.screenshot({
+ path: testInfo.outputPath('debounce.png'),
+ }),
+ contentType: 'image/png',
+ });
+ await expect(listbox).not.toContainText('No results found');
+ await expect(listbox.getByRole('option')).toHaveCount(0);
+ await expect(input).not.toHaveAttribute('aria-busy');
+ await expect(
+ page.locator('[data-astryx-live-region="polite"]'),
+ ).toBeEmpty();
+ await page.clock.runFor(1);
+ await expect(input).toHaveAttribute('aria-busy', 'true');
+ await expect(listbox.getByRole('option')).toHaveCount(0);
+ await expect(listbox).toBeEmpty();
+ await expect(page.getByRole('img', {name: 'Loading'})).toBeVisible();
+ await expect(input).not.toHaveAttribute('aria-activedescendant');
+ await expect(listbox).toMatchAriaSnapshot('- listbox "Search results"');
+ await testInfo.attach('pending', {
+ body: await page.screenshot({path: testInfo.outputPath('pending.png')}),
+ contentType: 'image/png',
+ });
+ await page.clock.runFor(999);
+ await expect(listbox).not.toContainText('No results found');
+ await expect(input).toHaveAttribute('aria-busy', 'true');
+ await page.clock.runFor(1);
+ await page.clock.runFor(32);
+ await expect(input).not.toHaveAttribute('aria-busy');
+ await expect(page.getByRole('img', {name: 'Loading'})).toHaveCount(0);
+ if (query === 'react') {
+ await expect(listbox.getByRole('option')).toHaveText('React');
+ await expect(
+ page.locator('[data-astryx-live-region="polite"]'),
+ ).toHaveText('1 result');
+ await testInfo.attach('settled', {
+ body: await page.screenshot({
+ path: testInfo.outputPath('settled.png'),
+ }),
+ contentType: 'image/png',
+ });
+ await input.press('Enter');
+ await expect(input).toHaveValue('');
+ await expect(input).toHaveAttribute('aria-expanded', 'false');
+ if (label === 'Framework tokens') {
+ await expect(
+ page.getByRole('button', {name: 'Remove React'}),
+ ).toBeVisible();
+ }
+ } else {
+ await expect(listbox.getByRole('option')).toHaveText(
+ 'No results found',
+ );
+ await expect(listbox.getByRole('option')).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ await expect(
+ page.locator('[data-astryx-live-region="polite"]'),
+ ).toHaveText('No results found');
+ await testInfo.attach('settled', {
+ body: await page.screenshot({
+ path: testInfo.outputPath('settled.png'),
+ }),
+ contentType: 'image/png',
+ });
+ }
+ });
+ }
+}
diff --git a/packages/core/src/Typeahead/BaseTypeahead.test.tsx b/packages/core/src/Typeahead/BaseTypeahead.test.tsx
index ee1c2ea854..68090c454b 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.test.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.test.tsx
@@ -2,16 +2,36 @@
/**
* @file BaseTypeahead.test.tsx
- * @input BaseTypeahead public props and a synchronous SearchSource
- * @output Combobox contract tests, including stale source refresh on focus and reopen
+ * @input BaseTypeahead and composed public props with synchronous and deferred SearchSources
+ * @output Combobox contracts, including source refresh and empty-to-pending red/green coverage
* @position Colocated verification for BaseTypeahead
*/
-import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest';
-import {fireEvent, render, screen, waitFor} from '@testing-library/react';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import * as stylex from '@stylexjs/stylex';
import {BaseTypeahead} from './BaseTypeahead';
+import {Typeahead} from './Typeahead';
+import {Tokenizer} from '../Tokenizer';
+import {InternationalizationProvider} from '../i18n';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import type {SearchSource, SearchableItem} from './types';
const popoverOpenState = new WeakMap<HTMLElement, boolean>();
@@ -353,4 +373,181 @@ describe('BaseTypeahead', () => {
).toHaveAttribute('aria-disabled', 'true');
});
});
+
+ describe('empty search followed by a newer query (#8903)', () => {
+ beforeEach(() => {
+ __resetLiveRegionsForTest();
+ vi.useFakeTimers({
+ toFake: [
+ 'setTimeout',
+ 'clearTimeout',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ ],
+ });
+ });
+ afterEach(() => {
+ __resetLiveRegionsForTest();
+ vi.useRealTimers();
+ });
+
+ it('keeps an empty focus bootstrap quiet when an empty search is cleared', async () => {
+ render(
+ <BaseTypeahead
+ searchSource={emptySource}
+ value={null}
+ onChange={() => {}}
+ hasEntriesOnFocus
+ debounceMs={0}
+ aria-label="Framework"
+ />,
+ );
+ const input = screen.getByRole('combobox', {name: 'Framework'});
+ fireEvent.focus(input);
+ fireEvent.change(input, {target: {value: 'none'}});
+ await act(async () => vi.advanceTimersByTimeAsync(32));
+ const options = within(screen.getByRole('listbox', {hidden: true}));
+ expect(options.getByRole('option', {hidden: true})).toHaveTextContent(
+ 'No results found',
+ );
+
+ fireEvent.change(input, {target: {value: ''}});
+ await act(async () => vi.advanceTimersByTimeAsync(32));
+ expect(input).toHaveValue('');
+ expect(input).not.toHaveAttribute('aria-busy');
+ expect(screen.queryByRole('img', {name: 'Loading'})).toBeNull();
+ expect(options.queryAllByRole('option', {hidden: true})).toHaveLength(0);
+ });
+
+ // Bare and composed fields have different busy-indicator owners. Zero
+ // debounce independently exercises the pending-request regression.
+ describe.each([
+ ['BaseTypeahead', 0],
+ ['BaseTypeahead', 150],
+ ['Typeahead', 150],
+ ['Tokenizer', 150],
+ ] as const)('%s with %i ms debounce', (field, debounceMs) => {
+ it.each(['populated', 'empty'] as const)(
+ 'withholds the old empty result until a %s final response settles',
+ async outcome => {
+ let resolveNext!: (items: SearchableItem[]) => void;
+ const pending = new Promise<SearchableItem[]>(resolve => {
+ resolveNext = resolve;
+ });
+ const search = vi
+ .fn<SearchSource<SearchableItem>['search']>()
+ .mockResolvedValueOnce([])
+ .mockReturnValueOnce(pending);
+ const searchSource: SearchSource<SearchableItem> = {
+ search,
+ bootstrap: () => [],
+ };
+ const onChange = vi.fn();
+ const props = {
+ searchSource,
+ onChange,
+ debounceMs,
+ emptySearchText: <span>No matching frameworks</span>,
+ };
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {
+ '@astryx.typeahead.loading': 'Recherche en cours',
+ '@astryx.typeahead.resultCount': '{count, number} résultat',
+ },
+ }}>
+ {field === 'Tokenizer' ? (
+ <Tokenizer {...props} label="Framework" value={[]} />
+ ) : field === 'Typeahead' ? (
+ <Typeahead {...props} label="Framework" value={null} />
+ ) : (
+ <BaseTypeahead {...props} aria-label="Framework" value={null} />
+ )}
+ </InternationalizationProvider>,
+ );
+ const input = screen.getByRole('combobox', {name: 'Framework'});
+ const liveRegion = () =>
+ document.querySelector('[data-astryx-live-region="polite"]');
+ fireEvent.focus(input);
+ fireEvent.change(input, {target: {value: 'none'}});
+ await act(async () => vi.advanceTimersByTimeAsync(debounceMs));
+ await act(async () => vi.advanceTimersByTimeAsync(32));
+ const options = within(screen.getByRole('listbox', {hidden: true}));
+ expect(options.getByRole('option', {hidden: true})).toHaveTextContent(
+ 'No matching frameworks',
+ );
+ expect(liveRegion()).toHaveTextContent('No matching frameworks');
+ expect(input).not.toHaveAttribute('aria-busy');
+ // Let the first announcement clear normally: a premature new
+ // empty-result announcement cannot hide behind the previous one.
+ await act(async () => vi.advanceTimersByTimeAsync(2000));
+ expect(liveRegion()?.textContent).toBe('');
+
+ fireEvent.change(input, {target: {value: 'next'}});
+ if (debounceMs > 0) {
+ await act(async () => vi.advanceTimersByTimeAsync(debounceMs - 1));
+ expect(search).toHaveBeenCalledTimes(1);
+ expect(options.queryByText('No matching frameworks')).toBeNull();
+ expect(
+ options.queryAllByRole('option', {hidden: true}),
+ ).toHaveLength(0);
+ expect(liveRegion()?.textContent).toBe('');
+ // Keep the existing spinner's request-start timing.
+ expect(input).not.toHaveAttribute('aria-busy');
+ await act(async () => vi.advanceTimersByTimeAsync(1));
+ }
+ expect(search).toHaveBeenLastCalledWith('next');
+ expect(input).toHaveAttribute('aria-busy', 'true');
+ expect(options.queryByText('No matching frameworks')).toBeNull();
+ expect(options.queryAllByRole('option', {hidden: true})).toHaveLength(
+ 0,
+ );
+ expect(
+ screen.getByRole('img', {name: 'Recherche en cours'}),
+ ).toBeInTheDocument();
+ expect(input).not.toHaveAttribute('aria-activedescendant');
+ await act(async () => vi.advanceTimersByTimeAsync(32));
+ expect(liveRegion()).toHaveTextContent('Recherche en cours');
+ expect(liveRegion()).not.toHaveTextContent('No matching frameworks');
+
+ await act(async () =>
+ resolveNext(outcome === 'empty' ? [] : [resultItem]),
+ );
+ await act(async () => vi.advanceTimersByTimeAsync(32));
+ expect(input).not.toHaveAttribute('aria-busy');
+ expect(
+ screen.queryByRole('img', {name: 'Recherche en cours'}),
+ ).toBeNull();
+ if (outcome === 'empty') {
+ expect(options.getByRole('option', {hidden: true})).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ expect(
+ options.getByRole('option', {hidden: true}),
+ ).toHaveTextContent('No matching frameworks');
+ expect(liveRegion()).toHaveTextContent('No matching frameworks');
+ expect(input).not.toHaveAttribute('aria-activedescendant');
+ } else {
+ expect(
+ options.getByRole('option', {name: 'Result', hidden: true}),
+ ).toBeInTheDocument();
+ expect(options.queryByText('No matching frameworks')).toBeNull();
+ expect(liveRegion()).toHaveTextContent('1 résultat');
+ fireEvent.keyDown(input, {key: 'Enter'});
+ if (field === 'Tokenizer') {
+ expect(onChange).toHaveBeenCalledWith([resultItem], {
+ type: 'add',
+ item: resultItem,
+ });
+ } else {
+ expect(onChange).toHaveBeenCalledWith(resultItem);
+ }
+ }
+ },
+ );
+ });
+ });
});
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index 4f4cc27b7b..7142fc4beb 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -5,7 +5,7 @@
/**
* @file BaseTypeahead.tsx
* @input Uses React, StyleX, usePopover, TypeaheadItem
- * @output Exports BaseTypeahead; focus bootstraps a replaced search source
+ * @output Exports BaseTypeahead; empty feedback belongs to the current settled query
* @position Core implementation; used by Typeahead and Tokenizer
*
* Pure combobox engine: input, search, keyboard navigation, dropdown.
@@ -531,14 +531,17 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
const [highlightedIndex, setHighlightedIndex] = useState(-1);
const [isLoading, setIsLoading] = useState(false);
const [hasSearched, setHasSearched] = useState(false);
-
- // Only the WORDS move here, not the timing. An empty query still reports
- // nothing — a focus-opened menu that bootstrapped to nothing is not a
- // search that failed — and a search still in flight reports nothing, which
- // matters because the row is in the DOM before the spinner clears.
+ // `isLoading` starts with the request, after debouncing. Until then the
+ // cached empty answer belongs to the old query, not the text now typed.
+ const [lastSearchedQuery, setLastSearchedQuery] = useState('');
+ const isSearchPending = isLoading || query !== lastSearchedQuery;
+
+ // An empty query reports nothing: an empty focus bootstrap is not a failed
+ // search. A newer query stays silent through debounce and pending work;
+ // only its settled empty row supplies the words to announce.
useAnnounceRenderedText(
emptyStateRef,
- results.length === 0 && hasSearched && query.length > 0 && !isLoading,
+ results.length === 0 && hasSearched && query.length > 0 && !isSearchPending,
query,
);
@@ -715,6 +718,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
// in-flight response for an older query fails the gen check below
// instead of overwriting the newer results.
const gen = ++searchGenRef.current;
+ setLastSearchedQuery(searchQuery);
setLoading(true);
setHasSearched(true);
try {
@@ -1250,7 +1254,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
themeProps('typeahead-dropdown'),
stylex.props(styles.dropdown),
)}>
- {results.length === 0 && hasSearched ? (
+ {results.length === 0 && hasSearched && !isSearchPending ? (
<div
ref={emptyStateRef}
role="option"