UNPKG

intl-tel-input

Version:

A JavaScript plugin for entering and validating international telephone numbers

723 lines (721 loc) 96.7 kB
/* * International Telephone Input v18.3.3 * https://github.com/jackocnr/intl-tel-input.git * Licensed under the MIT license */ // wrap in UMD (function(factory) { if (typeof module === "object" && module.exports) module.exports = factory(); else window.intlTelInput = factory(); })(function(undefined) { "use strict"; return function() { // Array of country objects for the flag dropdown. // Here is the criteria for the plugin to support a given country/territory // - It has an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 // - 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 // - It has a flag in the region-flags project: https://github.com/behdad/region-flags/tree/gh-pages/png // - It is supported by libphonenumber (it must be listed on this page): https://github.com/googlei18n/libphonenumber/blob/master/resources/ShortNumberMetadata.xml // Each country array has the following information: // [ // Country name, // iso2 code, // International dial code, // Order (if >1 country with same dial code), // Area codes // ] var allCountries = [ [ "Afghanistan (‫افغانستان‬‎)", "af", "93" ], [ "Albania (Shqipëri)", "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 (Österreich)", "at", "43" ], [ "Azerbaijan (Azərbaycan)", "az", "994" ], [ "Bahamas", "bs", "1", 8, [ "242" ] ], [ "Bahrain (‫البحرين‬‎)", "bh", "973" ], [ "Bangladesh (বাংলাদেশ)", "bd", "880" ], [ "Barbados", "bb", "1", 9, [ "246" ] ], [ "Belarus (Беларусь)", "by", "375" ], [ "Belgium (België)", "be", "32" ], [ "Belize", "bz", "501" ], [ "Benin (Bénin)", "bj", "229" ], [ "Bermuda", "bm", "1", 10, [ "441" ] ], [ "Bhutan (འབྲུག)", "bt", "975" ], [ "Bolivia", "bo", "591" ], [ "Bosnia and Herzegovina (Босна и Херцеговина)", "ba", "387" ], [ "Botswana", "bw", "267" ], [ "Brazil (Brasil)", "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 (Uburundi)", "bi", "257" ], [ "Cambodia (កម្ពុជា)", "kh", "855" ], [ "Cameroon (Cameroun)", "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 (Kabu Verdi)", "cv", "238" ], [ "Caribbean Netherlands", "bq", "599", 1, [ "3", "4", "7" ] ], [ "Cayman Islands", "ky", "1", 12, [ "345" ] ], [ "Central African Republic (République centrafricaine)", "cf", "236" ], [ "Chad (Tchad)", "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" ], [ "Côte d’Ivoire", "ci", "225" ], [ "Croatia (Hrvatska)", "hr", "385" ], [ "Cuba", "cu", "53" ], [ "Curaçao", "cw", "599", 0 ], [ "Cyprus (Κύπρος)", "cy", "357" ], [ "Czech Republic (Česká republika)", "cz", "420" ], [ "Denmark (Danmark)", "dk", "45" ], [ "Djibouti", "dj", "253" ], [ "Dominica", "dm", "1", 13, [ "767" ] ], [ "Dominican Republic (República Dominicana)", "do", "1", 2, [ "809", "829", "849" ] ], [ "Ecuador", "ec", "593" ], [ "Egypt (‫مصر‬‎)", "eg", "20" ], [ "El Salvador", "sv", "503" ], [ "Equatorial Guinea (Guinea Ecuatorial)", "gq", "240" ], [ "Eritrea", "er", "291" ], [ "Estonia (Eesti)", "ee", "372" ], [ "Eswatini", "sz", "268" ], [ "Ethiopia", "et", "251" ], [ "Falkland Islands (Islas Malvinas)", "fk", "500" ], [ "Faroe Islands (Føroyar)", "fo", "298" ], [ "Fiji", "fj", "679" ], [ "Finland (Suomi)", "fi", "358", 0 ], [ "France", "fr", "33" ], [ "French Guiana (Guyane française)", "gf", "594" ], [ "French Polynesia (Polynésie française)", "pf", "689" ], [ "Gabon", "ga", "241" ], [ "Gambia", "gm", "220" ], [ "Georgia (საქართველო)", "ge", "995" ], [ "Germany (Deutschland)", "de", "49" ], [ "Ghana (Gaana)", "gh", "233" ], [ "Gibraltar", "gi", "350" ], [ "Greece (Ελλάδα)", "gr", "30" ], [ "Greenland (Kalaallit Nunaat)", "gl", "299" ], [ "Grenada", "gd", "1", 14, [ "473" ] ], [ "Guadeloupe", "gp", "590", 0 ], [ "Guam", "gu", "1", 15, [ "671" ] ], [ "Guatemala", "gt", "502" ], [ "Guernsey", "gg", "44", 1, [ "1481", "7781", "7839", "7911" ] ], [ "Guinea (Guinée)", "gn", "224" ], [ "Guinea-Bissau (Guiné Bissau)", "gw", "245" ], [ "Guyana", "gy", "592" ], [ "Haiti", "ht", "509" ], [ "Honduras", "hn", "504" ], [ "Hong Kong (香港)", "hk", "852" ], [ "Hungary (Magyarország)", "hu", "36" ], [ "Iceland (Ísland)", "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 (Italia)", "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 (Latvija)", "lv", "371" ], [ "Lebanon (‫لبنان‬‎)", "lb", "961" ], [ "Lesotho", "ls", "266" ], [ "Liberia", "lr", "231" ], [ "Libya (‫ليبيا‬‎)", "ly", "218" ], [ "Liechtenstein", "li", "423" ], [ "Lithuania (Lietuva)", "lt", "370" ], [ "Luxembourg", "lu", "352" ], [ "Macau (澳門)", "mo", "853" ], [ "Madagascar (Madagasikara)", "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 (Moris)", "mu", "230" ], [ "Mayotte", "yt", "262", 1, [ "269", "639" ] ], [ "Mexico (México)", "mx", "52" ], [ "Micronesia", "fm", "691" ], [ "Moldova (Republica Moldova)", "md", "373" ], [ "Monaco", "mc", "377" ], [ "Mongolia (Монгол)", "mn", "976" ], [ "Montenegro (Crna Gora)", "me", "382" ], [ "Montserrat", "ms", "1", 16, [ "664" ] ], [ "Morocco (‫المغرب‬‎)", "ma", "212", 0 ], [ "Mozambique (Moçambique)", "mz", "258" ], [ "Myanmar (Burma) (မြန်မာ)", "mm", "95" ], [ "Namibia (Namibië)", "na", "264" ], [ "Nauru", "nr", "674" ], [ "Nepal (नेपाल)", "np", "977" ], [ "Netherlands (Nederland)", "nl", "31" ], [ "New Caledonia (Nouvelle-Calédonie)", "nc", "687" ], [ "New Zealand", "nz", "64" ], [ "Nicaragua", "ni", "505" ], [ "Niger (Nijar)", "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 (Norge)", "no", "47", 0 ], [ "Oman (‫عُمان‬‎)", "om", "968" ], [ "Pakistan (‫پاکستان‬‎)", "pk", "92" ], [ "Palau", "pw", "680" ], [ "Palestine (‫فلسطين‬‎)", "ps", "970" ], [ "Panama (Panamá)", "pa", "507" ], [ "Papua New Guinea", "pg", "675" ], [ "Paraguay", "py", "595" ], [ "Peru (Perú)", "pe", "51" ], [ "Philippines", "ph", "63" ], [ "Poland (Polska)", "pl", "48" ], [ "Portugal", "pt", "351" ], [ "Puerto Rico", "pr", "1", 3, [ "787", "939" ] ], [ "Qatar (‫قطر‬‎)", "qa", "974" ], [ "Réunion (La Réunion)", "re", "262", 0 ], [ "Romania (România)", "ro", "40" ], [ "Russia (Россия)", "ru", "7", 0 ], [ "Rwanda", "rw", "250" ], [ "Saint Barthélemy", "bl", "590", 1 ], [ "Saint Helena", "sh", "290" ], [ "Saint Kitts and Nevis", "kn", "1", 18, [ "869" ] ], [ "Saint Lucia", "lc", "1", 19, [ "758" ] ], [ "Saint Martin (Saint-Martin (partie française))", "mf", "590", 2 ], [ "Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)", "pm", "508" ], [ "Saint Vincent and the Grenadines", "vc", "1", 20, [ "784" ] ], [ "Samoa", "ws", "685" ], [ "San Marino", "sm", "378" ], [ "São Tomé and Príncipe (São Tomé e Príncipe)", "st", "239" ], [ "Saudi Arabia (‫المملكة العربية السعودية‬‎)", "sa", "966" ], [ "Senegal (Sénégal)", "sn", "221" ], [ "Serbia (Србија)", "rs", "381" ], [ "Seychelles", "sc", "248" ], [ "Sierra Leone", "sl", "232" ], [ "Singapore", "sg", "65" ], [ "Sint Maarten", "sx", "1", 21, [ "721" ] ], [ "Slovakia (Slovensko)", "sk", "421" ], [ "Slovenia (Slovenija)", "si", "386" ], [ "Solomon Islands", "sb", "677" ], [ "Somalia (Soomaaliya)", "so", "252" ], [ "South Africa", "za", "27" ], [ "South Korea (대한민국)", "kr", "82" ], [ "South Sudan (‫جنوب السودان‬‎)", "ss", "211" ], [ "Spain (España)", "es", "34" ], [ "Sri Lanka (ශ්‍රී ලංකාව)", "lk", "94" ], [ "Sudan (‫السودان‬‎)", "sd", "249" ], [ "Suriname", "sr", "597" ], [ "Svalbard and Jan Mayen", "sj", "47", 1, [ "79" ] ], [ "Sweden (Sverige)", "se", "46" ], [ "Switzerland (Schweiz)", "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 (Türkiye)", "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 (Oʻzbekiston)", "uz", "998" ], [ "Vanuatu", "vu", "678" ], [ "Vatican City (Città del Vaticano)", "va", "39", 1, [ "06698" ] ], [ "Venezuela", "ve", "58" ], [ "Vietnam (Việt Nam)", "vn", "84" ], [ "Wallis and Futuna (Wallis-et-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" ] ] ]; // loop over all of the countries above, restructuring the data to be objects with named keys for (var i = 0; i < allCountries.length; i++) { var c = allCountries[i]; allCountries[i] = { name: c[0], iso2: c[1], dialCode: c[2], priority: c[3] || 0, areaCodes: c[4] || null }; } "use strict"; function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? Object(arguments[i]) : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === "function") { ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function(key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } var intlTelInputGlobals = { getInstance: function getInstance(input) { var id = input.getAttribute("data-intl-tel-input-id"); return window.intlTelInputGlobals.instances[id]; }, instances: {}, // using a global like this allows us to mock it in the tests documentReady: function documentReady() { return document.readyState === "complete"; } }; if (typeof window === "object") { window.intlTelInputGlobals = intlTelInputGlobals; } // these vars persist through all instances of the plugin var id = 0; var defaults = { // whether or not to allow the dropdown allowDropdown: true, // auto insert dial code (A) on init, (B) on user selecting a country, (C) on calling setCountry // also listen for blur/submit and auto remove dial code if that's all there is autoInsertDialCode: false, // add a placeholder in the input with an example number for the selected country autoPlaceholder: "polite", // modify the parentClass customContainer: "", // modify the auto placeholder customPlaceholder: null, // append menu to specified element dropdownContainer: null, // don't display these countries excludeCountries: [], // format the input value during initialisation and on setNumber formatOnDisplay: true, // geoIp lookup function geoIpLookup: null, // inject a hidden input with this name, and on submit, populate it with the result of getNumber hiddenInput: "", // initial country initialCountry: "", // localized country names e.g. { 'de': 'Deutschland' } localizedCountries: null, // national vs international formatting for numbers e.g. placeholders and displaying existing numbers nationalMode: true, // display only these countries onlyCountries: [], // number type to use for placeholders placeholderNumberType: "MOBILE", // the countries at the top of the list. defaults to united states and united kingdom preferredCountries: [ "us", "gb" ], // display the country dial code next to the selected flag separateDialCode: false, // option to hide the flags - must be used with separateDialCode, or allowDropdown=false showFlags: true, // use full screen popup instead of dropdown for country list useFullscreenPopup: // we cannot just test screen size as some smartphones/website meta tags will report desktop // resolutions // Note: to target Android Mobiles (and not Tablets), we must find 'Android' and 'Mobile' /Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 500, // specify the path to the libphonenumber script to enable validation/formatting utilsScript: "" }; // https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes#Non-geographic_area_codes var regionlessNanpNumbers = [ "800", "822", "833", "844", "855", "866", "877", "880", "881", "882", "883", "884", "885", "886", "887", "888", "889" ]; // utility function to iterate over an object. can't use Object.entries or native forEach because // of IE11 var forEachProp = function forEachProp(obj, callback) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { callback(keys[i], obj[keys[i]]); } }; // run a method on each instance of the plugin var forEachInstance = function forEachInstance(method) { forEachProp(window.intlTelInputGlobals.instances, function(key) { window.intlTelInputGlobals.instances[key][method](); }); }; // this is our plugin class that we will create an instance of // eslint-disable-next-line no-unused-vars var Iti = /*#__PURE__*/ function() { function Iti(input, options) { var _this = this; _classCallCheck(this, Iti); this.id = id++; this.telInput = input; this.activeItem = null; this.highlightedItem = null; // process specified options / defaults // alternative to Object.assign, which isn't supported by IE11 var customOptions = options || {}; this.options = {}; forEachProp(defaults, function(key, value) { _this.options[key] = customOptions.hasOwnProperty(key) ? customOptions[key] : value; }); this.hadInitialPlaceholder = Boolean(input.getAttribute("placeholder")); } _createClass(Iti, [ { key: "_init", value: function _init() { var _this2 = this; // if in nationalMode, do not insert dial codes if (this.options.nationalMode) { this.options.autoInsertDialCode = false; } // if separateDialCode enabled, do not insert dial codes if (this.options.separateDialCode) { this.options.autoInsertDialCode = false; } // force showFlags=true if there's a dropdown and we're not displaying the dial code, // as otherwise you just have a down arrow on it's own which doesn't make sense var forceShowFlags = this.options.allowDropdown && !this.options.separateDialCode; if (!this.options.showFlags && forceShowFlags) { this.options.showFlags = true; } if (this.options.useFullscreenPopup) { // trigger the mobile dropdown css document.body.classList.add("iti-fullscreen-popup"); // on mobile, we want a full screen dropdown, so we must append it to the body if (!this.options.dropdownContainer) { this.options.dropdownContainer = document.body; } } // check if input has one parent with RTL this.isRTL = !!this.telInput.closest("[dir=rtl]"); // these promises get resolved when their individual requests complete // this way the dev can do something like iti.promise.then(...) to know when all requests are // complete if (typeof Promise !== "undefined") { var autoCountryPromise = new Promise(function(resolve, reject) { _this2.resolveAutoCountryPromise = resolve; _this2.rejectAutoCountryPromise = reject; }); var utilsScriptPromise = new Promise(function(resolve, reject) { _this2.resolveUtilsScriptPromise = resolve; _this2.rejectUtilsScriptPromise = reject; }); this.promise = Promise.all([ autoCountryPromise, utilsScriptPromise ]); } else { // prevent errors when Promise doesn't exist this.resolveAutoCountryPromise = this.rejectAutoCountryPromise = function() {}; this.resolveUtilsScriptPromise = this.rejectUtilsScriptPromise = function() {}; } // in various situations there could be no country selected initially, but we need to be able // to assume this variable exists this.selectedCountryData = {}; // process all the data: onlyCountries, excludeCountries, preferredCountries etc this._processCountryData(); // generate the markup this._generateMarkup(); // set the initial state of the input value and the selected flag this._setInitialState(); // start all of the event listeners: autoInsertDialCode, input keydown, selectedFlag click this._initListeners(); // utils script, and auto country this._initRequests(); } }, { key: "_processCountryData", value: function _processCountryData() { // process onlyCountries or excludeCountries array if present this._processAllCountries(); // process the countryCodes map this._processCountryCodes(); // process the preferredCountries this._processPreferredCountries(); // translate countries according to localizedCountries option if (this.options.localizedCountries) { this._translateCountriesByLocale(); } // sort countries by name if (this.options.onlyCountries.length || this.options.localizedCountries) { this.countries.sort(this._countryNameSort); } } }, { key: "_addCountryCode", value: function _addCountryCode(iso2, countryCode, priority) { if (countryCode.length > this.countryCodeMaxLen) { this.countryCodeMaxLen = countryCode.length; } if (!this.countryCodes.hasOwnProperty(countryCode)) { this.countryCodes[countryCode] = []; } // bail if we already have this country for this countryCode for (var i = 0; i < this.countryCodes[countryCode].length; i++) { if (this.countryCodes[countryCode][i] === iso2) { return; } } // check for undefined as 0 is falsy var index = priority !== undefined ? priority : this.countryCodes[countryCode].length; this.countryCodes[countryCode][index] = iso2; } }, { key: "_processAllCountries", value: function _processAllCountries() { if (this.options.onlyCountries.length) { var lowerCaseOnlyCountries = this.options.onlyCountries.map(function(country) { return country.toLowerCase(); }); this.countries = allCountries.filter(function(country) { return lowerCaseOnlyCountries.indexOf(country.iso2) > -1; }); } else if (this.options.excludeCountries.length) { var lowerCaseExcludeCountries = this.options.excludeCountries.map(function(country) { return country.toLowerCase(); }); this.countries = allCountries.filter(function(country) { return lowerCaseExcludeCountries.indexOf(country.iso2) === -1; }); } else { this.countries = allCountries; } } }, { key: "_translateCountriesByLocale", value: function _translateCountriesByLocale() { for (var i = 0; i < this.countries.length; i++) { var iso = this.countries[i].iso2.toLowerCase(); if (this.options.localizedCountries.hasOwnProperty(iso)) { this.countries[i].name = this.options.localizedCountries[iso]; } } } }, { key: "_countryNameSort", value: function _countryNameSort(a, b) { if (a.name < b.name) { return -1; } if (a.name > b.name) { return 1; } return 0; } }, { key: "_processCountryCodes", value: function _processCountryCodes() { this.countryCodeMaxLen = 0; // here we store just dial codes this.dialCodes = {}; // here we store "country codes" (both dial codes and their area codes) this.countryCodes = {}; // first: add dial codes for (var i = 0; i < this.countries.length; i++) { var c = this.countries[i]; if (!this.dialCodes[c.dialCode]) { this.dialCodes[c.dialCode] = true; } this._addCountryCode(c.iso2, c.dialCode, c.priority); } // next: add area codes // this is a second loop over countries, to make sure we have all of the "root" countries // already in the map, so that we can access them, as each time we add an area code substring // to the map, we also need to include the "root" country's code, as that also matches for (var _i = 0; _i < this.countries.length; _i++) { var _c = this.countries[_i]; // area codes if (_c.areaCodes) { var rootCountryCode = this.countryCodes[_c.dialCode][0]; // for each area code for (var j = 0; j < _c.areaCodes.length; j++) { var areaCode = _c.areaCodes[j]; // for each digit in the area code to add all partial matches as well for (var k = 1; k < areaCode.length; k++) { var partialDialCode = _c.dialCode + areaCode.substr(0, k); // start with the root country, as that also matches this dial code this._addCountryCode(rootCountryCode, partialDialCode); this._addCountryCode(_c.iso2, partialDialCode); } // add the full area code this._addCountryCode(_c.iso2, _c.dialCode + areaCode); } } } } }, { key: "_processPreferredCountries", value: function _processPreferredCountries() { this.preferredCountries = []; for (var i = 0; i < this.options.preferredCountries.length; i++) { var countryCode = this.options.preferredCountries[i].toLowerCase(); var countryData = this._getCountryData(countryCode, false, true); if (countryData) { this.preferredCountries.push(countryData); } } } }, { key: "_createEl", value: function _createEl(name, attrs, container) { var el = document.createElement(name); if (attrs) { forEachProp(attrs, function(key, value) { return el.setAttribute(key, value); }); } if (container) { container.appendChild(el); } return el; } }, { key: "_generateMarkup", value: function _generateMarkup() { // if autocomplete does not exist on the element and its form, then // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can // easily put the plugin in an inconsistent state e.g. the wrong flag selected for the // autocompleted number, which on submit could mean wrong number is saved if (!this.telInput.hasAttribute("autocomplete") && !(this.telInput.form && this.telInput.form.hasAttribute("autocomplete"))) { this.telInput.setAttribute("autocomplete", "off"); } var _this$options = this.options, allowDropdown = _this$options.allowDropdown, separateDialCode = _this$options.separateDialCode, showFlags = _this$options.showFlags, customContainer = _this$options.customContainer, hiddenInput = _this$options.hiddenInput, dropdownContainer = _this$options.dropdownContainer; // containers (mostly for positioning) var parentClass = "iti"; if (allowDropdown) { parentClass += " iti--allow-dropdown"; } if (separateDialCode) { parentClass += " iti--separate-dial-code"; } if (showFlags) { parentClass += " iti--show-flags"; } if (customContainer) { parentClass += " ".concat(customContainer); } var wrapper = this._createEl("div", { "class": parentClass }); this.telInput.parentNode.insertBefore(wrapper, this.telInput); // only hide the flagsContainer if allowDropdown, showFlags and separateDialCode are all false var showFlagsContainer = allowDropdown || showFlags || separateDialCode; if (showFlagsContainer) { this.flagsContainer = this._createEl("div", { "class": "iti__flag-container" }, wrapper); } wrapper.appendChild(this.telInput); // selected flag (displayed to left of input) // using Aria tags for "Select-Only Combobox Example" // https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-select-only/ if (showFlagsContainer) { this.selectedFlag = this._createEl("div", _objectSpread({ "class": "iti__selected-flag" }, allowDropdown && { role: "combobox", "aria-haspopup": "listbox", "aria-controls": "iti-".concat(this.id, "__country-listbox"), "aria-expanded": "false", "aria-label": "Telephone country code" }), this.flagsContainer); } if (showFlags) { this.selectedFlagInner = this._createEl("div", { "class": "iti__flag" }, this.selectedFlag); } if (this.selectedFlag && this.telInput.disabled) { this.selectedFlag.setAttribute("aria-disabled", "true"); } if (separateDialCode) { this.selectedDialCode = this._createEl("div", { "class": "iti__selected-dial-code" }, this.selectedFlag); } if (allowDropdown) { if (!this.telInput.disabled) { // make element focusable and tab navigable this.selectedFlag.setAttribute("tabindex", "0"); } this.dropdownArrow = this._createEl("div", { "class": "iti__arrow" }, this.selectedFlag); // country dropdown: preferred countries, then divider, then all countries this.countryList = this._createEl("ul", { "class": "iti__country-list iti__hide", id: "iti-".concat(this.id, "__country-listbox"), role: "listbox", "aria-label": "List of countries" }); if (this.preferredCountries.length) { this._appendListItems(this.preferredCountries, "iti__preferred", true); this._createEl("li", { "class": "iti__divider", "aria-hidden": "true" }, this.countryList); } this._appendListItems(this.countries, "iti__standard"); // create dropdownContainer markup if (dropdownContainer) { this.dropdown = this._createEl("div", { "class": "iti iti--container" }); this.dropdown.appendChild(this.countryList); } else { this.flagsContainer.appendChild(this.countryList); } } if (hiddenInput) { var hiddenInputName = hiddenInput; var name = this.telInput.getAttribute("name"); if (name) { var i = name.lastIndexOf("["); // if input name contains square brackets, then give the hidden input the same name, // replacing the contents of the last set of brackets with the given hiddenInput name if (i !== -1) { hiddenInputName = "".concat(name.substr(0, i), "[").concat(hiddenInputName, "]"); } } this.hiddenInput = this._createEl("input", { type: "hidden", name: hiddenInputName }); wrapper.appendChild(this.hiddenInput); } } }, { key: "_appendListItems", value: function _appendListItems(countries, className, preferred) { // we create so many DOM elements, it is faster to build a temp string // and then add everything to the DOM in one go at the end var tmp = ""; // for each country for (var i = 0; i < countries.length; i++) { var c = countries[i]; var idSuffix = preferred ? "-preferred" : ""; // open the list item 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'>"); // add the flag if (this.options.showFlags) { tmp += "<div class='iti__flag-box'><div class='iti__flag iti__".concat(c.iso2, "'></div></div>"); } // and the country name and dial code tmp += "<span class='iti__country-name'>".concat(c.name, "</span>"); tmp += "<span class='iti__dial-code'>+".concat(c.dialCode, "</span>"); // close the list item tmp += "</li>"; } this.countryList.insertAdjacentHTML("beforeend", tmp); } }, { key: "_setInitialState", value: function _setInitialState() { // fix firefox bug: when first load page (with input with value set to number with intl dial // code) and initialising plugin removes the dial code from the input, then refresh page, // and we try to init plugin again but this time on number without dial code so get grey flag var attributeValue = this.telInput.getAttribute("value"); var inputValue = this.telInput.value; var useAttribute = attributeValue && attributeValue.charAt(0) === "+" && (!inputValue || inputValue.charAt(0) !== "+"); var val = useAttribute ? attributeValue : inputValue; var dialCode = this._getDialCode(val); var isRegionlessNanp = this._isRegionlessNanp(val); var _this$options2 = this.options, initialCountry = _this$options2.initialCountry, autoInsertDialCode = _this$options2.autoInsertDialCode; // if we already have a dial code, and it's not a regionlessNanp, we can go ahead and set the // flag, else fall back to the default country if (dialCode && !isRegionlessNanp) { this._updateFlagFromNumber(val); } else if (initialCountry !== "auto") { // see if we should select a flag if (initialCountry) { this._setFlag(initialCountry.toLowerCase()); } else { if (dialCode && isRegionlessNanp) { // has intl dial code, is regionless nanp, and no initialCountry, so default to US this._setFlag("us"); } else { // no dial code and no initialCountry, so default to first in list this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2; if (!val) { this._setFlag(this.defaultCountry); } } } // if empty and autoInsertDialCode then insert the dial code if (!val && autoInsertDialCode) { this.telInput.value = "+".concat(this.selectedCountryData.dialCode); } } // NOTE: if initialCountry is set to auto, that will be handled separately // format - note this wont be run after _updateDialCode as that's only called if no val if (val) { this._updateValFromNumber(val); } } }, { key: "_initListeners", value: function _initListeners() { this._initKeyListeners(); if (this.options.autoInsertDialCode) { this._initBlurListeners(); } if (this.options.allowDropdown) { this._initDropdownListeners(); } if (this.hiddenInput) { this._initHiddenInputListener(); } } }, { key: "_initHiddenInputListener", value: function _initHiddenInputListener() { var _this3 = this; this._handleHiddenInputSubmit = function() { _this3.hiddenInput.value = _this3.getNumber(); }; if (this.telInput.form) { this.telInput.form.addEventListener("submit", this._handleHiddenInputSubmit); } } }, { key: "_getClosestLabel", value: function _getClosestLabel() { var el = this.telInput; while (el && el.tagName !== "LABEL") { el = el.parentNode; } return el; } }, { key: "_initDropdownListeners", value: function _initDropdownListeners() { var _this4 = this; // hack for input nested inside label (which is valid markup): clicking the selected-flag to // open the dropdown would then automatically trigger a 2nd click on the input which would // close it again this._handleLabelClick = function(e) { // if the dropdown is closed, then focus the input, else ignore the click if (_this4.countryList.classList.contains("iti__hide")) { _this4.telInput.focus(); } else { e.preventDefault(); } }; var label = this._getClosestLabel(); if (label) { label.addEventListener("click", this._handleLabelClick); } // toggle country dropdown on click this._handleClickSelectedFlag = function() { // only intercept this event if we're opening the dropdown // else let it bubble up to the top ("click-off-to-close" listener) // we cannot just stopPropagation as it may be needed to close another instance if (_this4.countryList.classList.contains("iti__hide") && !_this4.telInput.disabled && !_this4.telInput.readOnly) { _this4._showDropdown(); } }; this.selectedFlag.addEventListener("click", this._handleClickSelectedFlag); // open dropdown list if currently focused this._handleFlagsContainerKeydown = function(e) { var isDropdownHidden = _this4.countryList.classList.contains("iti__hide"); if (isDropdownHidden && [ "ArrowUp", "Up", "ArrowDown", "Down", " ", "Enter" ].indexOf(e.key) !== -1) { // prevent form from being submitted if "ENTER" was pressed e.preventDefault(); // prevent event from being handled again by document e.stopPropagation(); _this4._showDropdown(); } // allow navigation from dropdown to input on TAB if (e.key === "Tab") { _this4._closeDropdown(); } }; this.flagsContainer.addEventListener("keydown", this._handleFlagsContainerKeydown); } }, { key: "_initRequests", value: function _initRequests() { var _this5 = this; // if the user has specified the path to the utils script, fetch it on window.load, else resolve if (this.options.utilsScript && !window.intlTelInputUtils) { // if the plugin is being initialised after the window.load event has already been fired if (window.intlTelInputGlobals.documentReady()) { window.intlTelInputGlobals.loadUtils(this.options.utilsScript); } else { // wait until the load event so we don't block any other requests e.g. the flags image window.addEventListener("load", function() { window.intlTelInputGlobals.loadUtils(_this5.options.utilsScript); }); } } else { this.resolveUtilsScriptPromise(); } if (this.options.initialCountry === "auto") { this._loadAutoCountry(); } else { this.resolveAutoCountryPromise(); } } }, { key: "_loadAutoCountry", value: function _loadAutoCountry() { // 3 options: // 1) already loaded (we're done) // 2) not already started loading (start) // 3) already started loading (do nothing - just wait for loading callback to fire) if (window.intlTelInputGlobals.autoCountry) { this.handleAutoCountry(); } else if (!window.intlTelInputGlobals.startedLoadingAutoCountry) { // don't do this twice! window.intlTelInputGlobals.startedLoadingAutoCountry = true; if (typeof this.options.geoIpLookup === "function") { this.options.geoIpLookup(function(countryCode) { window.intlTelInputGlobals.autoCountry = countryCode.toLowerCase(); // tell all instances the auto country is ready // TODO: this should just be the current instances // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight // away (e.g. if they have already done the geo ip lookup somewhere else). Using // setTimeout means that the current thread of execution will finish before executing // this, which allows the plugin to finish initialising. setTimeout(function() { return forEachInstance("handleAutoCountry"); }); }, function() { return forEachInstance("rejectAutoCountryPromise"); }); }