Skip to content

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

TypeScript

feat(core): minQueryLength — hold the typeahead search until the query is long enough (#5385)

freddymeta70dea86aba58
diff --git a/.changeset/typeahead-tokenizer-minquerylength-holds-the-sea-qjc4.md b/.changeset/typeahead-tokenizer-minquerylength-holds-the-sea-qjc4.md
new file mode 100644
index 0000000000..3a835b390a
--- /dev/null
+++ b/.changeset/typeahead-tokenizer-minquerylength-holds-the-sea-qjc4.md
@@ -0,0 +1,13 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Typeahead + Tokenizer: minQueryLength holds the search and the menu until the query is long enough (#5385)
+
+Also fixes a stranded loading state that predates the prop: abandoning an in-flight search — by emptying the field, by falling below the threshold, or by selecting an item while the next search is still out — bumps the search generation, which makes that search's own `finally` decline to clear the loading flag. The field kept reporting "Loading" to assistive technology until another search settled.
+
+`hasCreate` is not gated by it. The "Create ..." entry is derived from the typed text rather than fetched for it, so it now reaches the menu through a separate internal path and is offered whatever the threshold says — the threshold exists to avoid a fetch too broad to be worth making, and creating costs no fetch. With `minQueryLength={3}`, typing `QA` offers `Create "QA"` and Enter commits it, while the search source is still never called.
+
+One consequence worth naming: the Create entry is appended after the results are cut to `maxMenuItems`, so with `hasCreate` a full menu now shows one option more than the cap — 11 where it used to show 10. The cap bounds how many _results_ a menu shows; creating is a separate capability and is not crowded out by them.
+
+@freddymeta
diff --git a/apps/storybook/stories/Typeahead.stories.tsx b/apps/storybook/stories/Typeahead.stories.tsx
index efebec4d23..4acadf6d44 100644
--- a/apps/storybook/stories/Typeahead.stories.tsx
+++ b/apps/storybook/stories/Typeahead.stories.tsx
@@ -42,6 +42,11 @@ const meta: Meta<typeof Typeahead> = {
hasEntriesOnFocus: {control: 'boolean'},
hasClear: {control: 'boolean'},
maxMenuItems: {control: 'number'},
+ minQueryLength: {
+ control: 'number',
+ description:
+ 'Minimum query length before the search source is queried. Below it no search runs and the menu stays closed.',
+ },
size: {
control: 'radio',
options: ['sm', 'md', 'lg'],
@@ -176,6 +181,18 @@ export const LimitedResults: Story = {
name: 'Max 3 Results',
};
+export const MinQueryLength: Story = {
+ ...Default,
+ args: {
+ ...Default.args,
+ label: 'Fruit (type 3 characters)',
+ placeholder: 'Search fruits...',
+ description: 'The search runs once three characters are typed.',
+ minQueryLength: 3,
+ },
+ name: 'Minimum Query Length',
+};
+
export const SizeVariants: Story = {
render: () => {
const [sm, setSm] = useState<SearchableItem | null>(null);
@@ -227,7 +244,8 @@ export const StatusVariantComparison: Story = {
const [a, setA] = useState<SearchableItem | null>(null);
const [b, setB] = useState<SearchableItem | null>(null);
return (
- <div style={{display: 'flex', flexDirection: 'column', gap: 24, width: 300}}>
+ <div
+ style={{display: 'flex', flexDirection: 'column', gap: 24, width: 300}}>
<Typeahead
label="Attached (default)"
searchSource={fruitSource}
diff --git a/packages/core/src/Tokenizer/Tokenizer.doc.mjs b/packages/core/src/Tokenizer/Tokenizer.doc.mjs
index abf5f3fc86..ea51c20728 100644
--- a/packages/core/src/Tokenizer/Tokenizer.doc.mjs
+++ b/packages/core/src/Tokenizer/Tokenizer.doc.mjs
@@ -132,7 +132,7 @@ export const docs = {
{
name: 'maxMenuItems',
type: 'number',
- description: 'Maximum number of dropdown items to display.',
+ description: 'Maximum number of search results to display. The hasCreate entry is offered on top of them, so a menu can show one more than this.',
default: '10',
},
{
@@ -140,6 +140,12 @@ export const docs = {
type: 'number',
description: 'Fixed dropdown width in pixels. The menu never shrinks below its anchor width.',
},
+ {
+ name: 'minQueryLength',
+ type: 'number',
+ description: 'Minimum query length before the search source is queried. Below it no search runs, and the menu stays closed — unless hasCreate is set, in which case the "Create ..." entry is still offered, being derived from the typed text rather than fetched for it.',
+ default: '1',
+ },
{
name: 'emptySearchResultsText',
type: 'string',
@@ -386,7 +392,7 @@ export const docsZh = {
{
name: 'maxMenuItems',
type: 'number',
- description: '\u4e0b\u62c9\u5217\u8868\u663e\u793a\u7684\u6700\u5927\u9879\u76ee\u6570\u3002',
+ description: '下拉列表显示的最大搜索结果数。“创建 ...”条目会在此之外额外提供,因此菜单可能比该数量多显示一项。',
default: '10',
},
{
@@ -394,6 +400,12 @@ export const docsZh = {
type: 'number',
description: '下拉菜单的固定像素宽度。菜单不会小于其锚点宽度。',
},
+ {
+ name: 'minQueryLength',
+ type: 'number',
+ description: '查询搜索源前的最小查询长度。低于该长度不会发起搜索,菜单保持关闭;但设置 hasCreate 时仍会提供“创建 ...”条目——该条目由输入的文本推导而来,并非通过搜索获取。',
+ default: '1',
+ },
{
name: 'emptySearchResultsText',
type: 'string',
@@ -515,8 +527,9 @@ export const docsDense = {
isOptional: 'Shows optional indicator on label.',
labelTooltip: 'Tooltip on label.',
hasEntriesOnFocus: 'Show bootstrap results on focus before typing.',
- maxMenuItems: 'Max dropdown items to display.',
+ maxMenuItems: 'Max search results shown; the hasCreate entry sits on top of them.',
menuWidth: 'Fixed dropdown width in pixels.',
+ minQueryLength: 'Min query length before searching. Menu stays closed below it, except the hasCreate entry.',
emptySearchResultsText: 'Text when search returns no results.',
hasAutoFocus: 'Auto-focus input on mount.',
size: 'Input+token size.',
diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsx
index 51c70d2765..8f42abebf2 100644
--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx
@@ -94,6 +94,37 @@ const userSource: SearchSource = {
bootstrap: () => users.slice(0, 3),
};
+describe('Tokenizer minQueryLength', () => {
+ it('forwards the threshold to the typeahead engine', async () => {
+ const search = vi.fn((query: string) =>
+ users.filter(u => u.label.toLowerCase().includes(query.toLowerCase())),
+ );
+ render(
+ <Tokenizer
+ label="People"
+ searchSource={{search, bootstrap: () => []}}
+ value={[]}
+ onChange={() => {}}
+ minQueryLength={3}
+ debounceMs={0}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+
+ fireEvent.change(input, {target: {value: 'Al'}});
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(search).not.toHaveBeenCalled();
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+
+ fireEvent.change(input, {target: {value: 'Ali'}});
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+ });
+});
+
describe('Tokenizer', () => {
it('forwards ref to the root field element', () => {
let root: HTMLDivElement | null = null;
@@ -606,6 +637,136 @@ describe('Tokenizer', () => {
bootstrap: () => [],
};
+ it('still offers Create below minQueryLength, and does not search', async () => {
+ // The threshold exists to avoid a fetch too broad to be worth making.
+ // Creating costs no fetch, so a field that can create `QA` should not
+ // stop being able to just because a search for `QA` would match too
+ // much. Reported on #5385.
+ const search = vi.fn(() => []);
+ const onChange = vi.fn();
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={{search, bootstrap: () => []}}
+ value={[]}
+ onChange={onChange}
+ hasCreate
+ minQueryLength={3}
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'QA'}});
+ });
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ // Offered...
+ expect(screen.queryByText('Create "QA"')).toBeInTheDocument();
+ // ...without the source ever being asked.
+ expect(search).not.toHaveBeenCalled();
+ // ...and it commits.
+ fireEvent.click(screen.getByText('Create "QA"'));
+ expect(onChange).toHaveBeenCalledWith(
+ [expect.objectContaining({id: 'QA', label: 'QA'})],
+ expect.objectContaining({type: 'create'}),
+ );
+ });
+
+ it('offers no menu below the threshold without hasCreate', async () => {
+ // The negative control for the case above: with nothing to derive from
+ // the text, a below-threshold query still opens nothing, and never
+ // reports "no results" for a query that was not searched.
+ const search = vi.fn(() => []);
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={{search, bootstrap: () => []}}
+ value={[]}
+ onChange={() => {}}
+ minQueryLength={3}
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'QA'}});
+ });
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ expect(search).not.toHaveBeenCalled();
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ expect(screen.queryByText('No results found')).not.toBeInTheDocument();
+ });
+
+ it('does not offer Create below the threshold for a token already held', async () => {
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={{search: () => [], bootstrap: () => []}}
+ value={[{id: 'QA', label: 'QA'}]}
+ onChange={() => {}}
+ hasCreate
+ minQueryLength={3}
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'QA'}});
+ });
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ expect(screen.queryByText('Create "QA"')).not.toBeInTheDocument();
+ });
+
+ it('offers Create on top of a full menu, not in place of a result', async () => {
+ // The Create entry is appended after the results are cut to
+ // `maxMenuItems`, so a full menu shows one more option rather than
+ // dropping its last result to make room. Deliberate: creating is a
+ // different capability from searching, and the cap exists to bound how
+ // many *results* a menu shows.
+ const many = Array.from({length: 20}, (_, i) => ({
+ id: `qa-${i}`,
+ label: `QA ${i}`,
+ }));
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={{search: () => many, bootstrap: () => []}}
+ value={[]}
+ onChange={() => {}}
+ hasCreate
+ maxMenuItems={3}
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'QA'}});
+ });
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ // Queried off the document rather than by role: the popover renders
+ // into a layer that jsdom keeps out of the accessibility tree, which is
+ // why the tests around this one reach for text too.
+ const options = document.querySelectorAll('[role="option"]');
+ expect(options).toHaveLength(4);
+ expect(options[3]).toHaveTextContent('Create "QA"');
+ });
+
it('shows a "Create" option when typing with hasCreate', async () => {
render(
<Tokenizer
diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsx
index c6bf6d470e..9b2494aaf3 100644
--- a/packages/core/src/Tokenizer/Tokenizer.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.tsx
@@ -158,6 +158,17 @@ export interface TokenizerProps<T extends SearchableItem> extends Omit<
maxMenuItems?: number;
/** Fixed dropdown width in pixels. Never shrinks below the input width. */
menuWidth?: number;
+ /**
+ * Minimum query length before the search source is queried. Below it no
+ * search runs and the menu stays closed — useful for remote sources where
+ * one or two characters match too much to be worth fetching.
+ *
+ * With `hasCreate`, the "Create" entry rides on the search results, so it
+ * also waits for the threshold.
+ *
+ * @default 1
+ */
+ minQueryLength?: number;
/** Text shown when no results found. @default 'No results found' */
emptySearchResultsText?: string;
/** Whether the input is disabled. @default false */
@@ -396,6 +407,7 @@ export function Tokenizer<T extends SearchableItem>({
hasEntriesOnFocus,
maxMenuItems,
menuWidth,
+ minQueryLength,
emptySearchResultsText,
isDisabled = false,
htmlName,
@@ -536,36 +548,47 @@ export function Tokenizer<T extends SearchableItem>({
() => ({
search: async (query: string) => {
const results = await searchSource.search(query);
- const filtered = results.filter(item => !selectedIds.has(item.id));
-
- // Append a "Create: X" synthetic item when hasCreate is true,
- // the user has typed something, and it doesn't exactly match an
- // existing result.
- if (hasCreate && query.trim()) {
- const trimmed = query.trim();
- const alreadyExists =
- selectedIds.has(trimmed) ||
- filtered.some(
- item => item.label.toLowerCase() === trimmed.toLowerCase(),
- );
- if (!alreadyExists) {
- const creatableItem = {
- id: `${CREATABLE_ID_PREFIX}${trimmed}`,
- label: `Create "${trimmed}"`,
- auxiliaryData: {__createdValue: trimmed},
- } as unknown as T;
- filtered.push(creatableItem);
- }
- }
-
- return filtered;
+ return results.filter(item => !selectedIds.has(item.id));
},
bootstrap: async () => {
const results = await searchSource.bootstrap();
return results.filter(item => !selectedIds.has(item.id));
},
}),
- [searchSource, selectedIds, hasCreate],
+ [searchSource, selectedIds],
+ );
+
+ /**
+ * The "Create X" entry. It is derived from the typed text, not fetched for
+ * it, so it is offered through `__queryEntries` rather than appended to the
+ * search results — which is what keeps it available when the query is too
+ * short to search. `minQueryLength` is there to avoid a fetch too broad to
+ * be worth making; creating `QA` costs no fetch, and a field that can
+ * create it should not stop being able to.
+ */
+ const createEntries = useCallback(
+ (query: string, results: T[]): T[] => {
+ const trimmed = query.trim();
+ if (!hasCreate || trimmed === '') {
+ return [];
+ }
+ const alreadyExists =
+ selectedIds.has(trimmed) ||
+ results.some(
+ item => item.label.toLowerCase() === trimmed.toLowerCase(),
+ );
+ if (alreadyExists) {
+ return [];
+ }
+ return [
+ {
+ id: `${CREATABLE_ID_PREFIX}${trimmed}`,
+ label: `Create "${trimmed}"`,
+ auxiliaryData: {__createdValue: trimmed},
+ } as unknown as T,
+ ];
+ },
+ [hasCreate, selectedIds],
);
const emptySource: SearchSource<T> = useMemo(
@@ -782,6 +805,7 @@ export function Tokenizer<T extends SearchableItem>({
hasEntriesOnFocus={isAtMax ? false : hasEntriesOnFocus}
maxMenuItems={maxMenuItems}
menuWidth={menuWidth}
+ minQueryLength={minQueryLength}
emptySearchResultsText={emptySearchResultsText}
isDisabled={isDisabled}
isFocusableDisabled={showsDisabledMessage}
@@ -789,6 +813,7 @@ export function Tokenizer<T extends SearchableItem>({
inputId={inputId}
ariaDescribedBy={ariaDescribedBy}
onChangeQuery={onChangeQuery}
+ __queryEntries={createEntries}
debounceMs={debounceMs}
onKeyDown={handleKeyDown}
anchorRef={wrapperRef}
diff --git a/packages/core/src/Typeahead/BaseTypeahead.doc.mjs b/packages/core/src/Typeahead/BaseTypeahead.doc.mjs
index ba59441828..db1e091ea4 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.doc.mjs
+++ b/packages/core/src/Typeahead/BaseTypeahead.doc.mjs
@@ -65,6 +65,12 @@ export const docs = {
type: 'number',
description: 'Fixed dropdown width in pixels. The menu never shrinks below its anchor width.',
},
+ {
+ name: 'minQueryLength',
+ type: 'number',
+ description: 'Minimum query length before the search source is queried. Below it no search runs and the menu stays closed.',
+ default: '1',
+ },
{
name: 'emptySearchResultsText',
type: 'string',
@@ -179,6 +185,12 @@ export const docsZh = {
type: 'number',
description: '下拉菜单的固定像素宽度。菜单不会小于其锚点宽度。',
},
+ {
+ name: 'minQueryLength',
+ type: 'number',
+ description: '查询搜索源前的最小查询长度。低于该长度不会发起搜索,菜单保持关闭。',
+ default: '1',
+ },
{
name: 'emptySearchResultsText',
type: 'string',
@@ -264,6 +276,7 @@ export const docsDense = {
hasEntriesOnFocus: 'Bootstrap results on focus.',
maxMenuItems: 'Max dropdown items.',
menuWidth: 'Fixed dropdown width in pixels.',
+ minQueryLength: 'Min query length before searching. Menu stays closed below it.',
emptySearchResultsText: 'Text when no results.',
isDisabled: 'Whether input disabled.',
hasAutoFocus: 'Auto-focus on mount.',
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index 287b128646..2f2b6af08b 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -97,6 +97,19 @@ export interface BaseTypeaheadProps<T extends SearchableItem> extends Omit<
/** Fixed dropdown width in pixels. Never shrinks below the anchor width. */
menuWidth?: number;
+ /**
+ * Minimum query length before the search source is queried. Below it no
+ * search runs and the menu stays closed, so a remote source is not asked
+ * for a result set that cannot be meaningful yet — and the user does not
+ * see "no results" for a query that was never searched.
+ *
+ * Measured with `String.length` (UTF-16 code units), like every other
+ * length check in the library.
+ *
+ * @default 1 — every non-empty query is searched.
+ */
+ minQueryLength?: number;
+
/**
* Text shown when no results found.
* @default 'No results found'
@@ -135,6 +148,28 @@ export interface BaseTypeaheadProps<T extends SearchableItem> extends Omit<
*/
onOpenChange?: (isOpen: boolean) => void;
+ /**
+ * Entries derived from the query text rather than fetched for it — today,
+ * Tokenizer's "Create ...".
+ *
+ * They are appended to whatever the search returned, and they are offered
+ * whatever `minQueryLength` says: that threshold exists to avoid a fetch
+ * that is too broad to be worth making, and these cost no fetch. A field
+ * that can create `QA` should not stop being able to just because a search
+ * for `QA` would match too much.
+ *
+ * Receives the results they will be appended to, so a caller can decline to
+ * offer an entry that duplicates one.
+ *
+ * Underscored and `@internal`: `BaseTypeaheadProps` is re-exported from the
+ * package entry point, so anything named on it ships as public API at the
+ * next cut. This is a wiring detail between Tokenizer and the base — the
+ * same reason `DefinedTheme.__inputTokens` carries its prefix.
+ *
+ * @internal
+ */
+ __queryEntries?: (query: string, results: T[]) => T[];
+
/**
* Debounce delay in ms before triggering search after typing.
* Set to 0 for synchronous/local search sources that don't need debouncing.
@@ -301,6 +336,19 @@ const itemSizeStyles = stylex.create({
},
});
+// =============================================================================
+// Helpers
+// =============================================================================
+
+/**
+ * A query that has been typed but is still shorter than the caller's
+ * threshold. An empty query is not "below the minimum" — it is the
+ * untouched state, and `hasEntriesOnFocus` owns what happens there.
+ */
+function isBelowMinQueryLength(query: string, minQueryLength: number): boolean {
+ return query.length > 0 && query.length < minQueryLength;
+}
+
// =============================================================================
// Component
// =============================================================================
@@ -333,12 +381,14 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
hasEntriesOnFocus = false,
maxMenuItems = 10,
menuWidth,
+ minQueryLength = 1,
emptySearchResultsText: emptySearchResultsTextFromProps,
isDisabled = false,
isFocusableDisabled = false,
hasAutoFocus = false,
onChangeQuery,
onOpenChange,
+ __queryEntries,
inputId: externalInputId,
ariaDescribedBy,
ariaLabelledBy,
@@ -457,7 +507,11 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
return;
}
resultsGenRef.current = gen;
- const shown = searchResults.slice(0, maxMenuItems);
+ const fetched = searchResults.slice(0, maxMenuItems);
+ const shown = [
+ ...fetched,
+ ...(__queryEntries?.(searchQuery, fetched) ?? []),
+ ];
setResults(shown);
setHighlightedIndex(shown.length > 0 ? 0 : -1);
if (searchResults.length > 0 || searchQuery.length > 0) {
@@ -490,6 +544,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
showLayer,
announce,
emptySearchResultsText,
+ __queryEntries,
t,
],
);
@@ -532,14 +587,35 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
clearTimeout(searchTimeoutRef.current);
}
- if (newQuery.length === 0 && !hasEntriesOnFocus) {
+ // Nothing to search: either the field was emptied, or the query is
+ // still shorter than `minQueryLength`. Both drop stale results and
+ // close the menu — showing the empty state for a query that was never
+ // searched would report "no results" that nobody looked for.
+ if (
+ (newQuery.length === 0 && !hasEntriesOnFocus) ||
+ isBelowMinQueryLength(newQuery, minQueryLength)
+ ) {
searchGenRef.current++;
searchSource.cancel?.();
- setResults([]);
+ // A query too short to search can still carry entries derived from
+ // the text itself. `hasSearched` stays false either way, so the menu
+ // never reports "no results" for a query nobody looked for.
+ const derived = __queryEntries?.(newQuery, []) ?? [];
+ setResults(derived);
+ setHighlightedIndex(derived.length > 0 ? 0 : -1);
setHasSearched(false);
+ // Bumping the generation abandons any in-flight search, which means
+ // its own `finally` will decline to clear this — so clear it here or
+ // the field spins forever. Backspacing below the threshold on a remote
+ // source is the everyday way to hit that.
+ setIsLoading(false);
// Clear any lingering result-count / no-results announcement.
announce('');
- popover.hide();
+ if (derived.length > 0) {
+ showLayer();
+ } else {
+ popover.hide();
+ }
return;
}
@@ -560,6 +636,9 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
[
onChangeQuery,
hasEntriesOnFocus,
+ minQueryLength,
+ __queryEntries,
+ showLayer,
performSearch,
performBootstrap,
popover,
@@ -591,6 +670,10 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
setQuery('');
setResults([]);
setHasSearched(false);
+ // Same reason as in handleQueryChange: the invalidated search will not
+ // clear this itself. Selecting a stale result while the next search is
+ // still in flight would otherwise leave the field spinning.
+ setIsLoading(false);
popover.hide();
inputRef.current?.focus();
},
@@ -674,7 +757,13 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
if (results.length > 0) {
popover.show();
setHighlightedIndex(0);
- } else if (hasEntriesOnFocus) {
+ } else if (
+ hasEntriesOnFocus &&
+ // A below-threshold query was never searched; falling back to the
+ // bootstrap entries here would open a menu of suggestions that
+ // ignore what the user has already typed.
+ !isBelowMinQueryLength(query, minQueryLength)
+ ) {
void performBootstrap();
}
}
@@ -740,7 +829,8 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
highlightedIndex,
handleSelect,
hasEntriesOnFocus,
- query.length,
+ query,
+ minQueryLength,
performBootstrap,
externalOnKeyDown,
],
diff --git a/packages/core/src/Typeahead/Typeahead.doc.mjs b/packages/core/src/Typeahead/Typeahead.doc.mjs
index 72c365583b..e60e323694 100644
--- a/packages/core/src/Typeahead/Typeahead.doc.mjs
+++ b/packages/core/src/Typeahead/Typeahead.doc.mjs
@@ -83,6 +83,12 @@ export const docs = {
description: 'Maximum number of dropdown items to display.',
default: '10',
},
+ {
+ name: 'minQueryLength',
+ type: 'number',
+ description: 'Minimum query length before the search source is queried. Below it no search runs and the menu stays closed.',
+ default: '1',
+ },
{
name: 'status',
type: "{type: 'warning' | 'error' | 'success', message?: string}",
diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsx
index b12de11a91..f639f6d114 100644
--- a/packages/core/src/Typeahead/Typeahead.test.tsx
+++ b/packages/core/src/Typeahead/Typeahead.test.tsx
@@ -778,6 +778,160 @@ describe('BaseTypeahead hasEntriesOnFocus', () => {
});
});
+describe('BaseTypeahead minQueryLength', () => {
+ it('does not search or open the menu below the threshold', async () => {
+ const search = vi.fn((query: string) =>
+ fruits.filter(f => f.label.toLowerCase().includes(query.toLowerCase())),
+ );
+ render(
+ <BaseTypeahead
+ searchSource={{search, bootstrap: () => []}}
+ value={null}
+ onChange={() => {}}
+ minQueryLength={3}
+ debounceMs={0}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+
+ fireEvent.change(input, {target: {value: 'Ap'}});
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(search).not.toHaveBeenCalled();
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+
+ // Positive control: the third character crosses the threshold, so the
+ // same harness does see the search and the open menu.
+ fireEvent.change(input, {target: {value: 'App'}});
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+ expect(search).toHaveBeenCalledExactlyOnceWith('App');
+ });
+
+ it('closes the menu again when the query falls back below the threshold', async () => {
+ render(
+ <BaseTypeahead
+ searchSource={fruitSource}
+ value={null}
+ onChange={() => {}}
+ minQueryLength={3}
+ debounceMs={0}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+
+ fireEvent.change(input, {target: {value: 'App'}});
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ fireEvent.change(input, {target: {value: 'Ap'}});
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ });
+ });
+
+ it('does not fall back to bootstrap entries on ArrowDown below the threshold', async () => {
+ const bootstrap = vi.fn(() => fruits.slice(0, 3));
+ render(
+ <BaseTypeahead
+ searchSource={{search: () => [], bootstrap}}
+ value={null}
+ onChange={() => {}}
+ hasEntriesOnFocus
+ minQueryLength={3}
+ debounceMs={0}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+
+ fireEvent.focus(input);
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+ bootstrap.mockClear();
+
+ // Typing below the threshold closes the bootstrap menu...
+ fireEvent.change(input, {target: {value: 'Ap'}});
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ // ...and ArrowDown must not re-open it with entries that ignore the
+ // two characters already typed.
+ fireEvent.keyDown(input, {key: 'ArrowDown'});
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(bootstrap).not.toHaveBeenCalled();
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('searches on the first character when minQueryLength is not set', async () => {
+ const search = vi.fn(() => fruits.slice(0, 1));
+ render(
+ <BaseTypeahead
+ searchSource={{search, bootstrap: () => []}}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+
+ fireEvent.change(input, {target: {value: 'A'}});
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+ expect(search).toHaveBeenCalledExactlyOnceWith('A');
+ });
+
+ it('stops reporting "Loading" when the query falls below the threshold mid-search', async () => {
+ // Falling below the threshold abandons the in-flight search by bumping the
+ // search generation, which also makes that search decline to clear the
+ // loading flag on its way out. Backspacing from three characters to two on
+ // a remote source is the everyday way to hit it, and the field would
+ // otherwise report "Loading" to a screen reader until the third character
+ // went back in.
+ let settle: (items: SearchableItem[]) => void = () => {};
+ const search = vi.fn(
+ async () =>
+ new Promise<SearchableItem[]>(resolve => {
+ settle = resolve;
+ }),
+ );
+ render(
+ <BaseTypeahead
+ searchSource={{search, bootstrap: () => []}}
+ value={null}
+ onChange={() => {}}
+ minQueryLength={3}
+ debounceMs={0}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+
+ fireEvent.change(input, {target: {value: 'App'}});
+ await waitFor(() => {
+ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();
+ });
+
+ fireEvent.change(input, {target: {value: 'Ap'}});
+ await act(async () => {
+ settle(fruits.slice(0, 1));
+ await Promise.resolve();
+ });
+
+ expect(
+ screen.queryByRole('status', {name: 'Loading'}),
+ ).not.toBeInTheDocument();
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ });
+});
+
describe('BaseTypeahead hasSearched reset', () => {
it('does not show "No results found" after selecting an item and re-entering', async () => {
const onChange = vi.fn();
diff --git a/packages/core/src/Typeahead/Typeahead.tsx b/packages/core/src/Typeahead/Typeahead.tsx
index aa32008f82..4c05dd1579 100644
--- a/packages/core/src/Typeahead/Typeahead.tsx
+++ b/packages/core/src/Typeahead/Typeahead.tsx
@@ -111,6 +111,13 @@ export interface TypeaheadProps<T extends SearchableItem> extends Omit<
hasEntriesOnFocus?: boolean;
/** Max dropdown items. @default 10 */
maxMenuItems?: number;
+ /**
+ * Minimum query length before the search source is queried. Below it no
+ * search runs and the menu stays closed — useful for remote sources where
+ * one or two characters match too much to be worth fetching.
+ * @default 1
+ */
+ minQueryLength?: number;
/** Text shown when no results found. @default 'No results found' */
emptySearchResultsText?: string;
/** Whether the input is disabled. @default false */
@@ -248,6 +255,7 @@ export function Typeahead<T extends SearchableItem>({
placeholder,
hasEntriesOnFocus,
maxMenuItems,
+ minQueryLength,
emptySearchResultsText,
isDisabled = false,
disabledMessage,
@@ -467,6 +475,7 @@ export function Typeahead<T extends SearchableItem>({
placeholder={showToken ? undefined : placeholder}
hasEntriesOnFocus={hasEntriesOnFocus}
maxMenuItems={maxMenuItems}
+ minQueryLength={minQueryLength}
emptySearchResultsText={emptySearchResultsText}
isDisabled={isDisabled}
hasAutoFocus={hasAutoFocus}