import { parsePhoneNumberFromString } from "libphonenumber-js"; import { COUNTRY_LIST } from "../constants"; import type { CountryItem } from "../types"; const COUNTRY_BY_DIAL_DESC = [...COUNTRY_LIST].sort( (a, b) => b.dialCode.length - a.dialCode.length ); export const sanitizeDigits = (input: string): string => input.replace(/\D/g, ""); export const defaultCountry = (): CountryItem => COUNTRY_LIST.find((country) => country.code === "US") ?? COUNTRY_LIST[0]; export const getCountryByCode = (code?: string | null): CountryItem | null => { if (!code) { return null; } return COUNTRY_LIST.find((country) => country.code === code.toUpperCase()) ?? null; }; export const getCountryByDialPrefix = (phone: string): CountryItem | null => { const normalized = phone.trim(); if (!normalized.startsWith("+")) { return null; } return COUNTRY_BY_DIAL_DESC.find((country) => normalized.startsWith(country.dialCode)) ?? null; }; export const resolveCountryFromPhone = ( phone: string, userSelectedCode: string | null ): CountryItem => { const userSelectedCountry = getCountryByCode(userSelectedCode); if (userSelectedCountry) { return userSelectedCountry; } const parsed = parsePhoneNumberFromString(phone); const parsedCountry = getCountryByCode(parsed?.country); if (parsedCountry) { return parsedCountry; } return getCountryByDialPrefix(phone) ?? defaultCountry(); }; export const getLocalDigits = (phone: string, dialCode: string): string => { if (phone.startsWith(dialCode)) { return phone.slice(dialCode.length); } return phone.replace(/^\+/, ""); }; export const filterCountries = (searchText: string): ReadonlyArray => { const query = searchText.trim().toLowerCase(); if (!query) { return COUNTRY_LIST; } const normalizedDialQuery = query.startsWith("+") ? query : `+${query}`; return COUNTRY_LIST.filter((country) => { return ( country.name.toLowerCase().includes(query) || country.code.toLowerCase().includes(query) || country.dialCode.includes(query) || country.dialCode.includes(normalizedDialQuery) ); }); };