@input-kit/phone 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,16 @@
1
1
  # @input-kit/phone
2
2
 
3
- Headless React phone input with a complete world country-code dataset, searchable country selection, and `libphonenumber-js` powered formatting and validation.
3
+ Headless React phone input with a complete world country-code dataset, searchable country selection, and `libphonenumber-js` powered formatting and validation.
4
+
5
+ ## Latest update
6
+
7
+ Version `0.1.3` tightens country coverage and compatibility:
8
+
9
+ - India is included as `IN` with `+91` and a localized phone placeholder.
10
+ - The country list now matches all `245` regions supported by `libphonenumber-js`.
11
+ - Fallback metadata is included for Ascension Island (`AC`), Tristan da Cunha (`TA`), and Caribbean Netherlands (`BQ`).
12
+ - Primary dial-code lookup now works for shared codes like `+1`, so `getCountriesByDialCode('+1')` returns matching regions.
13
+ - Older helper and hook aliases remain available for projects already using the previous API shape.
4
14
 
5
15
  ## Features
6
16
 
@@ -93,9 +103,9 @@ function Example() {
93
103
  - `getCountriesByDialCode(dialCode)`
94
104
  - `detectCountryFromPhone(phone)`
95
105
 
96
- ### Utilities
97
-
98
- - `cleanPhone(phone)`
106
+ ### Utilities
107
+
108
+ - `cleanPhone(phone)`
99
109
  - `formatPhone(phone, country)`
100
110
  - `unformatPhone(formattedPhone)`
101
111
  - `validatePhone(phone, country, validator?)`
@@ -103,7 +113,9 @@ function Example() {
103
113
  - `addDialCode(phone, country)`
104
114
  - `removeDialCode(phone, country)`
105
115
  - `filterCountries(countries, query, preferredCountries?)`
106
- - `getPlaceholder(country)`
116
+ - `getPlaceholder(country)`
117
+
118
+ Compatibility aliases are also exported for older consumers: `stripNonDigits`, `isInternationalFormat`, `detectCountry`, `formatPhoneNumber`, `parseToE164`, `getNationalNumber`, `validatePhoneNumber`, `isPhoneNumberComplete`, `formatAsYouType`, `normalizePhoneNumber`, `phoneNumbersEqual`, `getCountryDisplayLabel`, and `limitInputLength`.
107
119
 
108
120
  ## `usePhoneInput(options)`
109
121
 
@@ -140,7 +152,7 @@ Important returned fields:
140
152
 
141
153
  ## Notes
142
154
 
143
- - Country coverage now comes from current `libphonenumber-js` supported regions instead of a short hand-maintained list.
155
+ - Country coverage now comes from current `libphonenumber-js` supported regions instead of a short hand-maintained list, with fallback metadata for supported territories that are incomplete in `world-countries`.
144
156
  - Formatting and validation behavior follows `libphonenumber-js`, similar to libraries like `react-phone-number-input`.
145
157
  - The selector keeps a separate country button and number field, which matches the common multi-country pattern used by larger phone-input packages.
146
158
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var react=require('react'),libphonenumberJs=require('libphonenumber-js'),be=require('libphonenumber-js/mobile/examples'),xe=require('world-countries'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var be__default=/*#__PURE__*/_interopDefault(be);var xe__default=/*#__PURE__*/_interopDefault(xe);var Ie=["US","GB","CA","AU","DE","FR","IT","ES","JP","CN","IN","BR","MX","KR","NL","CH","SE","AE","SG","ZA","NG","SA","TR","ID","PH","TH","VN","MY","NZ","AR"],De=new Set(libphonenumberJs.getCountries());function Ne(e,t){let o=e.startsWith("+")?e:`+${e}`,n=t.replace(/\D/g,"");return `${o}${n}`}function we(e){let t=e.idd?.root;if(!t)return [];let n=(e.idd?.suffixes?.length?e.idd.suffixes:[""]).map(u=>Ne(t,u)).filter(u=>/^\+\d+$/.test(u));return Array.from(new Set(n))}function Re(e){let t=libphonenumberJs.getExampleNumber(e,be__default.default);return t?t.formatNational().replace(/\d/g,"#"):void 0}function ce(e){let t=Ie.indexOf(e);return t===-1?Number.MAX_SAFE_INTEGER:t}var Be=xe__default.default.filter(e=>De.has(e.cca2)).map(e=>{let t=e.cca2,o=we(e),n=`+${libphonenumberJs.getCountryCallingCode(t)}`;return !e.flag||o.length===0?null:{code:t,name:e.name.common,dialCode:n,dialCodes:o,flag:e.flag,format:Re(t)}}).filter(e=>e!==null).sort((e,t)=>{let o=ce(e.code)-ce(t.code);return o!==0?o:e.name.localeCompare(t.name)}),B=Be,ke=new Map(B.map(e=>[e.code,e])),Se=B.reduce((e,t)=>{for(let o of t.dialCodes){let n=e.get(o)??[];n.push(t),e.set(o,n);}return e},new Map),Ee=B.flatMap(e=>e.dialCodes.map(t=>({dialCode:t,country:e}))).sort((e,t)=>t.dialCode.length-e.dialCode.length);function Le(e){let t=e.replace(/\D/g,"");return t?`+${t}`:""}function k(e){return ke.get(e.toUpperCase())}function pe(e){return Se.get(Le(e))??[]}function $e(e){return pe(e)[0]}function re(e){let t=e.trim();if(!t)return;let o=t.startsWith("+")?`+${t.replace(/\D/g,"")}`:t.startsWith("00")?`+${t.slice(2).replace(/\D/g,"")}`:"";if(!o)return;let n=libphonenumberJs.parsePhoneNumberFromString(o);return n?.country?k(n.country):Ee.find(u=>o.startsWith(u.dialCode))?.country}function S(e){let t=e.trim(),o=R(t);return o?t.startsWith("+")?`+${o}`:o:""}function ie(e){return e?.code}function R(e){return e.replace(/\D/g,"")}function se(e,t){return e&&new libphonenumberJs.AsYouType(ie(t)).input(S(e))}function Q(e){return S(e)}function Ae(e,t){return !e||!t?false:e.trim().startsWith("+")?libphonenumberJs.validatePhoneNumberLength(S(e))===void 0:libphonenumberJs.validatePhoneNumberLength(R(e),ie(t))===void 0}function ae(e,t,o){if(!e)return false;if(o)return o(e,t);let n=S(e),u=ie(t);return u?n.startsWith("+")?libphonenumberJs.isValidPhoneNumber(n):libphonenumberJs.isValidPhoneNumber(R(n),u):libphonenumberJs.isPossiblePhoneNumber(n.startsWith("+")?n:`+${R(n)}`)}function E(e,t){if(!t)return e;let o=S(e);if(!o)return "";if(o.startsWith("+"))return o;let n=R(o);return t.dialCodes.find(c=>n.startsWith(c.replace("+","")))?`+${n}`:`${t.dialCode}${n}`}function G(e,t){if(!t)return e;let o=S(e),n=R(o);for(let u of t.dialCodes){let c=u.replace("+","");if(n.startsWith(c))return n.slice(c.length)}return n}function ue(e,t,o){let n=t.toLowerCase().trim();return n?e.filter(u=>u.name.toLowerCase().includes(n)||u.code.toLowerCase().includes(n)||u.dialCodes.some(c=>c.includes(n))):o?.length?[...e].sort((u,c)=>{let m=o.indexOf(u.code),P=o.indexOf(c.code);return m!==-1&&P!==-1?m-P:m!==-1?-1:P!==-1?1:u.name.localeCompare(c.name)}):e}function le(e){return e?.format?e.format.replace(/#/g,"0"):e?.dialCode?`${e.dialCode} 000 000 0000`:"Phone number"}function de(e={}){let{value:t,defaultValue:o="",onChange:n,onBlur:u,onFocus:c,defaultCountry:m="US",preferredCountries:P,excludeCountries:$,onlyCountries:W,autoDetect:z=true,formatOnType:U=true,includeDialCode:d=false,validator:H}=e,I=t!==void 0,g=react.useMemo(()=>{let i=B;return W?.length&&(i=i.filter(r=>W.includes(r.code))),$?.length&&(i=i.filter(r=>!$.includes(r.code))),i},[W,$]),_=k(m)||g[0],[X,V]=react.useState(o),[a,v]=react.useState(_),[f,p]=react.useState(false),[D,N]=react.useState(""),s=I?t:X;react.useEffect(()=>{let i=k(m)||g[0];i&&i.code!==a?.code&&v(i);},[m,g,a?.code]),react.useEffect(()=>{if(z&&s){let i=re(s);i&&g.some(r=>r.code===i.code)&&i.code!==a?.code&&v(i);}},[g,z,s,a?.code]);let b=react.useMemo(()=>U?se(d&&s.startsWith("+")?G(s,a):s,a):d&&s.startsWith("+")?G(s,a):s,[U,d,s,a]),C=react.useMemo(()=>d&&a?E(s,a):s,[s,a,d]),O=react.useMemo(()=>ae(s,a,H),[s,a,H]),Z=react.useMemo(()=>ue(g,D,P),[g,D,P]),A=react.useCallback(i=>{let r=Q(i);I||V(r),n?.(d?E(r,a):r,a);},[I,n,a,d]),j=react.useCallback(i=>{let r=k(i);r&&(v(r),n?.(d?E(s,r):s,r));},[s,n,d]),J=react.useCallback(i=>{v(i),p(false),N(""),n?.(d?E(s,i):s,i);},[s,n,d]),w=react.useCallback(()=>{p(i=>!i),f&&N("");},[f]),q=react.useCallback(()=>{p(true);},[]),ee=react.useCallback(()=>{p(false),N("");},[]),M=react.useCallback(()=>{I||V(""),n?.("",a);},[I,n,a]),te=react.useCallback(i=>{let r=i.target.value,y=r.trim().startsWith("+")?`+${r.replace(/\D/g,"")}`:Q(r);A(y);},[A]),ne=react.useCallback(()=>{c?.();},[c]),oe=react.useCallback(()=>{u?.();},[u]);return {phone:s,fullPhone:C,country:a,isValid:O,isOpen:f,searchQuery:D,setPhone:A,setCountry:j,toggleDropdown:w,openDropdown:q,closeDropdown:ee,setSearchQuery:N,clear:M,inputProps:{value:b,onChange:te,onFocus:ne,onBlur:oe,type:"tel",inputMode:"tel",autoComplete:"tel",placeholder:le(a),"aria-invalid":s?!O:void 0},countryButtonProps:{onClick:w,"aria-expanded":f,"aria-haspopup":"listbox"},filteredCountries:Z,selectCountry:J}}var He=({size:e=12})=>jsxRuntime.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("polyline",{points:"18 15 12 9 6 15"})}),Ve=({size:e=12})=>jsxRuntime.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("polyline",{points:"6 9 12 15 18 9"})}),Qe=react.forwardRef(function(t,o){let{value:n,defaultValue:u,onChange:c,onBlur:m,onFocus:P,inputClassName:$,selectorClassName:W,containerClassName:z,placeholder:U,disabled:d,readOnly:H,name:I,id:g,"aria-label":_,"aria-labelledby":X,...V}=t,a=react.useRef(null),v=react.useRef([]),[f,p]=react.useState(0),D=react.useId(),{inputProps:N,countryButtonProps:s,country:b,filteredCountries:C,isOpen:O,isValid:Z,searchQuery:A,setSearchQuery:j,setCountry:J,selectCountry:w,clear:q,openDropdown:ee,closeDropdown:M}=de({value:n,defaultValue:u,onChange:c,onBlur:m,onFocus:P,...V}),te=react.useCallback(()=>{a.current?.focus();},[]),ne=react.useCallback(()=>{a.current?.blur();},[]),oe=react.useCallback(r=>{w(r),p(0);},[w]),i=react.useCallback((r,y,x)=>{switch(r.key){case "Enter":case " ":r.preventDefault(),w(y),p(0);break;case "ArrowDown":if(r.preventDefault(),x<C.length-1){let F=x+1;p(F),v.current[F]?.focus();}break;case "ArrowUp":if(r.preventDefault(),x>0){let F=x-1;p(F),v.current[F]?.focus();}break;case "Escape":r.preventDefault(),M();break}},[w,C.length,M]);return react.useEffect(()=>{if(C.length===0){f!==0&&p(0);return}f>=C.length&&p(C.length-1);},[C.length,f]),react.useImperativeHandle(o,()=>({focus:te,blur:ne,clear:q,setCountry:J,getCountry:()=>b,open:ee,close:M})),jsxRuntime.jsxs("div",{className:z,"data-valid":Z,children:[jsxRuntime.jsxs("button",{...s,type:"button",className:W,disabled:d,tabIndex:d?-1:0,"aria-controls":D,children:[b?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{className:"phone-input-flag",children:b.flag}),jsxRuntime.jsx("span",{className:"phone-input-dial-code",children:b.dialCode})]}):jsxRuntime.jsx("span",{className:"phone-input-placeholder",children:"Select"}),jsxRuntime.jsx("span",{className:"phone-input-arrow","aria-hidden":"true",children:O?jsxRuntime.jsx(He,{size:12}):jsxRuntime.jsx(Ve,{size:12})})]}),jsxRuntime.jsx("input",{...N,ref:a,id:g,name:I,className:$,placeholder:U||N.placeholder,disabled:d,readOnly:H,"aria-label":_,"aria-labelledby":X}),O&&jsxRuntime.jsxs("div",{className:"phone-input-dropdown",children:[jsxRuntime.jsx("div",{className:"phone-input-search",children:jsxRuntime.jsx("input",{type:"text",value:A,onChange:r=>j(r.target.value),placeholder:"Search countries...",autoFocus:true,"aria-controls":D,"aria-label":"Search countries"})}),jsxRuntime.jsxs("ul",{className:"phone-input-country-list",id:D,role:"listbox","aria-label":"Country options",children:[C.map((r,y)=>jsxRuntime.jsxs("li",{ref:x=>{v.current[y]=x;},role:"option","aria-selected":r.code===b?.code,className:`phone-input-country-option ${r.code===b?.code?"selected":""} ${y===f?"highlighted":""}`,onClick:()=>oe(r),onKeyDown:x=>i(x,r,y),onMouseEnter:()=>p(y),tabIndex:y===f?0:-1,children:[jsxRuntime.jsx("span",{className:"phone-input-flag",children:r.flag}),jsxRuntime.jsx("span",{className:"phone-input-country-name",children:r.name}),jsxRuntime.jsx("span",{className:"phone-input-dial-code",children:r.dialCode})]},r.code)),C.length===0&&jsxRuntime.jsx("li",{className:"phone-input-no-results",children:"No countries found"})]})]})]})});exports.PhoneInput=Qe;exports.addDialCode=E;exports.cleanPhone=R;exports.countries=B;exports.detectCountryFromPhone=re;exports.filterCountries=ue;exports.formatPhone=se;exports.getCountriesByDialCode=pe;exports.getCountryByCode=k;exports.getCountryByDialCode=$e;exports.getPlaceholder=le;exports.removeDialCode=G;exports.unformatPhone=Q;exports.usePhoneInput=de;exports.validatePhone=ae;exports.validatePhoneLength=Ae;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var react=require('react'),libphonenumberJs=require('libphonenumber-js'),Ze=require('libphonenumber-js/mobile/examples'),Je=require('world-countries'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Ze__default=/*#__PURE__*/_interopDefault(Ze);var Je__default=/*#__PURE__*/_interopDefault(Je);var et=["US","GB","CA","AU","DE","FR","IT","ES","JP","CN","IN","BR","MX","KR","NL","CH","SE","AE","SG","ZA","NG","SA","TR","ID","PH","TH","VN","MY","NZ","AR"],tt=new Set(libphonenumberJs.getCountries()),nt=new Map(Je__default.default.map(e=>[e.cca2,e])),rt={AC:{name:"Ascension Island",dialCode:"+247"},TA:{name:"Tristan da Cunha",dialCode:"+290"},BQ:{name:"Caribbean Netherlands",dialCode:"+599"}};function ot(e,t){let n=e.startsWith("+")?e:`+${e}`,r=t.replace(/\D/g,"");return `${n}${r}`}function it(e){return e.toUpperCase().replace(/./g,t=>String.fromCodePoint(127397+t.charCodeAt(0)))}function at(e,t){let n=e?.idd?.root;if(!n)return [t];let o=(e.idd?.suffixes?.length?e.idd.suffixes:[""]).map(l=>ot(n,l)).filter(l=>/^\+\d+$/.test(l));return Array.from(new Set([t,...o.length?o:[]]))}function st(e){let t=libphonenumberJs.getExampleNumber(e,Ze__default.default);return t?t.formatNational().replace(/\d/g,"#"):void 0}function Ee(e){let t=et.indexOf(e);return t===-1?Number.MAX_SAFE_INTEGER:t}var ut=Array.from(tt).map(e=>{let t=nt.get(e),n=rt[e],r=n?.dialCode??`+${libphonenumberJs.getCountryCallingCode(e)}`,o=at(t,r);return {code:e,name:t?.name.common??n?.name??e,dialCode:r,dialCodes:o,flag:t?.flag||n?.flag||it(e),format:st(e)}}).sort((e,t)=>{let n=Ee(e.code)-Ee(t.code);return n!==0?n:e.name.localeCompare(t.name)}),R=ut,lt=new Map(R.map(e=>[e.code,e])),ct=R.reduce((e,t)=>{for(let n of t.dialCodes){let r=e.get(n)??[];r.push(t),e.set(n,r);}return e},new Map),dt=R.flatMap(e=>e.dialCodes.map(t=>({dialCode:t,country:e}))).sort((e,t)=>t.dialCode.length-e.dialCode.length),Me=new Map;function pt(e){return Array.isArray(e)?[...e]:e?[e]:[]}function ft(e){let t=pt(e);if(t.length===0||typeof Intl>"u"||typeof Intl.DisplayNames>"u")return;let n=t.join("|"),r=Me.get(n);if(r)return r;try{let o=new Intl.DisplayNames(t,{type:"region"});return Me.set(n,o),o}catch{return}}function Ct(e){let t=e.replace(/\D/g,"");return t?`+${t}`:""}function j(e){return lt.get(e.toUpperCase())}function Re(e,t){return e?ft(t)?.of(e.code)??e.displayName??e.name:void 0}function X(e,t){if(!e)return;let n=Re(e,t);return n?{...e,displayName:n}:e}function Le(e,t){return t?e.map(n=>X(n,t)??n):e}function Fe(e){return ct.get(Ct(e))??[]}function yt(e){return Fe(e)[0]}function U(e){let t=e.trim();if(!t)return;let n=t.startsWith("+")?`+${t.replace(/\D/g,"")}`:t.startsWith("00")?`+${t.slice(2).replace(/\D/g,"")}`:"";if(!n)return;let r=libphonenumberJs.parsePhoneNumberFromString(n);return r?.country?j(r.country):dt.find(o=>n.startsWith(o.dialCode))?.country}var Ne={selectCountry:"Select country",countrySearchPlaceholder:"Search countries...",noCountriesFound:"No countries found",searchCountriesAriaLabel:"Search countries",countryOptionsAriaLabel:"Country options",countryButtonAriaLabel:"Open country selector"},gt={en:Ne,fr:{selectCountry:"Choisir un pays",countrySearchPlaceholder:"Rechercher un pays...",noCountriesFound:"Aucun pays trouv\xE9",searchCountriesAriaLabel:"Rechercher des pays",countryOptionsAriaLabel:"Options de pays",countryButtonAriaLabel:"Ouvrir le s\xE9lecteur de pays"},de:{selectCountry:"Land ausw\xE4hlen",countrySearchPlaceholder:"Land suchen...",noCountriesFound:"Keine L\xE4nder gefunden",searchCountriesAriaLabel:"L\xE4nder suchen",countryOptionsAriaLabel:"L\xE4nderoptionen",countryButtonAriaLabel:"L\xE4nderauswahl \xF6ffnen"},es:{selectCountry:"Seleccionar pa\xEDs",countrySearchPlaceholder:"Buscar pa\xEDs...",noCountriesFound:"No se encontraron pa\xEDses",searchCountriesAriaLabel:"Buscar pa\xEDses",countryOptionsAriaLabel:"Opciones de pa\xEDs",countryButtonAriaLabel:"Abrir selector de pa\xEDs"},pt:{selectCountry:"Selecionar pa\xEDs",countrySearchPlaceholder:"Pesquisar pa\xEDs...",noCountriesFound:"Nenhum pa\xEDs encontrado",searchCountriesAriaLabel:"Pesquisar pa\xEDses",countryOptionsAriaLabel:"Op\xE7\xF5es de pa\xEDs",countryButtonAriaLabel:"Abrir seletor de pa\xEDs"},it:{selectCountry:"Seleziona paese",countrySearchPlaceholder:"Cerca paese...",noCountriesFound:"Nessun paese trovato",searchCountriesAriaLabel:"Cerca paesi",countryOptionsAriaLabel:"Opzioni paese",countryButtonAriaLabel:"Apri selettore paese"},ja:{selectCountry:"\u56FD\u3092\u9078\u629E",countrySearchPlaceholder:"\u56FD\u3092\u691C\u7D22...",noCountriesFound:"\u56FD\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",searchCountriesAriaLabel:"\u56FD\u3092\u691C\u7D22",countryOptionsAriaLabel:"\u56FD\u306E\u5019\u88DC",countryButtonAriaLabel:"\u56FD\u306E\u30BB\u30EC\u30AF\u30BF\u30FC\u3092\u958B\u304F"},ko:{selectCountry:"\uAD6D\uAC00 \uC120\uD0DD",countrySearchPlaceholder:"\uAD6D\uAC00 \uAC80\uC0C9...",noCountriesFound:"\uAD6D\uAC00\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4",searchCountriesAriaLabel:"\uAD6D\uAC00 \uAC80\uC0C9",countryOptionsAriaLabel:"\uAD6D\uAC00 \uC635\uC158",countryButtonAriaLabel:"\uAD6D\uAC00 \uC120\uD0DD\uAE30 \uC5F4\uAE30"},zh:{selectCountry:"\u9009\u62E9\u56FD\u5BB6",countrySearchPlaceholder:"\u641C\u7D22\u56FD\u5BB6...",noCountriesFound:"\u672A\u627E\u5230\u56FD\u5BB6",searchCountriesAriaLabel:"\u641C\u7D22\u56FD\u5BB6",countryOptionsAriaLabel:"\u56FD\u5BB6\u9009\u9879",countryButtonAriaLabel:"\u6253\u5F00\u56FD\u5BB6\u9009\u62E9\u5668"},ar:{selectCountry:"\u0627\u062E\u062A\u0631 \u0627\u0644\u062F\u0648\u0644\u0629",countrySearchPlaceholder:"\u0627\u0628\u062D\u062B \u0639\u0646 \u062F\u0648\u0644\u0629...",noCountriesFound:"\u0644\u0645 \u064A\u062A\u0645 \u0627\u0644\u0639\u062B\u0648\u0631 \u0639\u0644\u0649 \u062F\u0648\u0644",searchCountriesAriaLabel:"\u0627\u0628\u062D\u062B \u0639\u0646 \u0627\u0644\u062F\u0648\u0644",countryOptionsAriaLabel:"\u062E\u064A\u0627\u0631\u0627\u062A \u0627\u0644\u062F\u0648\u0644",countryButtonAriaLabel:"\u0627\u0641\u062A\u062D \u0645\u062D\u062F\u062F \u0627\u0644\u062F\u0648\u0644\u0629"},hi:{selectCountry:"\u0926\u0947\u0936 \u091A\u0941\u0928\u0947\u0902",countrySearchPlaceholder:"\u0926\u0947\u0936 \u0916\u094B\u091C\u0947\u0902...",noCountriesFound:"\u0915\u094B\u0908 \u0926\u0947\u0936 \u0928\u0939\u0940\u0902 \u092E\u093F\u0932\u093E",searchCountriesAriaLabel:"\u0926\u0947\u0936 \u0916\u094B\u091C\u0947\u0902",countryOptionsAriaLabel:"\u0926\u0947\u0936 \u0935\u093F\u0915\u0932\u094D\u092A",countryButtonAriaLabel:"\u0926\u0947\u0936 \u091A\u092F\u0928 \u0916\u094B\u0932\u0947\u0902"}};function mt(e){let n=(Array.isArray(e)?e:e?[e]:[]).find(Boolean);return n?n.toLowerCase().split("-")[0]:void 0}function xe(e,t){let n=mt(e),r=n?gt[n]:void 0;return {...Ne,...r,...t}}function _(e){let t=e.trim(),n=d(t);return t.startsWith("+")&&!n?"+":n?t.startsWith("+")?`+${n}`:n:""}function Ie(e){return e?.code}function ze(e){return e?.format?.replace(/[^#]/g,"").length}function d(e){return e.replace(/\D/g,"")}function H(e,t){return e&&new libphonenumberJs.AsYouType(Ie(t)).input(_(e))}function le(e){return _(e)}function Te(e,t){return !e||!t?false:e.trim().startsWith("+")?libphonenumberJs.validatePhoneNumberLength(_(e))===void 0:libphonenumberJs.validatePhoneNumberLength(d(e),Ie(t))===void 0}function ce(e,t,n){if(!e)return false;if(n)return n(e,t??void 0);let r=_(e),o=Ie(t);return o?r.startsWith("+")?libphonenumberJs.isValidPhoneNumber(r):libphonenumberJs.isValidPhoneNumber(d(r),o):libphonenumberJs.isPossiblePhoneNumber(r.startsWith("+")?r:`+${d(r)}`)}function B(e,t){if(!t)return e;let n=_(e);if(!n||n==="+")return "";if(n.startsWith("+"))return n;let r=d(n);return t.dialCodes.find(l=>r.startsWith(l.replace("+","")))?`+${r}`:`${t.dialCode}${r}`}function O(e,t){if(!t)return e;let n=_(e),r=d(n),o=d(t.dialCode);if(r.startsWith(o))return r.slice(o.length);for(let l of t.dialCodes){let y=l.replace("+","");if(r.startsWith(y))return r.slice(y.length)}return r}function De(e,t,n){let r=t.toLowerCase().trim();return r?e.filter(o=>o.name.toLowerCase().includes(r)||(o.displayName??"").toLowerCase().includes(r)||o.code.toLowerCase().includes(r)||o.dialCodes.some(l=>l.includes(r))):n?.length?[...e].sort((o,l)=>{let y=n.indexOf(o.code),C=n.indexOf(l.code);return y!==-1&&C!==-1?y-C:y!==-1?-1:C!==-1?1:(o.displayName??o.name).localeCompare(l.displayName??l.name)}):e}function de(e){return e?.displayName??e?.name??""}function ve(e){return e?.format?e.format.replace(/#/g,"0"):e?.dialCode?`${e.dialCode} 000 000 0000`:"Phone number"}var Pt=d;function Z(e){return e.trim().startsWith("+")||e.trim().startsWith("00")}function Lt(e){let t=d(e);if(!Z(e))return {dialCode:null,nationalNumber:t};let n=R.map(o=>o.dialCode).sort((o,l)=>l.length-o.length).find(o=>t.startsWith(d(o)));if(!n)return {dialCode:null,nationalNumber:t};let r=d(n);return {dialCode:r,nationalNumber:t.slice(r.length)}}function Nt(e){return U(e)??null}function xt(e,t,n="national"){if(!e)return "";if(n==="e164")return B(e,t);let r=Z(e)?O(e,t):e;if(!t&&n==="national")return d(r).slice(0,9).replace(/(\d{3})(?=\d)/g,"$1 ").trim();let o=H(r,t);return n==="international"?t?`${t.dialCode} ${o}`:B(e,t):o}function At(e,t){return B(e,t)}function It(e,t){if(t)return O(e,t);let n=U(e);return n?O(e,n):d(e)}function Se(e,t,n=false){let r=d(e);if(!r)return n?{isValid:false,error:"Phone number is required"}:{isValid:true,error:null};let o=ze(t),l=t?d(O(e,t)):r;return l.length<7?{isValid:false,error:"Phone number is too short"}:o&&l.length>o?{isValid:false,error:`Phone number is too long (max ${o} digits)`}:ce(e,t)?{isValid:true,error:null}:{isValid:false,error:"Invalid phone number"}}function Dt(e,t){return t?Te(e,t):d(e).length>=7}function vt(e,t){return Z(e)&&t?`${t.dialCode} ${H(O(e,t),t)}`:H(e,t)}var Ae=d;function St(e,t){return Ae(e)===Ae(t)}function wt(e,t=true){let n=`${e.flag} ${de(e)}`;return t?`${n} (${e.dialCode})`:n}function Bt(e,t){let n=ze(t);if(!n)return e;let r=Z(e),o=d(e),l=t?d(t.dialCode):"",y=r?l.length+n:n,C=o.slice(0,y);return r?`+${C}`:C}function Et(e,t){return e.slice(0,t).replace(/\D/g,"").length}function Mt(e,t){if(t<=0)return e.startsWith("+")?1:0;let n=0;for(let r=0;r<e.length;r+=1)if(/\d/.test(e[r])&&(n+=1,n===t))return r+1;return e.length}function Be(e={}){let{value:t,defaultValue:n="",onChange:r,onCountryChange:o,onBlur:l,onFocus:y,defaultCountry:C="US",preferredCountries:ee,excludeCountries:fe,excludedCountries:Ce,onlyCountries:ye,allowedCountries:ge,autoDetect:q,autoDetectCountry:me,formatOnType:te=true,includeDialCode:m=false,required:ne=false,validator:re,locale:N,labels:$}=e,F=ye??ge,I=fe??Ce,x=q??me??true,D=t!==void 0,z=react.useRef(null),G=react.useRef(null),v=react.useRef(C),p=react.useMemo(()=>{let i=R;return F?.length&&(i=i.filter(a=>F.includes(a.code))),I?.length&&(i=i.filter(a=>!I.includes(a.code))),i},[F,I]),Q=react.useMemo(()=>Le(p,N),[p,N]),T=react.useMemo(()=>xe(N,$),[N,$]),he=p.find(i=>i.code===C)||p[0],[be,oe]=react.useState(n),[s,W]=react.useState(he),[k,M]=react.useState(false),[S,P]=react.useState(""),u=D?t:be,g=react.useCallback(i=>X(i,N),[N]);react.useEffect(()=>{let i=v.current!==C;v.current=C;let a=p.find(Y=>Y.code===C)||p[0],h=s?p.some(Y=>Y.code===s.code):false;a&&(i||!h)&&W(a);},[C,p,s]),react.useEffect(()=>{if(x&&u){let i=U(u);i&&p.some(a=>a.code===i.code)&&i.code!==s?.code&&(W(i),o?.(g(i)));}},[p,x,u,s?.code,o,g]);let V=react.useMemo(()=>te?H(m&&u.startsWith("+")?O(u,s):u,s):m&&u.startsWith("+")?O(u,s):u,[te,m,u,s]),Pe=react.useMemo(()=>m&&s?B(u,s):u,[u,s,m]),ie=react.useMemo(()=>ce(u,s,re),[u,s,re]),c=react.useMemo(()=>Se(u,s,ne).error,[u,s,ne]),w=react.useMemo(()=>X(s,N),[s,N]),L=react.useMemo(()=>De(Q,S,ee),[Q,S,ee]);react.useLayoutEffect(()=>{let i=G.current,a=z.current;if(i===null||!a||typeof a.setSelectionRange!="function"||typeof document<"u"&&document.activeElement!==a)return;let h=Mt(V,i);a.setSelectionRange(h,h),G.current=null;},[V]);let A=react.useCallback(i=>{let a=le(i);D||oe(a),r?.(m?B(a,s):a,g(s));},[D,r,s,m,g]),Ue=react.useCallback(i=>{let a=j(i);a&&(W(a),o?.(g(a)),r?.(m?B(u,a):u,g(a)));},[u,r,o,m,g]),ae=react.useCallback(i=>{let a=j(i.code)??i;W(a),M(false),P(""),o?.(g(a)),r?.(m?B(u,a):u,g(a));},[u,r,o,m,g]),se=react.useCallback(()=>{M(i=>!i),k&&P("");},[k]),Oe=react.useCallback(()=>{M(true);},[]),ue=react.useCallback(()=>{M(false),P("");},[]),He=react.useCallback(()=>{D||oe(""),r?.("",g(s));},[D,r,s,g]),_e=react.useCallback(i=>{let a=i.target.value,h=i.target.selectionStart??a.length,Y=a.trim().startsWith("+")?`+${a.replace(/\D/g,"")}`:le(a);G.current=Et(a,h),A(Y);},[A]),Ke=react.useCallback(()=>{y?.();},[y]),qe=react.useCallback(()=>{l?.();},[l]),Ge=react.useCallback((i,a)=>({role:"option","aria-selected":i.code===s?.code,onClick:()=>ae(i),onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),ae(i)),h.key==="Escape"&&(h.preventDefault(),ue());},tabIndex:a===0?0:-1}),[ue,s?.code,ae]);return {phone:u,value:u,fullPhone:Pe,country:w,isValid:ie,error:c,isOpen:k,searchQuery:S,labels:T,formattedValue:V,setPhone:A,setValue:A,setCountry:Ue,toggleDropdown:se,toggle:se,openDropdown:Oe,open:Oe,closeDropdown:ue,close:ue,setSearchQuery:P,clear:He,inputProps:{ref:z,value:V,onChange:_e,onFocus:Ke,onBlur:qe,type:"tel",inputMode:"tel",autoComplete:"tel",placeholder:ve(s),"aria-invalid":u?!ie:void 0},countryButtonProps:{onClick:se,"aria-expanded":k,"aria-haspopup":"listbox","aria-label":T.countryButtonAriaLabel},countrySelectorProps:{onClick:se,"aria-expanded":k,"aria-haspopup":true,"aria-label":T.countryButtonAriaLabel},dropdownProps:{role:"listbox","aria-label":T.countryOptionsAriaLabel},filteredCountries:L,countries:L,selectCountry:ae,getCountryOptionProps:Ge}}var Tt=({size:e=12})=>jsxRuntime.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("polyline",{points:"18 15 12 9 6 15"})}),Wt=({size:e=12})=>jsxRuntime.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("polyline",{points:"6 9 12 15 18 9"})}),Vt=react.forwardRef(function(t,n){let{value:r,defaultValue:o,onChange:l,onBlur:y,onFocus:C,inputClassName:ee,selectorClassName:fe,containerClassName:Ce,searchable:ye=true,placeholder:ge,disabled:q,readOnly:me,name:te,id:m,"aria-label":ne,"aria-labelledby":re,...N}=t,$=react.useRef(null),F=react.useRef([]),[I,x]=react.useState(0),D=react.useId(),{inputProps:z,countryButtonProps:G,country:v,filteredCountries:p,isOpen:Q,isValid:T,searchQuery:he,setSearchQuery:be,setCountry:oe,selectCountry:s,clear:W,openDropdown:k,closeDropdown:M,labels:S}=Be({value:r,defaultValue:o,onChange:l,onBlur:y,onFocus:C,...N}),P=z.ref,u=react.useCallback(c=>{$.current=c,typeof P=="function"?P(c):P&&"current"in P&&(P.current=c);},[P]),g=react.useCallback(()=>{$.current?.focus();},[]),V=react.useCallback(()=>{$.current?.blur();},[]),Pe=react.useCallback(c=>{s(c),x(0);},[s]),ie=react.useCallback((c,w,L)=>{switch(c.key){case "Enter":case " ":c.preventDefault(),s(w),x(0);break;case "ArrowDown":if(c.preventDefault(),L<p.length-1){let A=L+1;x(A),F.current[A]?.focus();}break;case "ArrowUp":if(c.preventDefault(),L>0){let A=L-1;x(A),F.current[A]?.focus();}break;case "Escape":c.preventDefault(),M();break}},[s,p.length,M]);return react.useEffect(()=>{if(p.length===0){I!==0&&x(0);return}I>=p.length&&x(p.length-1);},[p.length,I]),react.useImperativeHandle(n,()=>({focus:g,blur:V,clear:W,setCountry:oe,getCountry:()=>v,open:k,close:M})),jsxRuntime.jsxs("div",{className:Ce,"data-valid":T,children:[jsxRuntime.jsxs("button",{...G,type:"button",className:fe,disabled:q,tabIndex:q?-1:0,"aria-controls":D,children:[v?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{className:"phone-input-flag",children:v.flag}),jsxRuntime.jsx("span",{className:"phone-input-dial-code",children:v.dialCode})]}):jsxRuntime.jsx("span",{className:"phone-input-placeholder",children:S.selectCountry}),jsxRuntime.jsx("span",{className:"phone-input-arrow","aria-hidden":"true",children:Q?jsxRuntime.jsx(Tt,{size:12}):jsxRuntime.jsx(Wt,{size:12})})]}),jsxRuntime.jsx("input",{...z,ref:u,id:m,name:te,className:ee,placeholder:ge||z.placeholder,disabled:q,readOnly:me,"aria-label":ne,"aria-labelledby":re}),Q&&jsxRuntime.jsxs("div",{className:"phone-input-dropdown",children:[ye&&jsxRuntime.jsx("div",{className:"phone-input-search",children:jsxRuntime.jsx("input",{type:"text",value:he,onChange:c=>be(c.target.value),placeholder:S.countrySearchPlaceholder,autoFocus:true,"aria-controls":D,"aria-label":S.searchCountriesAriaLabel})}),jsxRuntime.jsxs("ul",{className:"phone-input-country-list",id:D,role:"listbox","aria-label":S.countryOptionsAriaLabel,children:[p.map((c,w)=>jsxRuntime.jsxs("li",{ref:L=>{F.current[w]=L;},role:"option","aria-selected":c.code===v?.code,className:`phone-input-country-option ${c.code===v?.code?"selected":""} ${w===I?"highlighted":""}`,onClick:()=>Pe(c),onKeyDown:L=>ie(L,c,w),onMouseEnter:()=>x(w),tabIndex:w===I?0:-1,children:[jsxRuntime.jsx("span",{className:"phone-input-flag",children:c.flag}),jsxRuntime.jsx("span",{className:"phone-input-country-name",children:de(c)}),jsxRuntime.jsx("span",{className:"phone-input-dial-code",children:c.dialCode})]},c.code)),p.length===0&&jsxRuntime.jsx("li",{className:"phone-input-no-results",children:S.noCountriesFound})]})]})]})});exports.DEFAULT_PHONE_INPUT_LABELS=Ne;exports.PhoneInput=Vt;exports.addDialCode=B;exports.cleanPhone=d;exports.countries=R;exports.detectCountry=Nt;exports.detectCountryFromPhone=U;exports.extractDialCode=Lt;exports.filterCountries=De;exports.formatAsYouType=vt;exports.formatPhone=H;exports.formatPhoneNumber=xt;exports.getCountriesByDialCode=Fe;exports.getCountryByCode=j;exports.getCountryByDialCode=yt;exports.getCountryDisplayLabel=wt;exports.getCountryDisplayName=de;exports.getLocalizedCountryName=Re;exports.getNationalNumber=It;exports.getPlaceholder=ve;exports.isInternationalFormat=Z;exports.isPhoneNumberComplete=Dt;exports.limitInputLength=Bt;exports.localizeCountries=Le;exports.localizeCountry=X;exports.normalizePhoneNumber=Ae;exports.parseToE164=At;exports.phoneNumbersEqual=St;exports.removeDialCode=O;exports.resolvePhoneInputLabels=xe;exports.stripNonDigits=Pt;exports.unformatPhone=le;exports.usePhoneInput=Be;exports.validatePhone=ce;exports.validatePhoneLength=Te;exports.validatePhoneNumber=Se;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/countries.ts","../src/utils.ts","../src/usePhoneInput.ts","../src/PhoneInput.tsx"],"names":["PRIORITY_COUNTRIES","supportedCountries","getCountries","normalizeDialCode","root","suffix","normalizedRoot","digitsOnlySuffix","buildDialCodes","country","dialCodes","dialCode","getCountryFormat","code","example","getExampleNumber","examples","getCountryPriority","index","generatedCountries","worldCountries","getCountryCallingCode","left","right","priorityDelta","countries","countryMap","countriesByDialCode","map","matches","dialCodeMatchers","normalizeLookupDialCode","digits","getCountryByCode","getCountriesByDialCode","getCountryByDialCode","detectCountryFromPhone","phone","trimmed","normalized","parsedPhone","parsePhoneNumberFromString","entry","normalizePhoneInput","cleanPhone","getCountryCode","formatPhone","AsYouType","unformatPhone","formattedPhone","validatePhoneLength","validateLength","validatePhone","customValidator","countryCode","isValidPhoneNumber","isPossiblePhoneNumber","addDialCode","removeDialCode","dialDigits","filterCountries","query","preferredCountries","lowerQuery","a","b","aPreferred","bPreferred","getPlaceholder","usePhoneInput","options","controlledValue","defaultValue","onChange","onBlur","onFocus","defaultCountry","excludeCountries","onlyCountries","autoDetect","formatOnType","includeDialCode","validator","isControlled","availableCountries","useMemo","filtered","c","initialCountry","internalPhone","setInternalPhone","useState","setCountry","isOpen","setIsOpen","searchQuery","setSearchQuery","useEffect","nextCountry","detected","candidate","fullPhone","isValid","filteredCountries","setPhone","useCallback","newPhone","unformatted","setCountryByCode","newCountry","selectCountry","selectedCountry","toggleDropdown","prev","openDropdown","closeDropdown","clear","handleInputChange","event","rawValue","handleFocus","handleBlur","ChevronUpIcon","size","jsx","ChevronDownIcon","PhoneInput","forwardRef","props","ref","value","inputClassName","selectorClassName","containerClassName","placeholder","disabled","readOnly","name","id","ariaLabel","ariaLabelledBy","inputRef","useRef","optionRefs","highlightedIndex","setHighlightedIndex","listboxId","useId","inputProps","countryButtonProps","focus","blur","handleCountryClick","handleCountryKeyDown","e","nextIndex","useImperativeHandle","jsxs","Fragment","element"],"mappings":"+WAaA,IAAMA,EAAAA,CAAqB,CACzB,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CACpF,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,I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ountryCallingCode, getExampleNumber, parsePhoneNumberFromString, type CountryCode } from 'libphonenumber-js';\r\nimport examples from 'libphonenumber-js/mobile/examples';\r\nimport worldCountries from 'world-countries';\r\n\r\nexport interface Country {\r\n code: string;\r\n name: string;\r\n dialCode: string;\r\n dialCodes: string[];\r\n flag: string;\r\n format?: string;\r\n}\r\n\r\nconst PRIORITY_COUNTRIES = [\r\n 'US', 'GB', 'CA', 'AU', 'DE', 'FR', 'IT', 'ES', 'JP', 'CN', 'IN', 'BR', 'MX', 'KR', 'NL',\r\n 'CH', 'SE', 'AE', 'SG', 'ZA', 'NG', 'SA', 'TR', 'ID', 'PH', 'TH', 'VN', 'MY', 'NZ', 'AR'\r\n];\r\n\r\nconst supportedCountries = new Set(getCountries());\r\n\r\nfunction normalizeDialCode(root: string, suffix: string) {\r\n const normalizedRoot = root.startsWith('+') ? root : `+${root}`;\r\n const digitsOnlySuffix = suffix.replace(/\\D/g, '');\r\n return `${normalizedRoot}${digitsOnlySuffix}`;\r\n}\r\n\r\nfunction buildDialCodes(country: (typeof worldCountries)[number]) {\r\n const root = country.idd?.root;\r\n if (!root) {\r\n return [];\r\n }\r\n\r\n const suffixes = country.idd?.suffixes?.length ? country.idd.suffixes : [''];\r\n const dialCodes = suffixes\r\n .map((suffix) => normalizeDialCode(root, suffix))\r\n .filter((dialCode) => /^\\+\\d+$/.test(dialCode));\r\n\r\n return Array.from(new Set(dialCodes));\r\n}\r\n\r\nfunction getCountryFormat(code: CountryCode) {\r\n const example = getExampleNumber(code, examples);\r\n return example ? example.formatNational().replace(/\\d/g, '#') : undefined;\r\n}\r\n\r\nfunction getCountryPriority(code: string) {\r\n const index = PRIORITY_COUNTRIES.indexOf(code);\r\n return index === -1 ? Number.MAX_SAFE_INTEGER : index;\r\n}\r\n\r\nconst generatedCountries = worldCountries\r\n .filter((country) => supportedCountries.has(country.cca2 as CountryCode))\r\n .map<Country | null>((country) => {\r\n const code = country.cca2 as CountryCode;\r\n const dialCodes = buildDialCodes(country);\r\n const dialCode = `+${getCountryCallingCode(code)}`;\r\n\r\n if (!country.flag || dialCodes.length === 0) {\r\n return null;\r\n }\r\n\r\n return {\r\n code,\r\n name: country.name.common,\r\n dialCode,\r\n dialCodes,\r\n flag: country.flag,\r\n format: getCountryFormat(code),\r\n } satisfies Country;\r\n })\r\n .filter((country): country is Country => country !== null)\r\n .sort((left, right) => {\r\n const priorityDelta = getCountryPriority(left.code) - getCountryPriority(right.code);\r\n return priorityDelta !== 0 ? priorityDelta : left.name.localeCompare(right.name);\r\n });\r\n\r\nexport const countries: Country[] = generatedCountries;\r\n\r\nexport const countryMap = new Map(countries.map((country) => [country.code, country]));\r\n\r\nconst countriesByDialCode = countries.reduce((map, country) => {\r\n for (const dialCode of country.dialCodes) {\r\n const matches = map.get(dialCode) ?? [];\r\n matches.push(country);\r\n map.set(dialCode, matches);\r\n }\r\n\r\n return map;\r\n}, new Map<string, Country[]>());\r\n\r\nconst dialCodeMatchers = countries\r\n .flatMap((country) => country.dialCodes.map((dialCode) => ({ dialCode, country })))\r\n .sort((left, right) => right.dialCode.length - left.dialCode.length);\r\n\r\nfunction normalizeLookupDialCode(dialCode: string) {\r\n const digits = dialCode.replace(/\\D/g, '');\r\n return digits ? `+${digits}` : '';\r\n}\r\n\r\nexport function getCountryByCode(code: string): Country | undefined {\r\n return countryMap.get(code.toUpperCase());\r\n}\r\n\r\nexport function getCountriesByDialCode(dialCode: string): Country[] {\r\n return countriesByDialCode.get(normalizeLookupDialCode(dialCode)) ?? [];\r\n}\r\n\r\nexport function getCountryByDialCode(dialCode: string): Country | undefined {\r\n return getCountriesByDialCode(dialCode)[0];\r\n}\r\n\r\nexport function detectCountryFromPhone(phone: string): Country | undefined {\r\n const trimmed = phone.trim();\r\n\r\n if (!trimmed) {\r\n return undefined;\r\n }\r\n\r\n const normalized = trimmed.startsWith('+')\r\n ? `+${trimmed.replace(/\\D/g, '')}`\r\n : trimmed.startsWith('00')\r\n ? `+${trimmed.slice(2).replace(/\\D/g, '')}`\r\n : '';\r\n\r\n if (!normalized) {\r\n return undefined;\r\n }\r\n\r\n const parsedPhone = parsePhoneNumberFromString(normalized);\r\n if (parsedPhone?.country) {\r\n return getCountryByCode(parsedPhone.country);\r\n }\r\n\r\n return dialCodeMatchers.find((entry) => normalized.startsWith(entry.dialCode))?.country;\r\n}\r\n","import type { Country } from './countries';\r\nimport { AsYouType, isPossiblePhoneNumber, isValidPhoneNumber, validatePhoneNumberLength as validateLength, type CountryCode } from 'libphonenumber-js';\r\n\r\nfunction normalizePhoneInput(phone: string): string {\r\n const trimmed = phone.trim();\r\n const digits = cleanPhone(trimmed);\r\n\r\n if (!digits) {\r\n return '';\r\n }\r\n\r\n return trimmed.startsWith('+') ? `+${digits}` : digits;\r\n}\r\n\r\nfunction getCountryCode(country: Country | undefined): CountryCode | undefined {\r\n return country?.code as CountryCode | undefined;\r\n}\r\n\r\n/**\r\n * Remove all non-digit characters from phone number\r\n */\r\nexport function cleanPhone(phone: string): string {\r\n return phone.replace(/\\D/g, '');\r\n}\r\n\r\n/**\r\n * Format phone number according to country format\r\n */\r\nexport function formatPhone(phone: string, country: Country | undefined): string {\r\n if (!phone) return phone;\r\n\r\n const formatter = new AsYouType(getCountryCode(country));\r\n return formatter.input(normalizePhoneInput(phone));\r\n}\r\n\r\n/**\r\n * Get raw phone number without formatting\r\n */\r\nexport function unformatPhone(formattedPhone: string): string {\r\n return normalizePhoneInput(formattedPhone);\r\n}\r\n\r\n/**\r\n * Validate phone number length based on country\r\n */\r\nexport function validatePhoneLength(phone: string, country: Country | undefined): boolean {\r\n if (!phone || !country) return false;\r\n\r\n if (phone.trim().startsWith('+')) {\r\n return validateLength(normalizePhoneInput(phone)) === undefined;\r\n }\r\n\r\n return validateLength(cleanPhone(phone), getCountryCode(country)) === undefined;\r\n}\r\n\r\n/**\r\n * Validate phone number format\r\n */\r\nexport function validatePhone(\r\n phone: string,\r\n country: Country | undefined,\r\n customValidator?: (phone: string, country: Country | undefined) => boolean\r\n): boolean {\r\n if (!phone) return false;\r\n \r\n if (customValidator) {\r\n return customValidator(phone, country);\r\n }\r\n\r\n const normalized = normalizePhoneInput(phone);\r\n const countryCode = getCountryCode(country);\r\n\r\n if (!countryCode) {\r\n return isPossiblePhoneNumber(normalized.startsWith('+') ? normalized : `+${cleanPhone(normalized)}`);\r\n }\r\n\r\n if (normalized.startsWith('+')) {\r\n return isValidPhoneNumber(normalized);\r\n }\r\n\r\n return isValidPhoneNumber(cleanPhone(normalized), countryCode);\r\n}\r\n\r\n/**\r\n * Add dial code to phone number\r\n */\r\nexport function addDialCode(phone: string, country: Country | undefined): string {\r\n if (!country) return phone;\r\n\r\n const normalized = normalizePhoneInput(phone);\r\n if (!normalized) return '';\r\n if (normalized.startsWith('+')) return normalized;\r\n\r\n const digits = cleanPhone(normalized);\r\n const matchingDialCode = country.dialCodes.find((dialCode) => digits.startsWith(dialCode.replace('+', '')));\r\n return matchingDialCode ? `+${digits}` : `${country.dialCode}${digits}`;\r\n}\r\n\r\n/**\r\n * Remove dial code from phone number\r\n */\r\nexport function removeDialCode(phone: string, country: Country | undefined): string {\r\n if (!country) return phone;\r\n\r\n const normalized = normalizePhoneInput(phone);\r\n const digits = cleanPhone(normalized);\r\n\r\n for (const dialCode of country.dialCodes) {\r\n const dialDigits = dialCode.replace('+', '');\r\n if (digits.startsWith(dialDigits)) {\r\n return digits.slice(dialDigits.length);\r\n }\r\n }\r\n\r\n return digits;\r\n}\r\n\r\n/**\r\n * Filter countries by search query\r\n */\r\nexport function filterCountries(\r\n countries: Country[],\r\n query: string,\r\n preferredCountries?: string[]\r\n): Country[] {\r\n const lowerQuery = query.toLowerCase().trim();\r\n \r\n if (!lowerQuery) {\r\n // Sort by preferred countries first\r\n if (preferredCountries?.length) {\r\n return [...countries].sort((a, b) => {\r\n const aPreferred = preferredCountries.indexOf(a.code);\r\n const bPreferred = preferredCountries.indexOf(b.code);\r\n if (aPreferred !== -1 && bPreferred !== -1) return aPreferred - bPreferred;\r\n if (aPreferred !== -1) return -1;\r\n if (bPreferred !== -1) return 1;\r\n return a.name.localeCompare(b.name);\r\n });\r\n }\r\n return countries;\r\n }\r\n \r\n return countries.filter(\r\n country =>\r\n country.name.toLowerCase().includes(lowerQuery) ||\r\n country.code.toLowerCase().includes(lowerQuery) ||\r\n country.dialCodes.some((dialCode) => dialCode.includes(lowerQuery))\r\n );\r\n}\r\n\r\n/**\r\n * Get placeholder based on country format\r\n */\r\nexport function getPlaceholder(country: Country | undefined): string {\r\n if (!country?.format) return country?.dialCode ? `${country.dialCode} 000 000 0000` : 'Phone number';\r\n return country.format.replace(/#/g, '0');\r\n}\r\n","import { useCallback, useMemo, useState, useEffect } from 'react';\r\nimport type { PhoneInputOptions, UsePhoneInputReturn } from './types';\r\nimport type { Country } from './countries';\r\nimport { countries, getCountryByCode, detectCountryFromPhone } from './countries';\r\nimport {\r\n formatPhone,\r\n unformatPhone,\r\n validatePhone,\r\n addDialCode,\r\n removeDialCode,\r\n filterCountries,\r\n getPlaceholder,\r\n} from './utils';\r\n\r\nexport function usePhoneInput(\r\n options: PhoneInputOptions & {\r\n value?: string;\r\n defaultValue?: string;\r\n onChange?: (phone: string, country: Country | undefined) => void;\r\n onBlur?: () => void;\r\n onFocus?: () => void;\r\n } = {}\r\n): UsePhoneInputReturn {\r\n const {\r\n value: controlledValue,\r\n defaultValue = '',\r\n onChange,\r\n onBlur,\r\n onFocus,\r\n defaultCountry = 'US',\r\n preferredCountries,\r\n excludeCountries,\r\n onlyCountries,\r\n autoDetect = true,\r\n formatOnType = true,\r\n includeDialCode = false,\r\n validator,\r\n } = options;\r\n\r\n const isControlled = controlledValue !== undefined;\r\n\r\n // Filter available countries\r\n const availableCountries = useMemo(() => {\r\n let filtered = countries;\r\n \r\n if (onlyCountries?.length) {\r\n filtered = filtered.filter(c => onlyCountries.includes(c.code));\r\n }\r\n \r\n if (excludeCountries?.length) {\r\n filtered = filtered.filter(c => !excludeCountries.includes(c.code));\r\n }\r\n \r\n return filtered;\r\n }, [onlyCountries, excludeCountries]);\r\n\r\n // Initialize state\r\n const initialCountry = getCountryByCode(defaultCountry) || availableCountries[0];\r\n const [internalPhone, setInternalPhone] = useState(defaultValue);\r\n const [country, setCountry] = useState<Country | undefined>(initialCountry);\r\n const [isOpen, setIsOpen] = useState(false);\r\n const [searchQuery, setSearchQuery] = useState('');\r\n\r\n // Current phone value\r\n const phone = isControlled ? controlledValue : internalPhone;\r\n\r\n useEffect(() => {\r\n const nextCountry = getCountryByCode(defaultCountry) || availableCountries[0];\r\n if (nextCountry && nextCountry.code !== country?.code) {\r\n setCountry(nextCountry);\r\n }\r\n }, [defaultCountry, availableCountries, country?.code]);\r\n\r\n // Auto-detect country from phone\r\n useEffect(() => {\r\n if (autoDetect && phone) {\r\n const detected = detectCountryFromPhone(phone);\r\n if (detected && availableCountries.some((candidate) => candidate.code === detected.code) && detected.code !== country?.code) {\r\n setCountry(detected);\r\n }\r\n }\r\n }, [availableCountries, autoDetect, phone, country?.code]);\r\n\r\n // Format phone number\r\n const formattedPhone = useMemo(() => {\r\n if (formatOnType) {\r\n return formatPhone(includeDialCode && phone.startsWith('+') ? removeDialCode(phone, country) : phone, country);\r\n }\r\n return includeDialCode && phone.startsWith('+') ? removeDialCode(phone, country) : phone;\r\n }, [formatOnType, includeDialCode, phone, country]);\r\n\r\n // Full phone with dial code\r\n const fullPhone = useMemo(() => {\r\n if (includeDialCode && country) {\r\n return addDialCode(phone, country);\r\n }\r\n return phone;\r\n }, [phone, country, includeDialCode]);\r\n\r\n // Validation\r\n const isValid = useMemo(\r\n () => validatePhone(phone, country, validator),\r\n [phone, country, validator]\r\n );\r\n\r\n // Filtered countries for dropdown\r\n const filteredCountries = useMemo(\r\n () => filterCountries(availableCountries, searchQuery, preferredCountries),\r\n [availableCountries, searchQuery, preferredCountries]\r\n );\r\n\r\n // Set phone handler\r\n const setPhone = useCallback(\r\n (newPhone: string) => {\r\n const unformatted = unformatPhone(newPhone);\r\n if (!isControlled) {\r\n setInternalPhone(unformatted);\r\n }\r\n onChange?.(includeDialCode ? addDialCode(unformatted, country) : unformatted, country);\r\n },\r\n [isControlled, onChange, country, includeDialCode]\r\n );\r\n\r\n // Set country handler\r\n const setCountryByCode = useCallback(\r\n (code: string) => {\r\n const newCountry = getCountryByCode(code);\r\n if (newCountry) {\r\n setCountry(newCountry);\r\n onChange?.(includeDialCode ? addDialCode(phone, newCountry) : phone, newCountry);\r\n }\r\n },\r\n [phone, onChange, includeDialCode]\r\n );\r\n\r\n // Select country from dropdown\r\n const selectCountry = useCallback(\r\n (selectedCountry: Country) => {\r\n setCountry(selectedCountry);\r\n setIsOpen(false);\r\n setSearchQuery('');\r\n onChange?.(\r\n includeDialCode ? addDialCode(phone, selectedCountry) : phone,\r\n selectedCountry\r\n );\r\n },\r\n [phone, onChange, includeDialCode]\r\n );\r\n\r\n // Toggle dropdown\r\n const toggleDropdown = useCallback(() => {\r\n setIsOpen(prev => !prev);\r\n if (isOpen) {\r\n setSearchQuery('');\r\n }\r\n }, [isOpen]);\r\n\r\n // Open dropdown\r\n const openDropdown = useCallback(() => {\r\n setIsOpen(true);\r\n }, []);\r\n\r\n // Close dropdown\r\n const closeDropdown = useCallback(() => {\r\n setIsOpen(false);\r\n setSearchQuery('');\r\n }, []);\r\n\r\n // Clear input\r\n const clear = useCallback(() => {\r\n if (!isControlled) {\r\n setInternalPhone('');\r\n }\r\n onChange?.('', country);\r\n }, [isControlled, onChange, country]);\r\n\r\n // Handle input change\r\n const handleInputChange = useCallback(\r\n (event: React.ChangeEvent<HTMLInputElement>) => {\r\n const rawValue = event.target.value;\r\n const unformatted = rawValue.trim().startsWith('+') ? `+${rawValue.replace(/\\D/g, '')}` : unformatPhone(rawValue);\r\n setPhone(unformatted);\r\n },\r\n [setPhone]\r\n );\r\n\r\n // Handle focus\r\n const handleFocus = useCallback(() => {\r\n onFocus?.();\r\n }, [onFocus]);\r\n\r\n // Handle blur\r\n const handleBlur = useCallback(() => {\r\n onBlur?.();\r\n }, [onBlur]);\r\n\r\n return {\r\n // State\r\n phone,\r\n fullPhone,\r\n country,\r\n isValid,\r\n isOpen,\r\n searchQuery,\r\n // Actions\r\n setPhone,\r\n setCountry: setCountryByCode,\r\n toggleDropdown,\r\n openDropdown,\r\n closeDropdown,\r\n setSearchQuery,\r\n clear,\r\n // Props\r\n inputProps: {\r\n value: formattedPhone,\r\n onChange: handleInputChange,\r\n onFocus: handleFocus,\r\n onBlur: handleBlur,\r\n type: 'tel',\r\n inputMode: 'tel',\r\n autoComplete: 'tel',\r\n placeholder: getPlaceholder(country),\r\n 'aria-invalid': phone ? !isValid : undefined,\r\n },\r\n countryButtonProps: {\r\n onClick: toggleDropdown,\r\n 'aria-expanded': isOpen,\r\n 'aria-haspopup': 'listbox',\r\n },\r\n filteredCountries,\r\n selectCountry,\r\n };\r\n}\r\n","import { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useRef, useState } from 'react';\nimport { usePhoneInput } from './usePhoneInput';\nimport type { PhoneInputProps } from './types';\nimport type { Country } from './countries';\n\n// SVG Icon Components (Lucide-style)\nconst ChevronUpIcon = ({ size = 12 }: { size?: number }) => (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <polyline points=\"18 15 12 9 6 15\" />\n </svg>\n);\n\nconst ChevronDownIcon = ({ size = 12 }: { size?: number }) => (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <polyline points=\"6 9 12 15 18 9\" />\n </svg>\n);\n\nexport interface PhoneInputRef {\n /** Focus the input */\n focus: () => void;\n /** Blur the input */\n blur: () => void;\n /** Clear the input */\n clear: () => void;\n /** Set country */\n setCountry: (countryCode: string) => void;\n /** Get current country */\n getCountry: () => Country | undefined;\n /** Open country selector */\n open: () => void;\n /** Close country selector */\n close: () => void;\n}\n\n/**\n * PhoneInput component - headless phone input with country selection\n * \n * @example\n * ```tsx\n * <PhoneInput\n * value={value}\n * onChange={setValue}\n * defaultCountry=\"US\"\n * />\n * ```\n * \n * @example\n * ```tsx\n * // With custom styling\n * <PhoneInput\n * value={value}\n * onChange={setValue}\n * defaultCountry=\"GB\"\n * containerClassName=\"phone-input-container\"\n * inputClassName=\"phone-input\"\n * selectorClassName=\"country-selector\"\n * />\n * ```\n */\nexport const PhoneInput = forwardRef<PhoneInputRef, PhoneInputProps>(\n function PhoneInput(props, ref) {\n const {\n value,\n defaultValue,\n onChange,\n onBlur,\n onFocus,\n inputClassName,\n selectorClassName,\n containerClassName,\n placeholder,\n disabled,\n readOnly,\n name,\n id,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n ...options\n } = props;\n\n const inputRef = useRef<HTMLInputElement>(null);\n const optionRefs = useRef<Array<HTMLLIElement | null>>([]);\n const [highlightedIndex, setHighlightedIndex] = useState(0);\n const listboxId = useId();\n\n const {\n inputProps,\n countryButtonProps,\n country,\n filteredCountries,\n isOpen,\n isValid,\n searchQuery,\n setSearchQuery,\n setCountry,\n selectCountry,\n clear,\n openDropdown,\n closeDropdown,\n } = usePhoneInput({\n value,\n defaultValue,\n onChange,\n onBlur,\n onFocus,\n ...options,\n });\n\n // Focus the input\n const focus = useCallback(() => {\n inputRef.current?.focus();\n }, []);\n\n // Blur the input\n const blur = useCallback(() => {\n inputRef.current?.blur();\n }, []);\n\n // Handle country option click\n const handleCountryClick = useCallback((c: Country) => {\n selectCountry(c);\n setHighlightedIndex(0);\n }, [selectCountry]);\n\n // Handle country option keyboard navigation\n const handleCountryKeyDown = useCallback((e: React.KeyboardEvent, c: Country, index: number) => {\n switch (e.key) {\n case 'Enter':\n case ' ':\n e.preventDefault();\n selectCountry(c);\n setHighlightedIndex(0);\n break;\n case 'ArrowDown':\n e.preventDefault();\n if (index < filteredCountries.length - 1) {\n const nextIndex = index + 1;\n setHighlightedIndex(nextIndex);\n optionRefs.current[nextIndex]?.focus();\n }\n break;\n case 'ArrowUp':\n e.preventDefault();\n if (index > 0) {\n const nextIndex = index - 1;\n setHighlightedIndex(nextIndex);\n optionRefs.current[nextIndex]?.focus();\n }\n break;\n case 'Escape':\n e.preventDefault();\n closeDropdown();\n break;\n }\n }, [selectCountry, filteredCountries.length, closeDropdown]);\n\n useEffect(() => {\n if (filteredCountries.length === 0) {\n if (highlightedIndex !== 0) {\n setHighlightedIndex(0);\n }\n return;\n }\n\n if (highlightedIndex >= filteredCountries.length) {\n setHighlightedIndex(filteredCountries.length - 1);\n }\n }, [filteredCountries.length, highlightedIndex]);\n\n // Expose imperative methods\n useImperativeHandle(ref, () => ({\n focus,\n blur,\n clear,\n setCountry,\n getCountry: () => country,\n open: openDropdown,\n close: closeDropdown,\n }));\n\n // Render default UI\n return (\n <div className={containerClassName} data-valid={isValid}>\n {/* Country Selector Button */}\n <button\n {...countryButtonProps}\n type=\"button\"\n className={selectorClassName}\n disabled={disabled}\n tabIndex={disabled ? -1 : 0}\n aria-controls={listboxId}\n >\n {country ? (\n <>\n <span className=\"phone-input-flag\">{country.flag}</span>\n <span className=\"phone-input-dial-code\">{country.dialCode}</span>\n </>\n ) : (\n <span className=\"phone-input-placeholder\">Select</span>\n )}\n <span className=\"phone-input-arrow\" aria-hidden=\"true\">\n {isOpen ? <ChevronUpIcon size={12} /> : <ChevronDownIcon size={12} />}\n </span>\n </button>\n\n {/* Phone Input */}\n <input\n {...inputProps}\n ref={inputRef}\n id={id}\n name={name}\n className={inputClassName}\n placeholder={placeholder || inputProps.placeholder}\n disabled={disabled}\n readOnly={readOnly}\n aria-label={ariaLabel}\n aria-labelledby={ariaLabelledBy}\n />\n\n {/* Country Dropdown */}\n {isOpen && (\n <div className=\"phone-input-dropdown\">\n {/* Search Input */}\n <div className=\"phone-input-search\">\n <input\n type=\"text\"\n value={searchQuery}\n onChange={(e) => setSearchQuery(e.target.value)}\n placeholder=\"Search countries...\"\n autoFocus\n aria-controls={listboxId}\n aria-label=\"Search countries\"\n />\n </div>\n\n {/* Country List */}\n <ul className=\"phone-input-country-list\" id={listboxId} role=\"listbox\" aria-label=\"Country options\">\n {filteredCountries.map((c, index) => (\n <li\n key={c.code}\n ref={(element) => {\n optionRefs.current[index] = element;\n }}\n role=\"option\"\n aria-selected={c.code === country?.code}\n className={`phone-input-country-option ${\n c.code === country?.code ? 'selected' : ''\n } ${index === highlightedIndex ? 'highlighted' : ''}`}\n onClick={() => handleCountryClick(c)}\n onKeyDown={(e) => handleCountryKeyDown(e, c, index)}\n onMouseEnter={() => setHighlightedIndex(index)}\n tabIndex={index === highlightedIndex ? 0 : -1}\n >\n <span className=\"phone-input-flag\">{c.flag}</span>\n <span className=\"phone-input-country-name\">{c.name}</span>\n <span className=\"phone-input-dial-code\">{c.dialCode}</span>\n </li>\n ))}\n {filteredCountries.length === 0 && (\n <li className=\"phone-input-no-results\">No countries found</li>\n )}\n </ul>\n </div>\n )}\n </div>\n );\n }\n);\n\nexport default PhoneInput;\n"]}
1
+ {"version":3,"sources":["../src/countries.ts","../src/labels.ts","../src/utils.ts","../src/usePhoneInput.ts","../src/PhoneInput.tsx"],"names":["PRIORITY_COUNTRIES","supportedCountries","getCountries","worldCountryMap","worldCountries","country","FALLBACK_COUNTRIES","normalizeDialCode","root","suffix","normalizedRoot","digitsOnlySuffix","codeToFlag","code","char","buildDialCodes","fallbackDialCode","dialCodes","dialCode","getCountryFormat","example","getExampleNumber","examples","getCountryPriority","index","generatedCountries","fallback","getCountryCallingCode","left","right","priorityDelta","countries","countryMap","countriesByDialCode","map","matches","dialCodeMatchers","displayNameCache","normalizeLocales","locale","getDisplayNames","locales","cacheKey","cached","displayNames","normalizeLookupDialCode","digits","getCountryByCode","getLocalizedCountryName","localizeCountry","displayName","localizeCountries","list","getCountriesByDialCode","getCountryByDialCode","detectCountryFromPhone","phone","trimmed","normalized","parsedPhone","parsePhoneNumberFromString","entry","DEFAULT_PHONE_INPUT_LABELS","LABELS_BY_LANGUAGE","getPrimaryLanguage","firstLocale","resolvePhoneInputLabels","overrides","language","localizedDefaults","normalizePhoneInput","cleanPhone","getCountryCode","getMaxNationalDigits","formatPhone","AsYouType","unformatPhone","formattedPhone","validatePhoneLength","validateLength","validatePhone","customValidator","countryCode","isValidPhoneNumber","isPossiblePhoneNumber","addDialCode","removeDialCode","primaryDialDigits","dialDigits","filterCountries","query","preferredCountries","lowerQuery","a","b","aPreferred","bPreferred","getCountryDisplayName","getPlaceholder","stripNonDigits","isInternationalFormat","extractDialCode","match","detectCountry","formatPhoneNumber","format","nationalNumber","formattedNational","parseToE164","getNationalNumber","detectedCountry","validatePhoneNumber","required","maxDigits","nationalDigits","isPhoneNumberComplete","formatAsYouType","normalizePhoneNumber","phoneNumbersEqual","getCountryDisplayLabel","includeDialCode","label","limitInputLength","isInternational","maxLength","limited","countDigitsBeforePosition","value","position","getCaretPositionFromDigitCount","digitCount","seenDigits","usePhoneInput","options","controlledValue","defaultValue","onChange","onCountryChange","onBlur","onFocus","defaultCountry","excludeCountries","excludedCountries","onlyCountries","allowedCountries","autoDetect","autoDetectCountry","formatOnType","validator","labels","resolvedOnlyCountries","resolvedExcludeCountries","resolvedAutoDetect","isControlled","inputRef","useRef","pendingCaretDigitIndexRef","previousDefaultCountryRef","availableCountries","useMemo","filtered","c","localizedCountries","resolvedLabels","initialCountry","candidate","internalPhone","setInternalPhone","useState","setCountry","isOpen","setIsOpen","searchQuery","setSearchQuery","getOutputCountry","useCallback","nextCountry","useEffect","defaultCountryChanged","countryStillAvailable","detected","fullPhone","isValid","error","localizedCountry","filteredCountries","useLayoutEffect","nextDigitIndex","input","caretPosition","setPhone","newPhone","unformatted","setCountryByCode","newCountry","selectCountry","selectedCountry","rawCountry","toggleDropdown","prev","openDropdown","closeDropdown","clear","handleInputChange","event","rawValue","handleFocus","handleBlur","getCountryOptionProps","optionCountry","ChevronUpIcon","size","jsx","ChevronDownIcon","PhoneInput","forwardRef","props","ref","inputClassName","selectorClassName","containerClassName","searchable","placeholder","disabled","readOnly","name","id","ariaLabel","ariaLabelledBy","optionRefs","highlightedIndex","setHighlightedIndex","listboxId","useId","inputProps","countryButtonProps","hookInputRef","mergedInputRef","element","focus","blur","handleCountryClick","handleCountryKeyDown","e","nextIndex","useImperativeHandle","jsxs","Fragment"],"mappings":"+WAcA,IAAMA,GAAqB,CACzB,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,KAAM,IAAA,CAAM,IAAA,CAAM,KAAM,IAAA,CAAM,IAAA,CAAM,KAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CACpF,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,KAAM,IAAA,CAAM,IAAA,CAAM,KAAM,IAAA,CAAM,IAAA,CAAM,KAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IACtF,CAAA,CAEMC,GAAqB,IAAI,GAAA,CAAIC,+BAAc,CAAA,CAC3CC,GAAkB,IAAI,GAAA,CAAIC,mBAAAA,CAAe,GAAA,CAAKC,CAAAA,EAAY,CAACA,EAAQ,IAAA,CAAMA,CAAO,CAAC,CAAC,CAAA,CAClFC,GAAyF,CAC7F,EAAA,CAAI,CAAE,IAAA,CAAM,kBAAA,CAAoB,QAAA,CAAU,MAAO,CAAA,CACjD,EAAA,CAAI,CAAE,IAAA,CAAM,kBAAA,CAAoB,QAAA,CAAU,MAAO,CAAA,CACjD,EAAA,CAAI,CAAE,IAAA,CAAM,uBAAA,CAAyB,QAAA,CAAU,MAAO,CACxD,CAAA,CAEA,SAASC,EAAAA,CAAkBC,CAAAA,CAAcC,EAAgB,CACvD,IAAMC,CAAAA,CAAiBF,CAAAA,CAAK,UAAA,CAAW,GAAG,EAAIA,CAAAA,CAAO,CAAA,CAAA,EAAIA,CAAI,CAAA,CAAA,CACvDG,CAAAA,CAAmBF,EAAO,OAAA,CAAQ,KAAA,CAAO,EAAE,CAAA,CACjD,OAAO,CAAA,EAAGC,CAAc,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ACnC,SAAA,CAAYE,GAAMD,EAAAA,CAAqBC,CAAAA,CAAG,CAAA,CAAG3N,CAAK,CAAA,CAClD,YAAA,CAAc,IAAM+M,CAAAA,CAAoB/M,CAAK,EAC7C,QAAA,CAAUA,CAAAA,GAAU8M,EAAmB,CAAA,CAAI,EAAA,CAE3C,QAAA,CAAA,CAAAlB,cAAAA,CAAC,MAAA,CAAA,CAAK,SAAA,CAAU,mBAAoB,QAAA,CAAA,CAAA,CAAE,IAAA,CAAK,EAC3CA,cAAAA,CAAC,MAAA,CAAA,CAAK,UAAU,0BAAA,CAA4B,QAAA,CAAAnH,EAAAA,CAAsB,CAAC,CAAA,CAAE,CAAA,CACrEmH,eAAC,MAAA,CAAA,CAAK,SAAA,CAAU,wBAAyB,QAAA,CAAA,CAAA,CAAE,QAAA,CAAS,IAhB/C,CAAA,CAAE,IAiBT,CACD,CAAA,CACA3B,CAAAA,CAAkB,MAAA,GAAW,GAC5B2B,cAAAA,CAAC,IAAA,CAAA,CAAG,SAAA,CAAU,wBAAA,CAA0B,QAAA,CAAA/D,CAAAA,CAAO,iBAAiB,CAAA,CAAA,CAEpE,CAAA,CAAA,CACF,CAAA,CAAA,CAEJ,CAEJ,CACF","file":"index.cjs","sourcesContent":["import { getCountries, getCountryCallingCode, getExampleNumber, parsePhoneNumberFromString, type CountryCode } from 'libphonenumber-js';\r\nimport examples from 'libphonenumber-js/mobile/examples';\r\nimport worldCountries from 'world-countries';\r\n\r\nexport interface Country {\r\n code: string;\r\n name: string;\r\n dialCode: string;\r\n dialCodes: string[];\r\n flag: string;\r\n format?: string;\r\n displayName?: string;\r\n}\r\n\r\nconst PRIORITY_COUNTRIES = [\r\n 'US', 'GB', 'CA', 'AU', 'DE', 'FR', 'IT', 'ES', 'JP', 'CN', 'IN', 'BR', 'MX', 'KR', 'NL',\r\n 'CH', 'SE', 'AE', 'SG', 'ZA', 'NG', 'SA', 'TR', 'ID', 'PH', 'TH', 'VN', 'MY', 'NZ', 'AR'\r\n];\r\n\r\nconst supportedCountries = new Set(getCountries());\nconst worldCountryMap = new Map(worldCountries.map((country) => [country.cca2, country]));\nconst FALLBACK_COUNTRIES: Record<string, { name: string; dialCode?: string; flag?: string }> = {\n AC: { name: 'Ascension Island', dialCode: '+247' },\n TA: { name: 'Tristan da Cunha', dialCode: '+290' },\n BQ: { name: 'Caribbean Netherlands', dialCode: '+599' },\n};\n\r\nfunction normalizeDialCode(root: string, suffix: string) {\r\n const normalizedRoot = root.startsWith('+') ? root : `+${root}`;\r\n const digitsOnlySuffix = suffix.replace(/\\D/g, '');\r\n return `${normalizedRoot}${digitsOnlySuffix}`;\r\n}\r\n\r\nfunction codeToFlag(code: string): string {\n return code\n .toUpperCase()\n .replace(/./g, (char) => String.fromCodePoint(127397 + char.charCodeAt(0)));\n}\n\nfunction buildDialCodes(country: (typeof worldCountries)[number] | undefined, fallbackDialCode: string) {\n const root = country?.idd?.root;\n if (!root) {\n return [fallbackDialCode];\n }\n\n const suffixes = country.idd?.suffixes?.length ? country.idd.suffixes : [''];\n const dialCodes = suffixes\n .map((suffix) => normalizeDialCode(root, suffix))\n .filter((dialCode) => /^\\+\\d+$/.test(dialCode));\n\n return Array.from(new Set([fallbackDialCode, ...(dialCodes.length ? dialCodes : [])]));\n}\n\r\nfunction getCountryFormat(code: CountryCode) {\r\n const example = getExampleNumber(code, examples);\r\n return example ? example.formatNational().replace(/\\d/g, '#') : undefined;\r\n}\r\n\r\nfunction getCountryPriority(code: string) {\r\n const index = PRIORITY_COUNTRIES.indexOf(code);\r\n return index === -1 ? Number.MAX_SAFE_INTEGER : index;\r\n}\r\n\r\nconst generatedCountries = Array.from(supportedCountries)\n .map<Country>((code) => {\n const country = worldCountryMap.get(code);\n const fallback = FALLBACK_COUNTRIES[code];\n const dialCode = fallback?.dialCode ?? `+${getCountryCallingCode(code as CountryCode)}`;\n const dialCodes = buildDialCodes(country, dialCode);\n\n return {\n code,\n name: country?.name.common ?? fallback?.name ?? code,\n dialCode,\n dialCodes,\n flag: country?.flag || fallback?.flag || codeToFlag(code),\n format: getCountryFormat(code as CountryCode),\n } satisfies Country;\n })\n .sort((left, right) => {\n const priorityDelta = getCountryPriority(left.code) - getCountryPriority(right.code);\n return priorityDelta !== 0 ? priorityDelta : left.name.localeCompare(right.name);\n });\n\r\nexport const countries: Country[] = generatedCountries;\r\n\r\nexport const countryMap = new Map(countries.map((country) => [country.code, country]));\r\n\r\nconst countriesByDialCode = countries.reduce((map, country) => {\r\n for (const dialCode of country.dialCodes) {\r\n const matches = map.get(dialCode) ?? [];\r\n matches.push(country);\r\n map.set(dialCode, matches);\r\n }\r\n\r\n return map;\r\n}, new Map<string, Country[]>());\r\n\r\nconst dialCodeMatchers = countries\r\n .flatMap((country) => country.dialCodes.map((dialCode) => ({ dialCode, country })))\r\n .sort((left, right) => right.dialCode.length - left.dialCode.length);\r\n\r\nconst displayNameCache = new Map<string, Intl.DisplayNames>();\r\n\r\nfunction normalizeLocales(locale?: string | readonly string[]) {\r\n return Array.isArray(locale) ? [...locale] : locale ? [locale] : [];\r\n}\r\n\r\nfunction getDisplayNames(locale?: string | readonly string[]) {\r\n const locales = normalizeLocales(locale);\r\n if (locales.length === 0 || typeof Intl === 'undefined' || typeof Intl.DisplayNames === 'undefined') {\r\n return undefined;\r\n }\r\n\r\n const cacheKey = locales.join('|');\r\n const cached = displayNameCache.get(cacheKey);\r\n if (cached) {\r\n return cached;\r\n }\r\n\r\n try {\r\n const displayNames = new Intl.DisplayNames(locales, { type: 'region' });\r\n displayNameCache.set(cacheKey, displayNames);\r\n return displayNames;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\nfunction normalizeLookupDialCode(dialCode: string) {\r\n const digits = dialCode.replace(/\\D/g, '');\r\n return digits ? `+${digits}` : '';\r\n}\r\n\r\nexport function getCountryByCode(code: string): Country | undefined {\r\n return countryMap.get(code.toUpperCase());\r\n}\r\n\r\nexport function getLocalizedCountryName(\r\n country: Country | undefined,\r\n locale?: string | readonly string[]\r\n): string | undefined {\r\n if (!country) {\r\n return undefined;\r\n }\r\n\r\n const displayNames = getDisplayNames(locale);\r\n return displayNames?.of(country.code) ?? country.displayName ?? country.name;\r\n}\r\n\r\nexport function localizeCountry(\r\n country: Country | undefined,\r\n locale?: string | readonly string[]\r\n): Country | undefined {\r\n if (!country) {\r\n return undefined;\r\n }\r\n\r\n const displayName = getLocalizedCountryName(country, locale);\r\n return displayName ? { ...country, displayName } : country;\r\n}\r\n\r\nexport function localizeCountries(\r\n list: Country[],\r\n locale?: string | readonly string[]\r\n): Country[] {\r\n if (!locale) {\r\n return list;\r\n }\r\n\r\n return list.map((country) => localizeCountry(country, locale) ?? country);\r\n}\r\n\r\nexport function getCountriesByDialCode(dialCode: string): Country[] {\r\n return countriesByDialCode.get(normalizeLookupDialCode(dialCode)) ?? [];\r\n}\r\n\r\nexport function getCountryByDialCode(dialCode: string): Country | undefined {\r\n return getCountriesByDialCode(dialCode)[0];\r\n}\r\n\r\nexport function detectCountryFromPhone(phone: string): Country | undefined {\r\n const trimmed = phone.trim();\r\n\r\n if (!trimmed) {\r\n return undefined;\r\n }\r\n\r\n const normalized = trimmed.startsWith('+')\r\n ? `+${trimmed.replace(/\\D/g, '')}`\r\n : trimmed.startsWith('00')\r\n ? `+${trimmed.slice(2).replace(/\\D/g, '')}`\r\n : '';\r\n\r\n if (!normalized) {\r\n return undefined;\r\n }\r\n\r\n const parsedPhone = parsePhoneNumberFromString(normalized);\r\n if (parsedPhone?.country) {\r\n return getCountryByCode(parsedPhone.country);\r\n }\r\n\r\n return dialCodeMatchers.find((entry) => normalized.startsWith(entry.dialCode))?.country;\r\n}\r\n","import type { PhoneInputLabels } from './types';\r\n\r\nexport const DEFAULT_PHONE_INPUT_LABELS: PhoneInputLabels = {\r\n selectCountry: 'Select country',\r\n countrySearchPlaceholder: 'Search countries...',\r\n noCountriesFound: 'No countries found',\r\n searchCountriesAriaLabel: 'Search countries',\r\n countryOptionsAriaLabel: 'Country options',\r\n countryButtonAriaLabel: 'Open country selector',\r\n};\r\n\r\nconst LABELS_BY_LANGUAGE: Record<string, Partial<PhoneInputLabels>> = {\r\n en: DEFAULT_PHONE_INPUT_LABELS,\r\n fr: {\r\n selectCountry: 'Choisir un pays',\r\n countrySearchPlaceholder: 'Rechercher un pays...',\r\n noCountriesFound: 'Aucun pays trouvé',\r\n searchCountriesAriaLabel: 'Rechercher des pays',\r\n countryOptionsAriaLabel: 'Options de pays',\r\n countryButtonAriaLabel: 'Ouvrir le sélecteur de pays',\r\n },\r\n de: {\r\n selectCountry: 'Land auswählen',\r\n countrySearchPlaceholder: 'Land suchen...',\r\n noCountriesFound: 'Keine Länder gefunden',\r\n searchCountriesAriaLabel: 'Länder suchen',\r\n countryOptionsAriaLabel: 'Länderoptionen',\r\n countryButtonAriaLabel: 'Länderauswahl öffnen',\r\n },\r\n es: {\r\n selectCountry: 'Seleccionar país',\r\n countrySearchPlaceholder: 'Buscar país...',\r\n noCountriesFound: 'No se encontraron países',\r\n searchCountriesAriaLabel: 'Buscar países',\r\n countryOptionsAriaLabel: 'Opciones de país',\r\n countryButtonAriaLabel: 'Abrir selector de país',\r\n },\r\n pt: {\r\n selectCountry: 'Selecionar país',\r\n countrySearchPlaceholder: 'Pesquisar país...',\r\n noCountriesFound: 'Nenhum país encontrado',\r\n searchCountriesAriaLabel: 'Pesquisar países',\r\n countryOptionsAriaLabel: 'Opções de país',\r\n countryButtonAriaLabel: 'Abrir seletor de país',\r\n },\r\n it: {\r\n selectCountry: 'Seleziona paese',\r\n countrySearchPlaceholder: 'Cerca paese...',\r\n noCountriesFound: 'Nessun paese trovato',\r\n searchCountriesAriaLabel: 'Cerca paesi',\r\n countryOptionsAriaLabel: 'Opzioni paese',\r\n countryButtonAriaLabel: 'Apri selettore paese',\r\n },\r\n ja: {\r\n selectCountry: '国を選択',\r\n countrySearchPlaceholder: '国を検索...',\r\n noCountriesFound: '国が見つかりません',\r\n searchCountriesAriaLabel: '国を検索',\r\n countryOptionsAriaLabel: '国の候補',\r\n countryButtonAriaLabel: '国のセレクターを開く',\r\n },\r\n ko: {\r\n selectCountry: '국가 선택',\r\n countrySearchPlaceholder: '국가 검색...',\r\n noCountriesFound: '국가를 찾을 수 없습니다',\r\n searchCountriesAriaLabel: '국가 검색',\r\n countryOptionsAriaLabel: '국가 옵션',\r\n countryButtonAriaLabel: '국가 선택기 열기',\r\n },\r\n zh: {\r\n selectCountry: '选择国家',\r\n countrySearchPlaceholder: '搜索国家...',\r\n noCountriesFound: '未找到国家',\r\n searchCountriesAriaLabel: '搜索国家',\r\n countryOptionsAriaLabel: '国家选项',\r\n countryButtonAriaLabel: '打开国家选择器',\r\n },\r\n ar: {\r\n selectCountry: 'اختر الدولة',\r\n countrySearchPlaceholder: 'ابحث عن دولة...',\r\n noCountriesFound: 'لم يتم العثور على دول',\r\n searchCountriesAriaLabel: 'ابحث عن الدول',\r\n countryOptionsAriaLabel: 'خيارات الدول',\r\n countryButtonAriaLabel: 'افتح محدد الدولة',\r\n },\r\n hi: {\r\n selectCountry: 'देश चुनें',\r\n countrySearchPlaceholder: 'देश खोजें...',\r\n noCountriesFound: 'कोई देश नहीं मिला',\r\n searchCountriesAriaLabel: 'देश खोजें',\r\n countryOptionsAriaLabel: 'देश विकल्प',\r\n countryButtonAriaLabel: 'देश चयन खोलें',\r\n },\r\n};\r\n\r\nfunction getPrimaryLanguage(locale?: string | readonly string[]): string | undefined {\r\n const locales = Array.isArray(locale) ? locale : locale ? [locale] : [];\r\n const firstLocale = locales.find(Boolean);\r\n return firstLocale ? firstLocale.toLowerCase().split('-')[0] : undefined;\r\n}\r\n\r\nexport function resolvePhoneInputLabels(\r\n locale?: string | readonly string[],\r\n overrides?: Partial<PhoneInputLabels>\r\n): PhoneInputLabels {\r\n const language = getPrimaryLanguage(locale);\r\n const localizedDefaults = language ? LABELS_BY_LANGUAGE[language] : undefined;\r\n\r\n return {\r\n ...DEFAULT_PHONE_INPUT_LABELS,\r\n ...localizedDefaults,\r\n ...overrides,\r\n };\r\n}","import type { Country } from './countries';\nimport { countries, detectCountryFromPhone } from './countries';\nimport { AsYouType, isPossiblePhoneNumber, isValidPhoneNumber, validatePhoneNumberLength as validateLength, type CountryCode } from 'libphonenumber-js';\n\ntype MaybeCountry = Country | null | undefined;\n\nfunction normalizePhoneInput(phone: string): string {\n const trimmed = phone.trim();\r\n const digits = cleanPhone(trimmed);\r\n\r\n if (trimmed.startsWith('+') && !digits) {\r\n return '+';\r\n }\r\n\r\n if (!digits) {\r\n return '';\r\n }\r\n\r\n return trimmed.startsWith('+') ? `+${digits}` : digits;\r\n}\r\n\r\nfunction getCountryCode(country: MaybeCountry): CountryCode | undefined {\n return country?.code as CountryCode | undefined;\n}\n\nfunction getMaxNationalDigits(country: MaybeCountry): number | undefined {\n return country?.format?.replace(/[^#]/g, '').length;\n}\n\r\n/**\r\n * Remove all non-digit characters from phone number\r\n */\r\nexport function cleanPhone(phone: string): string {\r\n return phone.replace(/\\D/g, '');\r\n}\r\n\r\n/**\r\n * Format phone number according to country format\r\n */\r\nexport function formatPhone(phone: string, country: MaybeCountry): string {\n if (!phone) return phone;\r\n\r\n const formatter = new AsYouType(getCountryCode(country));\r\n return formatter.input(normalizePhoneInput(phone));\r\n}\r\n\r\n/**\r\n * Get raw phone number without formatting\r\n */\r\nexport function unformatPhone(formattedPhone: string): string {\r\n return normalizePhoneInput(formattedPhone);\r\n}\r\n\r\n/**\r\n * Validate phone number length based on country\r\n */\r\nexport function validatePhoneLength(phone: string, country: MaybeCountry): boolean {\n if (!phone || !country) return false;\r\n\r\n if (phone.trim().startsWith('+')) {\r\n return validateLength(normalizePhoneInput(phone)) === undefined;\r\n }\r\n\r\n return validateLength(cleanPhone(phone), getCountryCode(country)) === undefined;\r\n}\r\n\r\n/**\r\n * Validate phone number format\r\n */\r\nexport function validatePhone(\n phone: string,\n country: MaybeCountry,\n customValidator?: (phone: string, country: Country | undefined) => boolean\n): boolean {\n if (!phone) return false;\r\n \r\n if (customValidator) {\r\n return customValidator(phone, country ?? undefined);\n }\r\n\r\n const normalized = normalizePhoneInput(phone);\r\n const countryCode = getCountryCode(country);\r\n\r\n if (!countryCode) {\r\n return isPossiblePhoneNumber(normalized.startsWith('+') ? normalized : `+${cleanPhone(normalized)}`);\r\n }\r\n\r\n if (normalized.startsWith('+')) {\r\n return isValidPhoneNumber(normalized);\r\n }\r\n\r\n return isValidPhoneNumber(cleanPhone(normalized), countryCode);\r\n}\r\n\r\n/**\r\n * Add dial code to phone number\r\n */\r\nexport function addDialCode(phone: string, country: MaybeCountry): string {\n if (!country) return phone;\r\n\r\n const normalized = normalizePhoneInput(phone);\r\n if (!normalized) return '';\r\n if (normalized === '+') return '';\r\n if (normalized.startsWith('+')) return normalized;\r\n\r\n const digits = cleanPhone(normalized);\r\n const matchingDialCode = country.dialCodes.find((dialCode) => digits.startsWith(dialCode.replace('+', '')));\r\n return matchingDialCode ? `+${digits}` : `${country.dialCode}${digits}`;\r\n}\r\n\r\n/**\r\n * Remove dial code from phone number\r\n */\r\nexport function removeDialCode(phone: string, country: MaybeCountry): string {\n if (!country) return phone;\n\n const normalized = normalizePhoneInput(phone);\n const digits = cleanPhone(normalized);\n const primaryDialDigits = cleanPhone(country.dialCode);\n\n if (digits.startsWith(primaryDialDigits)) {\n return digits.slice(primaryDialDigits.length);\n }\n\n for (const dialCode of country.dialCodes) {\n const dialDigits = dialCode.replace('+', '');\r\n if (digits.startsWith(dialDigits)) {\r\n return digits.slice(dialDigits.length);\r\n }\r\n }\r\n\r\n return digits;\r\n}\r\n\r\n/**\r\n * Filter countries by search query\r\n */\r\nexport function filterCountries(\r\n countries: Country[],\r\n query: string,\r\n preferredCountries?: string[]\r\n): Country[] {\r\n const lowerQuery = query.toLowerCase().trim();\r\n \r\n if (!lowerQuery) {\r\n // Sort by preferred countries first\r\n if (preferredCountries?.length) {\r\n return [...countries].sort((a, b) => {\r\n const aPreferred = preferredCountries.indexOf(a.code);\r\n const bPreferred = preferredCountries.indexOf(b.code);\r\n if (aPreferred !== -1 && bPreferred !== -1) return aPreferred - bPreferred;\r\n if (aPreferred !== -1) return -1;\r\n if (bPreferred !== -1) return 1;\r\n return (a.displayName ?? a.name).localeCompare(b.displayName ?? b.name);\r\n });\r\n }\r\n return countries;\r\n }\r\n \r\n return countries.filter(\r\n country =>\r\n country.name.toLowerCase().includes(lowerQuery) ||\r\n (country.displayName ?? '').toLowerCase().includes(lowerQuery) ||\r\n country.code.toLowerCase().includes(lowerQuery) ||\r\n country.dialCodes.some((dialCode) => dialCode.includes(lowerQuery))\r\n );\r\n}\r\n\r\nexport function getCountryDisplayName(country: Country | undefined): string {\n return country?.displayName ?? country?.name ?? '';\n}\n\r\n/**\r\n * Get placeholder based on country format\r\n */\r\nexport function getPlaceholder(country: MaybeCountry): string {\n if (!country?.format) return country?.dialCode ? `${country.dialCode} 000 000 0000` : 'Phone number';\n return country.format.replace(/#/g, '0');\n}\n\nexport const stripNonDigits = cleanPhone;\n\nexport function isInternationalFormat(phone: string): boolean {\n return phone.trim().startsWith('+') || phone.trim().startsWith('00');\n}\n\nexport function extractDialCode(phone: string): { dialCode: string | null; nationalNumber: string } {\n const digits = cleanPhone(phone);\n if (!isInternationalFormat(phone)) {\n return { dialCode: null, nationalNumber: digits };\n }\n\n const match = countries\n .map((country) => country.dialCode)\n .sort((left, right) => right.length - left.length)\n .find((dialCode) => digits.startsWith(cleanPhone(dialCode)));\n\n if (!match) {\n return { dialCode: null, nationalNumber: digits };\n }\n\n const dialDigits = cleanPhone(match);\n return {\n dialCode: dialDigits,\n nationalNumber: digits.slice(dialDigits.length),\n };\n}\n\nexport function detectCountry(phone: string): Country | null {\n return detectCountryFromPhone(phone) ?? null;\n}\n\nexport function formatPhoneNumber(\n phone: string,\n country: MaybeCountry,\n format: 'national' | 'international' | 'e164' = 'national'\n): string {\n if (!phone) return '';\n if (format === 'e164') {\n return addDialCode(phone, country);\n }\n\n const nationalNumber = isInternationalFormat(phone) ? removeDialCode(phone, country) : phone;\n if (!country && format === 'national') {\n return cleanPhone(nationalNumber).slice(0, 9).replace(/(\\d{3})(?=\\d)/g, '$1 ').trim();\n }\n\n const formattedNational = formatPhone(nationalNumber, country);\n\n if (format === 'international') {\n return country ? `${country.dialCode} ${formattedNational}` : addDialCode(phone, country);\n }\n\n return formattedNational;\n}\n\nexport function parseToE164(phone: string, country: MaybeCountry): string {\n return addDialCode(phone, country);\n}\n\nexport function getNationalNumber(phone: string, country?: MaybeCountry): string {\n if (country) {\n return removeDialCode(phone, country);\n }\n\n const detectedCountry = detectCountryFromPhone(phone);\n return detectedCountry ? removeDialCode(phone, detectedCountry) : cleanPhone(phone);\n}\n\nexport function validatePhoneNumber(\n phone: string,\n country?: MaybeCountry,\n required = false\n): { isValid: boolean; error: string | null } {\n const digits = cleanPhone(phone);\n if (!digits) {\n return required\n ? { isValid: false, error: 'Phone number is required' }\n : { isValid: true, error: null };\n }\n\n const maxDigits = getMaxNationalDigits(country);\n const nationalDigits = country ? cleanPhone(removeDialCode(phone, country)) : digits;\n\n if (nationalDigits.length < 7) {\n return { isValid: false, error: 'Phone number is too short' };\n }\n\n if (maxDigits && nationalDigits.length > maxDigits) {\n return { isValid: false, error: `Phone number is too long (max ${maxDigits} digits)` };\n }\n\n const isValid = validatePhone(phone, country);\n return isValid ? { isValid: true, error: null } : { isValid: false, error: 'Invalid phone number' };\n}\n\nexport function isPhoneNumberComplete(phone: string, country?: MaybeCountry): boolean {\n if (!country) {\n return cleanPhone(phone).length >= 7;\n }\n\n return validatePhoneLength(phone, country);\n}\n\nexport function formatAsYouType(phone: string, country: MaybeCountry): string {\n if (isInternationalFormat(phone) && country) {\n return `${country.dialCode} ${formatPhone(removeDialCode(phone, country), country)}`;\n }\n\n return formatPhone(phone, country);\n}\n\nexport const normalizePhoneNumber = cleanPhone;\n\nexport function phoneNumbersEqual(left: string, right: string): boolean {\n return normalizePhoneNumber(left) === normalizePhoneNumber(right);\n}\n\nexport function getCountryDisplayLabel(country: Country, includeDialCode = true): string {\n const label = `${country.flag} ${getCountryDisplayName(country)}`;\n return includeDialCode ? `${label} (${country.dialCode})` : label;\n}\n\nexport function limitInputLength(phone: string, country?: MaybeCountry): string {\n const maxDigits = getMaxNationalDigits(country);\n if (!maxDigits) {\n return phone;\n }\n\n const isInternational = isInternationalFormat(phone);\n const digits = cleanPhone(phone);\n const dialDigits = country ? cleanPhone(country.dialCode) : '';\n const maxLength = isInternational ? dialDigits.length + maxDigits : maxDigits;\n const limited = digits.slice(0, maxLength);\n\n return isInternational ? `+${limited}` : limited;\n}\n","import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\r\nimport type { PhoneInputOptions, UsePhoneInputReturn } from './types';\r\nimport type { Country } from './countries';\r\nimport { countries, detectCountryFromPhone, getCountryByCode, localizeCountries, localizeCountry } from './countries';\r\nimport { resolvePhoneInputLabels } from './labels';\r\nimport {\r\n formatPhone,\r\n unformatPhone,\r\n validatePhone,\r\n addDialCode,\r\n removeDialCode,\r\n filterCountries,\n getPlaceholder,\n validatePhoneNumber,\n} from './utils';\n\r\nfunction countDigitsBeforePosition(value: string, position: number) {\r\n return value.slice(0, position).replace(/\\D/g, '').length;\r\n}\r\n\r\nfunction getCaretPositionFromDigitCount(value: string, digitCount: number) {\r\n if (digitCount <= 0) {\r\n return value.startsWith('+') ? 1 : 0;\r\n }\r\n\r\n let seenDigits = 0;\r\n\r\n for (let index = 0; index < value.length; index += 1) {\r\n if (/\\d/.test(value[index])) {\r\n seenDigits += 1;\r\n if (seenDigits === digitCount) {\r\n return index + 1;\r\n }\r\n }\r\n }\r\n\r\n return value.length;\r\n}\r\n\r\nexport function usePhoneInput(\r\n options: PhoneInputOptions & {\r\n value?: string;\n defaultValue?: string;\n onChange?: (phone: string, country: Country | undefined) => void;\n onCountryChange?: (country: Country | undefined) => void;\n onBlur?: () => void;\n onFocus?: () => void;\n } = {}\n): UsePhoneInputReturn {\r\n const {\r\n value: controlledValue,\r\n defaultValue = '',\n onChange,\n onCountryChange,\n onBlur,\n onFocus,\n defaultCountry = 'US',\n preferredCountries,\n excludeCountries,\n excludedCountries,\n onlyCountries,\n allowedCountries,\n autoDetect,\n autoDetectCountry,\n formatOnType = true,\n includeDialCode = false,\n required = false,\n validator,\n locale,\n labels,\n } = options;\n const resolvedOnlyCountries = onlyCountries ?? allowedCountries;\n const resolvedExcludeCountries = excludeCountries ?? excludedCountries;\n const resolvedAutoDetect = autoDetect ?? autoDetectCountry ?? true;\n\r\n const isControlled = controlledValue !== undefined;\n const inputRef = useRef<HTMLInputElement>(null);\n const pendingCaretDigitIndexRef = useRef<number | null>(null);\n const previousDefaultCountryRef = useRef(defaultCountry);\n\r\n // Filter available countries\r\n const availableCountries = useMemo(() => {\r\n let filtered = countries;\r\n \r\n if (resolvedOnlyCountries?.length) {\n filtered = filtered.filter(c => resolvedOnlyCountries.includes(c.code));\n }\n \n if (resolvedExcludeCountries?.length) {\n filtered = filtered.filter(c => !resolvedExcludeCountries.includes(c.code));\n }\n \n return filtered;\n }, [resolvedOnlyCountries, resolvedExcludeCountries]);\n\r\n const localizedCountries = useMemo(\r\n () => localizeCountries(availableCountries, locale),\r\n [availableCountries, locale]\r\n );\r\n\r\n const resolvedLabels = useMemo(\r\n () => resolvePhoneInputLabels(locale, labels),\r\n [locale, labels]\r\n );\r\n\r\n // Initialize state\r\n const initialCountry = availableCountries.find((candidate) => candidate.code === defaultCountry) || availableCountries[0];\r\n const [internalPhone, setInternalPhone] = useState(defaultValue);\r\n const [country, setCountry] = useState<Country | undefined>(initialCountry);\r\n const [isOpen, setIsOpen] = useState(false);\r\n const [searchQuery, setSearchQuery] = useState('');\r\n\r\n // Current phone value\n const phone = isControlled ? controlledValue : internalPhone;\n\n const getOutputCountry = useCallback(\n (nextCountry: Country | undefined) => localizeCountry(nextCountry, locale),\n [locale]\n );\n\n useEffect(() => {\n const defaultCountryChanged = previousDefaultCountryRef.current !== defaultCountry;\n previousDefaultCountryRef.current = defaultCountry;\n const nextCountry = availableCountries.find((candidate) => candidate.code === defaultCountry) || availableCountries[0];\n const countryStillAvailable = country\n ? availableCountries.some((candidate) => candidate.code === country.code)\n : false;\n\n if (nextCountry && (defaultCountryChanged || !countryStillAvailable)) {\n setCountry(nextCountry);\n }\n }, [defaultCountry, availableCountries, country]);\n\r\n // Auto-detect country from phone\r\n useEffect(() => {\r\n if (resolvedAutoDetect && phone) {\n const detected = detectCountryFromPhone(phone);\n if (detected && availableCountries.some((candidate) => candidate.code === detected.code) && detected.code !== country?.code) {\n setCountry(detected);\n onCountryChange?.(getOutputCountry(detected));\n }\n }\n }, [availableCountries, resolvedAutoDetect, phone, country?.code, onCountryChange, getOutputCountry]);\n\r\n // Format phone number\r\n const formattedPhone = useMemo(() => {\r\n if (formatOnType) {\r\n return formatPhone(includeDialCode && phone.startsWith('+') ? removeDialCode(phone, country) : phone, country);\r\n }\r\n return includeDialCode && phone.startsWith('+') ? removeDialCode(phone, country) : phone;\r\n }, [formatOnType, includeDialCode, phone, country]);\r\n\r\n // Full phone with dial code\r\n const fullPhone = useMemo(() => {\r\n if (includeDialCode && country) {\r\n return addDialCode(phone, country);\r\n }\r\n return phone;\r\n }, [phone, country, includeDialCode]);\r\n\r\n // Validation\r\n const isValid = useMemo(\n () => validatePhone(phone, country, validator),\n [phone, country, validator]\n );\n\n const error = useMemo(\n () => validatePhoneNumber(phone, country, required).error,\n [phone, country, required]\n );\n\r\n const localizedCountry = useMemo(\r\n () => localizeCountry(country, locale),\r\n [country, locale]\r\n );\r\n\r\n // Filtered countries for dropdown\r\n const filteredCountries = useMemo(\r\n () => filterCountries(localizedCountries, searchQuery, preferredCountries),\r\n [localizedCountries, searchQuery, preferredCountries]\r\n );\r\n\r\n useLayoutEffect(() => {\n const nextDigitIndex = pendingCaretDigitIndexRef.current;\r\n const input = inputRef.current;\r\n\r\n if (nextDigitIndex === null || !input || typeof input.setSelectionRange !== 'function') {\r\n return;\r\n }\r\n\r\n if (typeof document !== 'undefined' && document.activeElement !== input) {\r\n return;\r\n }\r\n\r\n const caretPosition = getCaretPositionFromDigitCount(formattedPhone, nextDigitIndex);\r\n input.setSelectionRange(caretPosition, caretPosition);\r\n pendingCaretDigitIndexRef.current = null;\r\n }, [formattedPhone]);\r\n\r\n // Set phone handler\r\n const setPhone = useCallback(\r\n (newPhone: string) => {\r\n const unformatted = unformatPhone(newPhone);\r\n if (!isControlled) {\r\n setInternalPhone(unformatted);\r\n }\r\n onChange?.(\r\n includeDialCode ? addDialCode(unformatted, country) : unformatted,\r\n getOutputCountry(country)\r\n );\r\n },\r\n [isControlled, onChange, country, includeDialCode, getOutputCountry]\r\n );\r\n\r\n // Set country handler\r\n const setCountryByCode = useCallback(\r\n (code: string) => {\r\n const newCountry = getCountryByCode(code);\r\n if (newCountry) {\r\n setCountry(newCountry);\n onCountryChange?.(getOutputCountry(newCountry));\n onChange?.(\n includeDialCode ? addDialCode(phone, newCountry) : phone,\r\n getOutputCountry(newCountry)\r\n );\r\n }\r\n },\r\n [phone, onChange, onCountryChange, includeDialCode, getOutputCountry]\n );\n\r\n // Select country from dropdown\r\n const selectCountry = useCallback(\r\n (selectedCountry: Country) => {\r\n const rawCountry = getCountryByCode(selectedCountry.code) ?? selectedCountry;\n setCountry(rawCountry);\n setIsOpen(false);\n setSearchQuery('');\n onCountryChange?.(getOutputCountry(rawCountry));\n onChange?.(\n includeDialCode ? addDialCode(phone, rawCountry) : phone,\r\n getOutputCountry(rawCountry)\r\n );\r\n },\r\n [phone, onChange, onCountryChange, includeDialCode, getOutputCountry]\n );\n\r\n // Toggle dropdown\r\n const toggleDropdown = useCallback(() => {\r\n setIsOpen(prev => !prev);\r\n if (isOpen) {\r\n setSearchQuery('');\r\n }\r\n }, [isOpen]);\r\n\r\n // Open dropdown\r\n const openDropdown = useCallback(() => {\r\n setIsOpen(true);\r\n }, []);\r\n\r\n // Close dropdown\r\n const closeDropdown = useCallback(() => {\r\n setIsOpen(false);\r\n setSearchQuery('');\r\n }, []);\r\n\r\n // Clear input\r\n const clear = useCallback(() => {\r\n if (!isControlled) {\r\n setInternalPhone('');\r\n }\r\n onChange?.('', getOutputCountry(country));\r\n }, [isControlled, onChange, country, getOutputCountry]);\r\n\r\n // Handle input change\r\n const handleInputChange = useCallback(\r\n (event: React.ChangeEvent<HTMLInputElement>) => {\r\n const rawValue = event.target.value;\r\n const caretPosition = event.target.selectionStart ?? rawValue.length;\r\n const unformatted = rawValue.trim().startsWith('+') ? `+${rawValue.replace(/\\D/g, '')}` : unformatPhone(rawValue);\r\n pendingCaretDigitIndexRef.current = countDigitsBeforePosition(rawValue, caretPosition);\r\n setPhone(unformatted);\r\n },\r\n [setPhone]\r\n );\r\n\r\n // Handle focus\r\n const handleFocus = useCallback(() => {\r\n onFocus?.();\r\n }, [onFocus]);\r\n\r\n // Handle blur\r\n const handleBlur = useCallback(() => {\n onBlur?.();\n }, [onBlur]);\n\n const getCountryOptionProps = useCallback(\n (optionCountry: Country, index: number) => ({\n role: 'option' as const,\n 'aria-selected': optionCountry.code === country?.code,\n onClick: () => selectCountry(optionCountry),\n onKeyDown: (event: { key: string; preventDefault: () => void }) => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault();\n selectCountry(optionCountry);\n }\n if (event.key === 'Escape') {\n event.preventDefault();\n closeDropdown();\n }\n },\n tabIndex: index === 0 ? 0 : -1,\n }),\n [closeDropdown, country?.code, selectCountry]\n );\n\r\n return {\r\n // State\r\n phone,\n value: phone,\n fullPhone,\n country: localizedCountry,\n isValid,\n error,\n isOpen,\n searchQuery,\n labels: resolvedLabels,\n formattedValue: formattedPhone,\n // Actions\n setPhone,\n setValue: setPhone,\n setCountry: setCountryByCode,\n toggleDropdown,\n toggle: toggleDropdown,\n openDropdown,\n open: openDropdown,\n closeDropdown,\n close: closeDropdown,\n setSearchQuery,\r\n clear,\r\n // Props\r\n inputProps: {\r\n ref: inputRef,\r\n value: formattedPhone,\r\n onChange: handleInputChange,\r\n onFocus: handleFocus,\r\n onBlur: handleBlur,\r\n type: 'tel',\r\n inputMode: 'tel',\r\n autoComplete: 'tel',\r\n placeholder: getPlaceholder(country),\r\n 'aria-invalid': phone ? !isValid : undefined,\r\n },\r\n countryButtonProps: {\n onClick: toggleDropdown,\n 'aria-expanded': isOpen,\n 'aria-haspopup': 'listbox',\n 'aria-label': resolvedLabels.countryButtonAriaLabel,\n },\n countrySelectorProps: {\n onClick: toggleDropdown,\n 'aria-expanded': isOpen,\n 'aria-haspopup': true,\n 'aria-label': resolvedLabels.countryButtonAriaLabel,\n },\n dropdownProps: {\n role: 'listbox',\n 'aria-label': resolvedLabels.countryOptionsAriaLabel,\n },\n filteredCountries,\n countries: filteredCountries,\n selectCountry,\n getCountryOptionProps,\n };\n}\n","import { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useRef, useState, type MutableRefObject, type Ref } from 'react';\nimport { usePhoneInput } from './usePhoneInput';\nimport type { PhoneInputProps } from './types';\nimport type { Country } from './countries';\nimport { getCountryDisplayName } from './utils';\n\n// SVG Icon Components (Lucide-style)\nconst ChevronUpIcon = ({ size = 12 }: { size?: number }) => (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <polyline points=\"18 15 12 9 6 15\" />\n </svg>\n);\n\nconst ChevronDownIcon = ({ size = 12 }: { size?: number }) => (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <polyline points=\"6 9 12 15 18 9\" />\n </svg>\n);\n\nexport interface PhoneInputRef {\n /** Focus the input */\n focus: () => void;\n /** Blur the input */\n blur: () => void;\n /** Clear the input */\n clear: () => void;\n /** Set country */\n setCountry: (countryCode: string) => void;\n /** Get current country */\n getCountry: () => Country | undefined;\n /** Open country selector */\n open: () => void;\n /** Close country selector */\n close: () => void;\n}\n\n/**\n * PhoneInput component - headless phone input with country selection\n * \n * @example\n * ```tsx\n * <PhoneInput\n * value={value}\n * onChange={setValue}\n * defaultCountry=\"US\"\n * />\n * ```\n * \n * @example\n * ```tsx\n * // With custom styling\n * <PhoneInput\n * value={value}\n * onChange={setValue}\n * defaultCountry=\"GB\"\n * containerClassName=\"phone-input-container\"\n * inputClassName=\"phone-input\"\n * selectorClassName=\"country-selector\"\n * />\n * ```\n */\nexport const PhoneInput = forwardRef<PhoneInputRef, PhoneInputProps>(\n function PhoneInput(props, ref) {\n const {\n value,\n defaultValue,\n onChange,\n onBlur,\n onFocus,\n inputClassName,\n selectorClassName,\n containerClassName,\n searchable = true,\n placeholder,\n disabled,\n readOnly,\n name,\n id,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n ...options\n } = props;\n\n const inputRef = useRef<HTMLInputElement | null>(null);\n const optionRefs = useRef<Array<HTMLLIElement | null>>([]);\n const [highlightedIndex, setHighlightedIndex] = useState(0);\n const listboxId = useId();\n\n const {\n inputProps,\n countryButtonProps,\n country,\n filteredCountries,\n isOpen,\n isValid,\n searchQuery,\n setSearchQuery,\n setCountry,\n selectCountry,\n clear,\n openDropdown,\n closeDropdown,\n labels,\n } = usePhoneInput({\n value,\n defaultValue,\n onChange,\n onBlur,\n onFocus,\n ...options,\n });\n\n const hookInputRef = (inputProps as typeof inputProps & { ref?: Ref<HTMLInputElement> }).ref;\n const mergedInputRef = useCallback((element: HTMLInputElement | null) => {\n inputRef.current = element;\n\n if (typeof hookInputRef === 'function') {\n hookInputRef(element);\n } else if (hookInputRef && 'current' in hookInputRef) {\n (hookInputRef as MutableRefObject<HTMLInputElement | null>).current = element;\n }\n }, [hookInputRef]);\n\n // Focus the input\n const focus = useCallback(() => {\n inputRef.current?.focus();\n }, []);\n\n // Blur the input\n const blur = useCallback(() => {\n inputRef.current?.blur();\n }, []);\n\n // Handle country option click\n const handleCountryClick = useCallback((c: Country) => {\n selectCountry(c);\n setHighlightedIndex(0);\n }, [selectCountry]);\n\n // Handle country option keyboard navigation\n const handleCountryKeyDown = useCallback((e: React.KeyboardEvent, c: Country, index: number) => {\n switch (e.key) {\n case 'Enter':\n case ' ':\n e.preventDefault();\n selectCountry(c);\n setHighlightedIndex(0);\n break;\n case 'ArrowDown':\n e.preventDefault();\n if (index < filteredCountries.length - 1) {\n const nextIndex = index + 1;\n setHighlightedIndex(nextIndex);\n optionRefs.current[nextIndex]?.focus();\n }\n break;\n case 'ArrowUp':\n e.preventDefault();\n if (index > 0) {\n const nextIndex = index - 1;\n setHighlightedIndex(nextIndex);\n optionRefs.current[nextIndex]?.focus();\n }\n break;\n case 'Escape':\n e.preventDefault();\n closeDropdown();\n break;\n }\n }, [selectCountry, filteredCountries.length, closeDropdown]);\n\n useEffect(() => {\n if (filteredCountries.length === 0) {\n if (highlightedIndex !== 0) {\n setHighlightedIndex(0);\n }\n return;\n }\n\n if (highlightedIndex >= filteredCountries.length) {\n setHighlightedIndex(filteredCountries.length - 1);\n }\n }, [filteredCountries.length, highlightedIndex]);\n\n // Expose imperative methods\n useImperativeHandle(ref, () => ({\n focus,\n blur,\n clear,\n setCountry,\n getCountry: () => country,\n open: openDropdown,\n close: closeDropdown,\n }));\n\n // Render default UI\n return (\n <div className={containerClassName} data-valid={isValid}>\n {/* Country Selector Button */}\n <button\n {...countryButtonProps}\n type=\"button\"\n className={selectorClassName}\n disabled={disabled}\n tabIndex={disabled ? -1 : 0}\n aria-controls={listboxId}\n >\n {country ? (\n <>\n <span className=\"phone-input-flag\">{country.flag}</span>\n <span className=\"phone-input-dial-code\">{country.dialCode}</span>\n </>\n ) : (\n <span className=\"phone-input-placeholder\">{labels.selectCountry}</span>\n )}\n <span className=\"phone-input-arrow\" aria-hidden=\"true\">\n {isOpen ? <ChevronUpIcon size={12} /> : <ChevronDownIcon size={12} />}\n </span>\n </button>\n\n {/* Phone Input */}\n <input\n {...inputProps}\n ref={mergedInputRef}\n id={id}\n name={name}\n className={inputClassName}\n placeholder={placeholder || inputProps.placeholder}\n disabled={disabled}\n readOnly={readOnly}\n aria-label={ariaLabel}\n aria-labelledby={ariaLabelledBy}\n />\n\n {/* Country Dropdown */}\n {isOpen && (\n <div className=\"phone-input-dropdown\">\n {/* Search Input */}\n {searchable && (\n <div className=\"phone-input-search\">\n <input\n type=\"text\"\n value={searchQuery}\n onChange={(e) => setSearchQuery(e.target.value)}\n placeholder={labels.countrySearchPlaceholder}\n autoFocus\n aria-controls={listboxId}\n aria-label={labels.searchCountriesAriaLabel}\n />\n </div>\n )}\n\n {/* Country List */}\n <ul className=\"phone-input-country-list\" id={listboxId} role=\"listbox\" aria-label={labels.countryOptionsAriaLabel}>\n {filteredCountries.map((c, index) => (\n <li\n key={c.code}\n ref={(element) => {\n optionRefs.current[index] = element;\n }}\n role=\"option\"\n aria-selected={c.code === country?.code}\n className={`phone-input-country-option ${\n c.code === country?.code ? 'selected' : ''\n } ${index === highlightedIndex ? 'highlighted' : ''}`}\n onClick={() => handleCountryClick(c)}\n onKeyDown={(e) => handleCountryKeyDown(e, c, index)}\n onMouseEnter={() => setHighlightedIndex(index)}\n tabIndex={index === highlightedIndex ? 0 : -1}\n >\n <span className=\"phone-input-flag\">{c.flag}</span>\n <span className=\"phone-input-country-name\">{getCountryDisplayName(c)}</span>\n <span className=\"phone-input-dial-code\">{c.dialCode}</span>\n </li>\n ))}\n {filteredCountries.length === 0 && (\n <li className=\"phone-input-no-results\">{labels.noCountriesFound}</li>\n )}\n </ul>\n </div>\n )}\n </div>\n );\n }\n);\n\nexport default PhoneInput;\n"]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as react from 'react';
2
- import { InputHTMLAttributes } from 'react';
2
+ import { InputHTMLAttributes, RefObject } from 'react';
3
3
 
4
4
  interface Country {
5
5
  code: string;
@@ -8,23 +8,41 @@ interface Country {
8
8
  dialCodes: string[];
9
9
  flag: string;
10
10
  format?: string;
11
+ displayName?: string;
11
12
  }
12
13
  declare const countries: Country[];
13
14
  declare function getCountryByCode(code: string): Country | undefined;
15
+ declare function getLocalizedCountryName(country: Country | undefined, locale?: string | readonly string[]): string | undefined;
16
+ declare function localizeCountry(country: Country | undefined, locale?: string | readonly string[]): Country | undefined;
17
+ declare function localizeCountries(list: Country[], locale?: string | readonly string[]): Country[];
14
18
  declare function getCountriesByDialCode(dialCode: string): Country[];
15
19
  declare function getCountryByDialCode(dialCode: string): Country | undefined;
16
20
  declare function detectCountryFromPhone(phone: string): Country | undefined;
17
21
 
22
+ interface PhoneInputLabels {
23
+ selectCountry: string;
24
+ countrySearchPlaceholder: string;
25
+ noCountriesFound: string;
26
+ searchCountriesAriaLabel: string;
27
+ countryOptionsAriaLabel: string;
28
+ countryButtonAriaLabel: string;
29
+ }
18
30
  interface PhoneInputOptions {
19
31
  defaultCountry?: string;
20
32
  preferredCountries?: string[];
21
33
  excludeCountries?: string[];
34
+ excludedCountries?: string[];
22
35
  onlyCountries?: string[];
36
+ allowedCountries?: string[];
23
37
  searchable?: boolean;
24
38
  autoDetect?: boolean;
39
+ autoDetectCountry?: boolean;
25
40
  formatOnType?: boolean;
26
41
  includeDialCode?: boolean;
42
+ required?: boolean;
27
43
  validator?: (phone: string, country: Country | undefined) => boolean;
44
+ locale?: string | readonly string[];
45
+ labels?: Partial<PhoneInputLabels>;
28
46
  }
29
47
  interface PhoneInputState {
30
48
  phone: string;
@@ -33,35 +51,69 @@ interface PhoneInputState {
33
51
  isValid: boolean;
34
52
  isOpen: boolean;
35
53
  searchQuery: string;
54
+ labels: PhoneInputLabels;
36
55
  }
37
56
  interface PhoneInputActions {
38
57
  setPhone: (phone: string) => void;
58
+ setValue: (phone: string) => void;
39
59
  setCountry: (code: string) => void;
40
60
  toggleDropdown: () => void;
61
+ toggle: () => void;
41
62
  openDropdown: () => void;
63
+ open: () => void;
42
64
  closeDropdown: () => void;
65
+ close: () => void;
43
66
  setSearchQuery: (query: string) => void;
44
67
  clear: () => void;
45
68
  }
46
69
  interface UsePhoneInputReturn extends PhoneInputState, PhoneInputActions {
47
- inputProps: InputHTMLAttributes<HTMLInputElement>;
70
+ value: string;
71
+ formattedValue: string;
72
+ error: string | null;
73
+ inputProps: InputHTMLAttributes<HTMLInputElement> & {
74
+ ref: RefObject<HTMLInputElement | null>;
75
+ };
48
76
  countryButtonProps: {
49
77
  onClick: () => void;
50
78
  'aria-expanded': boolean;
51
79
  'aria-haspopup': 'listbox';
80
+ 'aria-label': string;
81
+ };
82
+ countrySelectorProps: {
83
+ onClick: () => void;
84
+ 'aria-expanded': boolean;
85
+ 'aria-haspopup': true;
86
+ 'aria-label': string;
87
+ };
88
+ dropdownProps: {
89
+ role: 'listbox';
90
+ 'aria-label': string;
52
91
  };
53
92
  filteredCountries: Country[];
93
+ countries: Country[];
54
94
  selectCountry: (country: Country) => void;
95
+ getCountryOptionProps: (country: Country, index: number) => {
96
+ role: 'option';
97
+ 'aria-selected': boolean;
98
+ onClick: () => void;
99
+ onKeyDown: (event: {
100
+ key: string;
101
+ preventDefault: () => void;
102
+ }) => void;
103
+ tabIndex: number;
104
+ };
55
105
  }
56
106
  interface PhoneInputProps extends PhoneInputOptions {
57
107
  value?: string;
58
108
  defaultValue?: string;
59
109
  onChange?: (phone: string, country: Country | undefined) => void;
110
+ onCountryChange?: (country: Country | undefined) => void;
60
111
  onBlur?: () => void;
61
112
  onFocus?: () => void;
62
113
  containerClassName?: string;
63
114
  inputClassName?: string;
64
115
  selectorClassName?: string;
116
+ searchable?: boolean;
65
117
  placeholder?: string;
66
118
  disabled?: boolean;
67
119
  readOnly?: boolean;
@@ -75,6 +127,7 @@ declare function usePhoneInput(options?: PhoneInputOptions & {
75
127
  value?: string;
76
128
  defaultValue?: string;
77
129
  onChange?: (phone: string, country: Country | undefined) => void;
130
+ onCountryChange?: (country: Country | undefined) => void;
78
131
  onBlur?: () => void;
79
132
  onFocus?: () => void;
80
133
  }): UsePhoneInputReturn;
@@ -90,14 +143,39 @@ interface PhoneInputRef {
90
143
  }
91
144
  declare const PhoneInput: react.ForwardRefExoticComponent<PhoneInputProps & react.RefAttributes<PhoneInputRef>>;
92
145
 
146
+ declare const DEFAULT_PHONE_INPUT_LABELS: PhoneInputLabels;
147
+ declare function resolvePhoneInputLabels(locale?: string | readonly string[], overrides?: Partial<PhoneInputLabels>): PhoneInputLabels;
148
+
149
+ type MaybeCountry = Country | null | undefined;
93
150
  declare function cleanPhone(phone: string): string;
94
- declare function formatPhone(phone: string, country: Country | undefined): string;
151
+ declare function formatPhone(phone: string, country: MaybeCountry): string;
95
152
  declare function unformatPhone(formattedPhone: string): string;
96
- declare function validatePhoneLength(phone: string, country: Country | undefined): boolean;
97
- declare function validatePhone(phone: string, country: Country | undefined, customValidator?: (phone: string, country: Country | undefined) => boolean): boolean;
98
- declare function addDialCode(phone: string, country: Country | undefined): string;
99
- declare function removeDialCode(phone: string, country: Country | undefined): string;
153
+ declare function validatePhoneLength(phone: string, country: MaybeCountry): boolean;
154
+ declare function validatePhone(phone: string, country: MaybeCountry, customValidator?: (phone: string, country: Country | undefined) => boolean): boolean;
155
+ declare function addDialCode(phone: string, country: MaybeCountry): string;
156
+ declare function removeDialCode(phone: string, country: MaybeCountry): string;
100
157
  declare function filterCountries(countries: Country[], query: string, preferredCountries?: string[]): Country[];
101
- declare function getPlaceholder(country: Country | undefined): string;
158
+ declare function getCountryDisplayName(country: Country | undefined): string;
159
+ declare function getPlaceholder(country: MaybeCountry): string;
160
+ declare const stripNonDigits: typeof cleanPhone;
161
+ declare function isInternationalFormat(phone: string): boolean;
162
+ declare function extractDialCode(phone: string): {
163
+ dialCode: string | null;
164
+ nationalNumber: string;
165
+ };
166
+ declare function detectCountry(phone: string): Country | null;
167
+ declare function formatPhoneNumber(phone: string, country: MaybeCountry, format?: 'national' | 'international' | 'e164'): string;
168
+ declare function parseToE164(phone: string, country: MaybeCountry): string;
169
+ declare function getNationalNumber(phone: string, country?: MaybeCountry): string;
170
+ declare function validatePhoneNumber(phone: string, country?: MaybeCountry, required?: boolean): {
171
+ isValid: boolean;
172
+ error: string | null;
173
+ };
174
+ declare function isPhoneNumberComplete(phone: string, country?: MaybeCountry): boolean;
175
+ declare function formatAsYouType(phone: string, country: MaybeCountry): string;
176
+ declare const normalizePhoneNumber: typeof cleanPhone;
177
+ declare function phoneNumbersEqual(left: string, right: string): boolean;
178
+ declare function getCountryDisplayLabel(country: Country, includeDialCode?: boolean): string;
179
+ declare function limitInputLength(phone: string, country?: MaybeCountry): string;
102
180
 
103
- export { type Country, PhoneInput, type PhoneInputActions, type PhoneInputOptions, type PhoneInputProps, type PhoneInputRef, type PhoneInputState, type UsePhoneInputReturn, addDialCode, cleanPhone, countries, detectCountryFromPhone, filterCountries, formatPhone, getCountriesByDialCode, getCountryByCode, getCountryByDialCode, getPlaceholder, removeDialCode, unformatPhone, usePhoneInput, validatePhone, validatePhoneLength };
181
+ export { type Country, DEFAULT_PHONE_INPUT_LABELS, PhoneInput, type PhoneInputActions, type PhoneInputLabels, type PhoneInputOptions, type PhoneInputProps, type PhoneInputRef, type PhoneInputState, type UsePhoneInputReturn, addDialCode, cleanPhone, countries, detectCountry, detectCountryFromPhone, extractDialCode, filterCountries, formatAsYouType, formatPhone, formatPhoneNumber, getCountriesByDialCode, getCountryByCode, getCountryByDialCode, getCountryDisplayLabel, getCountryDisplayName, getLocalizedCountryName, getNationalNumber, getPlaceholder, isInternationalFormat, isPhoneNumberComplete, limitInputLength, localizeCountries, localizeCountry, normalizePhoneNumber, parseToE164, phoneNumbersEqual, removeDialCode, resolvePhoneInputLabels, stripNonDigits, unformatPhone, usePhoneInput, validatePhone, validatePhoneLength, validatePhoneNumber };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as react from 'react';
2
- import { InputHTMLAttributes } from 'react';
2
+ import { InputHTMLAttributes, RefObject } from 'react';
3
3
 
4
4
  interface Country {
5
5
  code: string;
@@ -8,23 +8,41 @@ interface Country {
8
8
  dialCodes: string[];
9
9
  flag: string;
10
10
  format?: string;
11
+ displayName?: string;
11
12
  }
12
13
  declare const countries: Country[];
13
14
  declare function getCountryByCode(code: string): Country | undefined;
15
+ declare function getLocalizedCountryName(country: Country | undefined, locale?: string | readonly string[]): string | undefined;
16
+ declare function localizeCountry(country: Country | undefined, locale?: string | readonly string[]): Country | undefined;
17
+ declare function localizeCountries(list: Country[], locale?: string | readonly string[]): Country[];
14
18
  declare function getCountriesByDialCode(dialCode: string): Country[];
15
19
  declare function getCountryByDialCode(dialCode: string): Country | undefined;
16
20
  declare function detectCountryFromPhone(phone: string): Country | undefined;
17
21
 
22
+ interface PhoneInputLabels {
23
+ selectCountry: string;
24
+ countrySearchPlaceholder: string;
25
+ noCountriesFound: string;
26
+ searchCountriesAriaLabel: string;
27
+ countryOptionsAriaLabel: string;
28
+ countryButtonAriaLabel: string;
29
+ }
18
30
  interface PhoneInputOptions {
19
31
  defaultCountry?: string;
20
32
  preferredCountries?: string[];
21
33
  excludeCountries?: string[];
34
+ excludedCountries?: string[];
22
35
  onlyCountries?: string[];
36
+ allowedCountries?: string[];
23
37
  searchable?: boolean;
24
38
  autoDetect?: boolean;
39
+ autoDetectCountry?: boolean;
25
40
  formatOnType?: boolean;
26
41
  includeDialCode?: boolean;
42
+ required?: boolean;
27
43
  validator?: (phone: string, country: Country | undefined) => boolean;
44
+ locale?: string | readonly string[];
45
+ labels?: Partial<PhoneInputLabels>;
28
46
  }
29
47
  interface PhoneInputState {
30
48
  phone: string;
@@ -33,35 +51,69 @@ interface PhoneInputState {
33
51
  isValid: boolean;
34
52
  isOpen: boolean;
35
53
  searchQuery: string;
54
+ labels: PhoneInputLabels;
36
55
  }
37
56
  interface PhoneInputActions {
38
57
  setPhone: (phone: string) => void;
58
+ setValue: (phone: string) => void;
39
59
  setCountry: (code: string) => void;
40
60
  toggleDropdown: () => void;
61
+ toggle: () => void;
41
62
  openDropdown: () => void;
63
+ open: () => void;
42
64
  closeDropdown: () => void;
65
+ close: () => void;
43
66
  setSearchQuery: (query: string) => void;
44
67
  clear: () => void;
45
68
  }
46
69
  interface UsePhoneInputReturn extends PhoneInputState, PhoneInputActions {
47
- inputProps: InputHTMLAttributes<HTMLInputElement>;
70
+ value: string;
71
+ formattedValue: string;
72
+ error: string | null;
73
+ inputProps: InputHTMLAttributes<HTMLInputElement> & {
74
+ ref: RefObject<HTMLInputElement | null>;
75
+ };
48
76
  countryButtonProps: {
49
77
  onClick: () => void;
50
78
  'aria-expanded': boolean;
51
79
  'aria-haspopup': 'listbox';
80
+ 'aria-label': string;
81
+ };
82
+ countrySelectorProps: {
83
+ onClick: () => void;
84
+ 'aria-expanded': boolean;
85
+ 'aria-haspopup': true;
86
+ 'aria-label': string;
87
+ };
88
+ dropdownProps: {
89
+ role: 'listbox';
90
+ 'aria-label': string;
52
91
  };
53
92
  filteredCountries: Country[];
93
+ countries: Country[];
54
94
  selectCountry: (country: Country) => void;
95
+ getCountryOptionProps: (country: Country, index: number) => {
96
+ role: 'option';
97
+ 'aria-selected': boolean;
98
+ onClick: () => void;
99
+ onKeyDown: (event: {
100
+ key: string;
101
+ preventDefault: () => void;
102
+ }) => void;
103
+ tabIndex: number;
104
+ };
55
105
  }
56
106
  interface PhoneInputProps extends PhoneInputOptions {
57
107
  value?: string;
58
108
  defaultValue?: string;
59
109
  onChange?: (phone: string, country: Country | undefined) => void;
110
+ onCountryChange?: (country: Country | undefined) => void;
60
111
  onBlur?: () => void;
61
112
  onFocus?: () => void;
62
113
  containerClassName?: string;
63
114
  inputClassName?: string;
64
115
  selectorClassName?: string;
116
+ searchable?: boolean;
65
117
  placeholder?: string;
66
118
  disabled?: boolean;
67
119
  readOnly?: boolean;
@@ -75,6 +127,7 @@ declare function usePhoneInput(options?: PhoneInputOptions & {
75
127
  value?: string;
76
128
  defaultValue?: string;
77
129
  onChange?: (phone: string, country: Country | undefined) => void;
130
+ onCountryChange?: (country: Country | undefined) => void;
78
131
  onBlur?: () => void;
79
132
  onFocus?: () => void;
80
133
  }): UsePhoneInputReturn;
@@ -90,14 +143,39 @@ interface PhoneInputRef {
90
143
  }
91
144
  declare const PhoneInput: react.ForwardRefExoticComponent<PhoneInputProps & react.RefAttributes<PhoneInputRef>>;
92
145
 
146
+ declare const DEFAULT_PHONE_INPUT_LABELS: PhoneInputLabels;
147
+ declare function resolvePhoneInputLabels(locale?: string | readonly string[], overrides?: Partial<PhoneInputLabels>): PhoneInputLabels;
148
+
149
+ type MaybeCountry = Country | null | undefined;
93
150
  declare function cleanPhone(phone: string): string;
94
- declare function formatPhone(phone: string, country: Country | undefined): string;
151
+ declare function formatPhone(phone: string, country: MaybeCountry): string;
95
152
  declare function unformatPhone(formattedPhone: string): string;
96
- declare function validatePhoneLength(phone: string, country: Country | undefined): boolean;
97
- declare function validatePhone(phone: string, country: Country | undefined, customValidator?: (phone: string, country: Country | undefined) => boolean): boolean;
98
- declare function addDialCode(phone: string, country: Country | undefined): string;
99
- declare function removeDialCode(phone: string, country: Country | undefined): string;
153
+ declare function validatePhoneLength(phone: string, country: MaybeCountry): boolean;
154
+ declare function validatePhone(phone: string, country: MaybeCountry, customValidator?: (phone: string, country: Country | undefined) => boolean): boolean;
155
+ declare function addDialCode(phone: string, country: MaybeCountry): string;
156
+ declare function removeDialCode(phone: string, country: MaybeCountry): string;
100
157
  declare function filterCountries(countries: Country[], query: string, preferredCountries?: string[]): Country[];
101
- declare function getPlaceholder(country: Country | undefined): string;
158
+ declare function getCountryDisplayName(country: Country | undefined): string;
159
+ declare function getPlaceholder(country: MaybeCountry): string;
160
+ declare const stripNonDigits: typeof cleanPhone;
161
+ declare function isInternationalFormat(phone: string): boolean;
162
+ declare function extractDialCode(phone: string): {
163
+ dialCode: string | null;
164
+ nationalNumber: string;
165
+ };
166
+ declare function detectCountry(phone: string): Country | null;
167
+ declare function formatPhoneNumber(phone: string, country: MaybeCountry, format?: 'national' | 'international' | 'e164'): string;
168
+ declare function parseToE164(phone: string, country: MaybeCountry): string;
169
+ declare function getNationalNumber(phone: string, country?: MaybeCountry): string;
170
+ declare function validatePhoneNumber(phone: string, country?: MaybeCountry, required?: boolean): {
171
+ isValid: boolean;
172
+ error: string | null;
173
+ };
174
+ declare function isPhoneNumberComplete(phone: string, country?: MaybeCountry): boolean;
175
+ declare function formatAsYouType(phone: string, country: MaybeCountry): string;
176
+ declare const normalizePhoneNumber: typeof cleanPhone;
177
+ declare function phoneNumbersEqual(left: string, right: string): boolean;
178
+ declare function getCountryDisplayLabel(country: Country, includeDialCode?: boolean): string;
179
+ declare function limitInputLength(phone: string, country?: MaybeCountry): string;
102
180
 
103
- export { type Country, PhoneInput, type PhoneInputActions, type PhoneInputOptions, type PhoneInputProps, type PhoneInputRef, type PhoneInputState, type UsePhoneInputReturn, addDialCode, cleanPhone, countries, detectCountryFromPhone, filterCountries, formatPhone, getCountriesByDialCode, getCountryByCode, getCountryByDialCode, getPlaceholder, removeDialCode, unformatPhone, usePhoneInput, validatePhone, validatePhoneLength };
181
+ export { type Country, DEFAULT_PHONE_INPUT_LABELS, PhoneInput, type PhoneInputActions, type PhoneInputLabels, type PhoneInputOptions, type PhoneInputProps, type PhoneInputRef, type PhoneInputState, type UsePhoneInputReturn, addDialCode, cleanPhone, countries, detectCountry, detectCountryFromPhone, extractDialCode, filterCountries, formatAsYouType, formatPhone, formatPhoneNumber, getCountriesByDialCode, getCountryByCode, getCountryByDialCode, getCountryDisplayLabel, getCountryDisplayName, getLocalizedCountryName, getNationalNumber, getPlaceholder, isInternationalFormat, isPhoneNumberComplete, limitInputLength, localizeCountries, localizeCountry, normalizePhoneNumber, parseToE164, phoneNumbersEqual, removeDialCode, resolvePhoneInputLabels, stripNonDigits, unformatPhone, usePhoneInput, validatePhone, validatePhoneLength, validatePhoneNumber };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {forwardRef,useRef,useState,useId,useCallback,useEffect,useImperativeHandle,useMemo}from'react';import {getCountries,getCountryCallingCode,getExampleNumber,parsePhoneNumberFromString,AsYouType,isValidPhoneNumber,isPossiblePhoneNumber,validatePhoneNumberLength}from'libphonenumber-js';import be from'libphonenumber-js/mobile/examples';import xe from'world-countries';import {jsxs,Fragment,jsx}from'react/jsx-runtime';var Ie=["US","GB","CA","AU","DE","FR","IT","ES","JP","CN","IN","BR","MX","KR","NL","CH","SE","AE","SG","ZA","NG","SA","TR","ID","PH","TH","VN","MY","NZ","AR"],De=new Set(getCountries());function Ne(e,t){let o=e.startsWith("+")?e:`+${e}`,n=t.replace(/\D/g,"");return `${o}${n}`}function we(e){let t=e.idd?.root;if(!t)return [];let n=(e.idd?.suffixes?.length?e.idd.suffixes:[""]).map(u=>Ne(t,u)).filter(u=>/^\+\d+$/.test(u));return Array.from(new Set(n))}function Re(e){let t=getExampleNumber(e,be);return t?t.formatNational().replace(/\d/g,"#"):void 0}function ce(e){let t=Ie.indexOf(e);return t===-1?Number.MAX_SAFE_INTEGER:t}var Be=xe.filter(e=>De.has(e.cca2)).map(e=>{let t=e.cca2,o=we(e),n=`+${getCountryCallingCode(t)}`;return !e.flag||o.length===0?null:{code:t,name:e.name.common,dialCode:n,dialCodes:o,flag:e.flag,format:Re(t)}}).filter(e=>e!==null).sort((e,t)=>{let o=ce(e.code)-ce(t.code);return o!==0?o:e.name.localeCompare(t.name)}),B=Be,ke=new Map(B.map(e=>[e.code,e])),Se=B.reduce((e,t)=>{for(let o of t.dialCodes){let n=e.get(o)??[];n.push(t),e.set(o,n);}return e},new Map),Ee=B.flatMap(e=>e.dialCodes.map(t=>({dialCode:t,country:e}))).sort((e,t)=>t.dialCode.length-e.dialCode.length);function Le(e){let t=e.replace(/\D/g,"");return t?`+${t}`:""}function k(e){return ke.get(e.toUpperCase())}function pe(e){return Se.get(Le(e))??[]}function $e(e){return pe(e)[0]}function re(e){let t=e.trim();if(!t)return;let o=t.startsWith("+")?`+${t.replace(/\D/g,"")}`:t.startsWith("00")?`+${t.slice(2).replace(/\D/g,"")}`:"";if(!o)return;let n=parsePhoneNumberFromString(o);return n?.country?k(n.country):Ee.find(u=>o.startsWith(u.dialCode))?.country}function S(e){let t=e.trim(),o=R(t);return o?t.startsWith("+")?`+${o}`:o:""}function ie(e){return e?.code}function R(e){return e.replace(/\D/g,"")}function se(e,t){return e&&new AsYouType(ie(t)).input(S(e))}function Q(e){return S(e)}function Ae(e,t){return !e||!t?false:e.trim().startsWith("+")?validatePhoneNumberLength(S(e))===void 0:validatePhoneNumberLength(R(e),ie(t))===void 0}function ae(e,t,o){if(!e)return false;if(o)return o(e,t);let n=S(e),u=ie(t);return u?n.startsWith("+")?isValidPhoneNumber(n):isValidPhoneNumber(R(n),u):isPossiblePhoneNumber(n.startsWith("+")?n:`+${R(n)}`)}function E(e,t){if(!t)return e;let o=S(e);if(!o)return "";if(o.startsWith("+"))return o;let n=R(o);return t.dialCodes.find(c=>n.startsWith(c.replace("+","")))?`+${n}`:`${t.dialCode}${n}`}function G(e,t){if(!t)return e;let o=S(e),n=R(o);for(let u of t.dialCodes){let c=u.replace("+","");if(n.startsWith(c))return n.slice(c.length)}return n}function ue(e,t,o){let n=t.toLowerCase().trim();return n?e.filter(u=>u.name.toLowerCase().includes(n)||u.code.toLowerCase().includes(n)||u.dialCodes.some(c=>c.includes(n))):o?.length?[...e].sort((u,c)=>{let m=o.indexOf(u.code),P=o.indexOf(c.code);return m!==-1&&P!==-1?m-P:m!==-1?-1:P!==-1?1:u.name.localeCompare(c.name)}):e}function le(e){return e?.format?e.format.replace(/#/g,"0"):e?.dialCode?`${e.dialCode} 000 000 0000`:"Phone number"}function de(e={}){let{value:t,defaultValue:o="",onChange:n,onBlur:u,onFocus:c,defaultCountry:m="US",preferredCountries:P,excludeCountries:$,onlyCountries:W,autoDetect:z=true,formatOnType:U=true,includeDialCode:d=false,validator:H}=e,I=t!==void 0,g=useMemo(()=>{let i=B;return W?.length&&(i=i.filter(r=>W.includes(r.code))),$?.length&&(i=i.filter(r=>!$.includes(r.code))),i},[W,$]),_=k(m)||g[0],[X,V]=useState(o),[a,v]=useState(_),[f,p]=useState(false),[D,N]=useState(""),s=I?t:X;useEffect(()=>{let i=k(m)||g[0];i&&i.code!==a?.code&&v(i);},[m,g,a?.code]),useEffect(()=>{if(z&&s){let i=re(s);i&&g.some(r=>r.code===i.code)&&i.code!==a?.code&&v(i);}},[g,z,s,a?.code]);let b=useMemo(()=>U?se(d&&s.startsWith("+")?G(s,a):s,a):d&&s.startsWith("+")?G(s,a):s,[U,d,s,a]),C=useMemo(()=>d&&a?E(s,a):s,[s,a,d]),O=useMemo(()=>ae(s,a,H),[s,a,H]),Z=useMemo(()=>ue(g,D,P),[g,D,P]),A=useCallback(i=>{let r=Q(i);I||V(r),n?.(d?E(r,a):r,a);},[I,n,a,d]),j=useCallback(i=>{let r=k(i);r&&(v(r),n?.(d?E(s,r):s,r));},[s,n,d]),J=useCallback(i=>{v(i),p(false),N(""),n?.(d?E(s,i):s,i);},[s,n,d]),w=useCallback(()=>{p(i=>!i),f&&N("");},[f]),q=useCallback(()=>{p(true);},[]),ee=useCallback(()=>{p(false),N("");},[]),M=useCallback(()=>{I||V(""),n?.("",a);},[I,n,a]),te=useCallback(i=>{let r=i.target.value,y=r.trim().startsWith("+")?`+${r.replace(/\D/g,"")}`:Q(r);A(y);},[A]),ne=useCallback(()=>{c?.();},[c]),oe=useCallback(()=>{u?.();},[u]);return {phone:s,fullPhone:C,country:a,isValid:O,isOpen:f,searchQuery:D,setPhone:A,setCountry:j,toggleDropdown:w,openDropdown:q,closeDropdown:ee,setSearchQuery:N,clear:M,inputProps:{value:b,onChange:te,onFocus:ne,onBlur:oe,type:"tel",inputMode:"tel",autoComplete:"tel",placeholder:le(a),"aria-invalid":s?!O:void 0},countryButtonProps:{onClick:w,"aria-expanded":f,"aria-haspopup":"listbox"},filteredCountries:Z,selectCountry:J}}var He=({size:e=12})=>jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("polyline",{points:"18 15 12 9 6 15"})}),Ve=({size:e=12})=>jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("polyline",{points:"6 9 12 15 18 9"})}),Qe=forwardRef(function(t,o){let{value:n,defaultValue:u,onChange:c,onBlur:m,onFocus:P,inputClassName:$,selectorClassName:W,containerClassName:z,placeholder:U,disabled:d,readOnly:H,name:I,id:g,"aria-label":_,"aria-labelledby":X,...V}=t,a=useRef(null),v=useRef([]),[f,p]=useState(0),D=useId(),{inputProps:N,countryButtonProps:s,country:b,filteredCountries:C,isOpen:O,isValid:Z,searchQuery:A,setSearchQuery:j,setCountry:J,selectCountry:w,clear:q,openDropdown:ee,closeDropdown:M}=de({value:n,defaultValue:u,onChange:c,onBlur:m,onFocus:P,...V}),te=useCallback(()=>{a.current?.focus();},[]),ne=useCallback(()=>{a.current?.blur();},[]),oe=useCallback(r=>{w(r),p(0);},[w]),i=useCallback((r,y,x)=>{switch(r.key){case "Enter":case " ":r.preventDefault(),w(y),p(0);break;case "ArrowDown":if(r.preventDefault(),x<C.length-1){let F=x+1;p(F),v.current[F]?.focus();}break;case "ArrowUp":if(r.preventDefault(),x>0){let F=x-1;p(F),v.current[F]?.focus();}break;case "Escape":r.preventDefault(),M();break}},[w,C.length,M]);return useEffect(()=>{if(C.length===0){f!==0&&p(0);return}f>=C.length&&p(C.length-1);},[C.length,f]),useImperativeHandle(o,()=>({focus:te,blur:ne,clear:q,setCountry:J,getCountry:()=>b,open:ee,close:M})),jsxs("div",{className:z,"data-valid":Z,children:[jsxs("button",{...s,type:"button",className:W,disabled:d,tabIndex:d?-1:0,"aria-controls":D,children:[b?jsxs(Fragment,{children:[jsx("span",{className:"phone-input-flag",children:b.flag}),jsx("span",{className:"phone-input-dial-code",children:b.dialCode})]}):jsx("span",{className:"phone-input-placeholder",children:"Select"}),jsx("span",{className:"phone-input-arrow","aria-hidden":"true",children:O?jsx(He,{size:12}):jsx(Ve,{size:12})})]}),jsx("input",{...N,ref:a,id:g,name:I,className:$,placeholder:U||N.placeholder,disabled:d,readOnly:H,"aria-label":_,"aria-labelledby":X}),O&&jsxs("div",{className:"phone-input-dropdown",children:[jsx("div",{className:"phone-input-search",children:jsx("input",{type:"text",value:A,onChange:r=>j(r.target.value),placeholder:"Search countries...",autoFocus:true,"aria-controls":D,"aria-label":"Search countries"})}),jsxs("ul",{className:"phone-input-country-list",id:D,role:"listbox","aria-label":"Country options",children:[C.map((r,y)=>jsxs("li",{ref:x=>{v.current[y]=x;},role:"option","aria-selected":r.code===b?.code,className:`phone-input-country-option ${r.code===b?.code?"selected":""} ${y===f?"highlighted":""}`,onClick:()=>oe(r),onKeyDown:x=>i(x,r,y),onMouseEnter:()=>p(y),tabIndex:y===f?0:-1,children:[jsx("span",{className:"phone-input-flag",children:r.flag}),jsx("span",{className:"phone-input-country-name",children:r.name}),jsx("span",{className:"phone-input-dial-code",children:r.dialCode})]},r.code)),C.length===0&&jsx("li",{className:"phone-input-no-results",children:"No countries found"})]})]})]})});export{Qe as PhoneInput,E as addDialCode,R as cleanPhone,B as countries,re as detectCountryFromPhone,ue as filterCountries,se as formatPhone,pe as getCountriesByDialCode,k as getCountryByCode,$e as getCountryByDialCode,le as getPlaceholder,G as removeDialCode,Q as unformatPhone,de as usePhoneInput,ae as validatePhone,Ae as validatePhoneLength};//# sourceMappingURL=index.js.map
1
+ import {forwardRef,useRef,useState,useId,useCallback,useEffect,useImperativeHandle,useMemo,useLayoutEffect}from'react';import {getCountries,getCountryCallingCode,getExampleNumber,parsePhoneNumberFromString,AsYouType,isValidPhoneNumber,isPossiblePhoneNumber,validatePhoneNumberLength}from'libphonenumber-js';import Ze from'libphonenumber-js/mobile/examples';import Je from'world-countries';import {jsxs,Fragment,jsx}from'react/jsx-runtime';var et=["US","GB","CA","AU","DE","FR","IT","ES","JP","CN","IN","BR","MX","KR","NL","CH","SE","AE","SG","ZA","NG","SA","TR","ID","PH","TH","VN","MY","NZ","AR"],tt=new Set(getCountries()),nt=new Map(Je.map(e=>[e.cca2,e])),rt={AC:{name:"Ascension Island",dialCode:"+247"},TA:{name:"Tristan da Cunha",dialCode:"+290"},BQ:{name:"Caribbean Netherlands",dialCode:"+599"}};function ot(e,t){let n=e.startsWith("+")?e:`+${e}`,r=t.replace(/\D/g,"");return `${n}${r}`}function it(e){return e.toUpperCase().replace(/./g,t=>String.fromCodePoint(127397+t.charCodeAt(0)))}function at(e,t){let n=e?.idd?.root;if(!n)return [t];let o=(e.idd?.suffixes?.length?e.idd.suffixes:[""]).map(l=>ot(n,l)).filter(l=>/^\+\d+$/.test(l));return Array.from(new Set([t,...o.length?o:[]]))}function st(e){let t=getExampleNumber(e,Ze);return t?t.formatNational().replace(/\d/g,"#"):void 0}function Ee(e){let t=et.indexOf(e);return t===-1?Number.MAX_SAFE_INTEGER:t}var ut=Array.from(tt).map(e=>{let t=nt.get(e),n=rt[e],r=n?.dialCode??`+${getCountryCallingCode(e)}`,o=at(t,r);return {code:e,name:t?.name.common??n?.name??e,dialCode:r,dialCodes:o,flag:t?.flag||n?.flag||it(e),format:st(e)}}).sort((e,t)=>{let n=Ee(e.code)-Ee(t.code);return n!==0?n:e.name.localeCompare(t.name)}),R=ut,lt=new Map(R.map(e=>[e.code,e])),ct=R.reduce((e,t)=>{for(let n of t.dialCodes){let r=e.get(n)??[];r.push(t),e.set(n,r);}return e},new Map),dt=R.flatMap(e=>e.dialCodes.map(t=>({dialCode:t,country:e}))).sort((e,t)=>t.dialCode.length-e.dialCode.length),Me=new Map;function pt(e){return Array.isArray(e)?[...e]:e?[e]:[]}function ft(e){let t=pt(e);if(t.length===0||typeof Intl>"u"||typeof Intl.DisplayNames>"u")return;let n=t.join("|"),r=Me.get(n);if(r)return r;try{let o=new Intl.DisplayNames(t,{type:"region"});return Me.set(n,o),o}catch{return}}function Ct(e){let t=e.replace(/\D/g,"");return t?`+${t}`:""}function j(e){return lt.get(e.toUpperCase())}function Re(e,t){return e?ft(t)?.of(e.code)??e.displayName??e.name:void 0}function X(e,t){if(!e)return;let n=Re(e,t);return n?{...e,displayName:n}:e}function Le(e,t){return t?e.map(n=>X(n,t)??n):e}function Fe(e){return ct.get(Ct(e))??[]}function yt(e){return Fe(e)[0]}function U(e){let t=e.trim();if(!t)return;let n=t.startsWith("+")?`+${t.replace(/\D/g,"")}`:t.startsWith("00")?`+${t.slice(2).replace(/\D/g,"")}`:"";if(!n)return;let r=parsePhoneNumberFromString(n);return r?.country?j(r.country):dt.find(o=>n.startsWith(o.dialCode))?.country}var Ne={selectCountry:"Select country",countrySearchPlaceholder:"Search countries...",noCountriesFound:"No countries found",searchCountriesAriaLabel:"Search countries",countryOptionsAriaLabel:"Country options",countryButtonAriaLabel:"Open country selector"},gt={en:Ne,fr:{selectCountry:"Choisir un pays",countrySearchPlaceholder:"Rechercher un pays...",noCountriesFound:"Aucun pays trouv\xE9",searchCountriesAriaLabel:"Rechercher des pays",countryOptionsAriaLabel:"Options de pays",countryButtonAriaLabel:"Ouvrir le s\xE9lecteur de pays"},de:{selectCountry:"Land ausw\xE4hlen",countrySearchPlaceholder:"Land suchen...",noCountriesFound:"Keine L\xE4nder gefunden",searchCountriesAriaLabel:"L\xE4nder suchen",countryOptionsAriaLabel:"L\xE4nderoptionen",countryButtonAriaLabel:"L\xE4nderauswahl \xF6ffnen"},es:{selectCountry:"Seleccionar pa\xEDs",countrySearchPlaceholder:"Buscar pa\xEDs...",noCountriesFound:"No se encontraron pa\xEDses",searchCountriesAriaLabel:"Buscar pa\xEDses",countryOptionsAriaLabel:"Opciones de pa\xEDs",countryButtonAriaLabel:"Abrir selector de pa\xEDs"},pt:{selectCountry:"Selecionar pa\xEDs",countrySearchPlaceholder:"Pesquisar pa\xEDs...",noCountriesFound:"Nenhum pa\xEDs encontrado",searchCountriesAriaLabel:"Pesquisar pa\xEDses",countryOptionsAriaLabel:"Op\xE7\xF5es de pa\xEDs",countryButtonAriaLabel:"Abrir seletor de pa\xEDs"},it:{selectCountry:"Seleziona paese",countrySearchPlaceholder:"Cerca paese...",noCountriesFound:"Nessun paese trovato",searchCountriesAriaLabel:"Cerca paesi",countryOptionsAriaLabel:"Opzioni paese",countryButtonAriaLabel:"Apri selettore paese"},ja:{selectCountry:"\u56FD\u3092\u9078\u629E",countrySearchPlaceholder:"\u56FD\u3092\u691C\u7D22...",noCountriesFound:"\u56FD\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",searchCountriesAriaLabel:"\u56FD\u3092\u691C\u7D22",countryOptionsAriaLabel:"\u56FD\u306E\u5019\u88DC",countryButtonAriaLabel:"\u56FD\u306E\u30BB\u30EC\u30AF\u30BF\u30FC\u3092\u958B\u304F"},ko:{selectCountry:"\uAD6D\uAC00 \uC120\uD0DD",countrySearchPlaceholder:"\uAD6D\uAC00 \uAC80\uC0C9...",noCountriesFound:"\uAD6D\uAC00\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4",searchCountriesAriaLabel:"\uAD6D\uAC00 \uAC80\uC0C9",countryOptionsAriaLabel:"\uAD6D\uAC00 \uC635\uC158",countryButtonAriaLabel:"\uAD6D\uAC00 \uC120\uD0DD\uAE30 \uC5F4\uAE30"},zh:{selectCountry:"\u9009\u62E9\u56FD\u5BB6",countrySearchPlaceholder:"\u641C\u7D22\u56FD\u5BB6...",noCountriesFound:"\u672A\u627E\u5230\u56FD\u5BB6",searchCountriesAriaLabel:"\u641C\u7D22\u56FD\u5BB6",countryOptionsAriaLabel:"\u56FD\u5BB6\u9009\u9879",countryButtonAriaLabel:"\u6253\u5F00\u56FD\u5BB6\u9009\u62E9\u5668"},ar:{selectCountry:"\u0627\u062E\u062A\u0631 \u0627\u0644\u062F\u0648\u0644\u0629",countrySearchPlaceholder:"\u0627\u0628\u062D\u062B \u0639\u0646 \u062F\u0648\u0644\u0629...",noCountriesFound:"\u0644\u0645 \u064A\u062A\u0645 \u0627\u0644\u0639\u062B\u0648\u0631 \u0639\u0644\u0649 \u062F\u0648\u0644",searchCountriesAriaLabel:"\u0627\u0628\u062D\u062B \u0639\u0646 \u0627\u0644\u062F\u0648\u0644",countryOptionsAriaLabel:"\u062E\u064A\u0627\u0631\u0627\u062A \u0627\u0644\u062F\u0648\u0644",countryButtonAriaLabel:"\u0627\u0641\u062A\u062D \u0645\u062D\u062F\u062F \u0627\u0644\u062F\u0648\u0644\u0629"},hi:{selectCountry:"\u0926\u0947\u0936 \u091A\u0941\u0928\u0947\u0902",countrySearchPlaceholder:"\u0926\u0947\u0936 \u0916\u094B\u091C\u0947\u0902...",noCountriesFound:"\u0915\u094B\u0908 \u0926\u0947\u0936 \u0928\u0939\u0940\u0902 \u092E\u093F\u0932\u093E",searchCountriesAriaLabel:"\u0926\u0947\u0936 \u0916\u094B\u091C\u0947\u0902",countryOptionsAriaLabel:"\u0926\u0947\u0936 \u0935\u093F\u0915\u0932\u094D\u092A",countryButtonAriaLabel:"\u0926\u0947\u0936 \u091A\u092F\u0928 \u0916\u094B\u0932\u0947\u0902"}};function mt(e){let n=(Array.isArray(e)?e:e?[e]:[]).find(Boolean);return n?n.toLowerCase().split("-")[0]:void 0}function xe(e,t){let n=mt(e),r=n?gt[n]:void 0;return {...Ne,...r,...t}}function _(e){let t=e.trim(),n=d(t);return t.startsWith("+")&&!n?"+":n?t.startsWith("+")?`+${n}`:n:""}function Ie(e){return e?.code}function ze(e){return e?.format?.replace(/[^#]/g,"").length}function d(e){return e.replace(/\D/g,"")}function H(e,t){return e&&new AsYouType(Ie(t)).input(_(e))}function le(e){return _(e)}function Te(e,t){return !e||!t?false:e.trim().startsWith("+")?validatePhoneNumberLength(_(e))===void 0:validatePhoneNumberLength(d(e),Ie(t))===void 0}function ce(e,t,n){if(!e)return false;if(n)return n(e,t??void 0);let r=_(e),o=Ie(t);return o?r.startsWith("+")?isValidPhoneNumber(r):isValidPhoneNumber(d(r),o):isPossiblePhoneNumber(r.startsWith("+")?r:`+${d(r)}`)}function B(e,t){if(!t)return e;let n=_(e);if(!n||n==="+")return "";if(n.startsWith("+"))return n;let r=d(n);return t.dialCodes.find(l=>r.startsWith(l.replace("+","")))?`+${r}`:`${t.dialCode}${r}`}function O(e,t){if(!t)return e;let n=_(e),r=d(n),o=d(t.dialCode);if(r.startsWith(o))return r.slice(o.length);for(let l of t.dialCodes){let y=l.replace("+","");if(r.startsWith(y))return r.slice(y.length)}return r}function De(e,t,n){let r=t.toLowerCase().trim();return r?e.filter(o=>o.name.toLowerCase().includes(r)||(o.displayName??"").toLowerCase().includes(r)||o.code.toLowerCase().includes(r)||o.dialCodes.some(l=>l.includes(r))):n?.length?[...e].sort((o,l)=>{let y=n.indexOf(o.code),C=n.indexOf(l.code);return y!==-1&&C!==-1?y-C:y!==-1?-1:C!==-1?1:(o.displayName??o.name).localeCompare(l.displayName??l.name)}):e}function de(e){return e?.displayName??e?.name??""}function ve(e){return e?.format?e.format.replace(/#/g,"0"):e?.dialCode?`${e.dialCode} 000 000 0000`:"Phone number"}var Pt=d;function Z(e){return e.trim().startsWith("+")||e.trim().startsWith("00")}function Lt(e){let t=d(e);if(!Z(e))return {dialCode:null,nationalNumber:t};let n=R.map(o=>o.dialCode).sort((o,l)=>l.length-o.length).find(o=>t.startsWith(d(o)));if(!n)return {dialCode:null,nationalNumber:t};let r=d(n);return {dialCode:r,nationalNumber:t.slice(r.length)}}function Nt(e){return U(e)??null}function xt(e,t,n="national"){if(!e)return "";if(n==="e164")return B(e,t);let r=Z(e)?O(e,t):e;if(!t&&n==="national")return d(r).slice(0,9).replace(/(\d{3})(?=\d)/g,"$1 ").trim();let o=H(r,t);return n==="international"?t?`${t.dialCode} ${o}`:B(e,t):o}function At(e,t){return B(e,t)}function It(e,t){if(t)return O(e,t);let n=U(e);return n?O(e,n):d(e)}function Se(e,t,n=false){let r=d(e);if(!r)return n?{isValid:false,error:"Phone number is required"}:{isValid:true,error:null};let o=ze(t),l=t?d(O(e,t)):r;return l.length<7?{isValid:false,error:"Phone number is too short"}:o&&l.length>o?{isValid:false,error:`Phone number is too long (max ${o} digits)`}:ce(e,t)?{isValid:true,error:null}:{isValid:false,error:"Invalid phone number"}}function Dt(e,t){return t?Te(e,t):d(e).length>=7}function vt(e,t){return Z(e)&&t?`${t.dialCode} ${H(O(e,t),t)}`:H(e,t)}var Ae=d;function St(e,t){return Ae(e)===Ae(t)}function wt(e,t=true){let n=`${e.flag} ${de(e)}`;return t?`${n} (${e.dialCode})`:n}function Bt(e,t){let n=ze(t);if(!n)return e;let r=Z(e),o=d(e),l=t?d(t.dialCode):"",y=r?l.length+n:n,C=o.slice(0,y);return r?`+${C}`:C}function Et(e,t){return e.slice(0,t).replace(/\D/g,"").length}function Mt(e,t){if(t<=0)return e.startsWith("+")?1:0;let n=0;for(let r=0;r<e.length;r+=1)if(/\d/.test(e[r])&&(n+=1,n===t))return r+1;return e.length}function Be(e={}){let{value:t,defaultValue:n="",onChange:r,onCountryChange:o,onBlur:l,onFocus:y,defaultCountry:C="US",preferredCountries:ee,excludeCountries:fe,excludedCountries:Ce,onlyCountries:ye,allowedCountries:ge,autoDetect:q,autoDetectCountry:me,formatOnType:te=true,includeDialCode:m=false,required:ne=false,validator:re,locale:N,labels:$}=e,F=ye??ge,I=fe??Ce,x=q??me??true,D=t!==void 0,z=useRef(null),G=useRef(null),v=useRef(C),p=useMemo(()=>{let i=R;return F?.length&&(i=i.filter(a=>F.includes(a.code))),I?.length&&(i=i.filter(a=>!I.includes(a.code))),i},[F,I]),Q=useMemo(()=>Le(p,N),[p,N]),T=useMemo(()=>xe(N,$),[N,$]),he=p.find(i=>i.code===C)||p[0],[be,oe]=useState(n),[s,W]=useState(he),[k,M]=useState(false),[S,P]=useState(""),u=D?t:be,g=useCallback(i=>X(i,N),[N]);useEffect(()=>{let i=v.current!==C;v.current=C;let a=p.find(Y=>Y.code===C)||p[0],h=s?p.some(Y=>Y.code===s.code):false;a&&(i||!h)&&W(a);},[C,p,s]),useEffect(()=>{if(x&&u){let i=U(u);i&&p.some(a=>a.code===i.code)&&i.code!==s?.code&&(W(i),o?.(g(i)));}},[p,x,u,s?.code,o,g]);let V=useMemo(()=>te?H(m&&u.startsWith("+")?O(u,s):u,s):m&&u.startsWith("+")?O(u,s):u,[te,m,u,s]),Pe=useMemo(()=>m&&s?B(u,s):u,[u,s,m]),ie=useMemo(()=>ce(u,s,re),[u,s,re]),c=useMemo(()=>Se(u,s,ne).error,[u,s,ne]),w=useMemo(()=>X(s,N),[s,N]),L=useMemo(()=>De(Q,S,ee),[Q,S,ee]);useLayoutEffect(()=>{let i=G.current,a=z.current;if(i===null||!a||typeof a.setSelectionRange!="function"||typeof document<"u"&&document.activeElement!==a)return;let h=Mt(V,i);a.setSelectionRange(h,h),G.current=null;},[V]);let A=useCallback(i=>{let a=le(i);D||oe(a),r?.(m?B(a,s):a,g(s));},[D,r,s,m,g]),Ue=useCallback(i=>{let a=j(i);a&&(W(a),o?.(g(a)),r?.(m?B(u,a):u,g(a)));},[u,r,o,m,g]),ae=useCallback(i=>{let a=j(i.code)??i;W(a),M(false),P(""),o?.(g(a)),r?.(m?B(u,a):u,g(a));},[u,r,o,m,g]),se=useCallback(()=>{M(i=>!i),k&&P("");},[k]),Oe=useCallback(()=>{M(true);},[]),ue=useCallback(()=>{M(false),P("");},[]),He=useCallback(()=>{D||oe(""),r?.("",g(s));},[D,r,s,g]),_e=useCallback(i=>{let a=i.target.value,h=i.target.selectionStart??a.length,Y=a.trim().startsWith("+")?`+${a.replace(/\D/g,"")}`:le(a);G.current=Et(a,h),A(Y);},[A]),Ke=useCallback(()=>{y?.();},[y]),qe=useCallback(()=>{l?.();},[l]),Ge=useCallback((i,a)=>({role:"option","aria-selected":i.code===s?.code,onClick:()=>ae(i),onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),ae(i)),h.key==="Escape"&&(h.preventDefault(),ue());},tabIndex:a===0?0:-1}),[ue,s?.code,ae]);return {phone:u,value:u,fullPhone:Pe,country:w,isValid:ie,error:c,isOpen:k,searchQuery:S,labels:T,formattedValue:V,setPhone:A,setValue:A,setCountry:Ue,toggleDropdown:se,toggle:se,openDropdown:Oe,open:Oe,closeDropdown:ue,close:ue,setSearchQuery:P,clear:He,inputProps:{ref:z,value:V,onChange:_e,onFocus:Ke,onBlur:qe,type:"tel",inputMode:"tel",autoComplete:"tel",placeholder:ve(s),"aria-invalid":u?!ie:void 0},countryButtonProps:{onClick:se,"aria-expanded":k,"aria-haspopup":"listbox","aria-label":T.countryButtonAriaLabel},countrySelectorProps:{onClick:se,"aria-expanded":k,"aria-haspopup":true,"aria-label":T.countryButtonAriaLabel},dropdownProps:{role:"listbox","aria-label":T.countryOptionsAriaLabel},filteredCountries:L,countries:L,selectCountry:ae,getCountryOptionProps:Ge}}var Tt=({size:e=12})=>jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("polyline",{points:"18 15 12 9 6 15"})}),Wt=({size:e=12})=>jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("polyline",{points:"6 9 12 15 18 9"})}),Vt=forwardRef(function(t,n){let{value:r,defaultValue:o,onChange:l,onBlur:y,onFocus:C,inputClassName:ee,selectorClassName:fe,containerClassName:Ce,searchable:ye=true,placeholder:ge,disabled:q,readOnly:me,name:te,id:m,"aria-label":ne,"aria-labelledby":re,...N}=t,$=useRef(null),F=useRef([]),[I,x]=useState(0),D=useId(),{inputProps:z,countryButtonProps:G,country:v,filteredCountries:p,isOpen:Q,isValid:T,searchQuery:he,setSearchQuery:be,setCountry:oe,selectCountry:s,clear:W,openDropdown:k,closeDropdown:M,labels:S}=Be({value:r,defaultValue:o,onChange:l,onBlur:y,onFocus:C,...N}),P=z.ref,u=useCallback(c=>{$.current=c,typeof P=="function"?P(c):P&&"current"in P&&(P.current=c);},[P]),g=useCallback(()=>{$.current?.focus();},[]),V=useCallback(()=>{$.current?.blur();},[]),Pe=useCallback(c=>{s(c),x(0);},[s]),ie=useCallback((c,w,L)=>{switch(c.key){case "Enter":case " ":c.preventDefault(),s(w),x(0);break;case "ArrowDown":if(c.preventDefault(),L<p.length-1){let A=L+1;x(A),F.current[A]?.focus();}break;case "ArrowUp":if(c.preventDefault(),L>0){let A=L-1;x(A),F.current[A]?.focus();}break;case "Escape":c.preventDefault(),M();break}},[s,p.length,M]);return useEffect(()=>{if(p.length===0){I!==0&&x(0);return}I>=p.length&&x(p.length-1);},[p.length,I]),useImperativeHandle(n,()=>({focus:g,blur:V,clear:W,setCountry:oe,getCountry:()=>v,open:k,close:M})),jsxs("div",{className:Ce,"data-valid":T,children:[jsxs("button",{...G,type:"button",className:fe,disabled:q,tabIndex:q?-1:0,"aria-controls":D,children:[v?jsxs(Fragment,{children:[jsx("span",{className:"phone-input-flag",children:v.flag}),jsx("span",{className:"phone-input-dial-code",children:v.dialCode})]}):jsx("span",{className:"phone-input-placeholder",children:S.selectCountry}),jsx("span",{className:"phone-input-arrow","aria-hidden":"true",children:Q?jsx(Tt,{size:12}):jsx(Wt,{size:12})})]}),jsx("input",{...z,ref:u,id:m,name:te,className:ee,placeholder:ge||z.placeholder,disabled:q,readOnly:me,"aria-label":ne,"aria-labelledby":re}),Q&&jsxs("div",{className:"phone-input-dropdown",children:[ye&&jsx("div",{className:"phone-input-search",children:jsx("input",{type:"text",value:he,onChange:c=>be(c.target.value),placeholder:S.countrySearchPlaceholder,autoFocus:true,"aria-controls":D,"aria-label":S.searchCountriesAriaLabel})}),jsxs("ul",{className:"phone-input-country-list",id:D,role:"listbox","aria-label":S.countryOptionsAriaLabel,children:[p.map((c,w)=>jsxs("li",{ref:L=>{F.current[w]=L;},role:"option","aria-selected":c.code===v?.code,className:`phone-input-country-option ${c.code===v?.code?"selected":""} ${w===I?"highlighted":""}`,onClick:()=>Pe(c),onKeyDown:L=>ie(L,c,w),onMouseEnter:()=>x(w),tabIndex:w===I?0:-1,children:[jsx("span",{className:"phone-input-flag",children:c.flag}),jsx("span",{className:"phone-input-country-name",children:de(c)}),jsx("span",{className:"phone-input-dial-code",children:c.dialCode})]},c.code)),p.length===0&&jsx("li",{className:"phone-input-no-results",children:S.noCountriesFound})]})]})]})});export{Ne as DEFAULT_PHONE_INPUT_LABELS,Vt as PhoneInput,B as addDialCode,d as cleanPhone,R as countries,Nt as detectCountry,U as detectCountryFromPhone,Lt as extractDialCode,De as filterCountries,vt as formatAsYouType,H as formatPhone,xt as formatPhoneNumber,Fe as getCountriesByDialCode,j as getCountryByCode,yt as getCountryByDialCode,wt as getCountryDisplayLabel,de as getCountryDisplayName,Re as getLocalizedCountryName,It as getNationalNumber,ve as getPlaceholder,Z as isInternationalFormat,Dt as isPhoneNumberComplete,Bt as limitInputLength,Le as localizeCountries,X as localizeCountry,Ae as normalizePhoneNumber,At as parseToE164,St as phoneNumbersEqual,O as removeDialCode,xe as resolvePhoneInputLabels,Pt as stripNonDigits,le as unformatPhone,Be as usePhoneInput,ce as validatePhone,Te as validatePhoneLength,Se as validatePhoneNumber};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/countries.ts","../src/utils.ts","../src/usePhoneInput.ts","../src/PhoneInput.tsx"],"names":["PRIORITY_COUNTRIES","supportedCountries","getCountries","normalizeDialCode","root","suffix","normalizedRoot","digitsOnlySuffix","buildDialCodes","country","dialCodes","dialCode","getCountryFormat","code","example","getExampleNumber","examples","getCountryPriority","index","generatedCountries","worldCountries","getCountryCallingCode","left","right","priorityDelta","countries","countryMap","countriesByDialCode","map","matches","dialCodeMatchers","normalizeLookupDialCode","digits","getCountryByCode","getCountriesByDialCode","getCountryByDialCode","detectCountryFromPhone","phone","trimmed","normalized","parsedPhone","parsePhoneNumberFromString","entry","normalizePhoneInput","cleanPhone","getCountryCode","formatPhone","AsYouType","unformatPhone","formattedPhone","validatePhoneLength","validateLength","validatePhone","customValidator","countryCode","isValidPhoneNumber","isPossiblePhoneNumber","addDialCode","removeDialCode","dialDigits","filterCountries","query","preferredCountries","lowerQuery","a","b","aPreferred","bPreferred","getPlaceholder","usePhoneInput","options","controlledValue","defaultValue","onChange","onBlur","onFocus","defaultCountry","excludeCountries","onlyCountries","autoDetect","formatOnType","includeDialCode","validator","isControlled","availableCountries","useMemo","filtered","c","initialCountry","internalPhone","setInternalPhone","useState","setCountry","isOpen","setIsOpen","searchQuery","setSearchQuery","useEffect","nextCountry","detected","candidate","fullPhone","isValid","filteredCountries","setPhone","useCallback","newPhone","unformatted","setCountryByCode","newCountry","selectCountry","selectedCountry","toggleDropdown","prev","openDropdown","closeDropdown","clear","handleInputChange","event","rawValue","handleFocus","handleBlur","ChevronUpIcon","size","jsx","ChevronDownIcon","PhoneInput","forwardRef","props","ref","value","inputClassName","selectorClassName","containerClassName","placeholder","disabled","readOnly","name","id","ariaLabel","ariaLabelledBy","inputRef","useRef","optionRefs","highlightedIndex","setHighlightedIndex","listboxId","useId","inputProps","countryButtonProps","focus","blur","handleCountryClick","handleCountryKeyDown","e","nextIndex","useImperativeHandle","jsxs","Fragment","element"],"mappings":"uaAaA,IAAMA,EAAAA,CAAqB,CACzB,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CACpF,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IACtF,CAAA,CAEMC,EAAAA,CAAqB,IAAI,IAAIC,YAAAA,EAAc,CAAA,CAEjD,SAASC,EAAAA,CAAkBC,CAAAA,CAAcC,CAAAA,CAAgB,CACvD,IAAMC,CAAAA,CAAiBF,CAAAA,CAAK,UAAA,CAAW,GAAG,CAAA,CAAIA,CAAAA,CAAO,CAAA,CAAA,EAAIA,CAAI,CAAA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SAAA,CAAYmE,CAAAA,EAAMD,CAAAA,CAAqBC,CAAAA,CAAGnE,CAAAA,CAAGrE,CAAK,CAAA,CAClD,YAAA,CAAc,IAAM+H,CAAAA,CAAoB/H,CAAK,CAAA,CAC7C,QAAA,CAAUA,CAAAA,GAAU8H,CAAAA,CAAmB,CAAA,CAAI,EAAA,CAE3C,QAAA,CAAA,CAAApB,GAAAA,CAAC,MAAA,CAAA,CAAK,SAAA,CAAU,kBAAA,CAAoB,QAAA,CAAArC,CAAAA,CAAE,IAAA,CAAK,CAAA,CAC3CqC,GAAAA,CAAC,MAAA,CAAA,CAAK,SAAA,CAAU,0BAAA,CAA4B,QAAA,CAAArC,CAAAA,CAAE,IAAA,CAAK,CAAA,CACnDqC,GAAAA,CAAC,MAAA,CAAA,CAAK,SAAA,CAAU,uBAAA,CAAyB,QAAA,CAAArC,CAAAA,CAAE,QAAA,CAAS,CAAA,CAAA,CAAA,CAhB/CA,CAAAA,CAAE,IAiBT,CACD,CAAA,CACAgB,CAAAA,CAAkB,MAAA,GAAW,CAAA,EAC5BqB,GAAAA,CAAC,IAAA,CAAA,CAAG,SAAA,CAAU,wBAAA,CAAyB,QAAA,CAAA,oBAAA,CAAkB,CAAA,CAAA,CAE7D,CAAA,CAAA,CACF,CAAA,CAAA,CAEJ,CAEJ,CACF","file":"index.js","sourcesContent":["import { getCountries, getCountryCallingCode, getExampleNumber, parsePhoneNumberFromString, type CountryCode } from 'libphonenumber-js';\r\nimport examples from 'libphonenumber-js/mobile/examples';\r\nimport worldCountries from 'world-countries';\r\n\r\nexport interface Country {\r\n code: string;\r\n name: string;\r\n dialCode: string;\r\n dialCodes: string[];\r\n flag: string;\r\n format?: string;\r\n}\r\n\r\nconst PRIORITY_COUNTRIES = [\r\n 'US', 'GB', 'CA', 'AU', 'DE', 'FR', 'IT', 'ES', 'JP', 'CN', 'IN', 'BR', 'MX', 'KR', 'NL',\r\n 'CH', 'SE', 'AE', 'SG', 'ZA', 'NG', 'SA', 'TR', 'ID', 'PH', 'TH', 'VN', 'MY', 'NZ', 'AR'\r\n];\r\n\r\nconst supportedCountries = new Set(getCountries());\r\n\r\nfunction normalizeDialCode(root: string, suffix: string) {\r\n const normalizedRoot = root.startsWith('+') ? root : `+${root}`;\r\n const digitsOnlySuffix = suffix.replace(/\\D/g, '');\r\n return `${normalizedRoot}${digitsOnlySuffix}`;\r\n}\r\n\r\nfunction buildDialCodes(country: (typeof worldCountries)[number]) {\r\n const root = country.idd?.root;\r\n if (!root) {\r\n return [];\r\n }\r\n\r\n const suffixes = country.idd?.suffixes?.length ? country.idd.suffixes : [''];\r\n const dialCodes = suffixes\r\n .map((suffix) => normalizeDialCode(root, suffix))\r\n .filter((dialCode) => /^\\+\\d+$/.test(dialCode));\r\n\r\n return Array.from(new Set(dialCodes));\r\n}\r\n\r\nfunction getCountryFormat(code: CountryCode) {\r\n const example = getExampleNumber(code, examples);\r\n return example ? example.formatNational().replace(/\\d/g, '#') : undefined;\r\n}\r\n\r\nfunction getCountryPriority(code: string) {\r\n const index = PRIORITY_COUNTRIES.indexOf(code);\r\n return index === -1 ? Number.MAX_SAFE_INTEGER : index;\r\n}\r\n\r\nconst generatedCountries = worldCountries\r\n .filter((country) => supportedCountries.has(country.cca2 as CountryCode))\r\n .map<Country | null>((country) => {\r\n const code = country.cca2 as CountryCode;\r\n const dialCodes = buildDialCodes(country);\r\n const dialCode = `+${getCountryCallingCode(code)}`;\r\n\r\n if (!country.flag || dialCodes.length === 0) {\r\n return null;\r\n }\r\n\r\n return {\r\n code,\r\n name: country.name.common,\r\n dialCode,\r\n dialCodes,\r\n flag: country.flag,\r\n format: getCountryFormat(code),\r\n } satisfies Country;\r\n })\r\n .filter((country): country is Country => country !== null)\r\n .sort((left, right) => {\r\n const priorityDelta = getCountryPriority(left.code) - getCountryPriority(right.code);\r\n return priorityDelta !== 0 ? priorityDelta : left.name.localeCompare(right.name);\r\n });\r\n\r\nexport const countries: Country[] = generatedCountries;\r\n\r\nexport const countryMap = new Map(countries.map((country) => [country.code, country]));\r\n\r\nconst countriesByDialCode = countries.reduce((map, country) => {\r\n for (const dialCode of country.dialCodes) {\r\n const matches = map.get(dialCode) ?? [];\r\n matches.push(country);\r\n map.set(dialCode, matches);\r\n }\r\n\r\n return map;\r\n}, new Map<string, Country[]>());\r\n\r\nconst dialCodeMatchers = countries\r\n .flatMap((country) => country.dialCodes.map((dialCode) => ({ dialCode, country })))\r\n .sort((left, right) => right.dialCode.length - left.dialCode.length);\r\n\r\nfunction normalizeLookupDialCode(dialCode: string) {\r\n const digits = dialCode.replace(/\\D/g, '');\r\n return digits ? `+${digits}` : '';\r\n}\r\n\r\nexport function getCountryByCode(code: string): Country | undefined {\r\n return countryMap.get(code.toUpperCase());\r\n}\r\n\r\nexport function getCountriesByDialCode(dialCode: string): Country[] {\r\n return countriesByDialCode.get(normalizeLookupDialCode(dialCode)) ?? [];\r\n}\r\n\r\nexport function getCountryByDialCode(dialCode: string): Country | undefined {\r\n return getCountriesByDialCode(dialCode)[0];\r\n}\r\n\r\nexport function detectCountryFromPhone(phone: string): Country | undefined {\r\n const trimmed = phone.trim();\r\n\r\n if (!trimmed) {\r\n return undefined;\r\n }\r\n\r\n const normalized = trimmed.startsWith('+')\r\n ? `+${trimmed.replace(/\\D/g, '')}`\r\n : trimmed.startsWith('00')\r\n ? `+${trimmed.slice(2).replace(/\\D/g, '')}`\r\n : '';\r\n\r\n if (!normalized) {\r\n return undefined;\r\n }\r\n\r\n const parsedPhone = parsePhoneNumberFromString(normalized);\r\n if (parsedPhone?.country) {\r\n return getCountryByCode(parsedPhone.country);\r\n }\r\n\r\n return dialCodeMatchers.find((entry) => normalized.startsWith(entry.dialCode))?.country;\r\n}\r\n","import type { Country } from './countries';\r\nimport { AsYouType, isPossiblePhoneNumber, isValidPhoneNumber, validatePhoneNumberLength as validateLength, type CountryCode } from 'libphonenumber-js';\r\n\r\nfunction normalizePhoneInput(phone: string): string {\r\n const trimmed = phone.trim();\r\n const digits = cleanPhone(trimmed);\r\n\r\n if (!digits) {\r\n return '';\r\n }\r\n\r\n return trimmed.startsWith('+') ? `+${digits}` : digits;\r\n}\r\n\r\nfunction getCountryCode(country: Country | undefined): CountryCode | undefined {\r\n return country?.code as CountryCode | undefined;\r\n}\r\n\r\n/**\r\n * Remove all non-digit characters from phone number\r\n */\r\nexport function cleanPhone(phone: string): string {\r\n return phone.replace(/\\D/g, '');\r\n}\r\n\r\n/**\r\n * Format phone number according to country format\r\n */\r\nexport function formatPhone(phone: string, country: Country | undefined): string {\r\n if (!phone) return phone;\r\n\r\n const formatter = new AsYouType(getCountryCode(country));\r\n return formatter.input(normalizePhoneInput(phone));\r\n}\r\n\r\n/**\r\n * Get raw phone number without formatting\r\n */\r\nexport function unformatPhone(formattedPhone: string): string {\r\n return normalizePhoneInput(formattedPhone);\r\n}\r\n\r\n/**\r\n * Validate phone number length based on country\r\n */\r\nexport function validatePhoneLength(phone: string, country: Country | undefined): boolean {\r\n if (!phone || !country) return false;\r\n\r\n if (phone.trim().startsWith('+')) {\r\n return validateLength(normalizePhoneInput(phone)) === undefined;\r\n }\r\n\r\n return validateLength(cleanPhone(phone), getCountryCode(country)) === undefined;\r\n}\r\n\r\n/**\r\n * Validate phone number format\r\n */\r\nexport function validatePhone(\r\n phone: string,\r\n country: Country | undefined,\r\n customValidator?: (phone: string, country: Country | undefined) => boolean\r\n): boolean {\r\n if (!phone) return false;\r\n \r\n if (customValidator) {\r\n return customValidator(phone, country);\r\n }\r\n\r\n const normalized = normalizePhoneInput(phone);\r\n const countryCode = getCountryCode(country);\r\n\r\n if (!countryCode) {\r\n return isPossiblePhoneNumber(normalized.startsWith('+') ? normalized : `+${cleanPhone(normalized)}`);\r\n }\r\n\r\n if (normalized.startsWith('+')) {\r\n return isValidPhoneNumber(normalized);\r\n }\r\n\r\n return isValidPhoneNumber(cleanPhone(normalized), countryCode);\r\n}\r\n\r\n/**\r\n * Add dial code to phone number\r\n */\r\nexport function addDialCode(phone: string, country: Country | undefined): string {\r\n if (!country) return phone;\r\n\r\n const normalized = normalizePhoneInput(phone);\r\n if (!normalized) return '';\r\n if (normalized.startsWith('+')) return normalized;\r\n\r\n const digits = cleanPhone(normalized);\r\n const matchingDialCode = country.dialCodes.find((dialCode) => digits.startsWith(dialCode.replace('+', '')));\r\n return matchingDialCode ? `+${digits}` : `${country.dialCode}${digits}`;\r\n}\r\n\r\n/**\r\n * Remove dial code from phone number\r\n */\r\nexport function removeDialCode(phone: string, country: Country | undefined): string {\r\n if (!country) return phone;\r\n\r\n const normalized = normalizePhoneInput(phone);\r\n const digits = cleanPhone(normalized);\r\n\r\n for (const dialCode of country.dialCodes) {\r\n const dialDigits = dialCode.replace('+', '');\r\n if (digits.startsWith(dialDigits)) {\r\n return digits.slice(dialDigits.length);\r\n }\r\n }\r\n\r\n return digits;\r\n}\r\n\r\n/**\r\n * Filter countries by search query\r\n */\r\nexport function filterCountries(\r\n countries: Country[],\r\n query: string,\r\n preferredCountries?: string[]\r\n): Country[] {\r\n const lowerQuery = query.toLowerCase().trim();\r\n \r\n if (!lowerQuery) {\r\n // Sort by preferred countries first\r\n if (preferredCountries?.length) {\r\n return [...countries].sort((a, b) => {\r\n const aPreferred = preferredCountries.indexOf(a.code);\r\n const bPreferred = preferredCountries.indexOf(b.code);\r\n if (aPreferred !== -1 && bPreferred !== -1) return aPreferred - bPreferred;\r\n if (aPreferred !== -1) return -1;\r\n if (bPreferred !== -1) return 1;\r\n return a.name.localeCompare(b.name);\r\n });\r\n }\r\n return countries;\r\n }\r\n \r\n return countries.filter(\r\n country =>\r\n country.name.toLowerCase().includes(lowerQuery) ||\r\n country.code.toLowerCase().includes(lowerQuery) ||\r\n country.dialCodes.some((dialCode) => dialCode.includes(lowerQuery))\r\n );\r\n}\r\n\r\n/**\r\n * Get placeholder based on country format\r\n */\r\nexport function getPlaceholder(country: Country | undefined): string {\r\n if (!country?.format) return country?.dialCode ? `${country.dialCode} 000 000 0000` : 'Phone number';\r\n return country.format.replace(/#/g, '0');\r\n}\r\n","import { useCallback, useMemo, useState, useEffect } from 'react';\r\nimport type { PhoneInputOptions, UsePhoneInputReturn } from './types';\r\nimport type { Country } from './countries';\r\nimport { countries, getCountryByCode, detectCountryFromPhone } from './countries';\r\nimport {\r\n formatPhone,\r\n unformatPhone,\r\n validatePhone,\r\n addDialCode,\r\n removeDialCode,\r\n filterCountries,\r\n getPlaceholder,\r\n} from './utils';\r\n\r\nexport function usePhoneInput(\r\n options: PhoneInputOptions & {\r\n value?: string;\r\n defaultValue?: string;\r\n onChange?: (phone: string, country: Country | undefined) => void;\r\n onBlur?: () => void;\r\n onFocus?: () => void;\r\n } = {}\r\n): UsePhoneInputReturn {\r\n const {\r\n value: controlledValue,\r\n defaultValue = '',\r\n onChange,\r\n onBlur,\r\n onFocus,\r\n defaultCountry = 'US',\r\n preferredCountries,\r\n excludeCountries,\r\n onlyCountries,\r\n autoDetect = true,\r\n formatOnType = true,\r\n includeDialCode = false,\r\n validator,\r\n } = options;\r\n\r\n const isControlled = controlledValue !== undefined;\r\n\r\n // Filter available countries\r\n const availableCountries = useMemo(() => {\r\n let filtered = countries;\r\n \r\n if (onlyCountries?.length) {\r\n filtered = filtered.filter(c => onlyCountries.includes(c.code));\r\n }\r\n \r\n if (excludeCountries?.length) {\r\n filtered = filtered.filter(c => !excludeCountries.includes(c.code));\r\n }\r\n \r\n return filtered;\r\n }, [onlyCountries, excludeCountries]);\r\n\r\n // Initialize state\r\n const initialCountry = getCountryByCode(defaultCountry) || availableCountries[0];\r\n const [internalPhone, setInternalPhone] = useState(defaultValue);\r\n const [country, setCountry] = useState<Country | undefined>(initialCountry);\r\n const [isOpen, setIsOpen] = useState(false);\r\n const [searchQuery, setSearchQuery] = useState('');\r\n\r\n // Current phone value\r\n const phone = isControlled ? controlledValue : internalPhone;\r\n\r\n useEffect(() => {\r\n const nextCountry = getCountryByCode(defaultCountry) || availableCountries[0];\r\n if (nextCountry && nextCountry.code !== country?.code) {\r\n setCountry(nextCountry);\r\n }\r\n }, [defaultCountry, availableCountries, country?.code]);\r\n\r\n // Auto-detect country from phone\r\n useEffect(() => {\r\n if (autoDetect && phone) {\r\n const detected = detectCountryFromPhone(phone);\r\n if (detected && availableCountries.some((candidate) => candidate.code === detected.code) && detected.code !== country?.code) {\r\n setCountry(detected);\r\n }\r\n }\r\n }, [availableCountries, autoDetect, phone, country?.code]);\r\n\r\n // Format phone number\r\n const formattedPhone = useMemo(() => {\r\n if (formatOnType) {\r\n return formatPhone(includeDialCode && phone.startsWith('+') ? removeDialCode(phone, country) : phone, country);\r\n }\r\n return includeDialCode && phone.startsWith('+') ? removeDialCode(phone, country) : phone;\r\n }, [formatOnType, includeDialCode, phone, country]);\r\n\r\n // Full phone with dial code\r\n const fullPhone = useMemo(() => {\r\n if (includeDialCode && country) {\r\n return addDialCode(phone, country);\r\n }\r\n return phone;\r\n }, [phone, country, includeDialCode]);\r\n\r\n // Validation\r\n const isValid = useMemo(\r\n () => validatePhone(phone, country, validator),\r\n [phone, country, validator]\r\n );\r\n\r\n // Filtered countries for dropdown\r\n const filteredCountries = useMemo(\r\n () => filterCountries(availableCountries, searchQuery, preferredCountries),\r\n [availableCountries, searchQuery, preferredCountries]\r\n );\r\n\r\n // Set phone handler\r\n const setPhone = useCallback(\r\n (newPhone: string) => {\r\n const unformatted = unformatPhone(newPhone);\r\n if (!isControlled) {\r\n setInternalPhone(unformatted);\r\n }\r\n onChange?.(includeDialCode ? addDialCode(unformatted, country) : unformatted, country);\r\n },\r\n [isControlled, onChange, country, includeDialCode]\r\n );\r\n\r\n // Set country handler\r\n const setCountryByCode = useCallback(\r\n (code: string) => {\r\n const newCountry = getCountryByCode(code);\r\n if (newCountry) {\r\n setCountry(newCountry);\r\n onChange?.(includeDialCode ? addDialCode(phone, newCountry) : phone, newCountry);\r\n }\r\n },\r\n [phone, onChange, includeDialCode]\r\n );\r\n\r\n // Select country from dropdown\r\n const selectCountry = useCallback(\r\n (selectedCountry: Country) => {\r\n setCountry(selectedCountry);\r\n setIsOpen(false);\r\n setSearchQuery('');\r\n onChange?.(\r\n includeDialCode ? addDialCode(phone, selectedCountry) : phone,\r\n selectedCountry\r\n );\r\n },\r\n [phone, onChange, includeDialCode]\r\n );\r\n\r\n // Toggle dropdown\r\n const toggleDropdown = useCallback(() => {\r\n setIsOpen(prev => !prev);\r\n if (isOpen) {\r\n setSearchQuery('');\r\n }\r\n }, [isOpen]);\r\n\r\n // Open dropdown\r\n const openDropdown = useCallback(() => {\r\n setIsOpen(true);\r\n }, []);\r\n\r\n // Close dropdown\r\n const closeDropdown = useCallback(() => {\r\n setIsOpen(false);\r\n setSearchQuery('');\r\n }, []);\r\n\r\n // Clear input\r\n const clear = useCallback(() => {\r\n if (!isControlled) {\r\n setInternalPhone('');\r\n }\r\n onChange?.('', country);\r\n }, [isControlled, onChange, country]);\r\n\r\n // Handle input change\r\n const handleInputChange = useCallback(\r\n (event: React.ChangeEvent<HTMLInputElement>) => {\r\n const rawValue = event.target.value;\r\n const unformatted = rawValue.trim().startsWith('+') ? `+${rawValue.replace(/\\D/g, '')}` : unformatPhone(rawValue);\r\n setPhone(unformatted);\r\n },\r\n [setPhone]\r\n );\r\n\r\n // Handle focus\r\n const handleFocus = useCallback(() => {\r\n onFocus?.();\r\n }, [onFocus]);\r\n\r\n // Handle blur\r\n const handleBlur = useCallback(() => {\r\n onBlur?.();\r\n }, [onBlur]);\r\n\r\n return {\r\n // State\r\n phone,\r\n fullPhone,\r\n country,\r\n isValid,\r\n isOpen,\r\n searchQuery,\r\n // Actions\r\n setPhone,\r\n setCountry: setCountryByCode,\r\n toggleDropdown,\r\n openDropdown,\r\n closeDropdown,\r\n setSearchQuery,\r\n clear,\r\n // Props\r\n inputProps: {\r\n value: formattedPhone,\r\n onChange: handleInputChange,\r\n onFocus: handleFocus,\r\n onBlur: handleBlur,\r\n type: 'tel',\r\n inputMode: 'tel',\r\n autoComplete: 'tel',\r\n placeholder: getPlaceholder(country),\r\n 'aria-invalid': phone ? !isValid : undefined,\r\n },\r\n countryButtonProps: {\r\n onClick: toggleDropdown,\r\n 'aria-expanded': isOpen,\r\n 'aria-haspopup': 'listbox',\r\n },\r\n filteredCountries,\r\n selectCountry,\r\n };\r\n}\r\n","import { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useRef, useState } from 'react';\nimport { usePhoneInput } from './usePhoneInput';\nimport type { PhoneInputProps } from './types';\nimport type { Country } from './countries';\n\n// SVG Icon Components (Lucide-style)\nconst ChevronUpIcon = ({ size = 12 }: { size?: number }) => (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <polyline points=\"18 15 12 9 6 15\" />\n </svg>\n);\n\nconst ChevronDownIcon = ({ size = 12 }: { size?: number }) => (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <polyline points=\"6 9 12 15 18 9\" />\n </svg>\n);\n\nexport interface PhoneInputRef {\n /** Focus the input */\n focus: () => void;\n /** Blur the input */\n blur: () => void;\n /** Clear the input */\n clear: () => void;\n /** Set country */\n setCountry: (countryCode: string) => void;\n /** Get current country */\n getCountry: () => Country | undefined;\n /** Open country selector */\n open: () => void;\n /** Close country selector */\n close: () => void;\n}\n\n/**\n * PhoneInput component - headless phone input with country selection\n * \n * @example\n * ```tsx\n * <PhoneInput\n * value={value}\n * onChange={setValue}\n * defaultCountry=\"US\"\n * />\n * ```\n * \n * @example\n * ```tsx\n * // With custom styling\n * <PhoneInput\n * value={value}\n * onChange={setValue}\n * defaultCountry=\"GB\"\n * containerClassName=\"phone-input-container\"\n * inputClassName=\"phone-input\"\n * selectorClassName=\"country-selector\"\n * />\n * ```\n */\nexport const PhoneInput = forwardRef<PhoneInputRef, PhoneInputProps>(\n function PhoneInput(props, ref) {\n const {\n value,\n defaultValue,\n onChange,\n onBlur,\n onFocus,\n inputClassName,\n selectorClassName,\n containerClassName,\n placeholder,\n disabled,\n readOnly,\n name,\n id,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n ...options\n } = props;\n\n const inputRef = useRef<HTMLInputElement>(null);\n const optionRefs = useRef<Array<HTMLLIElement | null>>([]);\n const [highlightedIndex, setHighlightedIndex] = useState(0);\n const listboxId = useId();\n\n const {\n inputProps,\n countryButtonProps,\n country,\n filteredCountries,\n isOpen,\n isValid,\n searchQuery,\n setSearchQuery,\n setCountry,\n selectCountry,\n clear,\n openDropdown,\n closeDropdown,\n } = usePhoneInput({\n value,\n defaultValue,\n onChange,\n onBlur,\n onFocus,\n ...options,\n });\n\n // Focus the input\n const focus = useCallback(() => {\n inputRef.current?.focus();\n }, []);\n\n // Blur the input\n const blur = useCallback(() => {\n inputRef.current?.blur();\n }, []);\n\n // Handle country option click\n const handleCountryClick = useCallback((c: Country) => {\n selectCountry(c);\n setHighlightedIndex(0);\n }, [selectCountry]);\n\n // Handle country option keyboard navigation\n const handleCountryKeyDown = useCallback((e: React.KeyboardEvent, c: Country, index: number) => {\n switch (e.key) {\n case 'Enter':\n case ' ':\n e.preventDefault();\n selectCountry(c);\n setHighlightedIndex(0);\n break;\n case 'ArrowDown':\n e.preventDefault();\n if (index < filteredCountries.length - 1) {\n const nextIndex = index + 1;\n setHighlightedIndex(nextIndex);\n optionRefs.current[nextIndex]?.focus();\n }\n break;\n case 'ArrowUp':\n e.preventDefault();\n if (index > 0) {\n const nextIndex = index - 1;\n setHighlightedIndex(nextIndex);\n optionRefs.current[nextIndex]?.focus();\n }\n break;\n case 'Escape':\n e.preventDefault();\n closeDropdown();\n break;\n }\n }, [selectCountry, filteredCountries.length, closeDropdown]);\n\n useEffect(() => {\n if (filteredCountries.length === 0) {\n if (highlightedIndex !== 0) {\n setHighlightedIndex(0);\n }\n return;\n }\n\n if (highlightedIndex >= filteredCountries.length) {\n setHighlightedIndex(filteredCountries.length - 1);\n }\n }, [filteredCountries.length, highlightedIndex]);\n\n // Expose imperative methods\n useImperativeHandle(ref, () => ({\n focus,\n blur,\n clear,\n setCountry,\n getCountry: () => country,\n open: openDropdown,\n close: closeDropdown,\n }));\n\n // Render default UI\n return (\n <div className={containerClassName} data-valid={isValid}>\n {/* Country Selector Button */}\n <button\n {...countryButtonProps}\n type=\"button\"\n className={selectorClassName}\n disabled={disabled}\n tabIndex={disabled ? -1 : 0}\n aria-controls={listboxId}\n >\n {country ? (\n <>\n <span className=\"phone-input-flag\">{country.flag}</span>\n <span className=\"phone-input-dial-code\">{country.dialCode}</span>\n </>\n ) : (\n <span className=\"phone-input-placeholder\">Select</span>\n )}\n <span className=\"phone-input-arrow\" aria-hidden=\"true\">\n {isOpen ? <ChevronUpIcon size={12} /> : <ChevronDownIcon size={12} />}\n </span>\n </button>\n\n {/* Phone Input */}\n <input\n {...inputProps}\n ref={inputRef}\n id={id}\n name={name}\n className={inputClassName}\n placeholder={placeholder || inputProps.placeholder}\n disabled={disabled}\n readOnly={readOnly}\n aria-label={ariaLabel}\n aria-labelledby={ariaLabelledBy}\n />\n\n {/* Country Dropdown */}\n {isOpen && (\n <div className=\"phone-input-dropdown\">\n {/* Search Input */}\n <div className=\"phone-input-search\">\n <input\n type=\"text\"\n value={searchQuery}\n onChange={(e) => setSearchQuery(e.target.value)}\n placeholder=\"Search countries...\"\n autoFocus\n aria-controls={listboxId}\n aria-label=\"Search countries\"\n />\n </div>\n\n {/* Country List */}\n <ul className=\"phone-input-country-list\" id={listboxId} role=\"listbox\" aria-label=\"Country options\">\n {filteredCountries.map((c, index) => (\n <li\n key={c.code}\n ref={(element) => {\n optionRefs.current[index] = element;\n }}\n role=\"option\"\n aria-selected={c.code === country?.code}\n className={`phone-input-country-option ${\n c.code === country?.code ? 'selected' : ''\n } ${index === highlightedIndex ? 'highlighted' : ''}`}\n onClick={() => handleCountryClick(c)}\n onKeyDown={(e) => handleCountryKeyDown(e, c, index)}\n onMouseEnter={() => setHighlightedIndex(index)}\n tabIndex={index === highlightedIndex ? 0 : -1}\n >\n <span className=\"phone-input-flag\">{c.flag}</span>\n <span className=\"phone-input-country-name\">{c.name}</span>\n <span className=\"phone-input-dial-code\">{c.dialCode}</span>\n </li>\n ))}\n {filteredCountries.length === 0 && (\n <li className=\"phone-input-no-results\">No countries found</li>\n )}\n </ul>\n </div>\n )}\n </div>\n );\n }\n);\n\nexport default PhoneInput;\n"]}
1
+ {"version":3,"sources":["../src/countries.ts","../src/labels.ts","../src/utils.ts","../src/usePhoneInput.ts","../src/PhoneInput.tsx"],"names":["PRIORITY_COUNTRIES","supportedCountries","getCountries","worldCountryMap","worldCountries","country","FALLBACK_COUNTRIES","normalizeDialCode","root","suffix","normalizedRoot","digitsOnlySuffix","codeToFlag","code","char","buildDialCodes","fallbackDialCode","dialCodes","dialCode","getCountryFormat","example","getExampleNumber","examples","getCountryPriority","index","generatedCountries","fallback","getCountryCallingCode","left","right","priorityDelta","countries","countryMap","countriesByDialCode","map","matches","dialCodeMatchers","displayNameCache","normalizeLocales","locale","getDisplayNames","locales","cacheKey","cached","displayNames","normalizeLookupDialCode","digits","getCountryByCode","getLocalizedCountryName","localizeCountry","displayName","localizeCountries","list","getCountriesByDialCode","getCountryByDialCode","detectCountryFromPhone","phone","trimmed","normalized","parsedPhone","parsePhoneNumberFromString","entry","DEFAULT_PHONE_INPUT_LABELS","LABELS_BY_LANGUAGE","getPrimaryLanguage","firstLocale","resolvePhoneInputLabels","overrides","language","localizedDefaults","normalizePhoneInput","cleanPhone","getCountryCode","getMaxNationalDigits","formatPhone","AsYouType","unformatPhone","formattedPhone","validatePhoneLength","validateLength","validatePhone","customValidator","countryCode","isValidPhoneNumber","isPossiblePhoneNumber","addDialCode","removeDialCode","primaryDialDigits","dialDigits","filterCountries","query","preferredCountries","lowerQuery","a","b","aPreferred","bPreferred","getCountryDisplayName","getPlaceholder","stripNonDigits","isInternationalFormat","extractDialCode","match","detectCountry","formatPhoneNumber","format","nationalNumber","formattedNational","parseToE164","getNationalNumber","detectedCountry","validatePhoneNumber","required","maxDigits","nationalDigits","isPhoneNumberComplete","formatAsYouType","normalizePhoneNumber","phoneNumbersEqual","getCountryDisplayLabel","includeDialCode","label","limitInputLength","isInternational","maxLength","limited","countDigitsBeforePosition","value","position","getCaretPositionFromDigitCount","digitCount","seenDigits","usePhoneInput","options","controlledValue","defaultValue","onChange","onCountryChange","onBlur","onFocus","defaultCountry","excludeCountries","excludedCountries","onlyCountries","allowedCountries","autoDetect","autoDetectCountry","formatOnType","validator","labels","resolvedOnlyCountries","resolvedExcludeCountries","resolvedAutoDetect","isControlled","inputRef","useRef","pendingCaretDigitIndexRef","previousDefaultCountryRef","availableCountries","useMemo","filtered","c","localizedCountries","resolvedLabels","initialCountry","candidate","internalPhone","setInternalPhone","useState","setCountry","isOpen","setIsOpen","searchQuery","setSearchQuery","getOutputCountry","useCallback","nextCountry","useEffect","defaultCountryChanged","countryStillAvailable","detected","fullPhone","isValid","error","localizedCountry","filteredCountries","useLayoutEffect","nextDigitIndex","input","caretPosition","setPhone","newPhone","unformatted","setCountryByCode","newCountry","selectCountry","selectedCountry","rawCountry","toggleDropdown","prev","openDropdown","closeDropdown","clear","handleInputChange","event","rawValue","handleFocus","handleBlur","getCountryOptionProps","optionCountry","ChevronUpIcon","size","jsx","ChevronDownIcon","PhoneInput","forwardRef","props","ref","inputClassName","selectorClassName","containerClassName","searchable","placeholder","disabled","readOnly","name","id","ariaLabel","ariaLabelledBy","optionRefs","highlightedIndex","setHighlightedIndex","listboxId","useId","inputProps","countryButtonProps","hookInputRef","mergedInputRef","element","focus","blur","handleCountryClick","handleCountryKeyDown","e","nextIndex","useImperativeHandle","jsxs","Fragment"],"mappings":"ubAcA,IAAMA,GAAqB,CACzB,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CAAM,KAAM,IAAA,CAAM,IAAA,CAAM,KAAM,IAAA,CAAM,IAAA,CAAM,KAAM,IAAA,CAAM,IAAA,CAAM,IAAA,CACpF,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AA,CACrEmH,IAAC,MAAA,CAAA,CAAK,SAAA,CAAU,wBAAyB,QAAA,CAAA,CAAA,CAAE,QAAA,CAAS,IAhB/C,CAAA,CAAE,IAiBT,CACD,CAAA,CACA3B,CAAAA,CAAkB,MAAA,GAAW,GAC5B2B,GAAAA,CAAC,IAAA,CAAA,CAAG,SAAA,CAAU,wBAAA,CAA0B,QAAA,CAAA/D,CAAAA,CAAO,iBAAiB,CAAA,CAAA,CAEpE,CAAA,CAAA,CACF,CAAA,CAAA,CAEJ,CAEJ,CACF","file":"index.js","sourcesContent":["import { getCountries, getCountryCallingCode, getExampleNumber, parsePhoneNumberFromString, type CountryCode } from 'libphonenumber-js';\r\nimport examples from 'libphonenumber-js/mobile/examples';\r\nimport worldCountries from 'world-countries';\r\n\r\nexport interface Country {\r\n code: string;\r\n name: string;\r\n dialCode: string;\r\n dialCodes: string[];\r\n flag: string;\r\n format?: string;\r\n displayName?: string;\r\n}\r\n\r\nconst PRIORITY_COUNTRIES = [\r\n 'US', 'GB', 'CA', 'AU', 'DE', 'FR', 'IT', 'ES', 'JP', 'CN', 'IN', 'BR', 'MX', 'KR', 'NL',\r\n 'CH', 'SE', 'AE', 'SG', 'ZA', 'NG', 'SA', 'TR', 'ID', 'PH', 'TH', 'VN', 'MY', 'NZ', 'AR'\r\n];\r\n\r\nconst supportedCountries = new Set(getCountries());\nconst worldCountryMap = new Map(worldCountries.map((country) => [country.cca2, country]));\nconst FALLBACK_COUNTRIES: Record<string, { name: string; dialCode?: string; flag?: string }> = {\n AC: { name: 'Ascension Island', dialCode: '+247' },\n TA: { name: 'Tristan da Cunha', dialCode: '+290' },\n BQ: { name: 'Caribbean Netherlands', dialCode: '+599' },\n};\n\r\nfunction normalizeDialCode(root: string, suffix: string) {\r\n const normalizedRoot = root.startsWith('+') ? root : `+${root}`;\r\n const digitsOnlySuffix = suffix.replace(/\\D/g, '');\r\n return `${normalizedRoot}${digitsOnlySuffix}`;\r\n}\r\n\r\nfunction codeToFlag(code: string): string {\n return code\n .toUpperCase()\n .replace(/./g, (char) => String.fromCodePoint(127397 + char.charCodeAt(0)));\n}\n\nfunction buildDialCodes(country: (typeof worldCountries)[number] | undefined, fallbackDialCode: string) {\n const root = country?.idd?.root;\n if (!root) {\n return [fallbackDialCode];\n }\n\n const suffixes = country.idd?.suffixes?.length ? country.idd.suffixes : [''];\n const dialCodes = suffixes\n .map((suffix) => normalizeDialCode(root, suffix))\n .filter((dialCode) => /^\\+\\d+$/.test(dialCode));\n\n return Array.from(new Set([fallbackDialCode, ...(dialCodes.length ? dialCodes : [])]));\n}\n\r\nfunction getCountryFormat(code: CountryCode) {\r\n const example = getExampleNumber(code, examples);\r\n return example ? example.formatNational().replace(/\\d/g, '#') : undefined;\r\n}\r\n\r\nfunction getCountryPriority(code: string) {\r\n const index = PRIORITY_COUNTRIES.indexOf(code);\r\n return index === -1 ? Number.MAX_SAFE_INTEGER : index;\r\n}\r\n\r\nconst generatedCountries = Array.from(supportedCountries)\n .map<Country>((code) => {\n const country = worldCountryMap.get(code);\n const fallback = FALLBACK_COUNTRIES[code];\n const dialCode = fallback?.dialCode ?? `+${getCountryCallingCode(code as CountryCode)}`;\n const dialCodes = buildDialCodes(country, dialCode);\n\n return {\n code,\n name: country?.name.common ?? fallback?.name ?? code,\n dialCode,\n dialCodes,\n flag: country?.flag || fallback?.flag || codeToFlag(code),\n format: getCountryFormat(code as CountryCode),\n } satisfies Country;\n })\n .sort((left, right) => {\n const priorityDelta = getCountryPriority(left.code) - getCountryPriority(right.code);\n return priorityDelta !== 0 ? priorityDelta : left.name.localeCompare(right.name);\n });\n\r\nexport const countries: Country[] = generatedCountries;\r\n\r\nexport const countryMap = new Map(countries.map((country) => [country.code, country]));\r\n\r\nconst countriesByDialCode = countries.reduce((map, country) => {\r\n for (const dialCode of country.dialCodes) {\r\n const matches = map.get(dialCode) ?? [];\r\n matches.push(country);\r\n map.set(dialCode, matches);\r\n }\r\n\r\n return map;\r\n}, new Map<string, Country[]>());\r\n\r\nconst dialCodeMatchers = countries\r\n .flatMap((country) => country.dialCodes.map((dialCode) => ({ dialCode, country })))\r\n .sort((left, right) => right.dialCode.length - left.dialCode.length);\r\n\r\nconst displayNameCache = new Map<string, Intl.DisplayNames>();\r\n\r\nfunction normalizeLocales(locale?: string | readonly string[]) {\r\n return Array.isArray(locale) ? [...locale] : locale ? [locale] : [];\r\n}\r\n\r\nfunction getDisplayNames(locale?: string | readonly string[]) {\r\n const locales = normalizeLocales(locale);\r\n if (locales.length === 0 || typeof Intl === 'undefined' || typeof Intl.DisplayNames === 'undefined') {\r\n return undefined;\r\n }\r\n\r\n const cacheKey = locales.join('|');\r\n const cached = displayNameCache.get(cacheKey);\r\n if (cached) {\r\n return cached;\r\n }\r\n\r\n try {\r\n const displayNames = new Intl.DisplayNames(locales, { type: 'region' });\r\n displayNameCache.set(cacheKey, displayNames);\r\n return displayNames;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\nfunction normalizeLookupDialCode(dialCode: string) {\r\n const digits = dialCode.replace(/\\D/g, '');\r\n return digits ? `+${digits}` : '';\r\n}\r\n\r\nexport function getCountryByCode(code: string): Country | undefined {\r\n return countryMap.get(code.toUpperCase());\r\n}\r\n\r\nexport function getLocalizedCountryName(\r\n country: Country | undefined,\r\n locale?: string | readonly string[]\r\n): string | undefined {\r\n if (!country) {\r\n return undefined;\r\n }\r\n\r\n const displayNames = getDisplayNames(locale);\r\n return displayNames?.of(country.code) ?? country.displayName ?? country.name;\r\n}\r\n\r\nexport function localizeCountry(\r\n country: Country | undefined,\r\n locale?: string | readonly string[]\r\n): Country | undefined {\r\n if (!country) {\r\n return undefined;\r\n }\r\n\r\n const displayName = getLocalizedCountryName(country, locale);\r\n return displayName ? { ...country, displayName } : country;\r\n}\r\n\r\nexport function localizeCountries(\r\n list: Country[],\r\n locale?: string | readonly string[]\r\n): Country[] {\r\n if (!locale) {\r\n return list;\r\n }\r\n\r\n return list.map((country) => localizeCountry(country, locale) ?? country);\r\n}\r\n\r\nexport function getCountriesByDialCode(dialCode: string): Country[] {\r\n return countriesByDialCode.get(normalizeLookupDialCode(dialCode)) ?? [];\r\n}\r\n\r\nexport function getCountryByDialCode(dialCode: string): Country | undefined {\r\n return getCountriesByDialCode(dialCode)[0];\r\n}\r\n\r\nexport function detectCountryFromPhone(phone: string): Country | undefined {\r\n const trimmed = phone.trim();\r\n\r\n if (!trimmed) {\r\n return undefined;\r\n }\r\n\r\n const normalized = trimmed.startsWith('+')\r\n ? `+${trimmed.replace(/\\D/g, '')}`\r\n : trimmed.startsWith('00')\r\n ? `+${trimmed.slice(2).replace(/\\D/g, '')}`\r\n : '';\r\n\r\n if (!normalized) {\r\n return undefined;\r\n }\r\n\r\n const parsedPhone = parsePhoneNumberFromString(normalized);\r\n if (parsedPhone?.country) {\r\n return getCountryByCode(parsedPhone.country);\r\n }\r\n\r\n return dialCodeMatchers.find((entry) => normalized.startsWith(entry.dialCode))?.country;\r\n}\r\n","import type { PhoneInputLabels } from './types';\r\n\r\nexport const DEFAULT_PHONE_INPUT_LABELS: PhoneInputLabels = {\r\n selectCountry: 'Select country',\r\n countrySearchPlaceholder: 'Search countries...',\r\n noCountriesFound: 'No countries found',\r\n searchCountriesAriaLabel: 'Search countries',\r\n countryOptionsAriaLabel: 'Country options',\r\n countryButtonAriaLabel: 'Open country selector',\r\n};\r\n\r\nconst LABELS_BY_LANGUAGE: Record<string, Partial<PhoneInputLabels>> = {\r\n en: DEFAULT_PHONE_INPUT_LABELS,\r\n fr: {\r\n selectCountry: 'Choisir un pays',\r\n countrySearchPlaceholder: 'Rechercher un pays...',\r\n noCountriesFound: 'Aucun pays trouvé',\r\n searchCountriesAriaLabel: 'Rechercher des pays',\r\n countryOptionsAriaLabel: 'Options de pays',\r\n countryButtonAriaLabel: 'Ouvrir le sélecteur de pays',\r\n },\r\n de: {\r\n selectCountry: 'Land auswählen',\r\n countrySearchPlaceholder: 'Land suchen...',\r\n noCountriesFound: 'Keine Länder gefunden',\r\n searchCountriesAriaLabel: 'Länder suchen',\r\n countryOptionsAriaLabel: 'Länderoptionen',\r\n countryButtonAriaLabel: 'Länderauswahl öffnen',\r\n },\r\n es: {\r\n selectCountry: 'Seleccionar país',\r\n countrySearchPlaceholder: 'Buscar país...',\r\n noCountriesFound: 'No se encontraron países',\r\n searchCountriesAriaLabel: 'Buscar países',\r\n countryOptionsAriaLabel: 'Opciones de país',\r\n countryButtonAriaLabel: 'Abrir selector de país',\r\n },\r\n pt: {\r\n selectCountry: 'Selecionar país',\r\n countrySearchPlaceholder: 'Pesquisar país...',\r\n noCountriesFound: 'Nenhum país encontrado',\r\n searchCountriesAriaLabel: 'Pesquisar países',\r\n countryOptionsAriaLabel: 'Opções de país',\r\n countryButtonAriaLabel: 'Abrir seletor de país',\r\n },\r\n it: {\r\n selectCountry: 'Seleziona paese',\r\n countrySearchPlaceholder: 'Cerca paese...',\r\n noCountriesFound: 'Nessun paese trovato',\r\n searchCountriesAriaLabel: 'Cerca paesi',\r\n countryOptionsAriaLabel: 'Opzioni paese',\r\n countryButtonAriaLabel: 'Apri selettore paese',\r\n },\r\n ja: {\r\n selectCountry: '国を選択',\r\n countrySearchPlaceholder: '国を検索...',\r\n noCountriesFound: '国が見つかりません',\r\n searchCountriesAriaLabel: '国を検索',\r\n countryOptionsAriaLabel: '国の候補',\r\n countryButtonAriaLabel: '国のセレクターを開く',\r\n },\r\n ko: {\r\n selectCountry: '국가 선택',\r\n countrySearchPlaceholder: '국가 검색...',\r\n noCountriesFound: '국가를 찾을 수 없습니다',\r\n searchCountriesAriaLabel: '국가 검색',\r\n countryOptionsAriaLabel: '국가 옵션',\r\n countryButtonAriaLabel: '국가 선택기 열기',\r\n },\r\n zh: {\r\n selectCountry: '选择国家',\r\n countrySearchPlaceholder: '搜索国家...',\r\n noCountriesFound: '未找到国家',\r\n searchCountriesAriaLabel: '搜索国家',\r\n countryOptionsAriaLabel: '国家选项',\r\n countryButtonAriaLabel: '打开国家选择器',\r\n },\r\n ar: {\r\n selectCountry: 'اختر الدولة',\r\n countrySearchPlaceholder: 'ابحث عن دولة...',\r\n noCountriesFound: 'لم يتم العثور على دول',\r\n searchCountriesAriaLabel: 'ابحث عن الدول',\r\n countryOptionsAriaLabel: 'خيارات الدول',\r\n countryButtonAriaLabel: 'افتح محدد الدولة',\r\n },\r\n hi: {\r\n selectCountry: 'देश चुनें',\r\n countrySearchPlaceholder: 'देश खोजें...',\r\n noCountriesFound: 'कोई देश नहीं मिला',\r\n searchCountriesAriaLabel: 'देश खोजें',\r\n countryOptionsAriaLabel: 'देश विकल्प',\r\n countryButtonAriaLabel: 'देश चयन खोलें',\r\n },\r\n};\r\n\r\nfunction getPrimaryLanguage(locale?: string | readonly string[]): string | undefined {\r\n const locales = Array.isArray(locale) ? locale : locale ? [locale] : [];\r\n const firstLocale = locales.find(Boolean);\r\n return firstLocale ? firstLocale.toLowerCase().split('-')[0] : undefined;\r\n}\r\n\r\nexport function resolvePhoneInputLabels(\r\n locale?: string | readonly string[],\r\n overrides?: Partial<PhoneInputLabels>\r\n): PhoneInputLabels {\r\n const language = getPrimaryLanguage(locale);\r\n const localizedDefaults = language ? LABELS_BY_LANGUAGE[language] : undefined;\r\n\r\n return {\r\n ...DEFAULT_PHONE_INPUT_LABELS,\r\n ...localizedDefaults,\r\n ...overrides,\r\n };\r\n}","import type { Country } from './countries';\nimport { countries, detectCountryFromPhone } from './countries';\nimport { AsYouType, isPossiblePhoneNumber, isValidPhoneNumber, validatePhoneNumberLength as validateLength, type CountryCode } from 'libphonenumber-js';\n\ntype MaybeCountry = Country | null | undefined;\n\nfunction normalizePhoneInput(phone: string): string {\n const trimmed = phone.trim();\r\n const digits = cleanPhone(trimmed);\r\n\r\n if (trimmed.startsWith('+') && !digits) {\r\n return '+';\r\n }\r\n\r\n if (!digits) {\r\n return '';\r\n }\r\n\r\n return trimmed.startsWith('+') ? `+${digits}` : digits;\r\n}\r\n\r\nfunction getCountryCode(country: MaybeCountry): CountryCode | undefined {\n return country?.code as CountryCode | undefined;\n}\n\nfunction getMaxNationalDigits(country: MaybeCountry): number | undefined {\n return country?.format?.replace(/[^#]/g, '').length;\n}\n\r\n/**\r\n * Remove all non-digit characters from phone number\r\n */\r\nexport function cleanPhone(phone: string): string {\r\n return phone.replace(/\\D/g, '');\r\n}\r\n\r\n/**\r\n * Format phone number according to country format\r\n */\r\nexport function formatPhone(phone: string, country: MaybeCountry): string {\n if (!phone) return phone;\r\n\r\n const formatter = new AsYouType(getCountryCode(country));\r\n return formatter.input(normalizePhoneInput(phone));\r\n}\r\n\r\n/**\r\n * Get raw phone number without formatting\r\n */\r\nexport function unformatPhone(formattedPhone: string): string {\r\n return normalizePhoneInput(formattedPhone);\r\n}\r\n\r\n/**\r\n * Validate phone number length based on country\r\n */\r\nexport function validatePhoneLength(phone: string, country: MaybeCountry): boolean {\n if (!phone || !country) return false;\r\n\r\n if (phone.trim().startsWith('+')) {\r\n return validateLength(normalizePhoneInput(phone)) === undefined;\r\n }\r\n\r\n return validateLength(cleanPhone(phone), getCountryCode(country)) === undefined;\r\n}\r\n\r\n/**\r\n * Validate phone number format\r\n */\r\nexport function validatePhone(\n phone: string,\n country: MaybeCountry,\n customValidator?: (phone: string, country: Country | undefined) => boolean\n): boolean {\n if (!phone) return false;\r\n \r\n if (customValidator) {\r\n return customValidator(phone, country ?? undefined);\n }\r\n\r\n const normalized = normalizePhoneInput(phone);\r\n const countryCode = getCountryCode(country);\r\n\r\n if (!countryCode) {\r\n return isPossiblePhoneNumber(normalized.startsWith('+') ? normalized : `+${cleanPhone(normalized)}`);\r\n }\r\n\r\n if (normalized.startsWith('+')) {\r\n return isValidPhoneNumber(normalized);\r\n }\r\n\r\n return isValidPhoneNumber(cleanPhone(normalized), countryCode);\r\n}\r\n\r\n/**\r\n * Add dial code to phone number\r\n */\r\nexport function addDialCode(phone: string, country: MaybeCountry): string {\n if (!country) return phone;\r\n\r\n const normalized = normalizePhoneInput(phone);\r\n if (!normalized) return '';\r\n if (normalized === '+') return '';\r\n if (normalized.startsWith('+')) return normalized;\r\n\r\n const digits = cleanPhone(normalized);\r\n const matchingDialCode = country.dialCodes.find((dialCode) => digits.startsWith(dialCode.replace('+', '')));\r\n return matchingDialCode ? `+${digits}` : `${country.dialCode}${digits}`;\r\n}\r\n\r\n/**\r\n * Remove dial code from phone number\r\n */\r\nexport function removeDialCode(phone: string, country: MaybeCountry): string {\n if (!country) return phone;\n\n const normalized = normalizePhoneInput(phone);\n const digits = cleanPhone(normalized);\n const primaryDialDigits = cleanPhone(country.dialCode);\n\n if (digits.startsWith(primaryDialDigits)) {\n return digits.slice(primaryDialDigits.length);\n }\n\n for (const dialCode of country.dialCodes) {\n const dialDigits = dialCode.replace('+', '');\r\n if (digits.startsWith(dialDigits)) {\r\n return digits.slice(dialDigits.length);\r\n }\r\n }\r\n\r\n return digits;\r\n}\r\n\r\n/**\r\n * Filter countries by search query\r\n */\r\nexport function filterCountries(\r\n countries: Country[],\r\n query: string,\r\n preferredCountries?: string[]\r\n): Country[] {\r\n const lowerQuery = query.toLowerCase().trim();\r\n \r\n if (!lowerQuery) {\r\n // Sort by preferred countries first\r\n if (preferredCountries?.length) {\r\n return [...countries].sort((a, b) => {\r\n const aPreferred = preferredCountries.indexOf(a.code);\r\n const bPreferred = preferredCountries.indexOf(b.code);\r\n if (aPreferred !== -1 && bPreferred !== -1) return aPreferred - bPreferred;\r\n if (aPreferred !== -1) return -1;\r\n if (bPreferred !== -1) return 1;\r\n return (a.displayName ?? a.name).localeCompare(b.displayName ?? b.name);\r\n });\r\n }\r\n return countries;\r\n }\r\n \r\n return countries.filter(\r\n country =>\r\n country.name.toLowerCase().includes(lowerQuery) ||\r\n (country.displayName ?? '').toLowerCase().includes(lowerQuery) ||\r\n country.code.toLowerCase().includes(lowerQuery) ||\r\n country.dialCodes.some((dialCode) => dialCode.includes(lowerQuery))\r\n );\r\n}\r\n\r\nexport function getCountryDisplayName(country: Country | undefined): string {\n return country?.displayName ?? country?.name ?? '';\n}\n\r\n/**\r\n * Get placeholder based on country format\r\n */\r\nexport function getPlaceholder(country: MaybeCountry): string {\n if (!country?.format) return country?.dialCode ? `${country.dialCode} 000 000 0000` : 'Phone number';\n return country.format.replace(/#/g, '0');\n}\n\nexport const stripNonDigits = cleanPhone;\n\nexport function isInternationalFormat(phone: string): boolean {\n return phone.trim().startsWith('+') || phone.trim().startsWith('00');\n}\n\nexport function extractDialCode(phone: string): { dialCode: string | null; nationalNumber: string } {\n const digits = cleanPhone(phone);\n if (!isInternationalFormat(phone)) {\n return { dialCode: null, nationalNumber: digits };\n }\n\n const match = countries\n .map((country) => country.dialCode)\n .sort((left, right) => right.length - left.length)\n .find((dialCode) => digits.startsWith(cleanPhone(dialCode)));\n\n if (!match) {\n return { dialCode: null, nationalNumber: digits };\n }\n\n const dialDigits = cleanPhone(match);\n return {\n dialCode: dialDigits,\n nationalNumber: digits.slice(dialDigits.length),\n };\n}\n\nexport function detectCountry(phone: string): Country | null {\n return detectCountryFromPhone(phone) ?? null;\n}\n\nexport function formatPhoneNumber(\n phone: string,\n country: MaybeCountry,\n format: 'national' | 'international' | 'e164' = 'national'\n): string {\n if (!phone) return '';\n if (format === 'e164') {\n return addDialCode(phone, country);\n }\n\n const nationalNumber = isInternationalFormat(phone) ? removeDialCode(phone, country) : phone;\n if (!country && format === 'national') {\n return cleanPhone(nationalNumber).slice(0, 9).replace(/(\\d{3})(?=\\d)/g, '$1 ').trim();\n }\n\n const formattedNational = formatPhone(nationalNumber, country);\n\n if (format === 'international') {\n return country ? `${country.dialCode} ${formattedNational}` : addDialCode(phone, country);\n }\n\n return formattedNational;\n}\n\nexport function parseToE164(phone: string, country: MaybeCountry): string {\n return addDialCode(phone, country);\n}\n\nexport function getNationalNumber(phone: string, country?: MaybeCountry): string {\n if (country) {\n return removeDialCode(phone, country);\n }\n\n const detectedCountry = detectCountryFromPhone(phone);\n return detectedCountry ? removeDialCode(phone, detectedCountry) : cleanPhone(phone);\n}\n\nexport function validatePhoneNumber(\n phone: string,\n country?: MaybeCountry,\n required = false\n): { isValid: boolean; error: string | null } {\n const digits = cleanPhone(phone);\n if (!digits) {\n return required\n ? { isValid: false, error: 'Phone number is required' }\n : { isValid: true, error: null };\n }\n\n const maxDigits = getMaxNationalDigits(country);\n const nationalDigits = country ? cleanPhone(removeDialCode(phone, country)) : digits;\n\n if (nationalDigits.length < 7) {\n return { isValid: false, error: 'Phone number is too short' };\n }\n\n if (maxDigits && nationalDigits.length > maxDigits) {\n return { isValid: false, error: `Phone number is too long (max ${maxDigits} digits)` };\n }\n\n const isValid = validatePhone(phone, country);\n return isValid ? { isValid: true, error: null } : { isValid: false, error: 'Invalid phone number' };\n}\n\nexport function isPhoneNumberComplete(phone: string, country?: MaybeCountry): boolean {\n if (!country) {\n return cleanPhone(phone).length >= 7;\n }\n\n return validatePhoneLength(phone, country);\n}\n\nexport function formatAsYouType(phone: string, country: MaybeCountry): string {\n if (isInternationalFormat(phone) && country) {\n return `${country.dialCode} ${formatPhone(removeDialCode(phone, country), country)}`;\n }\n\n return formatPhone(phone, country);\n}\n\nexport const normalizePhoneNumber = cleanPhone;\n\nexport function phoneNumbersEqual(left: string, right: string): boolean {\n return normalizePhoneNumber(left) === normalizePhoneNumber(right);\n}\n\nexport function getCountryDisplayLabel(country: Country, includeDialCode = true): string {\n const label = `${country.flag} ${getCountryDisplayName(country)}`;\n return includeDialCode ? `${label} (${country.dialCode})` : label;\n}\n\nexport function limitInputLength(phone: string, country?: MaybeCountry): string {\n const maxDigits = getMaxNationalDigits(country);\n if (!maxDigits) {\n return phone;\n }\n\n const isInternational = isInternationalFormat(phone);\n const digits = cleanPhone(phone);\n const dialDigits = country ? cleanPhone(country.dialCode) : '';\n const maxLength = isInternational ? dialDigits.length + maxDigits : maxDigits;\n const limited = digits.slice(0, maxLength);\n\n return isInternational ? `+${limited}` : limited;\n}\n","import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\r\nimport type { PhoneInputOptions, UsePhoneInputReturn } from './types';\r\nimport type { Country } from './countries';\r\nimport { countries, detectCountryFromPhone, getCountryByCode, localizeCountries, localizeCountry } from './countries';\r\nimport { resolvePhoneInputLabels } from './labels';\r\nimport {\r\n formatPhone,\r\n unformatPhone,\r\n validatePhone,\r\n addDialCode,\r\n removeDialCode,\r\n filterCountries,\n getPlaceholder,\n validatePhoneNumber,\n} from './utils';\n\r\nfunction countDigitsBeforePosition(value: string, position: number) {\r\n return value.slice(0, position).replace(/\\D/g, '').length;\r\n}\r\n\r\nfunction getCaretPositionFromDigitCount(value: string, digitCount: number) {\r\n if (digitCount <= 0) {\r\n return value.startsWith('+') ? 1 : 0;\r\n }\r\n\r\n let seenDigits = 0;\r\n\r\n for (let index = 0; index < value.length; index += 1) {\r\n if (/\\d/.test(value[index])) {\r\n seenDigits += 1;\r\n if (seenDigits === digitCount) {\r\n return index + 1;\r\n }\r\n }\r\n }\r\n\r\n return value.length;\r\n}\r\n\r\nexport function usePhoneInput(\r\n options: PhoneInputOptions & {\r\n value?: string;\n defaultValue?: string;\n onChange?: (phone: string, country: Country | undefined) => void;\n onCountryChange?: (country: Country | undefined) => void;\n onBlur?: () => void;\n onFocus?: () => void;\n } = {}\n): UsePhoneInputReturn {\r\n const {\r\n value: controlledValue,\r\n defaultValue = '',\n onChange,\n onCountryChange,\n onBlur,\n onFocus,\n defaultCountry = 'US',\n preferredCountries,\n excludeCountries,\n excludedCountries,\n onlyCountries,\n allowedCountries,\n autoDetect,\n autoDetectCountry,\n formatOnType = true,\n includeDialCode = false,\n required = false,\n validator,\n locale,\n labels,\n } = options;\n const resolvedOnlyCountries = onlyCountries ?? allowedCountries;\n const resolvedExcludeCountries = excludeCountries ?? excludedCountries;\n const resolvedAutoDetect = autoDetect ?? autoDetectCountry ?? true;\n\r\n const isControlled = controlledValue !== undefined;\n const inputRef = useRef<HTMLInputElement>(null);\n const pendingCaretDigitIndexRef = useRef<number | null>(null);\n const previousDefaultCountryRef = useRef(defaultCountry);\n\r\n // Filter available countries\r\n const availableCountries = useMemo(() => {\r\n let filtered = countries;\r\n \r\n if (resolvedOnlyCountries?.length) {\n filtered = filtered.filter(c => resolvedOnlyCountries.includes(c.code));\n }\n \n if (resolvedExcludeCountries?.length) {\n filtered = filtered.filter(c => !resolvedExcludeCountries.includes(c.code));\n }\n \n return filtered;\n }, [resolvedOnlyCountries, resolvedExcludeCountries]);\n\r\n const localizedCountries = useMemo(\r\n () => localizeCountries(availableCountries, locale),\r\n [availableCountries, locale]\r\n );\r\n\r\n const resolvedLabels = useMemo(\r\n () => resolvePhoneInputLabels(locale, labels),\r\n [locale, labels]\r\n );\r\n\r\n // Initialize state\r\n const initialCountry = availableCountries.find((candidate) => candidate.code === defaultCountry) || availableCountries[0];\r\n const [internalPhone, setInternalPhone] = useState(defaultValue);\r\n const [country, setCountry] = useState<Country | undefined>(initialCountry);\r\n const [isOpen, setIsOpen] = useState(false);\r\n const [searchQuery, setSearchQuery] = useState('');\r\n\r\n // Current phone value\n const phone = isControlled ? controlledValue : internalPhone;\n\n const getOutputCountry = useCallback(\n (nextCountry: Country | undefined) => localizeCountry(nextCountry, locale),\n [locale]\n );\n\n useEffect(() => {\n const defaultCountryChanged = previousDefaultCountryRef.current !== defaultCountry;\n previousDefaultCountryRef.current = defaultCountry;\n const nextCountry = availableCountries.find((candidate) => candidate.code === defaultCountry) || availableCountries[0];\n const countryStillAvailable = country\n ? availableCountries.some((candidate) => candidate.code === country.code)\n : false;\n\n if (nextCountry && (defaultCountryChanged || !countryStillAvailable)) {\n setCountry(nextCountry);\n }\n }, [defaultCountry, availableCountries, country]);\n\r\n // Auto-detect country from phone\r\n useEffect(() => {\r\n if (resolvedAutoDetect && phone) {\n const detected = detectCountryFromPhone(phone);\n if (detected && availableCountries.some((candidate) => candidate.code === detected.code) && detected.code !== country?.code) {\n setCountry(detected);\n onCountryChange?.(getOutputCountry(detected));\n }\n }\n }, [availableCountries, resolvedAutoDetect, phone, country?.code, onCountryChange, getOutputCountry]);\n\r\n // Format phone number\r\n const formattedPhone = useMemo(() => {\r\n if (formatOnType) {\r\n return formatPhone(includeDialCode && phone.startsWith('+') ? removeDialCode(phone, country) : phone, country);\r\n }\r\n return includeDialCode && phone.startsWith('+') ? removeDialCode(phone, country) : phone;\r\n }, [formatOnType, includeDialCode, phone, country]);\r\n\r\n // Full phone with dial code\r\n const fullPhone = useMemo(() => {\r\n if (includeDialCode && country) {\r\n return addDialCode(phone, country);\r\n }\r\n return phone;\r\n }, [phone, country, includeDialCode]);\r\n\r\n // Validation\r\n const isValid = useMemo(\n () => validatePhone(phone, country, validator),\n [phone, country, validator]\n );\n\n const error = useMemo(\n () => validatePhoneNumber(phone, country, required).error,\n [phone, country, required]\n );\n\r\n const localizedCountry = useMemo(\r\n () => localizeCountry(country, locale),\r\n [country, locale]\r\n );\r\n\r\n // Filtered countries for dropdown\r\n const filteredCountries = useMemo(\r\n () => filterCountries(localizedCountries, searchQuery, preferredCountries),\r\n [localizedCountries, searchQuery, preferredCountries]\r\n );\r\n\r\n useLayoutEffect(() => {\n const nextDigitIndex = pendingCaretDigitIndexRef.current;\r\n const input = inputRef.current;\r\n\r\n if (nextDigitIndex === null || !input || typeof input.setSelectionRange !== 'function') {\r\n return;\r\n }\r\n\r\n if (typeof document !== 'undefined' && document.activeElement !== input) {\r\n return;\r\n }\r\n\r\n const caretPosition = getCaretPositionFromDigitCount(formattedPhone, nextDigitIndex);\r\n input.setSelectionRange(caretPosition, caretPosition);\r\n pendingCaretDigitIndexRef.current = null;\r\n }, [formattedPhone]);\r\n\r\n // Set phone handler\r\n const setPhone = useCallback(\r\n (newPhone: string) => {\r\n const unformatted = unformatPhone(newPhone);\r\n if (!isControlled) {\r\n setInternalPhone(unformatted);\r\n }\r\n onChange?.(\r\n includeDialCode ? addDialCode(unformatted, country) : unformatted,\r\n getOutputCountry(country)\r\n );\r\n },\r\n [isControlled, onChange, country, includeDialCode, getOutputCountry]\r\n );\r\n\r\n // Set country handler\r\n const setCountryByCode = useCallback(\r\n (code: string) => {\r\n const newCountry = getCountryByCode(code);\r\n if (newCountry) {\r\n setCountry(newCountry);\n onCountryChange?.(getOutputCountry(newCountry));\n onChange?.(\n includeDialCode ? addDialCode(phone, newCountry) : phone,\r\n getOutputCountry(newCountry)\r\n );\r\n }\r\n },\r\n [phone, onChange, onCountryChange, includeDialCode, getOutputCountry]\n );\n\r\n // Select country from dropdown\r\n const selectCountry = useCallback(\r\n (selectedCountry: Country) => {\r\n const rawCountry = getCountryByCode(selectedCountry.code) ?? selectedCountry;\n setCountry(rawCountry);\n setIsOpen(false);\n setSearchQuery('');\n onCountryChange?.(getOutputCountry(rawCountry));\n onChange?.(\n includeDialCode ? addDialCode(phone, rawCountry) : phone,\r\n getOutputCountry(rawCountry)\r\n );\r\n },\r\n [phone, onChange, onCountryChange, includeDialCode, getOutputCountry]\n );\n\r\n // Toggle dropdown\r\n const toggleDropdown = useCallback(() => {\r\n setIsOpen(prev => !prev);\r\n if (isOpen) {\r\n setSearchQuery('');\r\n }\r\n }, [isOpen]);\r\n\r\n // Open dropdown\r\n const openDropdown = useCallback(() => {\r\n setIsOpen(true);\r\n }, []);\r\n\r\n // Close dropdown\r\n const closeDropdown = useCallback(() => {\r\n setIsOpen(false);\r\n setSearchQuery('');\r\n }, []);\r\n\r\n // Clear input\r\n const clear = useCallback(() => {\r\n if (!isControlled) {\r\n setInternalPhone('');\r\n }\r\n onChange?.('', getOutputCountry(country));\r\n }, [isControlled, onChange, country, getOutputCountry]);\r\n\r\n // Handle input change\r\n const handleInputChange = useCallback(\r\n (event: React.ChangeEvent<HTMLInputElement>) => {\r\n const rawValue = event.target.value;\r\n const caretPosition = event.target.selectionStart ?? rawValue.length;\r\n const unformatted = rawValue.trim().startsWith('+') ? `+${rawValue.replace(/\\D/g, '')}` : unformatPhone(rawValue);\r\n pendingCaretDigitIndexRef.current = countDigitsBeforePosition(rawValue, caretPosition);\r\n setPhone(unformatted);\r\n },\r\n [setPhone]\r\n );\r\n\r\n // Handle focus\r\n const handleFocus = useCallback(() => {\r\n onFocus?.();\r\n }, [onFocus]);\r\n\r\n // Handle blur\r\n const handleBlur = useCallback(() => {\n onBlur?.();\n }, [onBlur]);\n\n const getCountryOptionProps = useCallback(\n (optionCountry: Country, index: number) => ({\n role: 'option' as const,\n 'aria-selected': optionCountry.code === country?.code,\n onClick: () => selectCountry(optionCountry),\n onKeyDown: (event: { key: string; preventDefault: () => void }) => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault();\n selectCountry(optionCountry);\n }\n if (event.key === 'Escape') {\n event.preventDefault();\n closeDropdown();\n }\n },\n tabIndex: index === 0 ? 0 : -1,\n }),\n [closeDropdown, country?.code, selectCountry]\n );\n\r\n return {\r\n // State\r\n phone,\n value: phone,\n fullPhone,\n country: localizedCountry,\n isValid,\n error,\n isOpen,\n searchQuery,\n labels: resolvedLabels,\n formattedValue: formattedPhone,\n // Actions\n setPhone,\n setValue: setPhone,\n setCountry: setCountryByCode,\n toggleDropdown,\n toggle: toggleDropdown,\n openDropdown,\n open: openDropdown,\n closeDropdown,\n close: closeDropdown,\n setSearchQuery,\r\n clear,\r\n // Props\r\n inputProps: {\r\n ref: inputRef,\r\n value: formattedPhone,\r\n onChange: handleInputChange,\r\n onFocus: handleFocus,\r\n onBlur: handleBlur,\r\n type: 'tel',\r\n inputMode: 'tel',\r\n autoComplete: 'tel',\r\n placeholder: getPlaceholder(country),\r\n 'aria-invalid': phone ? !isValid : undefined,\r\n },\r\n countryButtonProps: {\n onClick: toggleDropdown,\n 'aria-expanded': isOpen,\n 'aria-haspopup': 'listbox',\n 'aria-label': resolvedLabels.countryButtonAriaLabel,\n },\n countrySelectorProps: {\n onClick: toggleDropdown,\n 'aria-expanded': isOpen,\n 'aria-haspopup': true,\n 'aria-label': resolvedLabels.countryButtonAriaLabel,\n },\n dropdownProps: {\n role: 'listbox',\n 'aria-label': resolvedLabels.countryOptionsAriaLabel,\n },\n filteredCountries,\n countries: filteredCountries,\n selectCountry,\n getCountryOptionProps,\n };\n}\n","import { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useRef, useState, type MutableRefObject, type Ref } from 'react';\nimport { usePhoneInput } from './usePhoneInput';\nimport type { PhoneInputProps } from './types';\nimport type { Country } from './countries';\nimport { getCountryDisplayName } from './utils';\n\n// SVG Icon Components (Lucide-style)\nconst ChevronUpIcon = ({ size = 12 }: { size?: number }) => (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <polyline points=\"18 15 12 9 6 15\" />\n </svg>\n);\n\nconst ChevronDownIcon = ({ size = 12 }: { size?: number }) => (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <polyline points=\"6 9 12 15 18 9\" />\n </svg>\n);\n\nexport interface PhoneInputRef {\n /** Focus the input */\n focus: () => void;\n /** Blur the input */\n blur: () => void;\n /** Clear the input */\n clear: () => void;\n /** Set country */\n setCountry: (countryCode: string) => void;\n /** Get current country */\n getCountry: () => Country | undefined;\n /** Open country selector */\n open: () => void;\n /** Close country selector */\n close: () => void;\n}\n\n/**\n * PhoneInput component - headless phone input with country selection\n * \n * @example\n * ```tsx\n * <PhoneInput\n * value={value}\n * onChange={setValue}\n * defaultCountry=\"US\"\n * />\n * ```\n * \n * @example\n * ```tsx\n * // With custom styling\n * <PhoneInput\n * value={value}\n * onChange={setValue}\n * defaultCountry=\"GB\"\n * containerClassName=\"phone-input-container\"\n * inputClassName=\"phone-input\"\n * selectorClassName=\"country-selector\"\n * />\n * ```\n */\nexport const PhoneInput = forwardRef<PhoneInputRef, PhoneInputProps>(\n function PhoneInput(props, ref) {\n const {\n value,\n defaultValue,\n onChange,\n onBlur,\n onFocus,\n inputClassName,\n selectorClassName,\n containerClassName,\n searchable = true,\n placeholder,\n disabled,\n readOnly,\n name,\n id,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n ...options\n } = props;\n\n const inputRef = useRef<HTMLInputElement | null>(null);\n const optionRefs = useRef<Array<HTMLLIElement | null>>([]);\n const [highlightedIndex, setHighlightedIndex] = useState(0);\n const listboxId = useId();\n\n const {\n inputProps,\n countryButtonProps,\n country,\n filteredCountries,\n isOpen,\n isValid,\n searchQuery,\n setSearchQuery,\n setCountry,\n selectCountry,\n clear,\n openDropdown,\n closeDropdown,\n labels,\n } = usePhoneInput({\n value,\n defaultValue,\n onChange,\n onBlur,\n onFocus,\n ...options,\n });\n\n const hookInputRef = (inputProps as typeof inputProps & { ref?: Ref<HTMLInputElement> }).ref;\n const mergedInputRef = useCallback((element: HTMLInputElement | null) => {\n inputRef.current = element;\n\n if (typeof hookInputRef === 'function') {\n hookInputRef(element);\n } else if (hookInputRef && 'current' in hookInputRef) {\n (hookInputRef as MutableRefObject<HTMLInputElement | null>).current = element;\n }\n }, [hookInputRef]);\n\n // Focus the input\n const focus = useCallback(() => {\n inputRef.current?.focus();\n }, []);\n\n // Blur the input\n const blur = useCallback(() => {\n inputRef.current?.blur();\n }, []);\n\n // Handle country option click\n const handleCountryClick = useCallback((c: Country) => {\n selectCountry(c);\n setHighlightedIndex(0);\n }, [selectCountry]);\n\n // Handle country option keyboard navigation\n const handleCountryKeyDown = useCallback((e: React.KeyboardEvent, c: Country, index: number) => {\n switch (e.key) {\n case 'Enter':\n case ' ':\n e.preventDefault();\n selectCountry(c);\n setHighlightedIndex(0);\n break;\n case 'ArrowDown':\n e.preventDefault();\n if (index < filteredCountries.length - 1) {\n const nextIndex = index + 1;\n setHighlightedIndex(nextIndex);\n optionRefs.current[nextIndex]?.focus();\n }\n break;\n case 'ArrowUp':\n e.preventDefault();\n if (index > 0) {\n const nextIndex = index - 1;\n setHighlightedIndex(nextIndex);\n optionRefs.current[nextIndex]?.focus();\n }\n break;\n case 'Escape':\n e.preventDefault();\n closeDropdown();\n break;\n }\n }, [selectCountry, filteredCountries.length, closeDropdown]);\n\n useEffect(() => {\n if (filteredCountries.length === 0) {\n if (highlightedIndex !== 0) {\n setHighlightedIndex(0);\n }\n return;\n }\n\n if (highlightedIndex >= filteredCountries.length) {\n setHighlightedIndex(filteredCountries.length - 1);\n }\n }, [filteredCountries.length, highlightedIndex]);\n\n // Expose imperative methods\n useImperativeHandle(ref, () => ({\n focus,\n blur,\n clear,\n setCountry,\n getCountry: () => country,\n open: openDropdown,\n close: closeDropdown,\n }));\n\n // Render default UI\n return (\n <div className={containerClassName} data-valid={isValid}>\n {/* Country Selector Button */}\n <button\n {...countryButtonProps}\n type=\"button\"\n className={selectorClassName}\n disabled={disabled}\n tabIndex={disabled ? -1 : 0}\n aria-controls={listboxId}\n >\n {country ? (\n <>\n <span className=\"phone-input-flag\">{country.flag}</span>\n <span className=\"phone-input-dial-code\">{country.dialCode}</span>\n </>\n ) : (\n <span className=\"phone-input-placeholder\">{labels.selectCountry}</span>\n )}\n <span className=\"phone-input-arrow\" aria-hidden=\"true\">\n {isOpen ? <ChevronUpIcon size={12} /> : <ChevronDownIcon size={12} />}\n </span>\n </button>\n\n {/* Phone Input */}\n <input\n {...inputProps}\n ref={mergedInputRef}\n id={id}\n name={name}\n className={inputClassName}\n placeholder={placeholder || inputProps.placeholder}\n disabled={disabled}\n readOnly={readOnly}\n aria-label={ariaLabel}\n aria-labelledby={ariaLabelledBy}\n />\n\n {/* Country Dropdown */}\n {isOpen && (\n <div className=\"phone-input-dropdown\">\n {/* Search Input */}\n {searchable && (\n <div className=\"phone-input-search\">\n <input\n type=\"text\"\n value={searchQuery}\n onChange={(e) => setSearchQuery(e.target.value)}\n placeholder={labels.countrySearchPlaceholder}\n autoFocus\n aria-controls={listboxId}\n aria-label={labels.searchCountriesAriaLabel}\n />\n </div>\n )}\n\n {/* Country List */}\n <ul className=\"phone-input-country-list\" id={listboxId} role=\"listbox\" aria-label={labels.countryOptionsAriaLabel}>\n {filteredCountries.map((c, index) => (\n <li\n key={c.code}\n ref={(element) => {\n optionRefs.current[index] = element;\n }}\n role=\"option\"\n aria-selected={c.code === country?.code}\n className={`phone-input-country-option ${\n c.code === country?.code ? 'selected' : ''\n } ${index === highlightedIndex ? 'highlighted' : ''}`}\n onClick={() => handleCountryClick(c)}\n onKeyDown={(e) => handleCountryKeyDown(e, c, index)}\n onMouseEnter={() => setHighlightedIndex(index)}\n tabIndex={index === highlightedIndex ? 0 : -1}\n >\n <span className=\"phone-input-flag\">{c.flag}</span>\n <span className=\"phone-input-country-name\">{getCountryDisplayName(c)}</span>\n <span className=\"phone-input-dial-code\">{c.dialCode}</span>\n </li>\n ))}\n {filteredCountries.length === 0 && (\n <li className=\"phone-input-no-results\">{labels.noCountriesFound}</li>\n )}\n </ul>\n </div>\n )}\n </div>\n );\n }\n);\n\nexport default PhoneInput;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@input-kit/phone",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Headless phone input with full world country codes, libphonenumber formatting, and TypeScript",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -44,15 +44,6 @@
44
44
  ],
45
45
  "author": "Harshit",
46
46
  "license": "MIT",
47
- "repository": {
48
- "type": "git",
49
- "url": "git+https://github.com/yourusername/input-kit.git",
50
- "directory": "packages/phone"
51
- },
52
- "bugs": {
53
- "url": "https://github.com/yourusername/input-kit/issues"
54
- },
55
- "homepage": "https://github.com/yourusername/input-kit/tree/main/packages/phone#readme",
56
47
  "engines": {
57
48
  "node": ">=18.0.0"
58
49
  },