1 import { useMemo, useState } from 'react';
3 import Option from '@proton/components/components/option/Option';
4 import type { SearcheableSelectProps } from '@proton/components/components/selectTwo/SearchableSelect';
5 import SearchableSelect from '@proton/components/components/selectTwo/SearchableSelect';
6 import { defaultFilterFunction } from '@proton/components/components/selectTwo/helpers';
7 import type { SelectChangeEvent } from '@proton/components/components/selectTwo/select';
8 import type { CountryItem } from '@proton/components/helpers/countries';
9 import { DEFAULT_SEPARATOR, getFullList } from '@proton/components/helpers/countries';
11 export const useCountries = () => {
12 const countries = useMemo(() => getFullList(), []);
14 const [country, innerSetCountry] = useState(countries[0]);
16 const getCountryByValue = (value: string) => countries.find((country) => country.value === value) ?? countries[0];
18 const setCountry = (value: string) => {
19 if (value === DEFAULT_SEPARATOR.value) {
23 innerSetCountry(getCountryByValue(value));
26 const getCountryByCode = (countryCode: string) => countries.find((country) => country.value === countryCode);
28 return { countries, country, setCountry, getCountryByCode };
32 onChange?: (countryCode: string) => void;
33 selectedCountryCode: string;
34 autoComplete?: string;
35 'data-testid'?: string;
45 const CountriesDropdown = ({ onChange, selectedCountryCode, ...rest }: Props) => {
46 const { countries, getCountryByCode } = useCountries();
47 const selectedCountryItem = getCountryByCode(selectedCountryCode);
49 const searchableSelectProps: SearcheableSelectProps<CountryItem> = {
50 onChange: ({ value: countryItem }: SelectChangeEvent<CountryItem>) => {
51 if (countryItem.value === DEFAULT_SEPARATOR.value) {
54 onChange?.(countryItem.value);
56 value: selectedCountryItem,
57 search: (option, keyword) => {
58 if (option.value.isTop) {
62 return defaultFilterFunction(option, keyword);
64 children: countries.map((countryItem) => {
65 const { key, value, label, disabled } = countryItem;
73 data-testid={`country-${value}`}
75 {value === DEFAULT_SEPARATOR.value ? <hr className="m-0" /> : label}
82 return <SearchableSelect {...searchableSelectProps} />;
85 export default CountriesDropdown;