intl-tel-input 20.3.0 → 21.0.0

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