An open source design system that's fully customizable and agent ready
TypeScript
perf(Typeahead): skip sync bootstrap loading cycle (#5956)
freddymetaaa565777492b
diff --git a/.changeset/typeahead-synchronous-bootstrap.md b/.changeset/typeahead-synchronous-bootstrap.mdnew file mode 100644index 0000000000..a7695569dd--- /dev/null+++ b/.changeset/typeahead-synchronous-bootstrap.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[perf] Typeahead: skip the loading cycle for synchronous bootstrap sources (#5955)++`BaseTypeahead` now applies an array returned by `SearchSource.bootstrap()` immediately instead of entering and leaving the asynchronous loading state. An empty synchronous bootstrap becomes a render no-op, while synchronous entries still open normally. Switching from an in-flight search to a synchronous bootstrap also clears the superseded search's loading state. Promise-backed bootstrap sources keep the existing loading behavior.++@freddymetadiff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex aab4d155c7..cb0741ceff 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -592,33 +592,63 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({],);- // Perform bootstrap- const performBootstrap = useCallback(async () => {- const gen = ++searchGenRef.current;- setLoading(true);- try {- const bootstrapResults = await searchSource.bootstrap();+ const applyBootstrapResults = useCallback(+ (bootstrapResults: T[], gen: number) => {if (searchGenRef.current !== gen) {return;}resultsGenRef.current = gen;const shown = bootstrapResults.slice(0, maxMenuItems);+ const nextHighlightedIndex = shown.length > 0 ? 0 : -1;+ if (+ results.length === 0 &&+ shown.length === 0 &&+ highlightedIndex === -1+ ) {+ return;+ }setResults(shown);- setHighlightedIndex(shown.length > 0 ? 0 : -1);+ setHighlightedIndex(nextHighlightedIndex);if (bootstrapResults.length > 0) {showLayer();}+ },+ [highlightedIndex, maxMenuItems, results.length, showLayer],+ );++ // Perform bootstrap+ const performBootstrap = useCallback(async () => {+ const gen = ++searchGenRef.current;+ let bootstrapResult: T[] | Promise<T[]>;+ try {+ bootstrapResult = searchSource.bootstrap();} catch {- if (searchGenRef.current !== gen) {- return;+ if (searchGenRef.current === gen) {+ setResults([]);+ setLoading(false);+ }+ return;+ }++ if (Array.isArray(bootstrapResult)) {+ setLoading(false);+ applyBootstrapResults(bootstrapResult, gen);+ return;+ }++ setLoading(true);+ try {+ applyBootstrapResults(await bootstrapResult, gen);+ } catch {+ if (searchGenRef.current === gen) {+ setResults([]);}- setResults([]);} finally {if (searchGenRef.current === gen) {setLoading(false);}}- }, [searchSource, maxMenuItems, showLayer, setLoading]);+ }, [searchSource, applyBootstrapResults, setLoading]);// Handle query changeconst handleQueryChange = useCallback(diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsxindex 13c6beaba0..c66e942a77 100644--- a/packages/core/src/Typeahead/Typeahead.test.tsx+++ b/packages/core/src/Typeahead/Typeahead.test.tsx@@ -20,6 +20,7 @@ import {} from 'vitest';import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import {Profiler, type ProfilerOnRenderCallback} from 'react';import {Typeahead} from './Typeahead';import {readFile} from 'node:fs/promises';import {resolve} from 'node:path';@@ -713,6 +714,126 @@ describe('Typeahead size', () => {});describe('BaseTypeahead hasEntriesOnFocus', () => {+ it('does not commit a loading cycle for an empty synchronous bootstrap', async () => {+ const bootstrap = vi.fn((): SearchableItem[] => []);+ const onRender = vi.fn<ProfilerOnRenderCallback>();+ render(+ <Profiler id="typeahead" onRender={onRender}>+ <BaseTypeahead+ searchSource={{search: () => [], bootstrap}}+ value={null}+ onChange={() => {}}+ hasEntriesOnFocus+ />+ </Profiler>,+ );+ const input = screen.getByRole('combobox');+ onRender.mockClear();++ await act(async () => {+ fireEvent.focus(input);+ await Promise.resolve();+ });++ expect(bootstrap).toHaveBeenCalledOnce();+ expect(onRender).not.toHaveBeenCalled();+ });++ it('does not report loading for synchronous bootstrap results', async () => {+ const lane = createBusyIndicatorLane();+ const onLoadingChange = vi.fn(lane.onBusyChange);+ render(+ <BusyIndicatorLaneProvider+ value={{...lane, onBusyChange: onLoadingChange}}>+ <BaseTypeahead+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ hasEntriesOnFocus+ />+ </BusyIndicatorLaneProvider>,+ );+ const input = screen.getByRole('combobox');++ fireEvent.focus(input);+ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'true');+ });++ expect(onLoadingChange).not.toHaveBeenCalled();+ });++ it('clears a pending search loading state before synchronous bootstrap', async () => {+ let settleSearch: (items: SearchableItem[]) => void = () => {};+ const searchSource: SearchSource = {+ search: async () =>+ new Promise<SearchableItem[]>(resolve => {+ settleSearch = resolve;+ }),+ bootstrap: () => [],+ };+ render(+ <BaseTypeahead+ searchSource={searchSource}+ value={null}+ onChange={() => {}}+ hasEntriesOnFocus+ debounceMs={0}+ />,+ );+ const input = screen.getByRole('combobox');++ fireEvent.change(input, {target: {value: 'a'}});+ await waitFor(() => {+ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();+ });++ fireEvent.change(input, {target: {value: ''}});+ await waitFor(() => {+ expect(+ screen.queryByRole('status', {name: 'Loading'}),+ ).not.toBeInTheDocument();+ });++ await act(async () => {+ settleSearch(fruits.slice(0, 1));+ await Promise.resolve();+ });+ expect(input).toHaveAttribute('aria-expanded', 'false');+ });++ it('keeps the loading state for an asynchronous bootstrap', async () => {+ let settle: (items: SearchableItem[]) => void = () => {};+ const bootstrap = vi.fn(+ async () =>+ new Promise<SearchableItem[]>(resolve => {+ settle = resolve;+ }),+ );+ render(+ <BaseTypeahead+ searchSource={{search: () => [], bootstrap}}+ value={null}+ onChange={() => {}}+ hasEntriesOnFocus+ />,+ );+ const input = screen.getByRole('combobox');++ fireEvent.focus(input);+ await waitFor(() => {+ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();+ });++ await act(async () => {+ settle([]);+ await Promise.resolve();+ });+ expect(+ screen.queryByRole('status', {name: 'Loading'}),+ ).not.toBeInTheDocument();+ });+it('shows bootstrap results on mouse click', async () => {render(<BaseTypeahead