Skip to content

Commit

Permalink
Улучшил ввод телефона. Добавил определение России по языку. Улучшил п…
Browse files Browse the repository at this point in the history
…оиск кода по введенному тексту.
  • Loading branch information
ugputu18 committed Nov 17, 2023
1 parent 67795c7 commit d032676
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 23 deletions.
8 changes: 3 additions & 5 deletions src/common/geolocator.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
export class Geolocator {
async getCurrentRegion(): Promise<string> {
return fetch('https://api.country.is').then((response) =>
response
.json()
.then((data: { ip: string; country: string }) => data.country)
)
const response = await fetch('https://api.country.is')
const json: { ip: string; country: string } = await response.json()
return json.country
}
}
37 changes: 23 additions & 14 deletions src/form/PhoneField/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,17 +115,20 @@ export const PhoneField: React.FC<PhoneFieldProps> = ({
)

const filterOption = useCallback((option: Option, rawInput: string) => {
let equal = true

if (rawInput) {
equal = [
option.value,
option.data.countryName,
option.data.code,
].some(x => x.startsWith(rawInput))
const inputLowerCase = rawInput.toLowerCase()
if (inputLowerCase.startsWith('+')) {
return inputLowerCase.length == 1 || option.data.code.startsWith(inputLowerCase.substr(1))
} else {
return [
option.value,
option.data.countryName,
option.data.code,
].some(x => x.toLowerCase().startsWith(inputLowerCase))
}
}

return equal
return true
}, [])

useEffect(() => {
Expand All @@ -135,13 +138,19 @@ export const PhoneField: React.FC<PhoneFieldProps> = ({
return
}

new Geolocator().getCurrentRegion().then((countryName) => {
const region = getRegionByPhone(
`+${getCountryCodeForRegion(countryName as CountryName) ?? 7}`
)
const languages = navigator.languages || [navigator.language]
const firstNonEnglish = languages.find(x => !x.toLowerCase().includes('en'))
if (firstNonEnglish?.toLowerCase() !== 'ru') {
new Geolocator().getCurrentRegion().then(countryName => {
const region = getRegionByPhone(
`+${getCountryCodeForRegion(countryName as CountryName) ?? 7}`
)

setRegion(region)
})
setRegion(region)
})
} else {
setRegion(getRegionByPhone('+7'))
}
}, [])

return useMemo(() => {
Expand Down
5 changes: 1 addition & 4 deletions src/form/PhoneField/utils/phone.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,7 @@ function prepareRegionData() {
return { byRegion, byCode }
}

export const {
byRegion: phoneNumberDataByRegion,
byCode: phoneNumberDataByCode,
} = prepareRegionData()
export const { byRegion: phoneNumberDataByRegion } = prepareRegionData()

export const regionSelectOptions: Region[] = values(
phoneNumberDataByRegion
Expand Down

0 comments on commit d032676

Please sign in to comment.