Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix select after query #182

Merged
merged 2 commits into from
Nov 21, 2024
Merged
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
4 changes: 4 additions & 0 deletions src/autocomplete/use-autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export interface Props<I> extends Base<I> {
disabled?: boolean;
onFocus?: (focused?: boolean) => void;
preserveOrder?: boolean;
defaultIndex?: number;
}

export const useAutocomplete = <I>({
Expand All @@ -57,6 +58,7 @@ export const useAutocomplete = <I>({
keepOpened,
keepQuery,
preserveOrder,
defaultIndex,
...thru
}: Props<I>) => {
const textual = useMemo(
Expand Down Expand Up @@ -178,6 +180,8 @@ export const useAutocomplete = <I>({
(val: I | I[]) => meta.onChange(without(val)(meta.value) as I[]),
[meta],
),
// whenever there is a query, override defaultIndex to 0, so the first result gets selected
defaultIndex: query?.length > 0 ? 0 : defaultIndex,
};
};

Expand Down
6 changes: 5 additions & 1 deletion src/listbox/use-items.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,12 @@
{ length } = items;

useEffect(() => {
// whenever the items list is empty, reset the position to defaultIndex
setPosition({
index: Math.min(position.index, items.length - 1),
index:
position.index < 0
? defaultIndex

Check warning on line 31 in src/listbox/use-items.ts

View check run for this annotation

Codecov / codecov/patch

src/listbox/use-items.ts#L31

Added line #L31 was not covered by tests
: Math.min(position.index, items.length - 1),
scroll: true,
});
}, [items, defaultIndex]);
Expand Down
Loading