import React, { forwardRef, useMemo, useCallback } from "react"; import { TextInput, Text, TouchableOpacity, StyleSheet, StyleProp, TextStyle, I18nManager, } from "react-native"; import CustomInput, { CustomInputProps } from "./Input"; import { useTheme } from "../../theme"; import { Ionicons } from "@expo/vector-icons"; import { useBottomSheetStack } from "../../contexts"; import { allCountries } from "country-telephone-data"; import { iso2ToFlagEmoji } from "../../utils/flags"; import CountryPickerView from "./CountryPickerView"; export type Country = { code: string; iso2: string; name: string; }; export interface PhoneInputProps extends Omit< CustomInputProps, | "leftIcon" | "rightIcon" | "onRightIconPress" | "keyboardType" | "style" | "placeholderTextColor" > { value: string; onChangeText: (text: string) => void; selectedCountry?: string; onSelectCountry?: (c: Country) => void; countries?: Country[]; //styles countryNameStyle?: StyleProp; countryCodeStyle?: StyleProp; listTitleStyle?: StyleProp; listTitle?: string; isBottomSheet?: boolean; disableCountryPicker?: boolean onCountryPickerPress?: () => void; } const DEFAULT_COUNTRIES: Country[] = allCountries.map((c) => ({ code: `+${c.dialCode}`, iso2: c.iso2, name: c.name, })); const PhoneInput = forwardRef( ( { value, onChangeText, selectedCountry, onSelectCountry, countries = DEFAULT_COUNTRIES, containerStyle, inputContainerStyle, inputStyle, label, labelStyle, error, errorStyle, helper, helperStyle, listTitle = "Select Country", listTitleStyle, countryCodeStyle, countryNameStyle, isBottomSheet, disableCountryPicker = false, onCountryPickerPress, ...rest }, ref ) => { const { theme } = useTheme(); const { push, clear } = useBottomSheetStack(); const sel = useMemo( () => countries.find((c) => c.iso2 === selectedCountry) || countries.find((c) => c.code === "+1") || countries[0], [selectedCountry, countries] ); const handleCountryPress = useCallback( (c: Country) => { onSelectCountry?.(c); clear(); }, [onSelectCountry, clear] ); const openCountryPicker = useCallback(() => { if(onCountryPickerPress){ onCountryPickerPress() return; } push({ component: ( ), snapPoints: ["80%"], }); }, [ push, countries, handleCountryPress, listTitle, listTitleStyle, countryNameStyle, countryCodeStyle, ]); const leftIcon = useMemo( () => ( {iso2ToFlagEmoji(sel.iso2)} {sel.code} ), [theme, sel, openCountryPicker] ); return ( ); } ); const styles = StyleSheet.create({ selector: { flexDirection: "row", alignItems: "center", borderEndWidth: 1, // borderRightWidth: I18nManager.isRTL ? 0 : 1, // borderLeftWidth: I18nManager.isRTL ? 1 : 0, paddingHorizontal: 8, }, flag: { fontSize: 22, }, code: { fontSize: 14, marginLeft: 6, }, }); export default PhoneInput;