Skip to content

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

TypeScript

fix(Typeahead): bootstrap a replaced search source on focus (#7157)

Xinzi Zhou1bd7016ff660
diff --git a/.changeset/base-typeahead-stale-focus-bootstrap.md b/.changeset/base-typeahead-stale-focus-bootstrap.md
new file mode 100644
index 0000000000..29b3329e55
--- /dev/null
+++ b/.changeset/base-typeahead-stale-focus-bootstrap.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `Typeahead`, `Tokenizer`, and `PowerSearch`: focusing an empty field with `hasEntriesOnFocus` after its search source changed now bootstraps entries from the new source. Previously the results cached from the old source were already invalidated but still blocked the bootstrap, so focusing or clicking into the field opened nothing until the user typed. Cached results that are still current are re-shown without a new bootstrap, as before.
+
+@imdreamrunner
diff --git a/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsx
index 14d3f6afd3..4fea3252ee 100644
--- a/packages/core/src/PowerSearch/PowerSearch.test.tsx
+++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx
@@ -733,3 +733,48 @@ describe('field menu grouping', () => {
});
});
});
+
+describe('field menu after the search source changes', () => {
+ it('opens the new field menu on the first click after a config change', async () => {
+ const user = userEvent.setup();
+ // A caller that loads field options asynchronously hands PowerSearch a
+ // new config, which builds a new search source.
+ const loadedConfig: PowerSearchConfig = {
+ ...config,
+ fields: [
+ ...config.fields,
+ {
+ key: 'owner',
+ label: 'Owner',
+ defaultOperator: 'is',
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ ],
+ };
+ const renderSearch = (searchConfig: PowerSearchConfig) => (
+ <>
+ <PowerSearch config={searchConfig} filters={[]} onChange={() => {}} />
+ <button type="button">Sort</button>
+ </>
+ );
+ const {rerender} = render(renderSearch(config));
+ const input = screen.getByRole('combobox');
+
+ await user.click(input);
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+ await user.click(screen.getByRole('button', {name: 'Sort'}));
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+
+ rerender(renderSearch(loadedConfig));
+ await user.click(input);
+
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ expect(
+ screen.getByRole('option', {name: /Owner/, hidden: true}),
+ ).toBeInTheDocument();
+ });
+ });
+});
diff --git a/packages/core/src/Typeahead/BaseTypeahead.test.tsx b/packages/core/src/Typeahead/BaseTypeahead.test.tsx
index 772a7ef9d8..ee1c2ea854 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.test.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.test.tsx
@@ -3,7 +3,7 @@
/**
* @file BaseTypeahead.test.tsx
* @input BaseTypeahead public props and a synchronous SearchSource
- * @output Combobox contract tests, including stale source refresh on reopen
+ * @output Combobox contract tests, including stale source refresh on focus and reopen
* @position Colocated verification for BaseTypeahead
*/
@@ -209,6 +209,104 @@ describe('BaseTypeahead', () => {
expect(input).toHaveFocus();
});
+ it.each([
+ ['a click', 'click'],
+ ['keyboard focus', 'tab'],
+ ] as const)(
+ 'bootstraps the replacement source when %s refocuses the input',
+ async (_label, refocus) => {
+ const user = userEvent.setup();
+ const originalSource: SearchSource<SearchableItem> = {
+ search: () => [],
+ bootstrap: () => [resultItem],
+ };
+ const updatedBootstrap = vi.fn(() => [
+ {id: '2', label: 'Updated result'},
+ ]);
+ const updatedSource: SearchSource<SearchableItem> = {
+ search: () => [],
+ bootstrap: updatedBootstrap,
+ };
+ const renderField = (searchSource: SearchSource<SearchableItem>) => (
+ <>
+ <BaseTypeahead
+ searchSource={searchSource}
+ value={null}
+ onChange={() => {}}
+ hasEntriesOnFocus
+ />
+ <button type="button">Sort</button>
+ </>
+ );
+ const {rerender} = render(renderField(originalSource));
+ const input = screen.getByRole('combobox');
+ const sortButton = screen.getByRole('button', {name: 'Sort'});
+
+ await user.click(input);
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ // Focus moves to another control, which then hands the field a new
+ // source (a sort or filter change rebuilding the caller's source).
+ await user.click(sortButton);
+ expect(input).not.toHaveFocus();
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ rerender(renderField(updatedSource));
+
+ if (refocus === 'click') {
+ await user.click(input);
+ } else {
+ await user.tab({shift: true});
+ }
+ expect(input).toHaveFocus();
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ expect(
+ screen.getByRole('option', {name: 'Updated result', hidden: true}),
+ ).toBeInTheDocument();
+ });
+ expect(
+ screen.queryByRole('option', {name: 'Result', hidden: true}),
+ ).not.toBeInTheDocument();
+ expect(updatedBootstrap).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('re-shows cached results without bootstrapping again when the source is unchanged', async () => {
+ const user = userEvent.setup();
+ const bootstrap = vi.fn(() => [resultItem]);
+ const source: SearchSource<SearchableItem> = {search: () => [], bootstrap};
+ render(
+ <>
+ <BaseTypeahead
+ searchSource={source}
+ value={null}
+ onChange={() => {}}
+ hasEntriesOnFocus
+ />
+ <button type="button">Sort</button>
+ </>,
+ );
+ const input = screen.getByRole('combobox');
+
+ await user.click(input);
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+ await user.click(screen.getByRole('button', {name: 'Sort'}));
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+
+ await user.click(input);
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+ expect(
+ screen.getByRole('option', {name: 'Result', hidden: true}),
+ ).toBeInTheDocument();
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+ });
+
it('counts grapheme clusters when enforcing minQueryLength', async () => {
const search = vi.fn(() => [resultItem]);
render(
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index 0dd1c0e31b..c9f1d89b77 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 with focused-input menu reactivation
+ * @output Exports BaseTypeahead; focus bootstraps a replaced search source
* @position Core implementation; used by Typeahead and Tokenizer
*
* Pure combobox engine: input, search, keyboard navigation, dropdown.
@@ -610,6 +610,10 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
// in the closure are stale (a selection cleared them) and shouldn't
// be re-shown.
const resultsGenRef = useRef(0);
+ // The generation at which the current searchSource took over. Results
+ // populated before it (resultsGenRef below this) came from a replaced
+ // 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.
@@ -617,7 +621,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
if (prevSearchSourceRef.current !== searchSource) {
prevSearchSourceRef.current.cancel?.();
prevSearchSourceRef.current = searchSource;
- searchGenRef.current++;
+ sourceGenRef.current = ++searchGenRef.current;
}
// Layer for dropdown
@@ -889,11 +893,21 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
// Shared by handleFocus and handleClick: bootstrap entries if none are
// loaded yet, or re-show cached results that haven't been invalidated by
// a selection since (comparing the two generation refs catches that).
+ // Results cached from a replaced search source count as none, so focusing
+ // an empty field bootstraps the new source instead of opening nothing.
+ // Results a selection invalidated still keep the menu closed when the
+ // selection returns focus to the input.
const openIfEligible = useCallback(() => {
if (isDisabled) {
return;
}
- if (hasEntriesOnFocus && results.length === 0 && query.length === 0) {
+ const hasResultsFromCurrentSource =
+ results.length > 0 && resultsGenRef.current >= sourceGenRef.current;
+ if (
+ hasEntriesOnFocus &&
+ !hasResultsFromCurrentSource &&
+ query.length === 0
+ ) {
void performBootstrap();
} else if (
results.length > 0 &&