Skip to content

Commit

Permalink
fix: Location input now properly auto selects on Enter key pressed
Browse files Browse the repository at this point in the history
  • Loading branch information
devcshort committed Oct 16, 2024
1 parent f81ce24 commit fbfa521
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/shared/components/search/location-search-bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { useAtomValue, useSetAtom } from 'jotai';
import {
prevSearchLocationAtom,
searchAtom,
searchCoordinatesAtom,
searchLocationAtom,
searchLocationValidationErrorAtom,
userCoordinatesAtom,
} from '../../store/search';
import { useDebounce } from '../../hooks/use-debounce';
import { useLocations } from '../../hooks/api/use-locations';
Expand All @@ -26,7 +26,7 @@ export function LocationSearchBar({ className }: LocationSearchBarProps) {
const [shouldSearch, setShouldSearch] = useState(false);
const setSearch = useSetAtom(searchAtom);
const searchLocation = useAtomValue(searchLocationAtom);
const coords = useAtomValue(userCoordinatesAtom);
const coords = useAtomValue(searchCoordinatesAtom);
const prevSearchLocation = useAtomValue(prevSearchLocationAtom);
const debouncedSearchLocation = useDebounce(searchLocation, 200);
const { data: locations } = useLocations(
Expand Down Expand Up @@ -106,6 +106,7 @@ export function LocationSearchBar({ className }: LocationSearchBarProps) {
let isNewCoords = false;
const coordinates = coords.coordinates;
if (
coords.type === 'invalid' ||
(coords.type === 'coordinates' &&
coordinates?.[0] !== prev['userCoordinates']?.[0] &&
coordinates?.[1] !== prev['userCoordinates']?.[1]) ||
Expand Down Expand Up @@ -165,7 +166,7 @@ export function LocationSearchBar({ className }: LocationSearchBarProps) {
onInputChange={handleInputChange}
onValueChange={setSearchLocation}
value={searchLocation}
autoSelectIndex={coords ? undefined : 1}
autoSelectIndex={coords?.length === 2 ? undefined : 1}
/>

<DistanceSelect />
Expand Down
9 changes: 9 additions & 0 deletions src/shared/components/ui/autocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -264,12 +264,21 @@ export function Autocomplete(props: AutocompleteProps) {
onInputChange?.(currentOption.value);
setLastManualInput(currentOption.value);
} else if (autoSelectIndex != null) {
e.preventDefault();
const defaultOption = rest.options[autoSelectIndex];
if (defaultOption) {
onInputChange?.(defaultOption.value);
setValue(defaultOption.value);
setLastManualInput(defaultOption.value);
}
const form = (e.target as HTMLElement).closest('form');
if (form) {
setTimeout(() => {
form.dispatchEvent(
new Event('submit', { cancelable: true, bubbles: true }),
);
}, 0);
}
}
setCurrentIndex(-1);
}
Expand Down

0 comments on commit fbfa521

Please sign in to comment.