diff --git a/packages/@adobe/react-spectrum/stories/combobox/ComboBox.stories.tsx b/packages/@adobe/react-spectrum/stories/combobox/ComboBox.stories.tsx
index 19472beea18..bd0510d9afb 100644
--- a/packages/@adobe/react-spectrum/stories/combobox/ComboBox.stories.tsx
+++ b/packages/@adobe/react-spectrum/stories/combobox/ComboBox.stories.tsx
@@ -445,6 +445,11 @@ export const SeverSideFiltering: ComboBoxStory = {
name: 'server side filtering with useAsyncList'
};
+export const ServerSideFilteringInitiallyEmpty: ComboBoxStory = {
+ render: args => ,
+ name: 'server side filtering with useAsyncList (initially empty)'
+};
+
export const SeverSideFilteringControlled: ComboBoxStory = {
render: args => ,
name: 'server side filtering with useAsyncList (controlled key)'
@@ -608,6 +613,50 @@ function AsyncLoadingExample(props) {
);
}
+function AsyncInitiallyEmptyExample(props) {
+ interface StarWarsChar {
+ name: string;
+ url: string;
+ }
+
+ let list = useAsyncList({
+ async load({signal, cursor, filterText}) {
+ if (!filterText) {
+ return {items: []};
+ }
+
+ if (cursor) {
+ cursor = cursor.replace(/^http:\/\//i, 'https://');
+ }
+
+ // Slow down load so progress circle can appear
+ await new Promise(resolve => setTimeout(resolve, 1500));
+ let res = await fetch(cursor || `https://swapi.py4e.com/api/people/?search=${filterText}`, {
+ signal
+ });
+ let json = await res.json();
+
+ return {
+ items: json.results,
+ cursor: json.next
+ };
+ }
+ });
+
+ return (
+
+ {(item: any) => - {item.name}
}
+
+ );
+}
+
function AsyncLoadingExampleControlledKey(props) {
interface StarWarsChar {
name: string;
diff --git a/packages/react-aria-components/stories/ComboBox.stories.tsx b/packages/react-aria-components/stories/ComboBox.stories.tsx
index 5aad7ecb568..ce10c7f68fe 100644
--- a/packages/react-aria-components/stories/ComboBox.stories.tsx
+++ b/packages/react-aria-components/stories/ComboBox.stories.tsx
@@ -237,6 +237,60 @@ export const ComboBoxAsyncLoadingExample: ComboBoxStory = {
}
};
+export const ComboBoxAsyncInitiallyEmptyExample: ComboBoxStory = {
+ render: function ComboBoxAsyncInitiallyEmptyExample() {
+ let list = useAsyncList({
+ async load({filterText}) {
+ if (!filterText) {
+ return {items: []};
+ }
+
+ let json = (await new Promise(resolve => {
+ setTimeout(() => {
+ resolve(
+ items.filter(item => {
+ let name = item.name.toLowerCase();
+ for (let filterChar of filterText.toLowerCase()) {
+ if (!name.includes(filterChar)) {
+ return false;
+ }
+ name = name.replace(filterChar, '');
+ }
+ return true;
+ })
+ );
+ }, 300);
+ })) as ComboBoxItem[];
+
+ return {
+ items: json
+ };
+ }
+ });
+
+ return (
+
+
+
+
+
+
+
+ className={styles.menu}>
+ {item => {item.name}}
+
+
+
+ );
+ }
+};
+
export const ComboBoxImeExample: ComboBoxStory = {
render: () => (
diff --git a/packages/react-aria-components/test/ComboBox.test.js b/packages/react-aria-components/test/ComboBox.test.js
index 8e2a6281e08..3d834e0bea7 100644
--- a/packages/react-aria-components/test/ComboBox.test.js
+++ b/packages/react-aria-components/test/ComboBox.test.js
@@ -1297,6 +1297,117 @@ describe('ComboBox', () => {
).toBeInTheDocument();
});
+ it.each(['ComboBox', 'ListBox'])(
+ 'should open on first character typed with initially-empty useAsyncList (%s items)',
+ async itemsTarget => {
+ const ASYNC_DELAY_MS = 50;
+ let onOpenChange = jest.fn();
+
+ function itemsForFilterText(filterText) {
+ if (!filterText) {
+ return [];
+ }
+ return [{id: 1, name: 'Luke Skywalker'}];
+ }
+
+ function InitiallyEmptyAsyncComboBox() {
+ let list = useAsyncList({
+ getKey: item => item.id,
+ async load({filterText}) {
+ let rows = itemsForFilterText(filterText);
+ await new Promise(resolve => setTimeout(resolve, ASYNC_DELAY_MS));
+ return {items: rows};
+ }
+ });
+
+ return (
+
+
+
+
+
+
+ {item => {item.name}}
+
+
+
+ );
+ }
+
+ let {container, queryByRole} = render();
+ let comboboxTester = testUtilUser.createTester('ComboBox', {root: container});
+
+ await act(async () => {
+ jest.runAllTimers();
+ });
+
+ await user.tab();
+ expect(queryByRole('listbox')).toBeNull();
+
+ await user.keyboard('l');
+ expect(queryByRole('listbox')).toBeNull();
+ await act(async () => {
+ jest.runAllTimers();
+ });
+ expect(comboboxTester.getListbox()).toBeVisible();
+ expect(
+ within(comboboxTester.getListbox()).getByRole('option', {name: 'Luke Skywalker'})
+ ).toBeInTheDocument();
+ expect(onOpenChange.mock.calls).toEqual([[true, 'input']]);
+
+ await user.keyboard('{Backspace}');
+ await act(async () => {
+ jest.runAllTimers();
+ });
+ expect(queryByRole('listbox')).toBeNull();
+ expect(onOpenChange.mock.calls).toEqual([
+ [true, 'input'],
+ [false, undefined]
+ ]);
+ }
+ );
+
+ it('should not open if dismissed with Escape while initially-empty async load is pending', async () => {
+ let onOpenChange = jest.fn();
+
+ function PendingAsyncComboBox() {
+ let [items, setItems] = useState([]);
+ return (
+ {
+ if (value) {
+ setTimeout(() => setItems([{id: 1, name: 'Luke Skywalker'}]), 50);
+ }
+ }}
+ onOpenChange={onOpenChange}>
+
+
+
+
+ {item => {item.name}}
+
+
+ );
+ }
+
+ let {queryByRole} = render();
+ await user.tab();
+ await user.keyboard('l');
+ expect(queryByRole('listbox')).toBeNull();
+
+ await user.keyboard('{Escape}');
+ await act(async () => {
+ jest.runAllTimers();
+ });
+ expect(queryByRole('listbox')).toBeNull();
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
it('should still close the menu when uncontrolled items are empty', async () => {
let onOpenChange = jest.fn();
diff --git a/packages/react-stately/src/combobox/useComboBoxState.ts b/packages/react-stately/src/combobox/useComboBoxState.ts
index 16b4a02c304..77cc42da1ca 100644
--- a/packages/react-stately/src/combobox/useComboBoxState.ts
+++ b/packages/react-stately/src/combobox/useComboBoxState.ts
@@ -383,6 +383,7 @@ export function useComboBoxState(
let toggleMenu = useCallback(
(focusStrategy: FocusStrategy | null = null) => {
if (triggerState.isOpen) {
+ closedDueToEmpty.current = false;
updateLastCollection();
}
@@ -415,15 +416,15 @@ export function useComboBoxState(
useEffect(() => {
// Open and close menu automatically when the input value changes if the input is focused,
// and there are items in the collection or allowEmptyCollection is true.
- if (
- isFocused &&
- (filteredCollection.size > 0 || allowsEmptyCollection) &&
- !triggerState.isOpen &&
- inputValue !== lastValue &&
- menuTrigger !== 'manual'
- ) {
- // oxlint-disable-next-line react/react-compiler
- open(null, 'input');
+ if (isFocused && !triggerState.isOpen && inputValue !== lastValue && menuTrigger !== 'manual') {
+ if (filteredCollection.size > 0 || allowsEmptyCollection) {
+ closedDueToEmpty.current = false;
+ // oxlint-disable-next-line react/react-compiler
+ open(null, 'input');
+ } else {
+ // Track pending empty collection so async items arriving on a later render open the menu.
+ closedDueToEmpty.current = true;
+ }
}
// Close the menu if the collection is empty. Don't close menu if filtered collection size is 0
@@ -438,8 +439,8 @@ export function useComboBoxState(
closeMenu();
}
- // Re-open the menu when items become non-empty after being auto-closed due to
- // an empty collection (e.g. async load completed with results after a previous empty response).
+ // Open or re-open the menu when items become non-empty after being skipped or auto-closed
+ // due to an empty collection (e.g. initially-empty or subsequent async searches).
// This works for both controlled items on ComboBox and Collection patterns
// (where items are provided on the ListBox rather than the ComboBox).
if (
@@ -459,6 +460,7 @@ export function useComboBoxState(
displayValue !== lastValueRef.current &&
selectionMode === 'single'
) {
+ closedDueToEmpty.current = false;
closeMenu();
}
@@ -602,6 +604,7 @@ export function useComboBoxState(
open(null, 'focus');
}
} else {
+ closedDueToEmpty.current = false;
if (shouldCloseOnBlur && !props.isReadOnly) {
commitValue();
}
diff --git a/packages/react-stately/test/combobox/useComboBoxState.test.js b/packages/react-stately/test/combobox/useComboBoxState.test.js
index 99aada1dac6..135034fb912 100644
--- a/packages/react-stately/test/combobox/useComboBoxState.test.js
+++ b/packages/react-stately/test/combobox/useComboBoxState.test.js
@@ -456,5 +456,68 @@ describe('useComboBoxState tests', function () {
// Menu should close because items are uncontrolled and filtered to empty
expect(result.current.isOpen).toBe(false);
});
+
+ it('should open the menu when initially-empty controlled items load after typing', function () {
+ let onOpenChange = jest.fn();
+ let initialProps = {
+ items: [],
+ inputValue: '',
+ children: props => - {props.name}
,
+ onOpenChange
+ };
+
+ let {result, rerender} = renderHook(props => useComboBoxState(props), {initialProps});
+
+ act(() => {
+ result.current.setFocused(true);
+ });
+ expect(result.current.isOpen).toBe(false);
+
+ // Simulate user typing while async search still has empty initial results
+ rerender({...initialProps, items: [], inputValue: 'L'});
+ expect(result.current.isOpen).toBe(false);
+ expect(onOpenChange).not.toHaveBeenCalled();
+
+ // Simulate async results arriving on a later render
+ rerender({...initialProps, items: [{id: 1, name: 'Luke Skywalker'}], inputValue: 'L'});
+ expect(result.current.isOpen).toBe(true);
+ expect(result.current.collection.size).toEqual(1);
+ expect(onOpenChange).toHaveBeenCalledTimes(1);
+ expect(onOpenChange).toHaveBeenLastCalledWith(true, 'input');
+ });
+
+ it('should not open the menu if blurred before initially-empty async items load', function () {
+ let onOpenChange = jest.fn();
+ let initialProps = {
+ items: [],
+ shouldCloseOnBlur: false,
+ children: props => - {props.name}
,
+ onOpenChange
+ };
+
+ let {result, rerender} = renderHook(props => useComboBoxState(props), {initialProps});
+
+ act(() => {
+ result.current.setFocused(true);
+ });
+ act(() => {
+ result.current.setInputValue('L');
+ });
+ expect(result.current.isOpen).toBe(false);
+
+ // Blur before async results arrive, then receive items while blurred
+ act(() => {
+ result.current.setFocused(false);
+ });
+ rerender({...initialProps, items: [{id: 1, name: 'Luke Skywalker'}]});
+ expect(result.current.isOpen).toBe(false);
+
+ // Refocusing afterwards should not trigger a delayed open from the earlier keystroke
+ act(() => {
+ result.current.setFocused(true);
+ });
+ expect(result.current.isOpen).toBe(false);
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
});
});