1/* 2 * International Telephone Input v19.5.7 3 * https://github.com/jackocnr/intl-tel-input.git 4 * Licensed under the MIT license 5 */ 6 7// wrap in UMD 8(function(factory) { 9 if (typeof module === "object" && module.exports) module.exports = factory(); else window.intlTelInput = factory(); 10})(function(undefined) { 11 "use strict"; 12 return function() { 13 // Array of country objects for the flag dropdown. 14 // Here is the criteria for the plugin to support a given country/territory 15 // - It has an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 16 // - It has it's own country calling code (it is not a sub-region of another country): https://en.wikipedia.org/wiki/List_of_country_calling_codes 17 // - It has a flag in the region-flags project: https://github.com/behdad/region-flags/tree/gh-pages/png 18 // - It is supported by libphonenumber (it must be listed on this page): https://github.com/googlei18n/libphonenumber/blob/master/resources/ShortNumberMetadata.xml 19 // Each country array has the following information: 20 // [ 21 // Country name, 22 // iso2 code, 23 // International dial code, 24 // Order (if >1 country with same dial code), 25 // Area codes 26 // ] 27 var allCountries = [ [ "Afghanistan", "af", "93" ], [ "Albania", "al", "355" ], [ "Algeria", "dz", "213" ], [ "American Samoa", "as", "1", 5, [ "684" ] ], [ "Andorra", "ad", "376" ], [ "Angola", "ao", "244" ], [ "Anguilla", "ai", "1", 6, [ "264" ] ], [ "Antigua & Barbuda", "ag", "1", 7, [ "268" ] ], [ "Argentina", "ar", "54" ], [ "Armenia", "am", "374" ], [ "Aruba", "aw", "297" ], [ "Ascension Island", "ac", "247" ], [ "Australia", "au", "61", 0 ], [ "Austria", "at", "43" ], [ "Azerbaijan", "az", "994" ], [ "Bahamas", "bs", "1", 8, [ "242" ] ], [ "Bahrain", "bh", "973" ], [ "Bangladesh", "bd", "880" ], [ "Barbados", "bb", "1", 9, [ "246" ] ], [ "Belarus", "by", "375" ], [ "Belgium", "be", "32" ], [ "Belize", "bz", "501" ], [ "Benin", "bj", "229" ], [ "Bermuda", "bm", "1", 10, [ "441" ] ], [ "Bhutan", "bt", "975" ], [ "Bolivia", "bo", "591" ], [ "Bosnia & Herzegovina", "ba", "387" ], [ "Botswana", "bw", "267" ], [ "Brazil", "br", "55" ], [ "British Indian Ocean Territory", "io", "246" ], [ "British Virgin Islands", "vg", "1", 11, [ "284" ] ], [ "Brunei", "bn", "673" ], [ "Bulgaria", "bg", "359" ], [ "Burkina Faso", "bf", "226" ], [ "Burundi", "bi", "257" ], [ "Cambodia", "kh", "855" ], [ "Cameroon", "cm", "237" ], [ "Canada", "ca", "1", 1, [ "204", "226", "236", "249", "250", "263", "289", "306", "343", "354", "365", "367", "368", "382", "387", "403", "416", "418", "428", "431", "437", "438", "450", "584", "468", "474", "506", "514", "519", "548", "579", "581", "584", "587", "604", "613", "639", "647", "672", "683", "705", "709", "742", "753", "778", "780", "782", "807", "819", "825", "867", "873", "902", "905" ] ], [ "Cape Verde", "cv", "238" ], [ "Caribbean Netherlands", "bq", "599", 1, [ "3", "4", "7" ] ], [ "Cayman Islands", "ky", "1", 12, [ "345" ] ], [ "Central African Republic", "cf", "236" ], [ "Chad", "td", "235" ], [ "Chile", "cl", "56" ], [ "China", "cn", "86" ], [ "Christmas Island", "cx", "61", 2, [ "89164" ] ], [ "Cocos (Keeling) Islands", "cc", "61", 1, [ "89162" ] ], [ "Colombia", "co", "57" ], [ "Comoros", "km", "269" ], [ "Congo - Brazzaville", "cg", "242" ], [ "Congo - Kinshasa", "cd", "243" ], [ "Cook Islands", "ck", "682" ], [ "Costa Rica", "cr", "506" ], [ "Côte dâIvoire", "ci", "225" ], [ "Croatia", "hr", "385" ], [ "Cuba", "cu", "53" ], [ "Curaçao", "cw", "599", 0 ], [ "Cyprus", "cy", "357" ], [ "Czech Republic", "cz", "420" ], [ "Denmark", "dk", "45" ], [ "Djibouti", "dj", "253" ], [ "Dominica", "dm", "1", 13, [ "767" ] ], [ "Dominican Republic", "do", "1", 2, [ "809", "829", "849" ] ], [ "Ecuador", "ec", "593" ], [ "Egypt", "eg", "20" ], [ "El Salvador", "sv", "503" ], [ "Equatorial Guinea", "gq", "240" ], [ "Eritrea", "er", "291" ], [ "Estonia", "ee", "372" ], [ "Eswatini", "sz", "268" ], [ "Ethiopia", "et", "251" ], [ "Falkland Islands", "fk", "500" ], [ "Faroe Islands", "fo", "298" ], [ "Fiji", "fj", "679" ], [ "Finland", "fi", "358", 0 ], [ "France", "fr", "33" ], [ "French Guiana", "gf", "594" ], [ "French Polynesia", "pf", "689" ], [ "Gabon", "ga", "241" ], [ "Gambia", "gm", "220" ], [ "Georgia", "ge", "995" ], [ "Germany", "de", "49" ], [ "Ghana", "gh", "233" ], [ "Gibraltar", "gi", "350" ], [ "Greece", "gr", "30" ], [ "Greenland", "gl", "299" ], [ "Grenada", "gd", "1", 14, [ "473" ] ], [ "Guadeloupe", "gp", "590", 0 ], [ "Guam", "gu", "1", 15, [ "671" ] ], [ "Guatemala", "gt", "502" ], [ "Guer
27nsey", "gg", "44", 1, [ "1481", "7781", "7839", "7911" ] ], [ "Guinea", "gn", "224" ], [ "Guinea-Bissau", "gw", "245" ], [ "Guyana", "gy", "592" ], [ "Haiti", "ht", "509" ], [ "Honduras", "hn", "504" ], [ "Hong Kong", "hk", "852" ], [ "Hungary", "hu", "36" ], [ "Iceland", "is", "354" ], [ "India", "in", "91" ], [ "Indonesia", "id", "62" ], [ "Iran", "ir", "98" ], [ "Iraq", "iq", "964" ], [ "Ireland", "ie", "353" ], [ "Isle of Man", "im", "44", 2, [ "1624", "74576", "7524", "7924", "7624" ] ], [ "Israel", "il", "972" ], [ "Italy", "it", "39", 0 ], [ "Jamaica", "jm", "1", 4, [ "876", "658" ] ], [ "Japan", "jp", "81" ], [ "Jersey", "je", "44", 3, [ "1534", "7509", "7700", "7797", "7829", "7937" ] ], [ "Jordan", "jo", "962" ], [ "Kazakhstan", "kz", "7", 1, [ "33", "7" ] ], [ "Kenya", "ke", "254" ], [ "Kiribati", "ki", "686" ], [ "Kosovo", "xk", "383" ], [ "Kuwait", "kw", "965" ], [ "Kyrgyzstan", "kg", "996" ], [ "Laos", "la", "856" ], [ "Latvia", "lv", "371" ], [ "Lebanon", "lb", "961" ], [ "Lesotho", "ls", "266" ], [ "Liberia", "lr", "231" ], [ "Libya", "ly", "218" ], [ "Liechtenstein", "li", "423" ], [ "Lithuania", "lt", "370" ], [ "Luxembourg", "lu", "352" ], [ "Macau", "mo", "853" ], [ "Madagascar", "mg", "261" ], [ "Malawi", "mw", "265" ], [ "Malaysia", "my", "60" ], [ "Maldives", "mv", "960" ], [ "Mali", "ml", "223" ], [ "Malta", "mt", "356" ], [ "Marshall Islands", "mh", "692" ], [ "Martinique", "mq", "596" ], [ "Mauritania", "mr", "222" ], [ "Mauritius", "mu", "230" ], [ "Mayotte", "yt", "262", 1, [ "269", "639" ] ], [ "Mexico", "mx", "52" ], [ "Micronesia", "fm", "691" ], [ "Moldova", "md", "373" ], [ "Monaco", "mc", "377" ], [ "Mongolia", "mn", "976" ], [ "Montenegro", "me", "382" ], [ "Montserrat", "ms", "1", 16, [ "664" ] ], [ "Morocco", "ma", "212", 0 ], [ "Mozambique", "mz", "258" ], [ "Myanmar (Burma)", "mm", "95" ], [ "Namibia", "na", "264" ], [ "Nauru", "nr", "674" ], [ "Nepal", "np", "977" ], [ "Netherlands", "nl", "31" ], [ "New Caledonia", "nc", "687" ], [ "New Zealand", "nz", "64" ], [ "Nicaragua", "ni", "505" ], [ "Niger", "ne", "227" ], [ "Nigeria", "ng", "234" ], [ "Niue", "nu", "683" ], [ "Norfolk Island", "nf", "672" ], [ "North Korea", "kp", "850" ], [ "North Macedonia", "mk", "389" ], [ "Northern Mariana Islands", "mp", "1", 17, [ "670" ] ], [ "Norway", "no", "47", 0 ], [ "Oman", "om", "968" ], [ "Pakistan", "pk", "92" ], [ "Palau", "pw", "680" ], [ "Palestine", "ps", "970" ], [ "Panama", "pa", "507" ], [ "Papua New Guinea", "pg", "675" ], [ "Paraguay", "py", "595" ], [ "Peru", "pe", "51" ], [ "Philippines", "ph", "63" ], [ "Poland", "pl", "48" ], [ "Portugal", "pt", "351" ], [ "Puerto Rico", "pr", "1", 3, [ "787", "939" ] ], [ "Qatar", "qa", "974" ], [ "Réunion", "re", "262", 0 ], [ "Romania", "ro", "40" ], [ "Russia", "ru", "7", 0 ], [ "Rwanda", "rw", "250" ], [ "Samoa", "ws", "685" ], [ "San Marino", "sm", "378" ], [ "São Tomé & PrÃncipe", "st", "239" ], [ "Saudi Arabia", "sa", "966" ], [ "Senegal", "sn", "221" ], [ "Serbia", "rs", "381" ], [ "Seychelles", "sc", "248" ], [ "Sierra Leone", "sl", "232" ], [ "Singapore", "sg", "65" ], [ "Sint Maarten", "sx", "1", 21, [ "721" ] ], [ "Slovakia", "sk", "421" ], [ "Slovenia", "si", "386" ], [ "Solomon Islands", "sb", "677" ], [ "Somalia", "so", "252" ], [ "South Africa", "za", "27" ], [ "South Korea", "kr", "82" ], [ "South Sudan", "ss", "211" ], [ "Spain", "es", "34" ], [ "Sri Lanka", "lk", "94" ], [ "St Barthélemy", "bl", "590", 1 ], [ "St Helena", "sh", "290" ], [ "St Kitts & Nevis", "kn", "1", 18, [ "869" ] ], [ "St Lucia", "lc", "1", 19, [ "758" ] ], [ "St Martin", "mf", "590", 2 ], [ "St Pierre & Miquelon", "pm", "508" ], [ "St Vincent & Grenadines", "vc", "1", 20, [ "784" ] ], [ "Sudan", "sd", "249" ], [ "Suriname", "sr", "597" ], [ "Svalbard & Jan Mayen", "sj", "47", 1, [ "79" ] ], [ "Sweden", "se", "46" ], [ "Switzerland", "ch", "41" ], [ "Syria", "sy", "963" ], [ "Taiwan", "tw", "886" ], [ "Tajikistan", "tj", "992" ], [ "Tanzania", "tz", "255" ], [ "Thailand", "th", "66" ], [ "Timor-Leste", "tl", "670" ], [ "Togo", "tg", "228" ], [ "Tokelau", "tk", "690" ], [ "Tonga", "to", "676" ], [ "Trinidad & Tobago", "tt", "1", 22, [ "868" ] ], [ "Tunisia", "tn", "216" ], [ "Turkey", "tr", "90" ], [ "Turkmenistan", "tm", "993" ], [ "Turks & Caicos Islands", "tc", "1", 23, [ "649" ] ], [ "Tuvalu", "tv", "688" ], [ "Uganda", "ug", "256" ], [ "Ukraine", "ua", "380" ], [ "United Arab Emirates", "ae", "971" ], [ "United Kingdom", "gb", "44", 0 ], [ "United States", "us", "1", 0 ], [ "Uruguay", "uy", "598" ], [ "US Virgin Islands", "vi", "1", 24, [ "340" ] ], [ "Uzbekistan", "uz", "998" ], [ "Vanuatu", "vu", "678" ], [ "Vatican City", "va", "39", 1, [ "06698" ] ], [ "Venezuela", "ve", "58" ], [ "Vietnam", "vn", "84" ], [ "Wallis & Futuna", "wf", "681" ], [ "Western Sahara", "eh", "212", 1, [ "5288", "5289" ] ], [ "Yemen", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ], [ "à land Islands", "ax", "358", 1, [ "18" ] ] ]; 28 // loop over all of the countries above, restructuring the data to be objects with named keys 29 for (var i = 0; i < allCountries.length; i++) { 30 var c = allCountries[i]; 31 allCountries[i] = { 32 name: c[0], 33 iso2: c[1], 34 dialCode: c[2], 35 priority: c[3] || 0, 36 areaCodes: c[4] || null, 37 nodeById: {} 38 }; 39 } 40 "use strict"; 41 function _objectSpread(target) { 42 for (var i = 1; i < arguments.length; i++) { 43 var source = arguments[i] != null ? Object(arguments[i]) : {}; 44 var ownKeys = Object.keys(source); 45 if (typeof Object.getOwnPropertySymbols === "function") { 46 ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function(sym) { 47 return Object.getOwnPropertyDescriptor(source, sym).enumerable; 48 })); 49 } 50 ownKeys.forEach(function(key) { 51 _defineProperty(target, key, source[key]); 52 }); 53 } 54 return target; 55 } 56 function _defineProperty(obj, key, value) { 57 key = _toPropertyKey(key); 58 if (key in obj) { 59 Object.defineProperty(obj, key, { 60 value: value, 61 enumerable: true, 62 configurable: true, 63 writable: true 64 }); 65 } else { 66 obj[key] = value; 67 } 68 return obj; 69 } 70 function _slicedToArray(arr, i) { 71 return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); 72 } 73 function _nonIterableRest() {
74 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); 75 } 76 function _unsupportedIterableToArray(o, minLen) { 77 if (!o) return; 78 if (typeof o === "string") return _arrayLikeToArray(o, minLen); 79 var n = Object.prototype.toString.call(o).slice(8, -1); 80 if (n === "Object" && o.constructor) n = o.constructor.name; 81 if (n === "Map" || n === "Set") return Array.from(o); 82 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); 83 } 84 function _arrayLikeToArray(arr, len) { 85 if (len == null || len > arr.length) len = arr.length; 86 for (var i = 0, arr2 = new Array(len); i < len; i++) { 87 arr2[i] = arr[i]; 88 } 89 return arr2; 90 } 91 function _iterableToArrayLimit(arr, i) { 92 var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; 93 if (null != _i) { 94 var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; 95 try { 96 if (_x = (_i = _i.call(arr)).next, 0 === i) { 97 if (Object(_i) !== _i) return; 98 _n = !1; 99 } else for (;!(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0) { 100 } 101 } catch (err) { 102 _d = !0, _e = err; 103 } finally { 104 try { 105 if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; 106 } finally { 107 if (_d) throw _e; 108 } 109 } 110 return _arr; 111 } 112 } 113 function _arrayWithHoles(arr) { 114 if (Array.isArray(arr)) return arr; 115 } 116 function _classCallCheck(instance, Constructor) { 117 if (!(instance instanceof Constructor)) { 118 throw new TypeError("Cannot call a class as a function"); 119 } 120 } 121 function _defineProperties(target, props) { 122 for (var i = 0; i < props.length; i++) { 123 var descriptor = props[i]; 124 descriptor.enumerable = descriptor.enumerable || false; 125 descriptor.configurable = true; 126 if ("value" in descriptor) descriptor.writable = true; 127 Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); 128 } 129 } 130 function _createClass(Constructor, protoProps, staticProps) { 131 if (protoProps) _defineProperties(Constructor.prototype, protoProps); 132 if (staticProps) _defineProperties(Constructor, staticProps); 133 Object.defineProperty(Constructor, "prototype", { 134 writable: false 135 }); 136 return Constructor; 137 } 138 function _toPropertyKey(arg) { 139 var key = _toPrimitive(arg, "string"); 140 return typeof key === "symbol" ? key : String(key); 141 } 142 function _toPrimitive(input, hint) { 143 if (typeof input !== "object" || input === null) return input; 144 var prim = input[Symbol.toPrimitive]; 145 if (prim !== undefined) { 146 var res = prim.call(input, hint || "default"); 147 if (typeof res !== "object") return res; 148 throw new TypeError("@@toPrimitive must return a primitive value."); 149 } 150 return (hint === "string" ? String : Number)(input); 151 } 152 var intlTelInputGlobals = { 153 getInstance: function getInstance(input) { 154 var id = input.getAttribute("data-intl-tel-input-id"); 155 return window.intlTelInputGlobals.instances[id]; 156 }, 157 instances: {}, 158 // using a global like this allows us to mock it in the tests 159 documentReady: function documentReady() { 160 return document.readyState === "complete"; 161 } 162 }; 163 if (typeof window === "object") { 164 window.intlTelInputGlobals = intlTelInputGlobals; 165 } 166 // these vars persist through all instances of the plugin 167 var id = 0; 168 var defaults = { 169 // whether or not to allow the dropdown 170 allowDropdown: true, 171 // auto insert dial code (A) on init, (B) on user selecting a country, (C) on calling setCountry 172 autoInsertDialCode: false, 173 // add a placeholder in the input with an example number for the selected country 174 autoPlaceholder: "polite", 175 // add a country search input at the top of the dropdown 176 countrySearch: true, 177 // modify the parentClass 178 containerClass: "", 179 // modify the auto placeholder 180 customPlaceholder: null, 181 // by default, initialise with the first country in the list selected (if no country set via the initial value or initialCountry option) 182 defaultToFirstCountry: true, 183 // append menu to specified element 184 dropdownContainer: null, 185 // don't display these countries 186 excludeCountries: [], 187 // fix the dropdown width to the input width (rather than being as wide as the longest country name) 188 fixDropdownWidth: true, 189 // format the number as the user types 190 formatAsYouType: true, 191 // format the input value during initialisation and on setNumber 192 formatOnDisplay: true, 193 // geoIp lookup function 194 geoIpLookup: null, 195 // inject a hidden input with this name, and on submit, populate it with the result of getNumber 196 hiddenInput: null, 197 // internationalise the plugin text e.g. search input placeholder, country names 198 i18n: {}, 199 // initial country 200 initialCountry: "", 201 // national vs international formatting for numbers e.g. placeholders and displaying existing numbers 202 nationalMode: true, 203 // display only these countries 204 onlyCountries: [], 205 // number type to use for placeholders 206 placeholderNumberType: "MOBILE", 207 // the countries at the top of the list 208 preferredCountries: [], 209 // option to hide the flags - must be used with showSelectedDialCode, or allowDropdown=false 210 showFlags: true, 211 // display the international dial code next to the selected flag 212 showSelectedDialCode: false,
213 // use full screen popup instead of dropdown for country list 214 useFullscreenPopup: typeof navigator !== "undefined" && typeof window !== "undefined" ? // we cannot just test screen size as some smartphones/website meta tags will report desktop 215 // resolutions 216 // Note: to target Android Mobiles (and not Tablets), we must find 'Android' and 'Mobile' 217 /Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 500 : false, 218 // specify the path to the libphonenumber script to enable validation/formatting 219 utilsScript: "" 220 }; 221 // https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes#Non-geographic_area_codes 222 var regionlessNanpNumbers = [ "800", "822", "833", "844", "855", "866", "877", "880", "881", "882", "883", "884", "885", "886", "887", "888", "889" ]; 223 // run a method on each instance of the plugin 224 var forEachInstance = function forEachInstance(method) { 225 var instances = window.intlTelInputGlobals.instances; 226 Object.values(instances).forEach(function(instance) { 227 return instance[method](); 228 }); 229 }; 230 // this is our plugin class that we will create an instance of 231 // eslint-disable-next-line no-unused-vars 232 var Iti = /*#__PURE__*/ function() { 233 function Iti(input) { 234 var customOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 235 _classCallCheck(this, Iti); 236 this.id = id++; 237 this.telInput = input; 238 this.activeItem = null; 239 this.highlightedItem = null; 240 // process specified options / defaults 241 this.options = Object.assign({}, defaults, customOptions); 242 this.hadInitialPlaceholder = Boolean(input.getAttribute("placeholder")); 243 } 244 _createClass(Iti, [ { 245 key: "_init", 246 value: function _init() { 247 var _this = this; 248 // if showing fullscreen popup, do not fix the width 249 if (this.options.useFullscreenPopup) { 250 this.options.fixDropdownWidth = false; 251 } 252 // when search enabled, we must fix the width else it would change with different results 253 if (this.options.countrySearch && !this.options.useFullscreenPopup) { 254 this.options.fixDropdownWidth = true; 255 } 256 // if in nationalMode, do not insert dial codes 257 if (this.options.nationalMode) { 258 this.options.autoInsertDialCode = false; 259 } 260 // if showSelectedDialCode enabled, do not insert dial codes 261 if (this.options.showSelectedDialCode) { 262 this.options.autoInsertDialCode = false; 263 } 264 // force showFlags=true if there's a dropdown and we're not displaying the dial code, 265 // as otherwise you just have a down arrow on it's own which doesn't make sense 266 var forceShowFlags = this.options.allowDropdown && !this.options.showSelectedDialCode; 267 if (!this.options.showFlags && forceShowFlags) { 268 this.options.showFlags = true; 269 } 270 // on mobile, we want a full screen dropdown, so we must append it to the body 271 if (this.options.useFullscreenPopup && !this.options.dropdownContainer) { 272 this.options.dropdownContainer = document.body; 273 } 274 // check if input has one parent with RTL 275 this.isRTL = !!this.telInput.closest("[dir=rtl]"); 276 // these promises get resolved when their individual requests complete 277 // this way the dev can do something like iti.promise.then(...) to know when all requests are 278 // complete 279 if (typeof Promise !== "undefined") { 280 var autoCountryPromise = new Promise(function(resolve, reject) { 281 _this.resolveAutoCountryPromise = resolve; 282 _this.rejectAutoCountryPromise = reject; 283 }); 284 var utilsScriptPromise = new Promise(function(resolve, reject) { 285 _this.resolveUtilsScriptPromise = resolve; 286 _this.rejectUtilsScriptPromise = reject; 287 }); 288 this.promise = Promise.all([ autoCountryPromise, utilsScriptPromise ]); 289 } else { 290 // prevent errors when Promise doesn't exist 291 this.resolveAutoCountryPromise = this.rejectAutoCountryPromise = function() {}; 292 this.resolveUtilsScriptPromise = this.rejectUtilsScriptPromise = function() {}; 293 } 294 // in various situations there could be no country selected initially, but we need to be able 295 // to assume this variable exists 296 this.selectedCountryData = {}; 297 // process all the data: onlyCountries, excludeCountries, preferredCountries etc 298 this._processCountryData(); 299 // generate the markup 300 this._generateMarkup(); 301 // set the initial state of the input value and the selected flag 302 this._setInitialState(); 303 // start all of the event listeners: autoInsertDialCode, input keydown, selectedFlag click 304 this._initListeners(); 305 // utils script, and auto country 306 this._initRequests(); 307 } 308 }, { 309 key: "_processCountryData", 310 value: function _processCountryData() { 311 // process onlyCountries or excludeCountries array if present 312 this._processAllCountries(); 313 // generate this.dialCodes and this.dialCodeToIso2Map 314 this._processDialCodes(); 315 // process the preferredCountries 316 this._processPreferredCountries(); 317 // translate country names according to i18n option 318 this._translateCountryNames(); 319 // sort countries by name 320 if (this.options.onlyCountries.length || this.options.i18n) { 321 this.countries.sort(this._countryNameSort); 322 } 323 } 324 }, { 325 key: "_addToDialCodeMap", 326 value: function _addToDialCodeMap(iso2, dialCode, priority) { 327 if (dialCode.length > this.dialCodeMaxLen) { 328 this.dialCodeMaxLen = dialCode.length; 329 } 330 if (!this.dialCodeToIso2Map.hasOwnProperty(dialCode)) { 331 this.dialCodeToIso2Map[dialCode] = []; 332 } 333 // bail if we already have this country for this dialCode 334 for (var i = 0; i < this.dialCodeToIso2Map[dialCode].length; i++) { 335 if (this.dialCodeToIso2Map[dialCode][i] === iso2) { 336 return; 337 } 338 } 339 // check for undefined as 0 is falsy 340 var index = priority !== undefined ? priority : this.dialCodeToIso2Map[dialCode].length; 341 this.dialCodeToIso2Map[dialCode][index] = iso2; 342 } 343 }, { 344 key: "_processAllCountries", 345 value: function _processAllCountries() { 346 if (this.options.onlyCountries.length) { 347 var lowerCaseOnlyCountries = this.options.onlyCountries.map(function(country) { 348 return country.toLowerCase(); 349 }); 350 this.countries = allCountries.filter(function(country) { 351 return lowerCaseOnlyCountries.indexOf(country.iso2) > -1; 352 }); 353 } else if (this.options.excludeCountries.length) { 354 var lowerCaseExcludeCountries = this.options.excludeCountries.map(function(country) { 355 return country.toLowerCase(); 356 }); 357 this.countries = allCountries.filter(function(country) { 358 return lowerCaseExcludeCountries.indexOf(country.iso2) === -1; 359 }); 360 } else { 361 this.countries = allCountries; 362 } 363 } 364 }, { 365 key: "_translateCountryNames", 366 value: function _translateCountryNames() { 367 for (var i = 0; i < this.countries.length; i++) { 368 var iso2 = this.countries[i].iso2.toLowerCase(); 369 if (this.options.i18n.hasOwnProperty(iso2)) { 370 this.countries[i].name = this.options.i18n[iso2]; 371 } 372 } 373 } 374 }, { 375 key: "_countryNameSort", 376 value: function _countryNameSort(a, b) { 377 if (a.name < b.name) { 378 return -1; 379 } 380 if (a.name > b.name) { 381 return 1; 382 } 383 return 0; 384 } 385 }, { 386 key: "_processDialCodes", 387 value: function _processDialCodes() { 388 // here we store just dial codes, where the key is the dial code, and the value is true 389 // e.g. { 1: true, 7: true, 20: true, ... } 390 this.dialCodes = {}; 391 this.dialCodeMaxLen = 0; 392 // here we map dialCodes (inc both dialCode and dialCode+areaCode) to iso2 codes 393 /* e.g. 394 * { 395 * 1: [ 'us', 'ca', ... ], # all NANP countries 396 * 12: [ 'us', 'ca', ... ], # subset of NANP countries 397 * 120: [ 'us', 'ca' ], # just US and Canada 398 * 1204: [ 'ca' ], # only Canada 399 * ... 400 * } 401 */ 402 this.dialCodeToIso2Map = {}; 403 // first: add dial codes 404 for (var i = 0; i < this.countries.length; i++) { 405 var c = this.countries[i]; 406 if (!this.dialCodes[c.dialCode]) { 407 this.dialCodes[c.dialCode] = true; 408 } 409 this._addToDialCodeMap(c.iso2, c.dialCode, c.priority); 410 } 411 // next: add area codes 412 // this is a second loop over countries, to make sure we have all of the "root" countries 413 // already in the map, so that we can access them, as each time we add an area code substring 414 // to the map, we also need to include the "root" country's code, as that also matches 415 for (var _i = 0; _i < this.countries.length; _i++) { 416 var _c = this.countries[_i]; 417 // area codes 418 if (_c.areaCodes) { 419 var rootIso2Code = this.dialCodeToIso2Map[_c.dialCode][0]; 420 // for each area code 421 for (var j = 0; j < _c.areaCodes.length; j++) { 422 var areaCode = _c.areaCodes[j]; 423 // for each digit in the area code to add all partial matches as well 424 for (var k = 1; k < areaCode.length; k++) { 425 var partialDialCode = _c.dialCode + areaCode.substr(0, k); 426 // start with the root country, as that also matches this dial code 427 this._addToDialCodeMap(rootIso2Code, partialDialCode); 428 this._addToDialCodeMap(_c.iso2, partialDialCode); 429 } 430 // add the full area code 431 this._addToDialCodeMap(_c.iso2, _c.dialCode + areaCode); 432 } 433 } 434 } 435 } 436 }, { 437 key: "_processPreferredCountries", 438 value: function _processPreferredCountries() { 439 this.preferredCountries = []; 440 for (var i = 0; i < this.options.preferredCountries.length; i++) { 441 var iso2 = this.options.preferredCountries[i].toLowerCase(); 442 var countryData = this._getCountryData(iso2, true); 443 if (countryData) { 444 this.preferredCountries.push(countryData); 445 } 446 } 447 } 448 }, { 449 key: "_createEl", 450 value: function _createEl(name, attrs, container) { 451 var el = document.createElement(name); 452 if (attrs) {
453 Object.entries(attrs).forEach(function(_ref) { 454 var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], value = _ref2[1]; 455 return el.setAttribute(key, value); 456 }); 457 } 458 if (container) { 459 container.appendChild(el); 460 } 461 return el; 462 } 463 }, { 464 key: "_generateMarkup", 465 value: function _generateMarkup() { 466 this.telInput.classList.add("iti__tel-input"); 467 // if autocomplete does not exist on the element and its form, then 468 // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can 469 // easily put the plugin in an inconsistent state e.g. the wrong flag selected for the 470 // autocompleted number, which on submit could mean wrong number is saved 471 if (!this.telInput.hasAttribute("autocomplete") && !(this.telInput.form && this.telInput.form.hasAttribute("autocomplete"))) { 472 this.telInput.setAttribute("autocomplete", "off"); 473 } 474 var _this$options = this.options, allowDropdown = _this$options.allowDropdown, showSelectedDialCode = _this$options.showSelectedDialCode, showFlags = _this$options.showFlags, containerClass = _this$options.containerClass, hiddenInput = _this$options.hiddenInput, dropdownContainer = _this$options.dropdownContainer, fixDropdownWidth = _this$options.fixDropdownWidth, useFullscreenPopup = _this$options.useFullscreenPopup, countrySearch = _this$options.countrySearch; 475 // containers (mostly for positioning) 476 var parentClass = "iti"; 477 if (allowDropdown) { 478 parentClass += " iti--allow-dropdown"; 479 } 480 if (showSelectedDialCode) { 481 parentClass += " iti--show-selected-dial-code"; 482 } 483 if (showFlags) { 484 parentClass += " iti--show-flags"; 485 } 486 if (containerClass) { 487 parentClass += " ".concat(containerClass); 488 } 489 if (!useFullscreenPopup) { 490 parentClass += " iti--inline-dropdown"; 491 } 492 var wrapper = this._createEl("div", { 493 "class": parentClass 494 }); 495 this.telInput.parentNode.insertBefore(wrapper, this.telInput); 496 // only hide the flagsContainer if allowDropdown, showFlags and showSelectedDialCode are all false 497 var showFlagsContainer = allowDropdown || showFlags || showSelectedDialCode; 498 if (showFlagsContainer) { 499 this.flagsContainer = this._createEl("div", { 500 "class": "iti__flag-container" 501 }, wrapper); 502 } 503 wrapper.appendChild(this.telInput); 504 // selected flag (displayed to left of input) 505 // using Aria tags for "Select-Only Combobox Example" 506 // https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-select-only/ 507 if (showFlagsContainer) { 508 this.selectedFlag = this._createEl("div", _objectSpread({ 509 "class": "iti__selected-flag" 510 }, allowDropdown && { 511 role: "combobox", 512 "aria-haspopup": "listbox", 513 "aria-controls": "iti-".concat(this.id, "__country-listbox"), 514 "aria-expanded": "false", 515 "aria-label": this.options.i18n.selectedCountryAriaLabel || "Selected country" 516 }), this.flagsContainer); 517 } 518 if (showFlags) { 519 this.selectedFlagInner = this._createEl("div", { 520 "class": "iti__flag" 521 }, this.selectedFlag); 522 } 523 if (this.selectedFlag && this.telInput.disabled) { 524 this.selectedFlag.setAttribute("aria-disabled", "true"); 525 } 526 if (showSelectedDialCode) { 527 this.selectedDialCode = this._createEl("div", { 528 "class": "iti__selected-dial-code" 529 }, this.selectedFlag); 530 } 531 if (allowDropdown) { 532 if (!this.telInput.disabled) { 533 // make element focusable and tab navigable 534 this.selectedFlag.setAttribute("tabindex", "0"); 535 } 536 this.dropdownArrow = this._createEl("div", { 537 "class": "iti__arrow" 538 }, this.selectedFlag);
539 var extraClasses = fixDropdownWidth ? "" : "iti--flexible-dropdown-width"; 540 this.dropdownContent = this._createEl("div", { 541 "class": "iti__dropdown-content iti__hide ".concat(extraClasses) 542 }); 543 if (countrySearch) { 544 this.searchInput = this._createEl("input", { 545 type: "text", 546 "class": "iti__search-input", 547 placeholder: this.options.i18n.searchPlaceholder || "Search" 548 }, this.dropdownContent); 549 } 550 // country list: preferred countries, then divider, then all countries 551 this.countryList = this._createEl("ul", { 552 "class": "iti__country-list", 553 id: "iti-".concat(this.id, "__country-listbox"), 554 role: "listbox", 555 "aria-label": this.options.i18n.countryListAriaLabel || "List of countries" 556 }, this.dropdownContent); 557 if (this.preferredCountries.length && !countrySearch) { 558 this._appendListItems(this.preferredCountries, "iti__preferred", true); 559 this._createEl("li", { 560 "class": "iti__divider", 561 "aria-hidden": "true" 562 }, this.countryList); 563 } 564 this._appendListItems(this.countries, "iti__standard"); 565 // create dropdownContainer markup 566 if (dropdownContainer) { 567 var dropdownClasses = "iti iti--container"; 568 if (useFullscreenPopup) { 569 dropdownClasses += " iti--fullscreen-popup"; 570 } else { 571 dropdownClasses += " iti--inline-dropdown"; 572 } 573 if (countrySearch) { 574 dropdownClasses += " iti--country-search"; 575 } 576 this.dropdown = this._createEl("div", { 577 "class": dropdownClasses 578 }); 579 this.dropdown.appendChild(this.dropdownContent); 580 } else { 581 this.flagsContainer.appendChild(this.dropdownContent); 582 } 583 } 584 if (hiddenInput) { 585 var telInputName = this.telInput.getAttribute("name"); 586 var result = hiddenInput(telInputName); 587 var isObject = result !== null && typeof result === "object"; 588 var hiddenInputPhoneName; 589 var hiddenInputCountryName; 590 if (isObject) { 591 hiddenInputPhoneName = result.phone || telInputName; 592 hiddenInputCountryName = result.country || "".concat(hiddenInputPhoneName, "_country"); 593 } else { 594 hiddenInputPhoneName = result || telInputName; 595 hiddenInputCountryName = "".concat(hiddenInputPhoneName, "_country"); 596 } 597 // Check if a name has been determined for the phone input field after all conditions 598 if (!hiddenInputPhoneName) { 599 return; 600 } 601 // Create hidden input for the full international number 602 this.hiddenInput = this._createEl("input", { 603 type: "hidden", 604 name: hiddenInputPhoneName 605 }); 606 // Create hidden input for the selected country iso2 code 607 this.hiddenInputCountry = this._createEl("input", { 608 type: "hidden", 609 name: hiddenInputCountryName 610 }); 611 wrapper.appendChild(this.hiddenInput); 612 wrapper.appendChild(this.hiddenInputCountry); 613 } 614 } 615 }, { 616 key: "_appendListItems", 617 value: function _appendListItems(countries, className, preferred) { 618 for (var i = 0; i < countries.length; i++) { 619 var c = countries[i]; 620 var idSuffix = preferred ? "-preferred" : ""; 621 var listItem = this._createEl("li", { 622 id: "iti-".concat(this.id, "__item-").concat(c.iso2).concat(idSuffix), 623 "class": "iti__country ".concat(className), 624 tabindex: "-1", 625 role: "option", 626 "data-dial-code": c.dialCode, 627 "data-country-code": c.iso2, 628 "aria-selected": "false" 629 }, this.countryList); 630 // store this for later use e.g. country search f
630iltering 631 c.nodeById[this.id] = listItem; 632 var content = ""; 633 // add the flag 634 if (this.options.showFlags) { 635 content += "<div class='iti__flag-box'><div class='iti__flag iti__".concat(c.iso2, "'></div></div>"); 636 } 637 // and the country name and dial code 638 content += "<span class='iti__country-name'>".concat(c.name, "</span>"); 639 content += "<span class='iti__dial-code'>+".concat(c.dialCode, "</span>"); 640 listItem.insertAdjacentHTML("beforeend", content); 641 } 642 } 643 }, { 644 key: "_setInitialState", 645 value: function _setInitialState() { 646 var overrideAutoCountry = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; 647 // fix firefox bug: when first load page (with input with value set to number with intl dial 648 // code) and initialising plugin removes the dial code from the input, then refresh page, 649 // and we try to init plugin again but this time on number without dial code so get grey flag 650 var attributeValue = this.telInput.getAttribute("value"); 651 var inputValue = this.telInput.value; 652 var useAttribute = attributeValue && attributeValue.charAt(0) === "+" && (!inputValue || inputValue.charAt(0) !== "+"); 653 var val = useAttribute ? attributeValue : inputValue; 654 var dialCode = this._getDialCode(val); 655 var isRegionlessNanp = this._isRegionlessNanp(val); 656 var _this$options2 = this.options, initialCountry = _this$options2.initialCountry, autoInsertDialCode = _this$options2.autoInsertDialCode, defaultToFirstCountry = _this$options2.defaultToFirstCountry; 657 // if we already have a dial code, and it's not a regionlessNanp, we can go ahead and set the 658 // flag, else fall back to the default country 659 if (dialCode && !isRegionlessNanp) { 660 this._updateFlagFromNumber(val); 661 } else if (initialCountry !== "auto" || overrideAutoCountry) { 662 var lowerInitialCountry = initialCountry ? initialCountry.toLowerCase() : ""; 663 var isValidInitialCountry = lowerInitialCountry && this._getCountryData(lowerInitialCountry, true); 664 // see if we should select a flag 665 if (isValidInitialCountry) { 666 this._setFlag(lowerInitialCountry); 667 } else { 668 if (dialCode && isRegionlessNanp) { 669 // has intl dial code, is regionless nanp, and no initialCountry, so default to US 670 this._setFlag("us"); 671 } else if (defaultToFirstCountry && !val) { 672 // no dial code and no initialCountry, so default to first in list 673 this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2; 674 this._setFlag(this.defaultCountry); 675 } else { 676 // display the empty state (globe icon) 677 this._setFlag(); 678 } 679 } 680 // if empty and autoInsertDialCode then insert the dial code 681 if (!val && autoInsertDialCode) { 682 this.telInput.value = "+".concat(this.selectedCountryData.dialCode); 683 } 684 } 685 // NOTE: if initialCountry is set to auto, that will be handled separately 686 // format - note this wont be run after _updateDialCode as that's only called
686if no val 687 if (val) { 688 this._updateValFromNumber(val); 689 } 690 } 691 }, { 692 key: "_initListeners", 693 value: function _initListeners() { 694 this._initKeyListeners(); 695 if (this.options.autoInsertDialCode) { 696 this._initBlurListeners(); 697 } 698 if (this.options.allowDropdown) { 699 this._initDropdownListeners(); 700 } 701 if (this.hiddenInput) { 702 this._initHiddenInputListener(); 703 } 704 } 705 }, { 706 key: "_initHiddenInputListener", 707 value: function _initHiddenInputListener() { 708 var _this2 = this; 709 this._handleHiddenInputSubmit = function() { 710 _this2.hiddenInput.value = _this2.getNumber(); 711 _this2.hiddenInputCountry.value = _this2.getSelectedCountryData().iso2; 712 }; 713 if (this.telInput.form) { 714 this.telInput.form.addEventListener("submit", this._handleHiddenInputSubmit); 715 } 716 } 717 }, { 718 key: "_initDropdownListeners", 719 value: function _initDropdownListeners() { 720 var _this3 = this; 721 // hack for input nested inside label (which is valid markup): clicking the selected-flag to 722 // open the dropdown would then automatically trigger a 2nd click on the input which would 723 // close it again 724 this._handleLabelClick = function(e) { 725 // if the dropdown is closed, then focus the input, else ignore the click 726 if (_this3.dropdownContent.classList.contains("iti__hide")) { 727 _this3.telInput.focus(); 728 } else { 729 e.preventDefault(); 730 } 731 }; 732 var label = this.telInput.closest("label"); 733 if (label) { 734 label.addEventListener("click", this._handleLabelClick); 735 } 736 // toggle country dropdown on click 737 this._handleClickSelectedFlag = function() { 738 // only intercept this event if we're opening the dropdown 739 // else let it bubble up to the top ("click-off-to-close" listener) 740 // we cannot just stopPropagation as it may be needed to close another instance 741 if (_this3.dropdownContent.classList.contains("iti__hide") && !_this3.telInput.disabled && !_this3.telInput.readOnly) { 742 _this3._showDropdown(); 743 } 744 }; 745 this.selectedFlag.addEventListener("click", this._handleClickSelectedFlag); 746 // open dropdown if selected flag is focused and they press up/down/space/enter 747 this._handleFlagsContainerKeydown = function(e) { 748 var isDropdownHidden = _this3.dropdownContent.classList.contains("iti__hide"); 749 if (isDropdownHidden && [ "ArrowUp", "ArrowDown", " ", "Enter" ].includes(e.key)) { 750 // prevent form from being submitted if "ENTER" was pressed 751 e.preventDefault(); 752 // prevent event from being handled again by document 753 e.stopPropagation(); 754 _this3._showDropdown(); 755 } 756 // allow navigation from dropdown to input on TAB 757 if (e.key === "Tab") { 758 _this3._closeDropdown(); 759 } 760 }; 761 this.flagsContainer.addEventListener("keydown", this._handleFlagsContainerKeydown); 762 } 763 }, { 764 key: "_initRequests", 765 value: function _initRequests() { 766 var _this4 = this; 767 // if the user has specified the path to the utils script, fetch it on window.load, else resolve 768 if (this.options.utilsScript && !window.intlTelInputUtils) { 769 // if the plugin is being initialised after the window.load event has already been fired 770 if (window.intlTelInputGlobals.documentReady()) { 771 window.intlTelInputGlobals.loadUtils(this.options.utilsScript); 772 } else { 773 // wait until the load event so we don't block any other requests e.g. the flags image 774 window.addEventListener("load", function() { 775 window.intlTelInputGlobals.loadUtils(_this4.options.utilsScript); 776 }); 777 } 778 } else { 779 this.resolveUtilsScriptPromise(); 780 } 781 // dont bother with IP lookup if we already have a selected country 782 if (this.options.initialCountry === "auto" && !this.selectedCountryData.iso2) { 783 this._loadAutoCountry(); 784 } else { 785 this.resolveAutoCountryPromise(); 786 } 787 } 788 }, { 789 key: "_loadAutoCountry", 790 value: function _loadAutoCountry() { 791 var _this5 = this; 792 // 3 options: 793 // 1) already loaded (we're done) 794 // 2) not already started loading (start) 795 // 3) already started loading (do nothing - just wait for loading callback to fire) 796 if (window.intlTelInputGlobals.autoCountry) { 797 this.handleAutoCountry(); 798 } else if (!window.intlTelInputGlobals.startedLoadingAutoCountry) { 799 // don't do this twice! 800 window.intlTelInputGlobals.startedLoadingAutoCountry = true; 801 if (typeof this.options.geoIpLookup === "function") { 802 this.options.geoIpLookup(function() { 803 var iso2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; 804 var iso2Lower = iso2.toLowerCase(); 805 var isValidIso2 = iso2Lower && _this5._getCountryData(iso2Lower, true); 806 if (isValidIso2) { 807 window.intlTelInputGlobals.autoCountry = iso2Lower; 808 // tell all instances the auto country is ready 809 // TODO: this should just be the current instances 810 // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight 811 // away (e.g. if they have already done the geo ip lookup somewhere else). Using 812 // setTimeout means that the current thread of execution will finish before executing 813 // this, which allows the plugin to finish initialising. 814 setTimeout(function() { 815 return forEachInstance("handleAutoCountry"); 816 }); 817 } else { 818 _this5._setInitialState(true);
819 forEachInstance("rejectAutoCountryPromise"); 820 } 821 }, function() { 822 return forEachInstance("rejectAutoCountryPromise"); 823 }); 824 } 825 } 826 } 827 }, { 828 key: "_initKeyListeners", 829 value: function _initKeyListeners() { 830 var _this6 = this; 831 var userOverrideFormatting = false; 832 // update flag on input event 833 this._handleKeyEvent = function(e) { 834 if (_this6._updateFlagFromNumber(_this6.telInput.value)) { 835 _this6._triggerCountryChange(); 836 } 837 // if user types their own formatting char (not a plus or a numeric), then set the override 838 var isFormattingChar = e && e.data && /[^+0-9]/.test(e.data); 839 var isPaste = e && e.inputType === "insertFromPaste" && _this6.telInput.value; 840 if (isFormattingChar || isPaste) { 841 userOverrideFormatting = true; 842 } else if (!/[^+0-9]/.test(_this6.telInput.value)) { 843 userOverrideFormatting = false; 844 } 845 // handle FAYT, unless userOverrideFormatting or it's a paste event 846 if (_this6.options.formatAsYouType && !userOverrideFormatting && e.inputType !== "insertFromPaste") { 847 // maintain caret position after reformatting 848 var currentCaretPos = _this6.telInput.selectionStart; 849 var valueBeforeCaret = _this6.telInput.value.substring(0, currentCaretPos); 850 var relevantCharsBeforeCaret = valueBeforeCaret.replace(/[^+0-9]/g, "").length; 851 var isDeleteForwards = e && e.inputType === "deleteContentForward"; 852 var formattedValue = _this6._formatNumberAsYouType(); 853 var newCaretPos = _this6._translateCursorPosition(relevantCharsBeforeCaret, formattedValue, currentCaretPos, isDeleteForwards); 854 _this6.telInput.value = formattedValue; 855 _this6.telInput.setSelectionRange(newCaretPos, newCaretPos); 856 } 857 }; 858 this.telInput.addEventListener("input", this._handleKeyEvent); 859 // update flag on cut/paste events (now supported in all major browsers) 860 this._handleClipboardEvent = function() { 861 // hack because "paste" event is fired before input is updated 862 setTimeout(_this6._handleKeyEvent); 863 }; 864 this.telInput.addEventListener("cut", this._handleClipboardEvent); 865 this.telInput.addEventListener("paste", this._handleClipboardEvent); 866 } 867 }, { 868 key: "_translateCursorPosition", 869 value: function _translateCursorPosition(relevantChars, formattedValue, prevCaretPos, isDeleteForwards) { 870 // if the first char is a formatting char, and they backspace delete it: 871 // cursor should stay at the start (pos 0), rather than stick to the first digit (pos 1) 872 if (prevCaretPos === 0 && !isDeleteForwards) { 873 return 0; 874 } 875 var count = 0; 876 for (var i = 0; i < formattedValue.length; i++) { 877 if (/[+0-9]/.test(formattedValue[i])) { 878 count++; 879 } 880 // normal case: stop when you hit the right number of relevant chars 881 // (cursor will be just after the final relevant char) 882 if (count === relevantChars && !isDeleteForwards) { 883 return i + 1; 884 } 885 // spacial case: delete forwards (fn + delete on a mac): 886 // wait until hit one extra relevant char, and put the cursor just before it (after any formatting chars) 887 if (isDeleteForwards && count === relevantChars + 1) { 888 return i; 889 } 890 } 891 return formattedValue.length; 892 } 893 }, { 894 key: "_cap", 895 value: function _cap(number) { 896 var max = this.telInput.getAttribute("maxlength"); 897 return max && number.length > max ? number.substr(0, max) : number; 898 } 899 }, { 900 key: "_initBlurListeners", 901 value: function _initBlurListeners() { 902 var _this7 = this; 903 // on blur or form submit: if just a dial code then remove it 904 this._handleSubmitOrBlurEvent = function() { 905 _this7._removeEmptyDialCode(); 906 }; 907 if (this.telInput.form) { 908 this.telInput.form.addEventListener("submit", this._handleSubmitOrBlurEvent); 909 } 910 this.telInput.addEventListener("blur", this._handleSubmitOrBlurEvent); 911 } 912 }, { 913 key: "_removeEmptyDialCode", 914 value: function _removeEmptyDialCode() { 915 if (this.telInput.value.charAt(0) === "+") { 916 var numeric = this._getNumeric(this.telInput.value); 917 // if just a plus, or if just a dial code 918 if (!numeric || this.selectedCountryData.dialCode === numeric) { 919 this.telInput.value = ""; 920 } 921 } 922 } 923 }, { 924 key: "_getNumeric", 925 value: function _getNumeric(s) { 926 return s.replace(/\D/g, ""); 927 } 928 }, { 929 key: "_trigger", 930 value: function _trigger(name) { 931 var e = new Event(name, { 932 bubbles: true, 933 cancelable: true 934 }); 935 this.telInput.dispatchEvent(e); 936 } 937 }, { 938 key: "_showDropdown", 939 value: function _showDropdown() { 940 if (this.options.fixDropdownWidth) { 941 this.dropdownContent.style.width = "".concat(this.telInput.offsetWidth, "px"); 942 } 943 this.dropdownContent.classList.remove("iti__hide"); 944 this.selectedFlag.setAttribute("aria-expanded", "true"); 945 this._setDropdownPosition(); 946 if (this.options.countrySearch) { 947 // start by highlighting the first item in the list 948 var firstElementChild = this.countryList.firstElementChild; 949 if (firstElementChild) { 950 this._highlightListItem(firstElementChild, false); 951 } 952 this.searchInput.focus(); 953 } else if (this.activeItem) { 954 // update highlighting and scroll to active list item 955 this._highlightListItem(this.activeItem, false); 956 this._scrollTo(this.activeItem, true); 957 } 958 // bind all the dropdown-related listeners: mouseover, click, click-off, keydown 959 this._bindDropdownListeners(); 960 // update the arrow 961 this.dropdownArrow.classList.add("iti__arrow--up"); 962 this._trigger("open:countrydropdown"); 963 } 964 }, { 965 key: "_toggleClass", 966 value: function _toggleClass(el, className, shouldHaveClass) { 967 if (shouldHaveClass && !el.classList.contains(className)) { 968 el.classList.add(className); 969 } else if (!shouldHaveClass && el.classList.contains(className)) { 970 el.classList.remove(className); 971 } 972 } 973 }, { 974 key: "_setDropdownPosition", 975 value: function _setDropdownPosition() { 976 var _this8 = this; 977 if (this.options.dropdownContainer) { 978 this.options.dropdownContainer.appendChild(this.dropdown); 979 } 980 if (!this.options.useFullscreenPopup) { 981 var pos = this.telInput.getBoundingClientRect(); 982 // windowTop from https://stackoverflow.com/a/14384091/2
98217866 983 var windowTop = document.documentElement.scrollTop; 984 var inputTop = pos.top + windowTop; 985 var dropdownHeight = this.dropdownContent.offsetHeight; 986 // dropdownFitsBelow = (dropdownBottom < windowBottom) 987 var dropdownFitsBelow = inputTop + this.telInput.offsetHeight + dropdownHeight < windowTop + window.innerHeight; 988 var dropdownFitsAbove = inputTop - dropdownHeight > windowTop; 989 // dont allow positioning above when country search enabled as the search box jumps around as you filter countries 990 var positionDropdownAboveInput = !this.options.countrySearch && !dropdownFitsBelow && dropdownFitsAbove; 991 // by default, the dropdown will be below the input. If we want to position it above the 992 // input, we add the dropup class. 993 this._toggleClass(this.dropdownContent, "iti__dropdown-content--dropup", positionDropdownAboveInput); 994 // if dropdownContainer is enabled, calculate postion 995 if (this.options.dropdownContainer) { 996 // if we want to position the dropdown below the input, we need to add the input height to the top value 997 var extraTop = positionDropdownAboveInput ? 0 : this.telInput.offsetHeight; 998 // calculate placement 999 this.dropdown.style.top = "".concat(inputTop + extraTop, "px"); 1000 this.dropdown.style.left = "".concat(pos.left + document.body.scrollLeft, "px"); 1001 // close menu on window scroll 1002 this._handleWindowScroll = function() { 1003 return _this8._closeDropdown(); 1004 }; 1005 window.addEventListener("scroll", this._handleWindowScroll); 1006 } 1007 } 1008 } 1009 }, { 1010 key: "_bindDropdownListeners", 1011 value: function _bindDropdownListeners() { 1012 var _this9 = this; 1013 // when mouse over a list item, just highlight that one 1014 // we add the class "highlight", so if they hit "enter" we know which one to select 1015 this._handleMouseoverCountryList = function(e) { 1016 // handle event delegation, as we're listening for this event on the countryList 1017 var listItem = e.target.closest(".iti__country"); 1018 if (listItem) { 1019 _this9._highlightListItem(listItem, false); 1020 } 1021 }; 1022 this.countryList.addEventListener("mouseover", this._handleMouseoverCountryList); 1023 // listen for country selection 1024 this._handleClickCountryList = function(e) { 1025 var listItem = e.target.closest(".iti__country"); 1026 if (listItem) { 1027 _this9._selectListItem(listItem); 1028 } 1029 }; 1030 this.countryList.addEventListener("click", this._handleClickCountryList); 1031 // click off to close 1032 // (except when this initial opening click is bubbling up) 1033 // we cannot just stopPropagation as it may be needed to close another instance 1034 var isOpening = true; 1035 this._handleClickOffToClose = function() { 1036 if (!isOpening) { 1037 _this9._closeDropdown(); 1038 } 1039 isOpening = false; 1040 }; 1041 document.documentElement.addEventListener("click", this._handleClickOffToClose); 1042 // listen for up/down scrolling, enter to select, or escape to close 1043 // use keydown as keypress doesn't fire for non-char keys and we want to catch if they 1044 // just hit down and hold it to scroll down (no keyup event). 1045 // listen on the document because that's where key events are triggered if no input has focus 1046 var query = ""; 1047 var queryTimer = null; 1048 this._handleKeydownOnDropdown = function(e) { 1049 // prevent down key from scrolling the whole page, 1050 // and enter key from submitting a form etc 1051 if ([ "ArrowUp", "ArrowDown", "Enter", "Escape" ].includes(e.ke
1051y)) { 1052 e.preventDefault(); 1053 e.stopPropagation(); 1054 // up and down to navigate 1055 if (e.key === "ArrowUp" || e.key === "ArrowDown") { 1056 _this9._handleUpDownKey(e.key); 1057 } else if (e.key === "Enter") { 1058 _this9._handleEnterKey(); 1059 } else if (e.key === "Escape") { 1060 _this9._closeDropdown(); 1061 } 1062 } 1063 // alpha chars to perform search 1064 // regex allows one latin alpha char or space, based on https://stackoverflow.com/a/26900132/217866) 1065 if (!_this9.options.countrySearch && /^[a-zA-ZÃ-ÿа-ÑÐ-Я ]$/.test(e.key)) { 1066 e.stopPropagation(); 1067 // jump to countries that start with the query string 1068 if (queryTimer) { 1069 clearTimeout(queryTimer); 1070 } 1071 query += e.key.toLowerCase(); 1072 _this9._searchForCountry(query); 1073 // if the timer hits 1 second, reset the query 1074 queryTimer = setTimeout(function() { 1075 query = ""; 1076 }, 1e3); 1077 } 1078 }; 1079 document.addEventListener("keydown", this._handleKeydownOnDropdown); 1080 if (this.options.countrySearch) { 1081 var doFilter = function doFilter() { 1082 var inputQuery = _this9.searchInput.value.trim(); 1083 if (inputQuery) { 1084 _this9._filterCountries(inputQuery); 1085 } else { 1086 _this9._filterCountries("", true); 1087 } 1088 }; 1089 var keyupTimer = null; 1090 this._handleSearchChange = function() { 1091 // filtering country nodes is expensive (lots of DOM manipulation), so rate limit it 1092 if (keyupTimer) { 1093 clearTimeout(keyupTimer); 1094 } 1095 keyupTimer = setTimeout(function() { 1096 doFilter(); 1097 keyupTimer = null; 1098 }, 100); 1099 }; 1100 this.searchInput.addEventListener("input", this._handleSearchChange); 1101 // stop propagation on search input click, so doesn't trigger click-off-to-close listener 1102 this.searchInput.addEventListener("click", function(e) { 1103 return e.stopPropagation(); 1104 }); 1105 } 1106 } 1107 }, { 1108 key: "_normaliseString", 1109 value: function _normaliseString() { 1110 var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; 1111 return s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase(); 1112 } 1113 }, { 1114 key: "_filterCountries", 1115 value: function _filterCountries(query) { 1116 var isReset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; 1117 var isFirst = true; 1118 this.countryList.innerHTML = ""; 1119 var normalisedQuery = this._normaliseString(query); 1120 for (var i = 0; i < this.countries.length; i++) { 1121 var c = this.countries[i]; 1122 var normalisedCountryName = this._normaliseString(c.name); 1123 var fullDialCode = "+".concat(c.dialCode); 1124 if (isReset || normalisedCountryName.includes(normalisedQuery) || fullDialCode.includes(normalisedQuery) || c.iso2.includes(normalisedQuery)) { 1125 this.countryList.appendChild(c.nodeById[this.id]); 1126 // highlight the first item 1127 if (isFirst) { 1128 this._highlightListItem(c.nodeById[this.id], false); 1129 isFirst = false;
1130 } 1131 } 1132 } 1133 } 1134 }, { 1135 key: "_handleUpDownKey", 1136 value: function _handleUpDownKey(key) { 1137 var next = key === "ArrowUp" ? this.highlightedItem.previousElementSibling : this.highlightedItem.nextElementSibling; 1138 if (next) { 1139 // skip the divider 1140 if (next.classList.contains("iti__divider")) { 1141 next = key === "ArrowUp" ? next.previousElementSibling : next.nextElementSibling; 1142 } 1143 } else if (this.countryList.childElementCount > 1) { 1144 // otherwise, we must be at the end, so loop round again 1145 next = key === "ArrowUp" ? this.countryList.lastElementChild : this.countryList.firstElementChild; 1146 } 1147 if (next) { 1148 // if country search enabled, dont lose focus from the search input on up/down 1149 var doFocus = !this.options.countrySearch; 1150 this._highlightListItem(next, doFocus); 1151 if (this.options.countrySearch) { 1152 this._scrollTo(next, false); 1153 } 1154 } 1155 } 1156 }, { 1157 key: "_handleEnterKey", 1158 value: function _handleEnterKey() { 1159 if (this.highlightedItem) { 1160 this._selectListItem(this.highlightedItem); 1161 } 1162 } 1163 }, { 1164 key: "_searchForCountry", 1165 value: function _searchForCountry(query) { 1166 for (var i = 0; i < this.countries.length; i++) { 1167 if (this._startsWith(this.countries[i].name, query)) { 1168 var listItem = this.countries[i].nodeById[this.id]; 1169 // update highlighting and scroll 1170 this._highlightListItem(listItem, false); 1171 this._scrollTo(listItem, true); 1172 break; 1173 } 1174 } 1175 } 1176 }, { 1177 key: "_startsWith", 1178 value: function _startsWith(a, b) { 1179 return a.substr(0, b.length).toLowerCase() === b; 1180 } 1181 }, { 1182 key: "_updateValFromNumber", 1183 value: function _updateValFromNumber(fullNumber) { 1184 var number = fullNumber; 1185 if (this.options.formatOnDisplay && window.intlTelInputUtils && this.selectedCountryData) { 1186 var useNational = this.options.nationalMode || number.charAt(0) !== "+" && !this.options.showSelectedDialCode; 1187 var _intlTelInputUtils$nu = intlTelInputUtils.numberFormat, NATIONAL = _intlTelInputUtils$nu.NATIONAL, INTERNATIONAL = _intlTelInputUtils$nu.INTERNATIONAL; 1188 var format = useNational ? NATIONAL : INTERNATIONAL; 1189 number = intlTelInputUtils.formatNumber(number, this.selectedCountryData.iso2, format); 1190 } 1191 number = this._beforeSetNumber(number); 1192 this.telInput.value = number; 1193 } 1194 }, { 1195 key: "_updateFlagFromNumber", 1196 value: function _updateFlagFromNumber(fullNumber) { 1197 var plusIndex = fullNumber.indexOf("+"); 1198 // if it contains a plus, discard any chars before it e.g. accidental space char. 1199 // this keeps the selected country auto-updating correctly, which we want as 1200 // libphonenumber's validation/getNumber methods will ignore these chars anyway 1201 var number = plusIndex ? fullNumber.substring(plusIndex) : fullNumber; 1202 // if we already have US/Canada selected, make sure the number starts 1203 // with a +1 so _getDialCode will be able to extract the area code 1204 // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag 1205 // from the number), that means we're initialising the plugin with a number that already has a 1206 // dial code, so fine to ignore this bit 1207 var selectedDialCode = this.selectedCountryData.dialCode; 1208 var isNanp = selectedDialCode === "1"; 1209 if (number && isNanp && number.charAt(0) !== "+") { 1210 if (number.charAt(0) !== "1") { 1211 number = "1".concat(number); 1212 } 1213 number = "+".concat(number); 1214 } 1215 // if showSelectedDialCode enabled, then consider the selected dial code to be part of the number 1216 if (this.options.showSelectedDialCode && selectedDialCode && number.charAt(0) !== "+") { 1217 number = "+".concat(selectedDialCode).concat(number); 1218 } 1219 // try and extract valid dial code from input 1220 var dialCode = this._getDialCode(number, true); 1221 var numeric = this._getNumeric(number); 1222 var iso2 = null; 1223 if (dialCode) { 1224 var iso2Codes = this.dialCodeToIso2Map[this._getNumeric(dialCode)]; 1225 // check if the right country is already selected. this should be false if the number is 1226 // longer than the matched dial code because in this case we need to make sure that if 1227 // there are multiple country matches, that the first one is selected (note: we could 1228 // just check that here, but it requires the same loop that we already have later) 1229 var alreadySelected = iso2Codes.indexOf(this.selectedCountryData.iso2) !== -1 && numeric.length <= dialCode.length - 1; 1230 var isRegionlessNanpNumber = selectedDialCode === "1" && this._isRegionlessNanp(numeric); 1231 // only update the flag if: 1232 // A) NOT (we currently have a NANP flag selected, and the number is a regionlessNanp) 1233 // AND 1234 // B) the right country is not already selected 1235 if (!isRegionlessNanpNumber && !alreadySelected) { 1236 // if using onlyCountries option, iso2Codes[0] may be empty, so we must find the first 1237 // non-empty index 1238 for (var j = 0; j < iso2Codes.length; j++) { 1239 if (iso2Codes[j]) { 1240 iso2 = iso2Codes[j]; 1241 break; 1242 } 1243 } 1244 } 1245 } else if (number.charAt(0) === "+" && numeric.length) { 1246 // invalid dial code, so empty 1247 // Note: use getNumeric here because the number has not been formatted yet, so could contain 1248 // bad chars 1249 iso2 = ""; 1250 } else if ((!number || number === "+") && !this.selectedCountryData.iso2) { 1251 // if no selected flag, and user either clears the input, or just types a plus, then show default 1252 iso2 = this.defaultCountry; 1253 } 1254 if (iso2 !== null) { 1255 return this._setFlag(iso2); 1256 } 1257 return false;
1258 } 1259 }, { 1260 key: "_isRegionlessNanp", 1261 value: function _isRegionlessNanp(number) { 1262 var numeric = this._getNumeric(number); 1263 if (numeric.charAt(0) === "1") { 1264 var areaCode = numeric.substr(1, 3); 1265 return regionlessNanpNumbers.indexOf(areaCode) !== -1; 1266 } 1267 return false; 1268 } 1269 }, { 1270 key: "_highlightListItem", 1271 value: function _highlightListItem(listItem, shouldFocus) { 1272 var prevItem = this.highlightedItem; 1273 if (prevItem) { 1274 prevItem.classList.remove("iti__highlight"); 1275 } 1276 this.highlightedItem = listItem; 1277 this.highlightedItem.classList.add("iti__highlight"); 1278 this.selectedFlag.setAttribute("aria-activedescendant", listItem.getAttribute("id")); 1279 if (shouldFocus) { 1280 this.highlightedItem.focus(); 1281 } 1282 } 1283 }, { 1284 key: "_getCountryData", 1285 value: function _getCountryData(iso2, allowFail) { 1286 for (var i = 0; i < this.countries.length; i++) { 1287 if (this.countries[i].iso2 === iso2) { 1288 return this.countries[i]; 1289 } 1290 } 1291 if (allowFail) { 1292 return null; 1293 } 1294 throw new Error("No country data for '".concat(iso2, "'")); 1295 } 1296 }, { 1297 key: "_setFlag", 1298 value: function _setFlag(iso2) { 1299 var _this$options3 = this.options, allowDropdown = _this$options3.allowDropdown, showSelectedDialCode = _this$options3.showSelectedDialCode, showFlags = _this$options3.showFlags, countrySearch = _this$options3.countrySearch; 1300 var prevCountry = this.selectedCountryData.iso2 ? this.selectedCountryData : {}; 1301 // do this first as it will throw an error and stop if iso2 is invalid 1302 this.selectedCountryData = iso2 ? this._getCountryData(iso2, false) : {}; 1303 // update the defaultCountry - we only need the iso2 from now on, so just store that 1304 if (this.selectedCountryData.iso2) { 1305 this.defaultCountry = this.selectedCountryData.iso2; 1306 } 1307 if (showFlags) { 1308 var flagClass = iso2 ? "iti__".concat(iso2) : "iti__globe"; 1309 this.selectedFlagInner.setAttribute("class", "iti__flag ".concat(flagClass)); 1310 } 1311 this._setSelectedCountryFlagTitleAttribute(iso2, showSelectedDialCode); 1312 if (showSelectedDialCode) { 1313 var dialCode = this.selectedCountryData.dialCode ? "+".concat(this.selectedCountryData.dialCode) : ""; 1314 this.selectedDialCode.innerHTML = dialCode; 1315 // offsetWidth is zero if input is in a hidden container during initialisation 1316 var selectedFlagWidth = this.selectedFlag.offsetWidth || this._getHiddenSelectedFlagWidth(); 1317 // add 6px of padding after the grey selected-dial-code box, as this is what we use in the css 1318 if (this.isRTL) { 1319 this.telInput.style.paddingRight = "".concat(selectedFlagWidth + 6, "px"); 1320 } else { 1321 this.telInput.style.paddingLeft = "".concat(selectedFlagWidth + 6, "px"); 1322 } 1323 } 1324 // and the input's placeholder 1325 this._updatePlaceholder(); 1326 // update the active list item (only if country search disabled, as country search doesn't store the active item) 1327 if (allowDropdown && !countrySearch) { 1328 var prevItem = this.activeItem; 1329 if (prevItem) { 1330 prevItem.classList.remove("iti__active"); 1331 prevItem.setAttribute("aria-selected", "false"); 1332 } 1333 if (iso2) { 1334 // check if there is a preferred item first, else fall back to standard 1335 var nextItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(iso2, "-preferred")) || this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(iso2)); 1336 nextItem.setAttribute("aria-selected", "true"); 1337 nextItem.classList.add("iti__active"); 1338 this.activeItem = nextItem; 1339 } 1340 } 1341 // return if the flag has changed or not 1342 return prevCountry.iso2 !== iso2; 1343 } 1344 }, { 1345 key: "_setSelectedCountryFlagTitleAttribute", 1346 value: function _setSelectedCountryFlagTitleAttribute(iso2, showSelectedDialCode) { 1347 if (!this.selectedFlag) { 1348 return; 1349 } 1350 var title; 1351 if (iso2 && !showSelectedDialCode) { 1352 title = "".concat(this.selectedCountryData.name, ": +").concat(this.selectedCountryData.dialCode); 1353 } else if (iso2) { 1354 // For screen reader output, we don't want to include the dial code in the reader output twice 1355 // so just use the selected country name here: 1356 title = this.selectedCountryData.name; 1357 } else { 1358 title = "Unknown"; 1359 } 1360 this.selectedFlag.setAttribute("title", title); 1361 } 1362 }, { 1363 key: "_getHiddenSelectedFlagWidth", 1364 value: function _getHiddenSelectedFlagWidth() { 1365 // to get the right styling to apply, all we need is a shallow clone of the container, 1366 // and then to inject a deep clone of the selectedFlag element 1367 var containerClone = this.telInput.parentNode.cloneNode(); 1368 containerClone.style.visibility = "hidden"; 1369 document.body.appendChild(containerClone); 1370 var flagsContainerClone = this.flagsContainer.cloneNode(); 1371 containerClone.appendChild(flagsContainerClone); 1372 var selectedFlagClone = this.selectedFlag.cloneNode(true); 1373 flagsContainerClone.appendChild(selectedFlagClone); 1374 var width = selectedFlagClone.offsetWidth; 1375 containerClone.parentNode.removeChild(containerClone); 1376 return width; 1377 } 1378 }, { 1379 key: "_updatePlaceholder", 1380 value: function _updatePlaceholder() { 1381 var _this$options4 = this.options, autoPlaceholder = _this$options4.autoPlaceholder, placeholderNumberType = _this$options4.placeholderNumberType, nationalMode = _this$options4.nationalMode, customPlaceholder = _this$options4.customPlaceholder; 1382 var shouldSetPlaceholder = autoPlaceholder === "aggressive" || !this.hadInitialPlaceholder && autoPlaceholder === "polite"; 1383 if (window.intlTelInputUtils && shouldSetPlaceholder) { 1384 var numberType = intlTelInputUtils.numberType[placeholderNumberType]; 1385 var placeholder = this.selectedCountryData.iso2 ? intlTelInputUtils.getExampleNumber(this.selectedCountryData.iso2, nationalMode, numberType) : ""; 1386 placeholder = this._beforeSetNumber(placeholder); 1387 if (typeof customPlaceholder === "function") { 1388 placeholder = customPlaceholder(placeholder, this.selectedCountryData); 1389 } 1390 this.telInput.setAttribute("placeholder", placeholder); 1391 } 1392 } 1393 }, { 1394 key: "_selectListItem", 1395 value: function _selectListItem(listItem) { 1396 // update selected flag and active list item 1397 var flagChanged = this._setFlag(listItem.getAttribute("data-country-code")); 1398 this._closeDropdown(); 1399 this._updateDialCode(listItem.getAttribute("data-dial-code")); 1400 // focus the input 1401 this.telInput.focus(); 1402 if (flagChanged) { 1403 this._triggerCountryChange(); 1404 } 1405 } 1406 }, { 1407 key: "_closeDropdown", 1408 value: function _closeDropdown() { 1409 this.dropdownContent.classList.add("iti__hide"); 1410 this.selectedFlag.setAttribute("aria-expanded", "false"); 1411 this.selectedFlag.removeAttribute("aria-activedescendant"); 1412 // update the arrow 1413 this.dropdownArrow.classList.remove("iti__arrow--up"); 1414 // unbind key events 1415 document.removeEventListener("keydown", this._handleKeydownOnDropdown); 1416 if (this.options.countrySearch) { 1417 this.searchInput.removeEventListener("input", this._handleSearchChange); 1418 } 1419 document.documentElement.removeEventListener("click", this._handleClickOffToClose); 1420 this.countryList.removeEventListener("mouseover", this._handleMouseoverCountryList); 1421 this.countryList.removeEventListener("click", this._handleClickCountryList); 1422 // remove menu from container 1423 if (this.options.dropdownContainer) { 1424 if (!this.options.useFullscreenPopup) { 1425 window.removeEventListener("scroll", this._handleWindowScroll); 1426 } 1427 if (this.dropdown.parentNode) { 1428 this.dropdown.parentNode.removeChild(this.dropdown); 1429 } 1430 } 1431 this._trigger("close:countrydropdown"); 1432 } 1433 }, { 1434 key: "_scrollTo", 1435 value: function _scrollTo(element, middle) { 1436 var container = this.countryList; 1437 // windowTop from https://stackoverflow.com/a/14384091/2
143717866 1438 var windowTop = document.documentElement.scrollTop; 1439 var containerHeight = container.offsetHeight; 1440 var containerTop = container.getBoundingClientRect().top + windowTop; 1441 var containerBottom = containerTop + containerHeight; 1442 var elementHeight = element.offsetHeight; 1443 var elementTop = element.getBoundingClientRect().top + windowTop; 1444 var elementBottom = elementTop + elementHeight; 1445 var newScrollTop = elementTop - containerTop + container.scrollTop; 1446 var middleOffset = containerHeight / 2 - elementHeight / 2; 1447 if (elementTop < containerTop) { 1448 // scroll up 1449 if (middle) { 1450 newScrollTop -= middleOffset; 1451 } 1452 container.scrollTop = newScrollTop; 1453 } else if (elementBottom > containerBottom) { 1454 // scroll down 1455 if (middle) { 1456 newScrollTop += middleOffset; 1457 } 1458 var heightDifference = containerHeight - elementHeight; 1459 container.scrollTop = newScrollTop - heightDifference; 1460 } 1461 } 1462 }, { 1463 key: "_updateDialCode", 1464 value: function _updateDialCode(newDialCodeBare) { 1465 var inputVal = this.telInput.value; 1466 // save having to pass this every time 1467 var newDialCode = "+".concat(newDialCodeBare); 1468 var newNumber; 1469 if (inputVal.charAt(0) === "+") { 1470 // there's a plus so we're dealing with a replacement 1471 var prevDialCode = this._getDialCode(inputVal); 1472 if (prevDialCode) { 1473 // current number contains a valid dial code, so replace it 1474 newNumber = inputVal.replace(prevDialCode, newDialCode); 1475 } else { 1476 // current number contains an invalid dial code, so ditch it 1477 // (no way to determine where the invalid dial code ends and the rest of the number begins) 1478 newNumber = newDialCode; 1479 } 1480 this.telInput.value = newNumber; 1481 } else if (this.options.autoInsertDialCode) { 1482 if (inputVal) { 1483 // there is an existing value with no dial code: prefix the new dial code 1484 newNumber = newDialCode + inputVal; 1485 } else { 1486 newNumber = newDialCode; 1487 } 1488 this.telInput.value = newNumber; 1489 } 1490 } 1491 }, { 1492 key: "_getDialCode", 1493 value: function _getDialCode(number, includeAreaCode) { 1494 var dialCode = ""; 1495 // only interested in international numbers (starting with a plus) 1496 if (number.charAt(0) === "+") { 1497 var numericChars = ""; 1498 // iterate over chars 1499 for (var i = 0; i < number.length; i++) { 1500 var c = number.charAt(i); 1501 // if char is number (https://stackoverflow.com/a/8935649/217866) 1502 if (!isNaN(parseInt(c, 10))) { 1503 numericChars += c; 1504 // if current numericChars make a valid dial code 1505 if (includeAreaCode) { 1506 if (this.dialCodeToIso2Map[numericChars]) { 1507 // store the actual raw string (useful for matching later) 1508 dialCode = number.substr(0, i + 1); 1509 } 1510 } else { 1511 if (this.dialCodes[numericChars]) { 1512 dialCode = number.substr(0, i + 1); 1513 // if we're just looking for a dial code, we can break as soon as we find one 1514 break; 1515 } 1516 } 1517 // stop searching as soon as we can - in this case when we hit max len 1518 if (numericChars.length === this.dialCodeMaxLen) { 1519 break; 1520 } 1521 } 1522 } 1523 } 1524 return dialCode; 1525 } 1526 }, { 1527 key: "_getFullNumber", 1528 value: function _getFullNumber() { 1529 var val = this.telInput.value.trim(); 1530 var dialCode = this.selectedCountryData.dialCode; 1531 var prefix; 1532 var numericVal = this._getNumeric(val); 1533 if (this.options.showSelectedDialCode && !this.options.nationalMode && val.charAt(0) !== "+" && dialCode && numericVal) { 1534 // when using showSelectedDialCode, it is visible so is effectively part of the typed number 1535 prefix = "+".concat(dialCode); 1536 } else { 1537 prefix = ""; 1538 } 1539 return prefix + val; 1540 } 1541 }, { 1542 key: "_beforeSetNumber", 1543 value: function _beforeSetNumber(fullNumber) { 1544 var number = fullNumber; 1545 if (this.options.showSelectedDialCode) { 1546 var dialCode = this._getDialCode(number); 1547 // if there is a valid dial code 1548 if (dialCode) { 1549 // in case _getDialCode returned an area code as well 1550 dialCode = "+".concat(this.selectedCountryData.dialCode); 1551 // a lot of numbers will have a space separating the dial code and the main number, and 1552 // some NANP numbers will have a hyphen e.g. +1 684-733-1234 - in both cases we want to get 1553 // rid of it 1554 // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc 1555 var start = number[dialCode.length] === " " || number[dialCode.length] === "-" ? dialCode.length + 1 : dialCode.length; 1556 number = number.substr(start); 1557 } 1558 } 1559 return this._cap(number); 1560 } 1561 }, { 1562 key: "_triggerCountryChange", 1563 value: function _triggerCountryChange() { 1564 this._trigger("countrychange"); 1565 } 1566 }, { 1567 key: "_formatNumberAsYouType", 1568 value: function _formatNumberAsYouType() { 1569 var val = this._getFullNumber(); 1570 var result = window.intlTelInputUtils ? intlTelInputUtils.formatNumberAsYouType(val, this.selectedCountryData.iso2) : val; 1571 // if showSelectedDialCode and they haven't (re)typed the dial code in the input as well, then remove the dial code 1572 var dialCode = this.selectedCountryData.dialCode; 1573 if (this.options.showSelectedDialCode && !this.options.nationalMode && this.telInput.value.charAt(0) !== "+" && result.includes("+".concat(dialCode))) { 1574 var afterDialCode = result.split("+".concat(dialCode))[1] || ""; 1575 return afterDialCode.trim(); 1576 } 1577 return result; 1578 } 1579 }, { 1580 key: "handleAutoCountry", 1581 value: function handleAutoCountry() { 1582 if (this.options.initialCountry === "auto") { 1583 // we must set this even if there is an initial val in the input: in case the initial val is 1584 // invalid and they delete it - they should see their auto country 1585 this.defaultCountry = window.intlTelInputGlobals.autoCountry; 1586 // if there's no initial value in the input, then update the flag 1587 if (!this.telInput.value) { 1588 this.setCountry(this.defaultCountry); 1589 } 1590 this.resolveAutoCountryPromise(); 1591 } 1592 } 1593 }, { 1594 key: "handleUtils", 1595 value: function handleUtils() { 1596 // if the request was successful 1597 if (window.intlTelInputUtils) { 1598 // if there's an initial value in the input, then format it 1599 if (this.telInput.value) {
1600 this._updateValFromNumber(this.telInput.value); 1601 } 1602 if (this.selectedCountryData.iso2) { 1603 this._updatePlaceholder(); 1604 } 1605 } 1606 this.resolveUtilsScriptPromise(); 1607 } 1608 }, { 1609 key: "destroy", 1610 value: function destroy() { 1611 var form = this.telInput.form; 1612 if (this.options.allowDropdown) { 1613 // make sure the dropdown is closed (and unbind listeners) 1614 this._closeDropdown(); 1615 this.selectedFlag.removeEventListener("click", this._handleClickSelectedFlag); 1616 this.flagsContainer.removeEventListener("keydown", this._handleFlagsContainerKeydown); 1617 // label click hack 1618 var label = this.telInput.closest("label"); 1619 if (label) { 1620 label.removeEventListener("click", this._handleLabelClick); 1621 } 1622 } 1623 // unbind hiddenInput listeners 1624 if (this.hiddenInput && form) { 1625 form.removeEventListener("submit", this._handleHiddenInputSubmit); 1626 } 1627 // unbind autoInsertDialCode listeners 1628 if (this.options.autoInsertDialCode) { 1629 if (form) { 1630 form.removeEventListener("submit", this._handleSubmitOrBlurEvent); 1631 } 1632 this.telInput.removeEventListener("blur", this._handleSubmitOrBlurEvent); 1633 } 1634 // unbind key events, and cut/paste events 1635 this.telInput.removeEventListener("input", this._handleKeyEvent); 1636 this.telInput.removeEventListener("cut", this._handleClipboardEvent); 1637 this.telInput.removeEventListener("paste", this._handleClipboardEvent); 1638 // remove attribute of id instance: data-intl-tel-input-id 1639 this.telInput.removeAttribute("data-intl-tel-input-id"); 1640 // remove markup (but leave the original input) 1641 var wrapper = this.telInput.parentNode; 1642 wrapper.parentNode.insertBefore(this.telInput, wrapper); 1643 wrapper.parentNode.removeChild(wrapper); 1644 delete window.intlTelInputGlobals.instances[this.id]; 1645 } 1646 }, { 1647 key: "getExtension", 1648 value: function getExtension() { 1649 if (window.intlTelInputUtils) { 1650 return intlTelInputUtils.getExtension(this._getFullNumber(), this.selectedCountryData.iso2); 1651 } 1652 return ""; 1653 } 1654 }, { 1655 key: "getNumber", 1656 value: function getNumber(format) { 1657 if (window.intlTelInputUtils) { 1658 var iso2 = this.selectedCountryData.iso2; 1659 return intlTelInputUtils.formatNumber(this._getFullNumber(), iso2, format); 1660 } 1661 return ""; 1662 } 1663 }, { 1664 key: "getNumberType", 1665 value: function getNumberType() { 1666 if (window.intlTelInputUtils) { 1667 return intlTelInputUtils.getNumberType(this._getFullNumber(), this.selectedCountryData.iso2); 1668 } 1669 return -99; 1670 } 1671 }, { 1672 key: "getSelectedCountryData", 1673 value: function getSelectedCountryData() { 1674 return this.selectedCountryData; 1675 } 1676 }, { 1677 key: "getValidationError", 1678 value: function getValidationError() { 1679 if (window.intlTelInputUtils) { 1680 var iso2 = this.selectedCountryData.iso2; 1681 return intlTelInputUtils.getValidationError(this._getFullNumber(), iso2); 1682 } 1683 return -99; 1684 } 1685 }, { 1686 key: "isValidNumber", 1687 value: function isValidNumber(mobileOnly) { 1688 var val = this._getFullNumber(); 1689 return window.intlTelInputUtils ? intlTelInputUtils.isPossibleNumber(val, this.selectedCountryData.iso2, mobileOnly) : null; 1690 } 1691 }, { 1692 key: "isValidNumberPrecise", 1693 value: function isValidNumberPrecise() { 1694 var val = this._getFullNumber(); 1695 return window.intlTelInputUtils ? intlTelInputUtils.isValidNumber(val, this.selectedCountryData.iso2) : null; 1696 } 1697 }, { 1698 key: "setCountry", 1699 value: function setCountry(iso2) { 1700 var iso2Lower = iso2.toLowerCase(); 1701 // check if already selected 1702 if (this.selectedCountryData.iso2 !== iso2Lower) { 1703 this._setFlag(iso2Lower); 1704 this._updateDialCode(this.selectedCountryData.dialCode); 1705 this._triggerCountryChange(); 1706 } 1707 } 1708 }, { 1709 key: "setNumber", 1710 value: function setNumber(number) { 1711 // we must update the flag first, which updates this.selectedCountryData, which is used for 1712 // formatting the number before displaying it 1713 var flagChanged = this._updateFlagFromNumber(number);
1714 this._updateValFromNumber(number); 1715 if (flagChanged) { 1716 this._triggerCountryChange(); 1717 } 1718 } 1719 }, { 1720 key: "setPlaceholderNumberType", 1721 value: function setPlaceholderNumberType(type) { 1722 this.options.placeholderNumberType = type; 1723 this._updatePlaceholder(); 1724 } 1725 } ]); 1726 return Iti; 1727 }(); 1728 /******************** 1729 * STATIC METHODS 1730 ********************/ 1731 // get the country data object 1732 intlTelInputGlobals.getCountryData = function() { 1733 return allCountries; 1734 }; 1735 // inject a <script> element to load utils.js 1736 var injectScript = function injectScript(path, handleSuccess, handleFailure) { 1737 // inject a new script element into the page 1738 var script = document.createElement("script"); 1739 script.onload = function() { 1740 forEachInstance("handleUtils"); 1741 if (handleSuccess) { 1742 handleSuccess(); 1743 } 1744 }; 1745 script.onerror = function() { 1746 forEachInstance("rejectUtilsScriptPromise"); 1747 if (handleFailure) { 1748 handleFailure(); 1749 } 1750 }; 1751 script.className = "iti-load-utils"; 1752 script.async = true; 1753 script.src = path; 1754 document.body.appendChild(script); 1755 }; 1756 // load the utils script 1757 intlTelInputGlobals.loadUtils = function(path) { 1758 // 2 options: 1759 // 1) not already started loading (start) 1760 // 2) already started loading (do nothing - just wait for the onload callback to fire, which will 1761 // trigger handleUtils on all instances, invoking their resolveUtilsScriptPromise functions) 1762 if (!window.intlTelInputUtils && !window.intlTelInputGlobals.startedLoadingUtilsScript) { 1763 // only do this once 1764 window.intlTelInputGlobals.startedLoadingUtilsScript = true; 1765 // if we have promises, then return a promise 1766 if (typeof Promise !== "undefined") { 1767 return new Promise(function(resolve, reject) { 1768 return injectScript(path, resolve, reject); 1769 }); 1770 } 1771 injectScript(path); 1772 } 1773 return null; 1774 }; 1775 // default options 1776 intlTelInputGlobals.defaults = defaults; 1777 // version 1778 intlTelInputGlobals.version = "19.5.7"; 1779 // convenience wrapper 1780 return function(input, options) { 1781 var iti = new Iti(input, options); 1782 iti._init(); 1783 input.setAttribute("data-intl-tel-input-id", iti.id); 1784 window.intlTelInputGlobals.instances[iti.id] = iti; 1785 return iti; 1786 }; 1787 }(); 1788});
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.