1/* 2 * International Telephone Input v17.0.14 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 and 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" ] ], [ "Bahrains", "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 and 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", "289", "306", "343", "365", "387", "403", "416", "418", "431", "437", "438", "450", "506", "514", "519", "548", "579", "581", "587", "604", "613", "639", "647", "672", "705", "709", "742", "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 (DRC) (Jamhuri ya Kidemokrasia ya Kongo)", "cd", "243" ], [ "Congo (Republic) (Congo-Brazzaville)", "cg", "242" ], [ "Cook Islands", "ck", "682" ], [ "Costa Rica", "cr", "506" ], [ "Croatia (Hrvatska)", "hr", "385" ], [ "Cuba", "cu", "53" ], [ "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" ], [ "Macedonia", "mk", "389" ], [ "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", "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" ], [ "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" ], [ "Romania", "ro", "40" ], [ "Russia", "ru", "7", 0 ], [ "Rwanda", "rw", "250" ], [ "Saint Helena", "sh", "290" ], [ "Saint Kitts and Nevis", "kn", "1", 18, [ "869" ] ], [ "Saint Lucia", "lc", "1", 19, [ "758" ] ], [ "Saint Martin", "mf", "590", 2 ], [ "Saint Pierre and Miquelon", "pm", "508" ], [ "Saint Vincent and the Grenadines", "vc", "1", 20, [ "784" ] ], [ "Samoa", "ws", "685" ], [ "San Marino", "sm", "378" ], [ "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" ], [ "Sudan", "sd", "249" ], [ "Suriname", "sr", "597" ], [ "Svalbard and 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 and Tobago", "tt", "1", 22, [ "868" ] ], [ "Tunisia", "tn", "216" ], [ "Turkey)", "tr", "90" ], [ "Turkmenistan", "tm", "993" ], [ "Turks and Caicos Islands", "tc", "1", 23, [ "649" ] ], [ "Tuvalu", "tv", "688" ], [ "U.S. Virgin Islands", "vi", "1", 24, [ "340" ] ], [ "Uganda", "ug", "256" ], [ "Ukraine", "ua", "380" ], [ "United Arab Emirates", "ae", "971" ], [ "United Kingdom", "gb", "44", 0 ], [ "United States", "us", "1", 0 ], [ "Uruguay", "uy", "598" ], [ "Uzbekistan", "uz", "998" ], [ "Vanuatu", "vu", "678" ], [ "Vatican City", "va", "39", 1, [ "06698" ] ], [ "Venezuela", "ve", "58" ], [ "Vietnam", "vn", "84" ], [ "Wallis and Futuna", "wf", "681" ], [ "Western Sahara", "eh", "212", 1, [ "5288", "5289" ] ], [ "Yemen", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ] ]; 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 }; 38 } 39 "use strict"; 40 function _classCallCheck(instance, Constructor) { 41 if (!(instance instanceof Constructor)) { 42 throw new TypeError("Cannot call a class as a function"); 43 } 44 } 45 function _defineProperties(target, props) { 46 for (var i = 0; i < props.length; i++) { 47 var descriptor = props[i]; 48 descriptor.enumerable = descriptor.enumerable || false; 49 descriptor.configurable = true; 50 if ("value" in descriptor) descriptor.writable = true; 51 Object.defineProperty(target, descriptor.key, descriptor); 52 } 53 } 54 function _createClass(Constructor, protoProps, staticProps) { 55 if (protoProps) _defineProperties(Constructor.prototype, protoProps); 56 if (staticProps) _defineProperties(Constructor, staticProps); 57 return Constructor; 58 } 59 var intlTelInputGlobals = { 60 getInstance: function getInstance(input) { 61 var id = input.getAttribute("data-intl-tel-input-id"); 62 return window.intlTelInputGlobals.instances[id]; 63 }, 64 instances: {}, 65 // using a global like this allows us to mock it in the tests 66 documentReady: function documentReady() { 67 return document.readyState === "complete"; 68 } 69 }; 70 if (typeof window === "object") window.intlTelInputGlobals = intlTelInputGlobals; 71 // these vars persist through all instances of the plugin 72 var id = 0; 73 var defaults = { 74 // whether or not to allow the dropdown 75 allowDropdown: true, 76 // if there is just a dial code in the input: remove it on blur 77 autoHideDialCode: true, 78 // add a placeholder in the input with an example number for the selected country 79 autoPlaceholder: "polite", 80 // modify the parentClass 81 customContainer: "", 82 // modify the auto placeholder 83 customPlaceholder: null, 84 // append menu to specified element 85 dropdownContainer: null, 86 // don't display these countries 87 excludeCountries: [], 88 // format the input value during initialisation and on setNumber 89 formatOnDisplay: true, 90 // geoIp lookup function 91 geoIpLookup: null, 92 // inject a hidden input with this name, and on submit, populate it with the result of getNumber 93 hiddenInput: "", 94 // initial country 95 initialCountry: "", 96 // localized country names e.g. { 'de': 'Deutschland' } 97 localizedCountries: null, 98 // don't insert international dial codes 99 nationalMode: true, 100 // display only these countries 101 onlyCountries: [], 102 // number type to use for placeholders 103 placeholderNumberType: "MOBILE", 104 // the countries at the top of the list. defaults to united states and united kingdom 105 preferredCountries: [ "us", "gb" ], 106 // display the country dial code next to the selected flag so it's not part of the typed number 107 separateDialCode: false, 108 // specify the path to the libphonenumber script to enable validation/formatting 109 utilsScript: "" 110 }; 111 // https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes#Non-geographic_area_codes 112 var regionlessNanpNumbers = [ "800", "822", "833", "844", "855", "866", "877", "880", "881", "882", "883", "884", "885", "886", "887", "888", "889" ]; 113 // utility function to iterate over an object. can't use Object.entries or native forEac
113h because 114 // of IE11 115 var forEachProp = function forEachProp(obj, callback) { 116 var keys = Object.keys(obj); 117 for (var i = 0; i < keys.length; i++) { 118 callback(keys[i], obj[keys[i]]); 119 } 120 }; 121 // run a method on each instance of the plugin 122 var forEachInstance = function forEachInstance(method) { 123 forEachProp(window.intlTelInputGlobals.instances, function(key) { 124 window.intlTelInputGlobals.instances[key][method](); 125 }); 126 }; 127 // this is our plugin class that we will create an instance of 128 // eslint-disable-next-line no-unused-vars 129 var Iti = /*#__PURE__*/ 130 function() { 131 function Iti(input, options) { 132 var _this = this; 133 _classCallCheck(this, Iti); 134 this.id = id++; 135 this.telInput = input; 136 this.activeItem = null; 137 this.highlightedItem = null; 138 // process specified options / defaults 139 // alternative to Object.assign, which isn't supported by IE11 140 var customOptions = options || {}; 141 this.options = {}; 142 forEachProp(defaults, function(key, value) { 143 _this.options[key] = customOptions.hasOwnProperty(key) ? customOptions[key] : value; 144 }); 145 this.hadInitialPlaceholder = Boolean(input.getAttribute("placeholder")); 146 } 147 _createClass(Iti, [ { 148 key: "_init", 149 value: function _init() { 150 var _this2 = this; 151 // if in nationalMode, disable options relating to dial codes 152 if (this.options.nationalMode) this.options.autoHideDialCode = false; 153 // if separateDialCode then doesn't make sense to A) insert dial code into input 154 // (autoHideDialCode), and B) display national numbers (because we're displaying the country 155 // dial code next to them) 156 if (this.options.separateDialCode) { 157 this.options.autoHideDialCode = this.options.nationalMode = false; 158 } 159 // we cannot just test screen size as some smartphones/website meta tags will report desktop 160 // resolutions 161 // Note: for some reason jasmine breaks if you put this in the main Plugin function with the 162 // rest of these declarations 163 // Note: to target Android Mobiles (and not Tablets), we must find 'Android' and 'Mobile' 164 this.isMobile = /Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); 165 if (this.isMobile) { 166 // trigger the mobile dropdown css 167 document.body.classList.add("iti-mobile"); 168 // on mobile, we want a full screen dropdown, so we must append it to the body 169 if (!this.options.dropdownContainer) this.options.dropdownContainer = document.body; 170 } 171 // these promises get resolved when their individual requests complete 172 // this way the dev can do something like iti.promise.then(...) to know when all requests are 173 // complete 174 if (typeof Promise !== "undefined") { 175 var autoCountryPromise = new Promise(function(resolve, reject) { 176 _this2.resolveAutoCountryPromise = resolve; 177 _this2.rejectAutoCountryPromise = reject; 178 }); 179 var utilsScriptPromise = new Promise(function(resolve, reject) { 180 _this2.resolveUtilsScriptPromise = resolve; 181 _this2.rejectUtilsScriptPromise = reject; 182 }); 183 this.promise = Promise.all([ autoCountryPromise, utilsScriptPromise ]); 184 } else { 185 // prevent errors when Promise doesn't exist 186 this.resolveAutoCountryPromise = this.rejectAutoCountryPromise = function() {}; 187 this.resolveUtilsScriptPromise = this.rejectUtilsScriptPromise = function() {}; 188 } 189 // in various situations there could be no country selected initially, but we need to be able 190 // to assume this variable exists 191 this.selectedCountryData = {}; 192 // process all the data: onlyCountries, excludeCountries, preferredCountries etc 193 this._processCountryData(); 194 // generate the markup 195 this._generateMarkup(); 196 // set the initial state of the input value and the selected flag 197 this._setInitialState(); 198 // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click 199 this._initListeners(); 200 // utils script, and auto country 201 this._initRequests(); 202 } 203 }, { 204 key: "_processCountryData", 205 value: function _processCountryData() { 206 // process onlyCountries or excludeCountries array if present 207 this._processAllCountries(); 208 // process the countryCodes map 209 this._processCountryCodes(); 210 // process the preferredCountries 211 this._processPreferredCountries(); 212 // translate countries according to localizedCountries option 213 if (this.options.localizedCountries) this._translateCountriesByLocale(); 214 // sort countries by name 215 if (this.options.onlyCountries.length || this.options.localizedCountries) { 216 this.countries.sort(this._countryNameSort); 217 } 218 } 219 }, { 220 key: "_addCountryCode", 221 value: function _addCountryCode(iso2, countryCode, priority) { 222 if (countryCode.length > this.countryCodeMaxLen) { 223 this.countryCodeMaxLen = countryCode.length; 224 } 225 if (!this.countryCodes.hasOwnProperty(countryCode)) { 226 this.countryCodes[countryCode] = []; 227 } 228 // bail if we already have this country for this countryCode 229 for (var i = 0; i < this.countryCodes[countryCode].length; i++) { 230 if (this.countryCodes[countryCode][i] === iso2) return; 231 } 232 // check for undefined as 0 is falsy 233 var index = priority !== undefined ? priority : this.countryCodes[countryCode].length; 234 this.countryCodes[countryCode][index] = iso2; 235 } 236 }, { 237 key: "_processAllCountries", 238 value: function _processAllCountries() { 239 if (this.options.onlyCountries.length) { 240 var lowerCaseOnlyCountries = this.options.onlyCountries.map(function(country) { 241 return country.toLowerCase(); 242 }); 243 this.countries = allCountries.filter(function(country) { 244 return lowerCaseOnlyCountries.indexOf(country.iso2) > -1; 245 }); 246 } else if (this.options.excludeCountries.length) { 247 var lowerCaseExcludeCountries = this.options.excludeCountries.map(function(country) { 248 return country.toLowerCase(); 249 }); 250 this.countries = allCountries.filter(function(country) { 251 return lowerCaseExcludeCountries.indexOf(country.iso2) === -1; 252 }); 253 } else { 254 this.countries = allCountries; 255 } 256 } 257 }, { 258 key: "_translateCountriesByLocale", 259 value: function _translateCountriesByLocale() { 260 for (var i = 0; i < this.countries.length; i++) { 261 var iso = this.countries[i].iso2.toLowerCase(); 262 if (this.options.localizedCountries.hasOwnProperty(iso)) { 263 this.countries[i].name = this.options.localizedCountries[iso]; 264 } 265 } 266 } 267 }, { 268 key: "_countryNameSort", 269 value: function _countryNameSort(a, b) { 270 return a.name.localeCompare(b.name); 271 } 272 }, { 273 key: "_processCountryCodes", 274 value: function _processCountryCodes() { 275 this.countryCodeMaxLen = 0; 276 // here we store just dial codes 277 this.dialCodes = {}; 278 // here we store "country codes" (both dial codes and their area codes) 279 this.countryCodes = {}; 280 // first: add dial codes 281 for (var i = 0; i < this.countries.length; i++) { 282 var c = this.countries[i]; 283 if (!this.dialCodes[c.dialCode]) this.dialCodes[c.dialCode] = true; 284 this._addCountryCode(c.iso2, c.dialCode, c.priority); 285 } 286 // next: add area codes 287 // this is a second loop over countries, to make sure we have all of the "root" countries 288 // already in the map, so that we can access them, as each time we add an area code substring 289 // to the map, we also need to include the "root" country's code, as that also matches 290 for (var _i = 0; _i < this.countries.length; _i++) { 291 var _c = this.countries[_i]; 292 // area codes 293 if (_c.areaCodes) { 294 var rootCountryCode = this.countryCodes[_c.dialCode][0]; 295 // for each area code 296 for (var j = 0; j < _c.areaCodes.length; j++) { 297 var areaCode = _c.areaCodes[j]; 298 // for each digit in the area code to add all partial matches as well 299 for (var k = 1; k < areaCode.length; k++) { 300 var partialDialCode = _c.dialCode + areaCode.substr(0, k); 301 // start with the root country, as that also matches this dial code 302 this._addCountryCode(rootCountryCode, partialDialCode); 303 this._addCountryCode(_c.iso2, partialDialCode); 304 } 305 // add the full area code 306 this._addCountryCode(_c.iso2, _c.dialCode + areaCode); 307 } 308 } 309 } 310 } 311 }, { 312 key: "_processPreferredCountries", 313 value: function _processPreferredCountries() { 314 this.preferredCountries = []; 315 for (var i = 0; i < this.options.preferredCountries.length; i++) { 316 var countryCode = this.options.preferredCountries[i].toLowerCase(); 317 var countryData = this._getCountryData(countryCode, false, true); 318 if (countryData) this.preferredCountries.push(countryData); 319 } 320 } 321 }, { 322 key: "_createEl", 323 value: function _createEl(name, attrs, container) { 324 var el = document.createElement(name); 325 if (attrs) forEachProp(attrs, function(key, value) { 326 return el.setAttribute(key, value); 327 }); 328 if (container) container.appendChild(el); 329 return el; 330 } 331 }, { 332 key: "_generateMarkup", 333 value: function _generateMarkup() { 334 // if autocomplete does not exist on the element and its form, then 335 // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can 336 // easily put the plugin in an inconsistent state e.g. the wrong flag selected for the
337 // autocompleted number, which on submit could mean wrong number is saved (esp in nationalMode) 338 if (!this.telInput.hasAttribute("autocomplete") && !(this.telInput.form && this.telInput.form.hasAttribute("autocomplete"))) { 339 this.telInput.setAttribute("autocomplete", "off"); 340 } 341 // containers (mostly for positioning) 342 var parentClass = "iti"; 343 if (this.options.allowDropdown) parentClass += " iti--allow-dropdown"; 344 if (this.options.separateDialCode) parentClass += " iti--separate-dial-code"; 345 if (this.options.customContainer) { 346 parentClass += " "; 347 parentClass += this.options.customContainer; 348 } 349 var wrapper = this._createEl("div", { 350 "class": parentClass 351 }); 352 this.telInput.parentNode.insertBefore(wrapper, this.telInput); 353 this.flagsContainer = this._createEl("div", { 354 "class": "iti__flag-container" 355 }, wrapper); 356 wrapper.appendChild(this.telInput); 357 // selected flag (displayed to left of input) 358 this.selectedFlag = this._createEl("div", { 359 "class": "iti__selected-flag", 360 role: "combobox", 361 "aria-controls": "iti-".concat(this.id, "__country-listbox"), 362 "aria-owns": "iti-".concat(this.id, "__country-listbox"), 363 "aria-expanded": "false" 364 }, this.flagsContainer); 365 this.selectedFlagInner = this._createEl("div", { 366 "class": "iti__flag" 367 }, this.selectedFlag); 368 if (this.options.separateDialCode) { 369 this.selectedDialCode = this._createEl("div", { 370 "class": "iti__selected-dial-code" 371 }, this.selectedFlag); 372 } 373 if (this.options.allowDropdown) { 374 // make element focusable and tab navigable 375 this.selectedFlag.setAttribute("tabindex", "0"); 376 this.dropdownArrow = this._createEl("div", { 377 "class": "iti__arrow" 378 }, this.selectedFlag); 379 // country dropdown: preferred countries, then divider, then all countries 380 this.countryList = this._createEl("ul", { 381 "class": "iti__country-list iti__hide", 382 id: "iti-".concat(this.id, "__country-listbox"), 383 role: "listbox", 384 "aria-label": "List of countries" 385 }); 386 if (this.preferredCountries.length) { 387 this._appendListItems(this.preferredCountries, "iti__preferred", true); 388 this._createEl("li", { 389 "class": "iti__divider", 390 role: "separator", 391 "aria-disabled": "true" 392 }, this.countryList); 393 } 394 this._appendListItems(this.countries, "iti__standard"); 395 // create dropdownContainer markup 396 if (this.options.dropdownContainer) { 397 this.dropdown = this._createEl("div", { 398 "class": "iti iti--container" 399 }); 400 this.dropdown.appendChild(this.countryList); 401 } else { 402 this.flagsContainer.appendChild(this.countryList); 403 } 404 } 405 if (this.options.hiddenInput) { 406 var hiddenInputName = this.options.hiddenInput; 407 var name = this.telInput.getAttribute("name"); 408 if (name) { 409 var i = name.lastIndexOf("["); 410 // if input name contains square brackets, then give the hidden input the same name, 411 // replacing the contents of the last set of brackets with the given hiddenInput name 412 if (i !== -1) hiddenInputName = "".concat(name.substr(0, i), "[").concat(hiddenInputName, "]"); 413 } 414 this.hiddenInput = this._createEl("input", { 415 type: "hidden", 416 name: hiddenInputName 417 }); 418 wrapper.appendChild(this.hiddenInput); 419 } 420 } 421 }, { 422 key: "_appendListItems", 423 value: function _appendListItems(countries, className, preferred) { 424 // we create so many DOM elements, it is faster to build a temp string 425 // and then add everything to the DOM in one go at the end 426 var tmp = ""; 427 // for each country 428 for (var i = 0; i < countries.length; i++) { 429 var c = countries[i]; 430 var idSuffix = preferred ? "-preferred" : ""; 431 // open the list item 432 tmp += "<li class='iti__country ".concat(className, "' tabIndex='-1' id='iti-").concat(this.id, "__item-").concat(c.iso2).concat(idSuffix, "' role='option' data-dial-code='").concat(c.dialCode, "' data-country-code='").concat(c.iso2, "' aria-selected='false'>"); 433 // add the flag 434 tmp += "<div class='iti__flag-box'><div class='iti__flag iti__".concat(c.iso2, "'></div></div>"); 435 // and the country name and dial code 436 tmp += "<span class='iti__country-name'>
436".concat(c.name, "</span>"); 437 tmp += "<span class='iti__dial-code'>+".concat(c.dialCode, "</span>"); 438 // close the list item 439 tmp += "</li>"; 440 } 441 this.countryList.insertAdjacentHTML("beforeend", tmp); 442 } 443 }, { 444 key: "_setInitialState", 445 value: function _setInitialState() { 446 // fix firefox bug: when first load page (with input with value set to number with intl dial 447 // code) and initialising plugin removes the dial code from the input, then refresh page, 448 // and we try to init plugin again but this time on number without dial code so get grey flag 449 var attributeValue = this.telInput.getAttribute("value"); 450 var inputValue = this.telInput.value; 451 var useAttribute = attributeValue && attributeValue.charAt(0) === "+" && (!inputValue || inputValue.charAt(0) !== "+"); 452 var val = useAttribute ? attributeValue : inputValue; 453 var dialCode = this._getDialCode(val); 454 var isRegionlessNanp = this._isRegionlessNanp(val); 455 var _this$options = this.options, initialCountry = _this$options.initialCountry, nationalMode = _this$options.nationalMode, autoHideDialCode = _this$options.autoHideDialCode, separateDialCode = _this$options.separateDialCode; 456 // if we already have a dial code, and it's not a regionlessNanp, we can go ahead and set the 457 // flag, else fall back to the default country 458 if (dialCode && !isRegionlessNanp) { 459 this._updateFlagFromNumber(val); 460 } else if (initialCountry !== "auto") { 461 // see if we should select a flag 462 if (initialCountry) { 463 this._setFlag(initialCountry.toLowerCase()); 464 } else { 465 if (dialCode && isRegionlessNanp) { 466 // has intl dial code, is regionless nanp, and no initialCountry, so default to US 467 this._setFlag("us"); 468 } else { 469 // no dial code and no initialCountry, so default to first in list 470 this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2; 471 if (!val) { 472 this._setFlag(this.defaultCountry); 473 } 474 } 475 } 476 // if empty and no nationalMode and no autoHideDialCode then insert the default dial code 477 if (!val && !nationalMode && !autoHideDialCode && !separateDialCode) { 478 this.telInput.value = "+".concat(this.selectedCountryData.dialCode); 479 } 480 } 481 // NOTE: if initialCountry is set to auto, that will be handled separately 482 // format - note this wont be run after _updateDialCode as that's only called
482if no val 483 if (val) this._updateValFromNumber(val); 484 } 485 }, { 486 key: "_initListeners", 487 value: function _initListeners() { 488 this._initKeyListeners(); 489 if (this.options.autoHideDialCode) this._initBlurListeners(); 490 if (this.options.allowDropdown) this._initDropdownListeners(); 491 if (this.hiddenInput) this._initHiddenInputListener(); 492 } 493 }, { 494 key: "_initHiddenInputListener", 495 value: function _initHiddenInputListener() { 496 var _this3 = this; 497 this._handleHiddenInputSubmit = function() { 498 _this3.hiddenInput.value = _this3.getNumber(); 499 }; 500 if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleHiddenInputSubmit); 501 } 502 }, { 503 key: "_getClosestLabel", 504 value: function _getClosestLabel() { 505 var el = this.telInput; 506 while (el && el.tagName !== "LABEL") { 507 el = el.parentNode; 508 } 509 return el; 510 } 511 }, { 512 key: "_initDropdownListeners", 513 value: function _initDropdownListeners() { 514 var _this4 = this; 515 // hack for input nested inside label (which is valid markup): clicking the selected-flag to 516 // open the dropdown would then automatically trigger a 2nd click on the input which would 517 // close it again 518 this._handleLabelClick = function(e) { 519 // if the dropdown is closed, then focus the input, else ignore the click 520 if (_this4.countryList.classList.contains("iti__hide")) _this4.telInput.focus(); else e.preventDefault(); 521 }; 522 var label = this._getClosestLabel(); 523 if (label) label.addEventListener("click", this._handleLabelClick); 524 // toggle country dropdown on click 525 this._handleClickSelectedFlag = function() { 526 // only intercept this event if we're opening the dropdown 527 // else let it bubble up to the top ("click-off-to-close" listener) 528 // we cannot just stopPropagation as it may be needed to close another instance 529 if (_this4.countryList.classList.contains("iti__hide") && !_this4.telInput.disabled && !_this4.telInput.readOnly) { 530 _this4._showDropdown(); 531 } 532 }; 533 this.selectedFlag.addEventListener("click", this._handleClickSelectedFlag); 534 // open dropdown list if currently focused 535 this._handleFlagsContainerKeydown = function(e) { 536 var isDropdownHidden = _this4.countryList.classList.contains("iti__hide"); 537 if (isDropdownHidden && [ "ArrowUp", "Up", "ArrowDown", "Down", " ", "Enter" ].indexOf(e.key) !== -1) { 538 // prevent form from being submitted if "ENTER" was pressed 539 e.preventDefault(); 540 // prevent event from being handled again by document 541 e.stopPropagation(); 542 _this4._showDropdown(); 543 } 544 // allow navigation from dropdown to input on TAB 545 if (e.key === "Tab") _this4._closeDropdown(); 546 }; 547 this.flagsContainer.addEventListener("keydown", this._handleFlagsContainerKeydown); 548 } 549 }, { 550 key: "_initRequests", 551 value: function _initRequests() { 552 var _this5 = this; 553 // if the user has specified the path to the utils script, fetch it on window.load, else resolve 554 if (this.options.utilsScript && !window.intlTelInputUtils) { 555 // if the plugin is being initialised after the window.load event has already been fired 556 if (window.intlTelInputGlobals.documentReady()) { 557 window.intlTelInputGlobals.loadUtils(this.options.utilsScript); 558 } else { 559 // wait until the load event so we don't block any other requests e.g. the flags image 560 window.addEventListener("load", function() { 561 window.intlTelInputGlobals.loadUtils(_this5.options.utilsScript); 562 }); 563 } 564 } else this.resolveUtilsScriptPromise(); 565 if (this.options.initialCountry === "auto") this._loadAutoCountry(); else this.resolveAutoCountryPromise(); 566 } 567 }, { 568 key: "_loadAutoCountry", 569 value: function _loadAutoCountry() { 570 // 3 options: 571 // 1) already loaded (we're done) 572 // 2) not already started loading (start) 573 // 3) already started loading (do nothing - just wait for loading callback to fire) 574 if (window.intlTelInputGlobals.autoCountry) { 575 this.handleAutoCountry(); 576 } else if (!window.intlTelInputGlobals.startedLoadingAutoCountry) { 577 // don't do this twice! 578 window.intlTelInputGlobals.startedLoadingAutoCountry = true; 579 if (typeof this.options.geoIpLookup === "function") { 580 this.options.geoIpLookup(function(countryCode) { 581 window.intlTelInputGlobals.autoCountry = countryCode.toLowerCase(); 582 // tell all instances the auto country is ready 583 // TODO: this should just be the current instances 584 // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight 585 // away (e.g. if they have already done the geo ip lookup somewhere else). Using 586 // setTimeout means that the current thread of execution will finish before executing 587 // this, which allows the plugin to finish initialising. 588 setTimeout(function() { 589 return forEachInstance("handleAutoCountry"); 590 }); 591 }, function() { 592 return forEachInstance("rejectAutoCountryPromise"); 593 }); 594 } 595 } 596 } 597 }, { 598 key: "_initKeyListeners", 599 value: function _initKeyListeners() { 600 var _this6 = this; 601 // update flag on keyup 602 this._handleKeyupEvent = function() { 603 if (_this6._updateFlagFromNumber(_this6.telInput.value)) { 604 _this6._triggerCountryChange(); 605 } 606 }; 607 this.telInput.addEventListener("keyup", this._handleKeyupEvent); 608 // update flag on cut/paste events (now supported in all major browsers) 609 this._handleClipboardEvent = function() { 610 // hack because "paste" event is fired before input is updated 611 setTimeout(_this6._handleKeyupEvent); 612 }; 613 this.telInput.addEventListener("cut", this._handleClipboardEvent); 614 this.telInput.addEventListener("paste", this._handleClipboardEvent); 615 } 616 }, { 617 key: "_cap", 618 value: function _cap(number) { 619 var max = this.telInput.getAttribute("maxlength"); 620 return max && number.length > max ? number.substr(0, max) : number; 621 } 622 }, { 623 key: "_initBlurListeners", 624 value: function _initBlurListeners() { 625 var _this7 = this; 626 // on blur or form submit: if just a dial code then remove it 627 this._handleSubmitOrBlurEvent = function() { 628 _this7._removeEmptyDialCode(); 629 }; 630 if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleSubmitOrBlurEvent); 631 this.telInput.addEventListener("blur", this._handleSubmitOrBlurEvent); 632 } 633 }, { 634 key: "_removeEmptyDialCode", 635 value: function _removeEmptyDialCode() { 636 if (this.telInput.value.charAt(0) === "+") { 637 var numeric = this._getNumeric(this.telInput.value); 638 // if just a plus, or if just a dial code 639 if (!numeric || this.selectedCountryData.dialCode === numeric) { 640 this.telInput.value = ""; 641 } 642 } 643 } 644 }, { 645 key: "_getNumeric", 646 value: function _getNumeric(s) { 647 return s.replace(/\D/g, ""); 648 } 649 }, { 650 key: "_trigger", 651 value: function _trigger(name) {
652 // have to use old school document.createEvent as IE11 doesn't support `new Event()` syntax 653 var e = document.createEvent("Event"); 654 e.initEvent(name, true, true); 655 // can bubble, and is cancellable 656 this.telInput.dispatchEvent(e); 657 } 658 }, { 659 key: "_showDropdown", 660 value: function _showDropdown() { 661 this.countryList.classList.remove("iti__hide"); 662 this.selectedFlag.setAttribute("aria-expanded", "true"); 663 this._setDropdownPosition(); 664 // update highlighting and scroll to active list item 665 if (this.activeItem) { 666 this._highlightListItem(this.activeItem, false); 667 this._scrollTo(this.activeItem, true); 668 } 669 // bind all the dropdown-related listeners: mouseover, click, click-off, keydown 670 this._bindDropdownListeners(); 671 // update the arrow 672 this.dropdownArrow.classList.add("iti__arrow--up"); 673 this._trigger("open:countrydropdown"); 674 } 675 }, { 676 key: "_toggleClass", 677 value: function _toggleClass(el, className, shouldHaveClass) { 678 if (shouldHaveClass && !el.classList.contains(className)) el.classList.add(className); else if (!shouldHaveClass && el.classList.contains(className)) el.classList.remove(className); 679 } 680 }, { 681 key: "_setDropdownPosition", 682 value: function _setDropdownPosition() { 683 var _this8 = this; 684 if (this.options.dropdownContainer) { 685 this.options.dropdownContainer.appendChild(this.dropdown); 686 } 687 if (!this.isMobile) { 688 var pos = this.telInput.getBoundingClientRect(); 689 // windowTop from https://stackoverflow.com/a/14384091/217866 690 var windowTop = window.pageYOffset || document.documentElement.scrollTop; 691 var inputTop = pos.top + windowTop; 692 var dropdownHeight = this.countryList.offsetHeight; 693 // dropdownFitsBelow = (dropdownBottom < windowBottom) 694 var dropdownFitsBelow = inputTop + this.telInput.offsetHeight + dropdownHeight < windowTop + window.innerHeight; 695 var dropdownFitsAbove = inputTop - dropdownHeight > windowTop; 696 // by default, the dropdown will be below the input. If we want to position it above the 697 // input, we add the dropup class. 698 this._toggleClass(this.countryList, "iti__country-list--dropup", !dropdownFitsBelow && dropdownFitsAbove); 699 // if dropdownContainer is enabled, calculate postion 700 if (this.options.dropdownContainer) { 701 // by default the dropdown will be directly over the input because it's not in the flow. 702 // If we want to position it below, we need to add some extra top value. 703 var extraTop = !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.offsetHeight; 704 // calculate placement 705 this.dropdown.style.top = "".concat(inputTop + extraTop, "px"); 706 this.dropdown.style.left = "".concat(pos.left + document.body.scrollLeft, "px"); 707 // close menu on window scroll 708 this._handleWindowScroll = function() { 709 return _this8._closeDropdown(); 710 }; 711 window.addEventListener("scroll", this._handleWindowScroll); 712 } 713 } 714 } 715 }, { 716 key: "_getClosestListItem", 717 value: function _getClosestListItem(target) { 718 var el = target; 719 while (el && el !== this.countryList && !el.classList.contains("iti__country")) { 720 el = el.parentNode; 721 } 722 // if we reached the countryList element, then return null 723 return el === this.countryList ? null : el; 724 } 725 }, { 726 key: "_bindDropdownListeners", 727 value: function _bindDropdownListeners() { 728 var _this9 = this; 729 // when mouse over a list item, just highlight that one 730 // we add the class "highlight", so if they hit "enter" we know
730which one to select 731 this._handleMouseoverCountryList = function(e) { 732 // handle event delegation, as we're listening for this event on the countryList 733 var listItem = _this9._getClosestListItem(e.target); 734 if (listItem) _this9._highlightListItem(listItem, false); 735 }; 736 this.countryList.addEventListener("mouseover", this._handleMouseoverCountryList); 737 // listen for country selection 738 this._handleClickCountryList = function(e) { 739 var listItem = _this9._getClosestListItem(e.target); 740 if (listItem) _this9._selectListItem(listItem); 741 }; 742 this.countryList.addEventListener("click", this._handleClickCountryList); 743 // click off to close 744 // (except when this initial opening click is bubbling up) 745 // we cannot just stopPropagation as it may be needed to close another instance 746 var isOpening = true; 747 this._handleClickOffToClose = function() { 748 if (!isOpening) _this9._closeDropdown(); 749 isOpening = false; 750 }; 751 document.documentElement.addEventListener("click", this._handleClickOffToClose); 752 // listen for up/down scrolling, enter to select, or letters to jump to country name. 753 // use keydown as keypress doesn't fire for non-char keys and we want to catch if they 754 // just hit down and hold it to scroll down (no keyup event). 755 // listen on the document because that's where key events are triggered if no input has focus 756 var query = ""; 757 var queryTimer = null; 758 this._handleKeydownOnDropdown = function(e) { 759 // prevent down key from scrolling the whole page, 760 // and enter key from submitting a form etc 761 e.preventDefault(); 762 // up and down to navigate 763 if (e.key === "ArrowUp" || e.key === "Up" || e.key === "ArrowDown" || e.key === "Down") _this9._handleUpDownKey(e.key); else if (e.key === "Enter") _this9._handleEnterKey(); else if (e.key === "Escape") _this9._closeDropdown(); else if (/^[a-zA-Z ]$/.test(e.key)) { 764 // jump to countries that start with the query string 765 if (queryTimer) clearTimeout(queryTimer); 766 query += e.key.toLowerCase(); 767 _this9._searchForCountry(query); 768 // if the timer hits 1 second, reset the query 769 queryTimer = setTimeout(function() { 770 query = ""; 771 }, 1e3); 772 } 773 }; 774 document.addEventListener("keydown", this._handleKeydownOnDropdown); 775 } 776 }, { 777 key: "_handleUpDownKey", 778 value: function _handleUpDownKey(key) { 779 var next = key === "ArrowUp" || key === "Up" ? this.highlightedItem.previousElementSibling : this.highlightedItem.nextElementSibling; 780 if (next) { 781 // skip the divider 782 if (next.classList.contains("iti__divider")) { 783 next = key === "ArrowUp" || key === "Up" ? next.previousElementSibling : next.nextElementSibling; 784 } 785 this._highlightListItem(next, true); 786 } 787 } 788 }, { 789 key: "_handleEnterKey", 790 value: function _handleEnterKey() { 791 if (this.highlightedItem) this._selectListItem(this.highlightedItem); 792 } 793 }, { 794 key: "_searchForCountry", 795 value: function _searchForCountry(query) { 796 for (var i = 0; i < this.countries.length; i++) { 797 if (this._startsWith(this.countries[i].name, query)) { 798 var listItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(this.countries[i].iso2)); 799 // update highlighting and scroll 800 this._highlightListItem(listItem, false); 801 this._scrollTo(listItem, true); 802 break; 803 } 804 } 805 } 806 }, { 807 key: "_startsWith", 808 value: function _startsWith(a, b) { 809 return a.substr(0, b.length).toLowerCase() === b; 810 } 811 }, {
812 key: "_updateValFromNumber", 813 value: function _updateValFromNumber(originalNumber) { 814 var number = originalNumber; 815 if (this.options.formatOnDisplay && window.intlTelInputUtils && this.selectedCountryData) { 816 var useNational = !this.options.separateDialCode && (this.options.nationalMode || number.charAt(0) !== "+"); 817 var _intlTelInputUtils$nu = intlTelInputUtils.numberFormat, NATIONAL = _intlTelInputUtils$nu.NATIONAL, INTERNATIONAL = _intlTelInputUtils$nu.INTERNATIONAL; 818 var format = useNational ? NATIONAL : INTERNATIONAL; 819 number = intlTelInputUtils.formatNumber(number, this.selectedCountryData.iso2, format); 820 } 821 number = this._beforeSetNumber(number); 822 this.telInput.value = number; 823 } 824 }, { 825 key: "_updateFlagFromNumber", 826 value: function _updateFlagFromNumber(originalNumber) { 827 // if we're in nationalMode and we already have US/Canada selected, make sure the number starts 828 // with a +1 so _getDialCode will be able to extract the area code 829 // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag 830 // from the number), that means we're initialising the plugin with a number that already has a 831 // dial code, so fine to ignore this bit 832 var number = originalNumber; 833 var selectedDialCode = this.selectedCountryData.dialCode; 834 var isNanp = selectedDialCode === "1"; 835 if (number && this.options.nationalMode && isNanp && number.charAt(0) !== "+") { 836 if (number.charAt(0) !== "1") number = "1".concat(number); 837 number = "+".concat(number); 838 } 839 // update flag if user types area code for another country 840 if (this.options.separateDialCode && selectedDialCode && number.charAt(0) !== "+") { 841 number = "+".concat(selectedDialCode).concat(number); 842 } 843 // try and extract valid dial code from input 844 var dialCode = this._getDialCode(number, true); 845 var numeric = this._getNumeric(number); 846 var countryCode = null; 847 if (dialCode) { 848 var countryCodes = this.countryCodes[this._getNumeric(dialCode)]; 849 // check if the right country is already selected. this should be false if the number is 850 // longer than the matched dial code because in this case we need to make sure that if 851 // there are multiple country matches, that the first one is selected (note: we could 852 // just check that here, but it requires the same loop that we already have later) 853 var alreadySelected = countryCodes.indexOf(this.selectedCountryData.iso2) !== -1 && numeric.length <= dialCode.length - 1; 854 var isRegionlessNanpNumber = selectedDialCode === "1" && this._isRegionlessNanp(numeric); 855 // only update the flag if: 856 // A) NOT (we currently have a NANP flag selected, and the number is a regionlessNanp) 857 // AND 858 // B) the right country is not already selected 859 if (!isRegionlessNanpNumber && !alreadySelected) { 860 // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first 861 // non-empty index 862 for (var j = 0; j < countryCodes.length; j++) { 863 if (countryCodes[j]) { 864 countryCode = countryCodes[j]; 865 break; 866 } 867 } 868 } 869 } else if (number.charAt(0) === "+" && numeric.length) { 870 // invalid dial code, so empty 871 // Note: use getNumeric here because the number has not been formatted yet, so could contain 872 // bad chars 873 countryCode = ""; 874 } else if (!number || number === "+") { 875 // empty, or just a plus, so default 876 countryCode = this.defaultCountry; 877 } 878 if (countryCode !== null) { 879 return this._setFlag(countryCode); 880 } 881 return false;
882 } 883 }, { 884 key: "_isRegionlessNanp", 885 value: function _isRegionlessNanp(number) { 886 var numeric = this._getNumeric(number); 887 if (numeric.charAt(0) === "1") { 888 var areaCode = numeric.substr(1, 3); 889 return regionlessNanpNumbers.indexOf(areaCode) !== -1; 890 } 891 return false; 892 } 893 }, { 894 key: "_highlightListItem", 895 value: function _highlightListItem(listItem, shouldFocus) { 896 var prevItem = this.highlightedItem; 897 if (prevItem) prevItem.classList.remove("iti__highlight"); 898 this.highlightedItem = listItem; 899 this.highlightedItem.classList.add("iti__highlight"); 900 if (shouldFocus) this.highlightedItem.focus(); 901 } 902 }, { 903 key: "_getCountryData", 904 value: function _getCountryData(countryCode, ignoreOnlyCountriesOption, allowFail) { 905 var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries; 906 for (var i = 0; i < countryList.length; i++) { 907 if (countryList[i].iso2 === countryCode) { 908 return countryList[i]; 909 } 910 } 911 if (allowFail) { 912 return null; 913 } 914 throw new Error("No country data for '".concat(countryCode, "'")); 915 } 916 }, { 917 key: "_setFlag", 918 value: function _setFlag(countryCode) { 919 var prevCountry = this.selectedCountryData.iso2 ? this.selectedCountryData : {}; 920 // do this first as it will throw an error and stop if countryCode is invalid 921 this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {}; 922 // update the defaultCountry - we only need the iso2 from now on, so just store that 923 if (this.selectedCountryData.iso2) { 924 this.defaultCountry = this.selectedCountryData.iso2; 925 } 926 this.selectedFlagInner.setAttribute("class", "iti__flag iti__".concat(countryCode)); 927 // update the selected country's title attribute 928 var title = countryCode ? "".concat(this.selectedCountryData.name, ": +").concat(this.selectedCountryData.dialCode) : "Unknown"; 929 this.selectedFlag.setAttribute("title", title); 930 if (this.options.separateDialCode) { 931 var dialCode = this.selectedCountryData.dialCode ? "+".concat(this.selectedCountryData.dialCode) : ""; 932 this.selectedDialCode.innerHTML = dialCode; 933 // offsetWidth is zero if input is in a hidden container during initialisation 934 var selectedFlagWidth = this.selectedFlag.offsetWidth || this._getHiddenSelectedFlagWidth(); 935 // add 6px of padding after the grey selected-dial-code box, as this is what we use in the css 936 this.telInput.style.paddingLeft = "".concat(selectedFlagWidth + 6, "px"); 937 } 938 // and the input's placeholder 939 this._updatePlaceholder(); 940 // update the active list item 941 if (this.options.allowDropdown) { 942 var prevItem = this.activeItem; 943 if (prevItem) { 944 prevItem.classList.remove("iti__active"); 945 prevItem.setAttribute("aria-selected", "false"); 946 } 947 if (countryCode) { 948 // check if there is a preferred item first, else fall back to standard 949 var nextItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode, "-preferred")) || this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode)); 950 nextItem.setAttribute("aria-selected", "true"); 951 nextItem.classList.add("iti__active"); 952 this.activeItem = nextItem; 953 this.selectedFlag.setAttribute("aria-activedescendant", nextItem.getAttribute("id")); 954 } 955 } 956 // return if the flag has changed or not 957 return prevCountry.iso2 !== countryCode; 958 } 959 }, { 960 key: "_getHiddenSelectedFlagWidth", 961 value: function _getHiddenSelectedFlagWidth() { 962 // to get the right styling to apply, all we need is a shallow clone of the container, 963 // and then to inject a deep clone of the selectedFlag element 964 var containerClone = this.telInput.parentNode.cloneNode(); 965 containerClone.style.visibility = "hidden"; 966 document.body.appendChild(containerClone); 967 var flagsContainerClone = this.flagsContainer.cloneNode(); 968 containerClone.appendChild(flagsContainerClone); 969 var selectedFlagClone = this.selectedFlag.cloneNode(true); 970 flagsContainerClone.appendChild(selectedFlagClone); 971 var width = selectedFlagClone.offsetWidth; 972 containerClone.parentNode.removeChild(containerClone); 973 return width; 974 } 975 }, { 976 key: "_updatePlaceholder", 977 value: function _updatePlaceholder() { 978 var shouldSetPlaceholder = this.options.autoPlaceholder === "aggressive" || !this.hadInitialPlaceholder && this.options.autoPlaceholder === "polite"; 979 if (window.intlTelInputUtils && shouldSetPlaceholder) { 980 var numberType = intlTelInputUtils.numberType[this.options.placeholderNumberType]; 981 var placeholder = this.selectedCountryData.iso2 ? intlTelInputUtils.getExampleNumber(this.selectedCountryData.iso2, this.options.nationalMode, numberType) : ""; 982 placeholder = this._beforeSetNumber(placeholder); 983 if (typeof this.options.customPlaceholder === "function") { 984 placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData); 985 } 986 this.telInput.setAttribute("placeholder", placeholder); 987 } 988 } 989 }, { 990 key: "_selectListItem", 991 value: function _selectListItem(listItem) { 992 // update selected flag and active list item 993 var flagChanged = this._setFlag(listItem.getAttribute("data-country-code")); 994 this._closeDropdown(); 995 this._updateDialCode(listItem.getAttribute("data-dial-code"), true); 996 // focus the input 997 this.telInput.focus(); 998 // put cursor at end - this fix is required for FF and IE11 (with nationalMode=false i.e. auto 999 // inserting dial code), who try to put the cursor at the beginning the first time 1000 var len = this.telInput.value.length; 1001 this.telInput.setSelectionRange(len, len); 1002 if (flagChanged) { 1003 this._triggerCountryChange(); 1004 } 1005 } 1006 }, { 1007 key: "_closeDropdown", 1008 value: function _closeDropdown() { 1009 this.countryList.classList.add("iti__hide"); 1010 this.selectedFlag.setAttribute("aria-expanded", "false"); 1011 // update the arrow 1012 this.dropdownArrow.classList.remove("iti__arrow--up"); 1013 // unbind key events 1014 document.removeEventListener("keydown", this._handleKeydownOnDropdown); 1015 document.documentElement.removeEventListener("click", this._handleClickOffToClose); 1016 this.countryList.removeEventListener("mouseover", this._handleMouseoverCountryList); 1017 this.countryList.removeEventListener("click", this._handleClickCountryList); 1018 // remove menu from container 1019 if (this.options.dropdownContainer) { 1020 if (!this.isMobile) window.removeEventListener("scroll", this._handleWindowScroll); 1021 if (this.dropdown.parentNode) this.dropdown.parentNode.removeChild(this.dropdown); 1022 } 1023 this._trigger("close:countrydropdown"); 1024 } 1025 }, { 1026 key: "_scrollTo", 1027 value: function _scrollTo(element, middle) { 1028 var container = this.countryList; 1029 // windowTop from https://stackoverflow.com/a/14384091/2
102917866 1030 var windowTop = window.pageYOffset || document.documentElement.scrollTop; 1031 var containerHeight = container.offsetHeight; 1032 var containerTop = container.getBoundingClientRect().top + windowTop; 1033 var containerBottom = containerTop + containerHeight; 1034 var elementHeight = element.offsetHeight; 1035 var elementTop = element.getBoundingClientRect().top + windowTop; 1036 var elementBottom = elementTop + elementHeight; 1037 var newScrollTop = elementTop - containerTop + container.scrollTop; 1038 var middleOffset = containerHeight / 2 - elementHeight / 2; 1039 if (elementTop < containerTop) { 1040 // scroll up 1041 if (middle) newScrollTop -= middleOffset; 1042 container.scrollTop = newScrollTop; 1043 } else if (elementBottom > containerBottom) { 1044 // scroll down 1045 if (middle) newScrollTop += middleOffset; 1046 var heightDifference = containerHeight - elementHeight; 1047 container.scrollTop = newScrollTop - heightDifference; 1048 } 1049 } 1050 }, { 1051 key: "_updateDialCode", 1052 value: function _updateDialCode(newDialCodeBare, hasSelectedListItem) { 1053 var inputVal = this.telInput.value; 1054 // save having to pass this every time 1055 var newDialCode = "+".concat(newDialCodeBare); 1056 var newNumber; 1057 if (inputVal.charAt(0) === "+") { 1058 // there's a plus so we're dealing with a replacement (doesn't matter if nationalMode or not) 1059 var prevDialCode = this._getDialCode(inputVal); 1060 if (prevDialCode) { 1061 // current number contains a valid dial code, so replace it 1062 newNumber = inputVal.replace(prevDialCode, newDialCode); 1063 } else { 1064 // current number contains an invalid dial code, so ditch it 1065 // (no way to determine where the invalid dial code ends and the rest of the number begins) 1066 newNumber = newDialCode; 1067 } 1068 } else if (this.options.nationalMode || this.options.separateDialCode) { 1069 // don't do anything 1070 return; 1071 } else { 1072 // nationalMode is disabled 1073 if (inputVal) { 1074 // there is an existing value with no dial code: prefix the new dial code 1075 newNumber = newDialCode + inputVal; 1076 } else if (hasSelectedListItem || !this.options.autoHideDialCode) { 1077 // no existing value and either they've just selected a list item, or autoHideDialCode is 1078 // disabled: insert new dial code 1079 newNumber = newDialCode; 1080 } else { 1081 return; 1082 } 1083 } 1084 this.telInput.value = newNumber; 1085 } 1086 }, { 1087 key: "_getDialCode", 1088 value: function _getDialCode(number, includeAreaCode) { 1089 var dialCode = ""; 1090 // only interested in international numbers (starting with a plus) 1091 if (number.charAt(0) === "+") { 1092 var numericChars = ""; 1093 // iterate over chars 1094 for (var i = 0; i < number.length; i++) { 1095 var c = number.charAt(i); 1096 // if char is number (https://stackoverflow.com/a/8935649/217866) 1097 if (!isNaN(parseInt(c, 10))) { 1098 numericChars += c; 1099 // if current numericChars make a valid dial code 1100 if (includeAreaCode) { 1101 if (this.countryCodes[numericChars]) { 1102 // store the actual raw string (useful for matching later) 1103 dialCode = number.substr(0, i + 1); 1104 } 1105 } else { 1106 if (this.dialCodes[numericChars]) { 1107 dialCode = number.substr(0, i + 1); 1108 // if we're just looking for a dial code, we can break as soon as we find one 1109 break; 1110 } 1111 } 1112 // stop searching as soon as we can - in this case when we hit max len 1113 if (numericChars.length === this.countryCodeMaxLen) { 1114 break; 1115 } 1116 } 1117 } 1118 } 1119 return dialCode; 1120 } 1121 }, { 1122 key: "_getFullNumber", 1123 value: function _getFullNumber() { 1124 var val = this.telInput.value.trim(); 1125 var dialCode = this.selectedCountryData.dialCode; 1126 var prefix; 1127 var numericVal = this._getNumeric(val); 1128 if (this.options.separateDialCode && val.charAt(0) !== "+" && dialCode && numericVal) { 1129 // when using separateDialCode, it is visible so is effectively part of the typed number 1130 prefix = "+".concat(dialCode); 1131 } else { 1132 prefix = ""; 1133 } 1134 return prefix + val; 1135 } 1136 }, { 1137 key: "_beforeSetNumber", 1138 value: function _beforeSetNumber(originalNumber) { 1139 var number = originalNumber; 1140 if (this.options.separateDialCode) { 1141 var dialCode = this._getDialCode(number); 1142 // if there is a valid dial code 1143 if (dialCode) { 1144 // in case _getDialCode returned an area code as well 1145 dialCode = "+".concat(this.selectedCountryData.dialCode); 1146 // a lot of numbers will have a space separating the dial code and the main number, and 1147 // some NANP numbers will have a hyphen e.g. +1 684-733-1234 - in both cases we want to get 1148 // rid of it 1149 // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc 1150 var start = number[dialCode.length] === " " || number[dialCode.length] === "-" ? dialCode.length + 1 : dialCode.length; 1151 number = number.substr(start); 1152 } 1153 } 1154 return this._cap(number); 1155 } 1156 }, { 1157 key: "_triggerCountryChange", 1158 value: function _triggerCountryChange() { 1159 this._trigger("countrychange"); 1160 } 1161 }, { 1162 key: "handleAutoCountry", 1163 value: function handleAutoCountry() { 1164 if (this.options.initialCountry === "auto") { 1165 // we must set this even if there is an initial val in the input: in case the initial val is 1166 // invalid and they delete it - they should see their auto country 1167 this.defaultCountry = window.intlTelInputGlobals.autoCountry; 1168 // if there's no initial value in the input, then update the flag 1169 if (!this.telInput.value) { 1170 this.setCountry(this.defaultCountry); 1171 } 1172 this.resolveAutoCountryPromise(); 1173 } 1174 } 1175 }, { 1176 key: "handleUtils", 1177 value: function handleUtils() { 1178 // if the request was successful 1179 if (window.intlTelInputUtils) { 1180 // if there's an initial value in the input, then format it 1181 if (this.telInput.value) {
1182 this._updateValFromNumber(this.telInput.value); 1183 } 1184 this._updatePlaceholder(); 1185 } 1186 this.resolveUtilsScriptPromise(); 1187 } 1188 }, { 1189 key: "destroy", 1190 value: function destroy() { 1191 var form = this.telInput.form; 1192 if (this.options.allowDropdown) { 1193 // make sure the dropdown is closed (and unbind listeners) 1194 this._closeDropdown(); 1195 this.selectedFlag.removeEventListener("click", this._handleClickSelectedFlag); 1196 this.flagsContainer.removeEventListener("keydown", this._handleFlagsContainerKeydown); 1197 // label click hack 1198 var label = this._getClosestLabel(); 1199 if (label) label.removeEventListener("click", this._handleLabelClick); 1200 } 1201 // unbind hiddenInput listeners 1202 if (this.hiddenInput && form) form.removeEventListener("submit", this._handleHiddenInputSubmit); 1203 // unbind autoHideDialCode listeners 1204 if (this.options.autoHideDialCode) { 1205 if (form) form.removeEventListener("submit", this._handleSubmitOrBlurEvent); 1206 this.telInput.removeEventListener("blur", this._handleSubmitOrBlurEvent); 1207 } 1208 // unbind key events, and cut/paste events 1209 this.telInput.removeEventListener("keyup", this._handleKeyupEvent); 1210 this.telInput.removeEventListener("cut", this._handleClipboardEvent); 1211 this.telInput.removeEventListener("paste", this._handleClipboardEvent); 1212 // remove attribute of id instance: data-intl-tel-input-id 1213 this.telInput.removeAttribute("data-intl-tel-input-id"); 1214 // remove markup (but leave the original input) 1215 var wrapper = this.telInput.parentNode; 1216 wrapper.parentNode.insertBefore(this.telInput, wrapper); 1217 wrapper.parentNode.removeChild(wrapper); 1218 delete window.intlTelInputGlobals.instances[this.id]; 1219 } 1220 }, { 1221 key: "getExtension", 1222 value: function getExtension() { 1223 if (window.intlTelInputUtils) { 1224 return intlTelInputUtils.getExtension(this._getFullNumber(), this.selectedCountryData.iso2); 1225 } 1226 return ""; 1227 } 1228 }, { 1229 key: "getNumber", 1230 value: function getNumber(format) { 1231 if (window.intlTelInputUtils) { 1232 var iso2 = this.selectedCountryData.iso2; 1233 return intlTelInputUtils.formatNumber(this._getFullNumber(), iso2, format); 1234 } 1235 return ""; 1236 } 1237 }, { 1238 key: "getNumberType", 1239 value: function getNumberType() { 1240 if (window.intlTelInputUtils) { 1241 return intlTelInputUtils.getNumberType(this._getFullNumber(), this.selectedCountryData.iso2); 1242 } 1243 return -99; 1244 } 1245 }, { 1246 key: "getSelectedCountryData", 1247 value: function getSelectedCountryData() { 1248 return this.selectedCountryData; 1249 } 1250 }, { 1251 key: "getValidationError", 1252 value: function getValidationError() { 1253 if (window.intlTelInputUtils) { 1254 var iso2 = this.selectedCountryData.iso2; 1255 return intlTelInputUtils.getValidationError(this._getFullNumber(), iso2); 1256 } 1257 return -99; 1258 } 1259 }, { 1260 key: "isValidNumber", 1261 value: function isValidNumber() { 1262 var val = this._getFullNumber().trim(); 1263 var countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : ""; 1264 return window.intlTelInputUtils ? intlTelInputUtils.isValidNumber(val, countryCode) : null; 1265 } 1266 }, { 1267 key: "setCountry", 1268 value: function setCountry(originalCountryCode) { 1269 var countryCode = originalCountryCode.toLowerCase(); 1270 // check if already selected 1271 if (!this.selectedFlagInner.classList.contains("iti__".concat(countryCode))) { 1272 this._setFlag(countryCode); 1273 this._updateDialCode(this.selectedCountryData.dialCode, false); 1274 this._triggerCountryChange(); 1275 } 1276 } 1277 }, { 1278 key: "setNumber", 1279 value: function setNumber(number) { 1280 // we must update the flag first, which updates this.selectedCountryData, which is used for 1281 // formatting the number before displaying it 1282 var flagChanged = this._updateFlagFromNumber(number);
1283 this._updateValFromNumber(number); 1284 if (flagChanged) { 1285 this._triggerCountryChange(); 1286 } 1287 } 1288 }, { 1289 key: "setPlaceholderNumberType", 1290 value: function setPlaceholderNumberType(type) { 1291 this.options.placeholderNumberType = type; 1292 this._updatePlaceholder(); 1293 } 1294 } ]); 1295 return Iti; 1296 }(); 1297 /******************** 1298 * STATIC METHODS 1299 ********************/ 1300 // get the country data object 1301 intlTelInputGlobals.getCountryData = function() { 1302 return allCountries; 1303 }; 1304 // inject a <script> element to load utils.js 1305 var injectScript = function injectScript(path, handleSuccess, handleFailure) { 1306 // inject a new script element into the page 1307 var script = document.createElement("script"); 1308 script.onload = function() { 1309 forEachInstance("handleUtils"); 1310 if (handleSuccess) handleSuccess(); 1311 }; 1312 script.onerror = function() { 1313 forEachInstance("rejectUtilsScriptPromise"); 1314 if (handleFailure) handleFailure(); 1315 }; 1316 script.className = "iti-load-utils"; 1317 script.async = true; 1318 script.src = path; 1319 document.body.appendChild(script); 1320 }; 1321 // load the utils script 1322 intlTelInputGlobals.loadUtils = function(path) { 1323 // 2 options: 1324 // 1) not already started loading (start) 1325 // 2) already started loading (do nothing - just wait for the onload callback to fire, which will 1326 // trigger handleUtils on all instances, invoking their resolveUtilsScriptPromise functions) 1327 if (!window.intlTelInputUtils && !window.intlTelInputGlobals.startedLoadingUtilsScript) { 1328 // only do this once 1329 window.intlTelInputGlobals.startedLoadingUtilsScript = true; 1330 // if we have promises, then return a promise 1331 if (typeof Promise !== "undefined") { 1332 return new Promise(function(resolve, reject) { 1333 return injectScript(path, resolve, reject); 1334 }); 1335 } 1336 injectScript(path); 1337 } 1338 return null; 1339 }; 1340 // default options 1341 intlTelInputGlobals.defaults = defaults; 1342 // version 1343 intlTelInputGlobals.version = "17.0.14"; 1344 // convenience wrapper 1345 return function(input, options) { 1346 var iti = new Iti(input, options); 1347 iti._init(); 1348 input.setAttribute("data-intl-tel-input-id", iti.id); 1349 window.intlTelInputGlobals.instances[iti.id] = iti; 1350 return iti; 1351 }; 1352 }(); 1353});
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.