Skip to content

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

TypeScript

fix(Typeahead): a source replacement that React discards no longer leaves the field busy (#9713)

Xinzi Zhou3f39a18bf1b7
diff --git a/.changeset/typeahead-discarded-source-busy.md b/.changeset/typeahead-discarded-source-busy.md
new file mode 100644
index 0000000000..3aa2a17f37
--- /dev/null
+++ b/.changeset/typeahead-discarded-source-busy.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `Typeahead`, `Tokenizer`, `PowerSearch`: a search no longer stays busy forever when React renders a new search source and then discards that render, for example a transition that suspends and that a newer update replaces before it commits. The search of the source that stays now finishes: its results show, and the loading indicator and `aria-busy` clear.
+
+@imdreamrunner
diff --git a/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsx
index 31376bc6bf..8b2d7527a4 100644
--- a/packages/core/src/PowerSearch/PowerSearch.test.tsx
+++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx
@@ -9,7 +9,7 @@
* SYNC: When PowerSearch.tsx changes, update tests to match
*/
-import {StrictMode, useState} from 'react';
+import {StrictMode, useMemo, useState} from 'react';
import {describe, it, expect, vi, beforeAll, afterAll, afterEach} from 'vitest';
import {
render,
@@ -1138,4 +1138,48 @@ describe('field menu after the search source changes', () => {
).toBeInTheDocument();
});
});
+
+ it('settles the busy state when applying a filter replaces the search source while the focus read is pending', async () => {
+ const user = userEvent.setup();
+ // A caller whose config follows its filters hands PowerSearch a new search
+ // source in the same update that commits a filter. Applying the filter
+ // also returns focus to the input, which starts a read of the focus list.
+ function FilterDerivedConfig() {
+ const [filters, setFilters] = useState<PowerSearchFilter[]>([]);
+ const filterConfig = useMemo<PowerSearchConfig>(
+ () => ({...config, name: `TestSearch-${filters.length}`}),
+ [filters],
+ );
+ return (
+ <PowerSearch
+ config={filterConfig}
+ filters={filters}
+ onChange={newFilters => setFilters([...newFilters])}
+ />
+ );
+ }
+ render(<FilterDerivedConfig />);
+ const input = screen.getByRole('combobox');
+
+ await user.click(input);
+ await user.click(
+ await screen.findByRole('option', {name: 'Title', hidden: true}),
+ );
+ const apply = await screen.findByRole('button', {
+ name: 'Apply',
+ hidden: true,
+ });
+ await user.type(screen.getByRole('textbox', {hidden: true}), 'bug');
+ await user.click(apply);
+ expect(input).toHaveFocus();
+
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+ expect(screen.getByText(/bug/)).toBeInTheDocument();
+ expect(input).not.toHaveAttribute('aria-busy');
+ expect(
+ screen.queryByRole('img', {name: 'Loading'}),
+ ).not.toBeInTheDocument();
+ });
});
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index 554d8be98d..150fa25511 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -24,6 +24,7 @@ import React, {
useCallback,
useEffect,
useId,
+ useInsertionEffect,
useMemo,
useRef,
useState,
@@ -775,15 +776,6 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
// source: they can never be re-shown, so focus bootstraps the new source.
const sourceGenRef = useRef(0);
- // Results still arriving from a replaced source must not land in the new
- // one's menu.
- const prevSearchSourceRef = useRef(searchSource);
- if (prevSearchSourceRef.current !== searchSource) {
- prevSearchSourceRef.current.cancel?.();
- prevSearchSourceRef.current = searchSource;
- 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);
@@ -793,7 +785,6 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
setIsLoading(false);
setHasSearched(false);
}
- loadingRef.current = false;
}
// A field that becomes disabled stops showing a search as busy in the same
// render, and the dropped query shows no outcome, so no empty state; the
@@ -807,15 +798,34 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
}
}
- // 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;
+ // Results that arrive from a replaced source must not land in the new
+ // source's menu, so the replacement starts a new generation. That happens
+ // when the replacement commits, not in render. React can render a
+ // replacement and then discard it, for example when a transition suspends
+ // and a newer update replaces it. The source that stays then keeps its read.
+ // An insertion effect runs before every layout effect and ref callback of
+ // its commit. A read that one of them starts against the replacement gets a
+ // later generation, after the replaced source stopped its requests.
+ const prevSearchSourceRef = useRef(searchSource);
+ const isSourceReplacedRef = useRef(false);
+ useInsertionEffect(() => {
+ if (prevSearchSourceRef.current === searchSource) {
+ return;
+ }
+ prevSearchSourceRef.current.cancel?.();
+ prevSearchSourceRef.current = searchSource;
+ sourceGenRef.current = ++searchGenRef.current;
+ // The replacing render cleared the busy state.
+ loadingRef.current = false;
+ isSourceReplacedRef.current = true;
+ }, [searchSource]);
+ // Syncs the wrapper's busy lane. A read of the replacement that already
+ // started keeps the lane busy.
+ useIsomorphicLayoutEffect(() => {
+ if (!isSourceReplacedRef.current) {
return;
}
+ isSourceReplacedRef.current = false;
if (!loadingRef.current) {
onLoadingChangeRef.current?.(false);
}
diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsx
index da427f2066..9b2fba7143 100644
--- a/packages/core/src/Typeahead/Typeahead.test.tsx
+++ b/packages/core/src/Typeahead/Typeahead.test.tsx
@@ -38,6 +38,8 @@ import {
startTransition,
StrictMode,
Suspense,
+ useLayoutEffect,
+ useRef,
useState,
type ProfilerOnRenderCallback,
} from 'react';
@@ -769,12 +771,14 @@ describe('Typeahead', () => {
const input = screen.getByRole('combobox');
fireEvent.change(input, {target: {value: 'a'}});
fireEvent.change(input, {target: {value: 'ap'}});
+ expect(input).toHaveAttribute('aria-busy', 'true');
// The newer query resolves first…
await act(async () => {
resolvers.get('ap')!([{id: 'apple', label: 'Apple'}]);
});
expect(screen.getByText('Apple')).toBeInTheDocument();
+ expect(input).not.toHaveAttribute('aria-busy');
// …then the abandoned query's slow response arrives and must be
// discarded rather than overwriting the current results.
@@ -786,6 +790,7 @@ describe('Typeahead', () => {
});
expect(screen.getByText('Apple')).toBeInTheDocument();
expect(screen.queryByText('Avocado')).not.toBeInTheDocument();
+ expect(input).not.toHaveAttribute('aria-busy');
});
it('discards a response from a source that was replaced while it was in flight', async () => {
@@ -1466,6 +1471,154 @@ describe('BaseTypeahead hasEntriesOnFocus', () => {
expect(queryBusySpinner()).not.toBeInTheDocument();
});
+ it('keeps the in-flight search when a replacement source renders in a transition that never commits', async () => {
+ let settleSearch: (items: SearchableItem[]) => void = () => {};
+ const committedSource: SearchSource = {
+ search: async () =>
+ new Promise<SearchableItem[]>(resolve => {
+ settleSearch = resolve;
+ }),
+ bootstrap: () => [],
+ };
+ const discardedSource: SearchSource = {
+ search: async () => [],
+ bootstrap: () => [],
+ };
+ const neverSettles = new Promise<void>(() => {});
+
+ function SuspendingSibling({shouldSuspend}: {shouldSuspend: boolean}) {
+ if (shouldSuspend) {
+ // eslint-disable-next-line @typescript-eslint/only-throw-error
+ throw neverSettles;
+ }
+ return null;
+ }
+
+ let updateState!: (source: SearchSource, shouldSuspend: boolean) => void;
+
+ function TransitionContainer() {
+ const [source, setSource] = useState<SearchSource>(committedSource);
+ 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');
+ fireEvent.change(input, {target: {value: 'query'}});
+ expect(input).toHaveAttribute('aria-busy', 'true');
+
+ // React renders the replacement source, the render suspends, and a newer
+ // transition replaces it before it commits: the committed source stays.
+ act(() => {
+ startTransition(() => {
+ updateState(discardedSource, true);
+ });
+ });
+ act(() => {
+ startTransition(() => {
+ updateState(committedSource, false);
+ });
+ });
+ expect(input).toHaveAttribute('aria-busy', 'true');
+
+ // The search still belongs to the committed source, so its answer lists
+ // and settles the busy state.
+ await act(async () => {
+ settleSearch([{id: 'q', label: 'Query result'}]);
+ await Promise.resolve();
+ });
+ expect(input).not.toHaveAttribute('aria-busy');
+ expect(queryBusySpinner()).not.toBeInTheDocument();
+ expect(
+ screen.getByRole('option', {name: 'Query result', hidden: true}),
+ ).toBeInTheDocument();
+ });
+
+ it('keeps a read that the replacement source starts earlier in the commit that replaces it', async () => {
+ let settleBootstrap: (items: SearchableItem[]) => void = () => {};
+ // Both sources share one request controller, so cancelling the replaced
+ // source aborts whatever request is pending.
+ let abortPending: (() => void) | null = null;
+ const cancel = () => {
+ abortPending?.();
+ abortPending = null;
+ };
+ const firstSource: SearchSource = {
+ search: () => [],
+ bootstrap: () => [],
+ cancel,
+ };
+ const replacementSource: SearchSource = {
+ search: () => [],
+ bootstrap: async () =>
+ new Promise<SearchableItem[]>((resolve, reject) => {
+ settleBootstrap = resolve;
+ abortPending = () => reject(new Error('aborted'));
+ }),
+ cancel,
+ };
+
+ // A component committed before the field focuses it when the scope
+ // changes, in the same commit that hands the field its new source.
+ function FocusOnScopeChange({scope}: {scope: string}) {
+ const isFirstRef = useRef(true);
+ useLayoutEffect(() => {
+ if (isFirstRef.current) {
+ isFirstRef.current = false;
+ return;
+ }
+ screen.getByRole('combobox').focus();
+ }, [scope]);
+ return null;
+ }
+ function ScopedField({scope}: {scope: string}) {
+ return (
+ <>
+ <FocusOnScopeChange scope={scope} />
+ <Typeahead
+ label="Test"
+ searchSource={scope === 'first' ? firstSource : replacementSource}
+ value={null}
+ onChange={() => {}}
+ hasEntriesOnFocus
+ />
+ </>
+ );
+ }
+
+ const {rerender} = render(<ScopedField scope="first" />);
+ const input = screen.getByRole('combobox');
+ rerender(<ScopedField scope="replacement" />);
+ expect(input).toHaveFocus();
+ expect(input).toHaveAttribute('aria-busy', 'true');
+
+ await act(async () => {
+ settleBootstrap([{id: 'entry', label: 'Entry'}]);
+ await Promise.resolve();
+ });
+ expect(input).not.toHaveAttribute('aria-busy');
+ expect(queryBusySpinner()).not.toBeInTheDocument();
+ expect(
+ screen.getByRole('option', {name: 'Entry', hidden: true}),
+ ).toBeInTheDocument();
+ });
+
it('shows bootstrap results on mouse click', async () => {
render(
<BaseTypeahead