Skip to content

Commit

Permalink
fix(CountrySelector): update countries ordering logic
Browse files Browse the repository at this point in the history
  • Loading branch information
ybrusentsov committed Jan 15, 2024
1 parent c35a266 commit bcb8b89
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 16 deletions.
28 changes: 12 additions & 16 deletions src/components/CountrySelector/CountrySelectorDropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,22 +66,17 @@ export const CountrySelectorDropdown: React.FC<
const listRef = useRef<HTMLUListElement>(null);
const lastScrolledCountry = useRef<CountryIso2>();

const preferredCountrySet = useMemo(() => {
return new Set(preferredCountries);
}, [preferredCountries]);

const orderedCountries = useMemo(() => {
const preferred: CountryData[] = [];
const others = [...countries];

preferredCountries.forEach((iso2) => {
const idx = others.findIndex((c) => parseCountry(c).iso2 === iso2);
if (idx !== -1) {
preferred.push(others.splice(idx, 1)[0]);
}
});
const orderedCountries = useMemo<CountryData[]>(() => {
if (!preferredCountries || !preferredCountries.length) {
return countries;
}

return preferred.concat(others);
return [...countries].sort((c) => {
const country = parseCountry(c);
const isPreferredCountry = preferredCountries.includes(country.iso2);

return isPreferredCountry ? -1 : 0;
});
}, [countries, preferredCountries]);

const searchRef = useRef<{
Expand Down Expand Up @@ -265,6 +260,7 @@ export const CountrySelectorDropdown: React.FC<
const country = parseCountry(c);
const isSelected = country.iso2 === selectedCountry;
const isFocused = index === focusedItemIndex;
const isPreferred = preferredCountries.includes(country.iso2);
const flag = flags?.find((f) => f.iso2 === country.iso2);

return (
Expand All @@ -278,7 +274,7 @@ export const CountrySelectorDropdown: React.FC<
className={buildClassNames({
addPrefix: [
'country-selector-dropdown__list-item',
preferredCountrySet.has(country.iso2) &&
isPreferred &&
'country-selector-dropdown__list-item--preferred',
isSelected && 'country-selector-dropdown__list-item--selected',
isFocused && 'country-selector-dropdown__list-item--focused',
Expand Down
3 changes: 3 additions & 0 deletions src/components/PhoneInput/PhoneInput.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -908,6 +908,9 @@ describe('PhoneInput', () => {
expect(getCountrySelectorDropdown().childNodes[1]).toBe(
getDropdownOption('gb'),
);
expect(getCountrySelectorDropdown().childNodes.length).toBe(
defaultCountries.length,
);
});

test('should ignore invalid preferred countries', () => {
Expand Down

0 comments on commit bcb8b89

Please sign in to comment.