|
| 1 | +import {useCallback, useEffect, useRef, useState} from "react"; |
| 2 | + |
| 3 | +import {displayFormat, getRawValue, parsePhoneNumber, usePhone} from "../src"; |
| 4 | + |
| 5 | +const usePhoneTester = ({ |
| 6 | + country = "us", |
| 7 | + initialValue = "", |
| 8 | + onlyCountries = [], |
| 9 | + excludeCountries = [], |
| 10 | + preferredCountries = [], |
| 11 | + }) => { |
| 12 | + const initiatedRef = useRef<boolean>(false); |
| 13 | + const [query, setQuery] = useState<string>(""); |
| 14 | + const [countryCode, setCountryCode] = useState<string>(country); |
| 15 | + |
| 16 | + const { |
| 17 | + clean, |
| 18 | + value, |
| 19 | + metadata, |
| 20 | + setValue, |
| 21 | + countriesList, |
| 22 | + } = usePhone({ |
| 23 | + query, |
| 24 | + country, |
| 25 | + countryCode, |
| 26 | + initialValue, |
| 27 | + onlyCountries, |
| 28 | + excludeCountries, |
| 29 | + preferredCountries, |
| 30 | + }); |
| 31 | + |
| 32 | + const update = useCallback((value: string) => { |
| 33 | + const formattedNumber = displayFormat(clean(value).join("")); |
| 34 | + const phoneMetadata = parsePhoneNumber(formattedNumber, countriesList); |
| 35 | + setCountryCode(phoneMetadata.isoCode as any); |
| 36 | + setValue(formattedNumber); |
| 37 | + }, [clean, countriesList, setValue]); |
| 38 | + |
| 39 | + const backspace = useCallback(() => { |
| 40 | + const rawValue = getRawValue(value); |
| 41 | + const formattedNumber = displayFormat(rawValue.slice(0, -1)); |
| 42 | + const phoneMetadata = parsePhoneNumber(formattedNumber, countriesList); |
| 43 | + setCountryCode(phoneMetadata.isoCode as any); |
| 44 | + setValue(formattedNumber); |
| 45 | + }, [value, countriesList, setValue]); |
| 46 | + |
| 47 | + const search = useCallback(setQuery, []); |
| 48 | + |
| 49 | + const select = useCallback(setCountryCode, []); |
| 50 | + |
| 51 | + useEffect(() => { |
| 52 | + if (initiatedRef.current) return; |
| 53 | + initiatedRef.current = true; |
| 54 | + let initialValue = getRawValue(value); |
| 55 | + if (!initialValue.startsWith(metadata?.[2] as string)) { |
| 56 | + initialValue = metadata?.[2] as string; |
| 57 | + } |
| 58 | + const formattedNumber = displayFormat(clean(initialValue).join("")); |
| 59 | + const phoneMetadata = parsePhoneNumber(formattedNumber, countriesList); |
| 60 | + setCountryCode(phoneMetadata.isoCode as any); |
| 61 | + setValue(formattedNumber); |
| 62 | + }, [clean, countriesList, metadata, setValue, value]) |
| 63 | + |
| 64 | + return {update, search, select, value, metadata, backspace, countriesList}; |
| 65 | +} |
| 66 | + |
| 67 | +describe("Verifying the functionality of hooks", () => { |
| 68 | +}) |
0 commit comments