An open source design system that's fully customizable and agent ready
TypeScript
fix(Typeahead): clear loading state when search source is replaced (#7457) (#7487)
Geervanb06a093637dd
diff --git a/.changeset/typeahead-searchsource-clear-loading.md b/.changeset/typeahead-searchsource-clear-loading.mdnew file mode 100644index 0000000000..158bf17bac--- /dev/null+++ b/.changeset/typeahead-searchsource-clear-loading.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Typeahead`, `Tokenizer`, and `PowerSearch`: clear loading state and stop busy indicator when search source is replaced (#7457)++@Geervandiff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsxindex 8ff89d7a35..528c22cb32 100644--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx@@ -20,7 +20,7 @@ import {afterEach,} from 'vitest';import {render, screen, fireEvent, act, waitFor} from '@testing-library/react';-import {createRef, Profiler} from 'react';+import {createRef, Profiler, useState} from 'react';import userEvent from '@testing-library/user-event';import {Tokenizer} from './Tokenizer';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';@@ -1790,6 +1790,59 @@ describe('Tokenizer end-lane reserve', () => {expect(renderedTokens).toEqual([]);});+ it('clears the busy spinner when a token is added while a bootstrap load is in flight', async () => {+ let settle: (items: SearchableItem[]) => void = () => {};+ const bootstrap = vi.fn(+ async () =>+ new Promise<SearchableItem[]>(resolve => {+ settle = resolve;+ }),+ );+ const source: SearchSource = {search: () => [], bootstrap};++ function Harness() {+ const [value, setValue] = useState<SearchableItem[]>([]);+ return (+ <>+ <Tokenizer+ label="Items"+ searchSource={source}+ value={value}+ onChange={setValue}+ hasEntriesOnFocus+ />+ <button type="button" onClick={() => setValue([users[0]])}>+ Add Token+ </button>+ </>+ );+ }++ render(<Harness />);+ const input = screen.getByRole('combobox');++ fireEvent.focus(input);+ await waitFor(() => {+ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();+ });++ fireEvent.click(screen.getByRole('button', {name: 'Add Token'}));++ await waitFor(() => {+ expect(+ screen.queryByRole('status', {name: 'Loading'}),+ ).not.toBeInTheDocument();+ });++ await act(async () => {+ settle([]);+ await Promise.resolve();+ });+ expect(+ screen.queryByRole('status', {name: 'Loading'}),+ ).not.toBeInTheDocument();+ });+it('shares one observer across every field on the page', () => {// Browsers batch per observer instance, so one observer per lane meant N// callback dispatches a frame for N fields.diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex c9f1d89b77..40ecb8e53f 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -624,6 +624,32 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({sourceGenRef.current = ++searchGenRef.current;}+ // The previous source is remembered in state, not a ref, so a render React+ // discards cannot consume the comparison without its state updates.+ const [sourceOfState, setSourceOfState] = useState(searchSource);+ if (sourceOfState !== searchSource) {+ setSourceOfState(searchSource);+ if (isLoading) {+ setIsLoading(false);+ setHasSearched(false);+ }+ loadingRef.current = false;+ }++ // When the search source is replaced, any in-flight load from the previous+ // source is abandoned (generation bumped above). Notify the wrapper's busy lane+ // in an effect so external store listeners run safely after commit.+ const isInitialMountRef = useRef(true);+ useEffect(() => {+ if (isInitialMountRef.current) {+ isInitialMountRef.current = false;+ return;+ }+ if (!loadingRef.current) {+ onLoadingChangeRef.current?.(false);+ }+ }, [searchSource]);+// Layer for dropdownconst handleLayerShow = useCallback(() => {onOpenChange?.(true);diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsxindex 84a0f7ee32..73a1c0a2f2 100644--- a/packages/core/src/Typeahead/Typeahead.test.tsx+++ b/packages/core/src/Typeahead/Typeahead.test.tsx@@ -17,10 +17,20 @@ import {beforeAll,afterAll,beforeEach,+ afterEach,} from 'vitest';import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';-import {createRef, Profiler, type ProfilerOnRenderCallback} from 'react';+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';+import {+ createRef,+ Profiler,+ startTransition,+ StrictMode,+ Suspense,+ useState,+ type ProfilerOnRenderCallback,+} from 'react';import {Typeahead} from './Typeahead';import {readFile} from 'node:fs/promises';import {resolve} from 'node:path';@@ -70,6 +80,10 @@ afterAll(() => {(HTMLElement.prototype as any).matches = originalMatches;});+afterEach(() => {+ __resetLiveRegionsForTest();+});+// Test dataconst fruits: SearchableItem[] = [{id: '1', label: 'Apple'},@@ -964,6 +978,193 @@ describe('BaseTypeahead hasEntriesOnFocus', () => {).not.toBeInTheDocument();});+ it('clears the loading state when the search source is replaced during an in-flight load', async () => {+ let settle: (items: SearchableItem[]) => void = () => {};+ const bootstrap = vi.fn(+ async () =>+ new Promise<SearchableItem[]>(resolve => {+ settle = resolve;+ }),+ );+ const initialSource: SearchSource = {search: () => [], bootstrap};+ const replacementSource: SearchSource = {+ search: () => [],+ bootstrap: () => [],+ };++ const {rerender} = render(+ <BaseTypeahead+ searchSource={initialSource}+ value={null}+ onChange={() => {}}+ hasEntriesOnFocus+ />,+ );+ const input = screen.getByRole('combobox');++ fireEvent.focus(input);+ await waitFor(() => {+ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();+ });++ rerender(+ <BaseTypeahead+ searchSource={replacementSource}+ value={null}+ onChange={() => {}}+ hasEntriesOnFocus+ />,+ );++ await waitFor(() => {+ expect(+ screen.queryByRole('status', {name: 'Loading'}),+ ).not.toBeInTheDocument();+ });++ await act(async () => {+ settle([]);+ await Promise.resolve();+ });+ expect(+ screen.queryByRole('status', {name: 'Loading'}),+ ).not.toBeInTheDocument();+ });++ it('keeps the loading state under StrictMode for a pending autofocus bootstrap', async () => {+ let settle: (items: SearchableItem[]) => void = () => {};+ const bootstrap = vi.fn(+ async () =>+ new Promise<SearchableItem[]>(resolve => {+ settle = resolve;+ }),+ );+ render(+ <StrictMode>+ <Typeahead+ label="Test"+ searchSource={{search: () => [], bootstrap}}+ value={null}+ onChange={() => {}}+ hasAutoFocus+ hasEntriesOnFocus+ />+ </StrictMode>,+ );++ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();++ await act(async () => {+ settle([]);+ await Promise.resolve();+ });+ expect(+ screen.queryByRole('status', {name: 'Loading'}),+ ).not.toBeInTheDocument();+ });++ let settlePendingTransitionA: (items: SearchableItem[]) => void = () => {};+ const stableTransitionSourceA: SearchSource = {+ search: vi.fn(+ async () =>+ new Promise<SearchableItem[]>(resolve => {+ settlePendingTransitionA = resolve;+ }),+ ),+ bootstrap: () => [],+ };+ const stableTransitionSourceB: SearchSource = {+ search: vi.fn(async () => []),+ bootstrap: () => [],+ };++ it('clears loading and aria-busy when source is replaced in a transition that suspends and retries', async () => {+ let isSuspended = false;+ let resolveSuspension: () => void = () => {};+ let pendingSuspension: Promise<void> | null = null;++ function SuspendingSibling({shouldSuspend}: {shouldSuspend: boolean}) {+ if (shouldSuspend && isSuspended && pendingSuspension) {+ // eslint-disable-next-line @typescript-eslint/only-throw-error+ throw pendingSuspension;+ }+ return null;+ }++ let updateState!: (source: SearchSource, shouldSuspend: boolean) => void;++ function TransitionContainer() {+ const [source, setSource] = useState<SearchSource>(+ stableTransitionSourceA,+ );+ const [shouldSuspend, setShouldSuspend] = useState(false);+ updateState = (newSource, suspend) => {+ setSource(newSource);+ setShouldSuspend(suspend);+ };++ return (+ <Suspense fallback={<div>Suspended...</div>}>+ <Typeahead+ label="Test"+ searchSource={source}+ value={null}+ onChange={() => {}}+ debounceMs={0}+ />+ <SuspendingSibling shouldSuspend={shouldSuspend} />+ </Suspense>+ );+ }++ render(<TransitionContainer />);+ const input = screen.getByRole('combobox');++ // Trigger a load so aria-busy="true" is set on the combobox+ fireEvent.change(input, {target: {value: 'query'}});+ await waitFor(() => {+ expect(input).toHaveAttribute('aria-busy', 'true');+ });+ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();++ // Create the pending promise for suspension+ isSuspended = true;+ pendingSuspension = new Promise<void>(resolve => {+ resolveSuspension = () => {+ isSuspended = false;+ resolve();+ };+ });++ // Inside startTransition, switch from source A to source B while sibling suspends+ act(() => {+ startTransition(() => {+ updateState(stableTransitionSourceB, true);+ });+ });++ // The render suspended, so the previous committed state remains+ expect(input).toHaveAttribute('aria-busy', 'true');++ // Resolve the pending promise and let the transition commit+ await act(async () => {+ resolveSuspension();+ await pendingSuspension;+ });++ // Settle the abandoned load+ await act(async () => {+ settlePendingTransitionA([]);+ await Promise.resolve();+ });++ // The combobox must not keep aria-busy and the spinner must be gone+ expect(input).not.toHaveAttribute('aria-busy');+ expect(+ screen.queryByRole('status', {name: 'Loading'}),+ ).not.toBeInTheDocument();+ });+it('shows bootstrap results on mouse click', async () => {render(<BaseTypeahead@@ -1323,6 +1524,63 @@ describe('BaseTypeahead hasSearched reset', () => {// "No results found" should disappear since hasSearched is resetexpect(screen.queryByText('No results found')).not.toBeInTheDocument();});++ it('resets hasSearched and does not announce "No results found" when search source is replaced during a pending search', async () => {+ let settle: (items: SearchableItem[]) => void = () => {};+ const initialSource: SearchSource = {+ search: vi.fn(+ async () =>+ new Promise<SearchableItem[]>(resolve => {+ settle = resolve;+ }),+ ),+ bootstrap: () => [],+ };+ const replacementSource: SearchSource = {+ search: vi.fn(async () => []),+ bootstrap: () => [],+ };++ const {rerender} = render(+ <BaseTypeahead+ searchSource={initialSource}+ value={null}+ onChange={() => {}}+ debounceMs={0}+ />,+ );+ const input = screen.getByRole('combobox');++ // Type a query that starts an asynchronous search+ fireEvent.change(input, {target: {value: 'abc'}});+ expect(initialSource.search).toHaveBeenCalledWith('abc');++ // Replace the search source while the search is still pending+ rerender(+ <BaseTypeahead+ searchSource={replacementSource}+ value={null}+ onChange={() => {}}+ debounceMs={0}+ />,+ );++ // Settle the abandoned search+ await act(async () => {+ settle([]);+ await Promise.resolve();+ });++ await act(+ async () =>+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),+ );+ expect(+ document.querySelector('[data-astryx-live-region="polite"]')+ ?.textContent ?? '',+ ).not.toContain('No results found');+ expect(screen.queryByText('No results found')).not.toBeInTheDocument();+ });});describe('BaseTypeahead popover after selection', () => {@@ -2313,7 +2571,7 @@ describe('Typeahead consumer key handler order', () => {currentTarget = event.currentTarget;event.preventDefault();});- const {container} = render(+ render(<Typeaheadlabel="Fruit"searchSource={fruitSource}