Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,11 @@ export const SeverSideFiltering: ComboBoxStory = {
name: 'server side filtering with useAsyncList'
};

export const ServerSideFilteringInitiallyEmpty: ComboBoxStory = {
render: args => <AsyncInitiallyEmptyExample {...args} />,
name: 'server side filtering with useAsyncList (initially empty)'
};

export const SeverSideFilteringControlled: ComboBoxStory = {
render: args => <AsyncLoadingExampleControlledKey {...args} />,
name: 'server side filtering with useAsyncList (controlled key)'
Expand Down Expand Up @@ -608,6 +613,50 @@ function AsyncLoadingExample(props) {
);
}

function AsyncInitiallyEmptyExample(props) {
interface StarWarsChar {
name: string;
url: string;
}

let list = useAsyncList<StarWarsChar>({
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 (
<ComboBox
label="Star Wars Character Lookup (Initially Empty)"
{...props}
items={list.items}
inputValue={list.filterText}
onInputChange={list.setFilterText}
loadingState={list.loadingState}
onLoadMore={chain(props?.onLoadMore, list.loadMore)}>
{(item: any) => <Item key={item.name}>{item.name}</Item>}
</ComboBox>
);
}

function AsyncLoadingExampleControlledKey(props) {
interface StarWarsChar {
name: string;
Expand Down
54 changes: 54 additions & 0 deletions packages/react-aria-components/stories/ComboBox.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,60 @@ export const ComboBoxAsyncLoadingExample: ComboBoxStory = {
}
};

export const ComboBoxAsyncInitiallyEmptyExample: ComboBoxStory = {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I see a difference when i type "F", but the behaviour before and after is the same for "f". It doesn't open until I delete and re-type the "f", then they both open. I'm surprised that "f" works on the second time, but not the first. Any idea what's going on there? is it related to this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, the second try part is related. On main, typing "f" the first time still loads [Foo] into useAsyncList even though the menu stays closed. When you backspace, useAsyncList keeps [Foo] for a render while inputValue changes to "", which briefly opens the menu. Then load({filterText: ''}) resolves [], so it auto-closes and sets closedDueToEmpty.current = true. That's why typing "f" again opens on both branches.

I'm not sure why "f" vs "F" would behave differently on the first try though. Both the story (filterText.toLowerCase()) and useComboBoxState are case-insensitive, and lowercase works in the tests. Did "f" blur the input or hit a shortcut, or does it happen consistently on a fresh reload?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't notice it blur or hit a shortcut, it happened every time i tried it. Were you able to reproduce it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just spun up Storybook locally on this branch (Chromium) and tested both ComboBoxAsyncInitiallyEmptyExample and ServerSideFilteringInitiallyEmpty, but I couldn't reproduce the difference. Both "f" and "F" opened the menu on the first keystroke for me.

Which browser/OS and story are you seeing that in? Also, if you inspect the wrapper when "f" fails to open, does .react-aria-ComboBox still have data-focused="true"? That might help narrow down whether something in the manager or browser setup is dropping focus or intercepting the key.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I must've had something in my storybook cache, i cleared out everything and it's no longer different between the two. Thanks for also trying it out

render: function ComboBoxAsyncInitiallyEmptyExample() {
let list = useAsyncList<ComboBoxItem>({
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 (
<ComboBox items={list.items} inputValue={list.filterText} onInputChange={list.setFilterText}>
<Label style={{display: 'block'}}>
Initially Empty Async Search (type &quot;F&quot; or &quot;B&quot;)
</Label>
<div style={{display: 'flex'}}>
<Input />
<Button>
<span aria-hidden="true" style={{padding: '0 2px'}}>
▼
</span>
</Button>
</div>
<Popover placement="bottom end">
<ListBox<ComboBoxItem> className={styles.menu}>
{item => <MyListBoxItem>{item.name}</MyListBoxItem>}
</ListBox>
</Popover>
</ComboBox>
);
}
};

export const ComboBoxImeExample: ComboBoxStory = {
render: () => (
<ComboBox>
Expand Down
111 changes: 111 additions & 0 deletions packages/react-aria-components/test/ComboBox.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<ComboBox
items={itemsTarget === 'ComboBox' ? list.items : undefined}
inputValue={list.filterText}
onInputChange={list.setFilterText}
onOpenChange={onOpenChange}>
<Label>SW Characters</Label>
<Input />
<Button>{'<'}</Button>
<Popover>
<ListBox items={itemsTarget === 'ListBox' ? list.items : undefined}>
{item => <ListBoxItem id={item.id}>{item.name}</ListBoxItem>}
</ListBox>
</Popover>
</ComboBox>
);
}

let {container, queryByRole} = render(<InitiallyEmptyAsyncComboBox />);
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 (
<ComboBox
items={items}
onInputChange={value => {
if (value) {
setTimeout(() => setItems([{id: 1, name: 'Luke Skywalker'}]), 50);
}
}}
onOpenChange={onOpenChange}>
<Label>SW Characters</Label>
<Input />
<Button>{'<'}</Button>
<Popover>
<ListBox>{item => <ListBoxItem id={item.id}>{item.name}</ListBoxItem>}</ListBox>
</Popover>
</ComboBox>
);
}

let {queryByRole} = render(<PendingAsyncComboBox />);
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();

Expand Down
25 changes: 14 additions & 11 deletions packages/react-stately/src/combobox/useComboBoxState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,7 @@ export function useComboBoxState<T, M extends SelectionMode = 'single'>(
let toggleMenu = useCallback(
(focusStrategy: FocusStrategy | null = null) => {
if (triggerState.isOpen) {
closedDueToEmpty.current = false;
updateLastCollection();
}

Expand Down Expand Up @@ -415,15 +416,15 @@ export function useComboBoxState<T, M extends SelectionMode = 'single'>(
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
Expand All @@ -438,8 +439,8 @@ export function useComboBoxState<T, M extends SelectionMode = 'single'>(
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 (
Expand All @@ -459,6 +460,7 @@ export function useComboBoxState<T, M extends SelectionMode = 'single'>(
displayValue !== lastValueRef.current &&
selectionMode === 'single'
) {
closedDueToEmpty.current = false;
closeMenu();
}

Expand Down Expand Up @@ -602,6 +604,7 @@ export function useComboBoxState<T, M extends SelectionMode = 'single'>(
open(null, 'focus');
}
} else {
closedDueToEmpty.current = false;
if (shouldCloseOnBlur && !props.isReadOnly) {
commitValue();
}
Expand Down
63 changes: 63 additions & 0 deletions packages/react-stately/test/combobox/useComboBoxState.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 => <Item>{props.name}</Item>,
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 => <Item>{props.name}</Item>,
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();
});
});
});
Loading