PluginProbe
SellKit – Funnel builder and checkout optimizer for WooCommerce to sell more, faster / 1.5.1
SellKit – Funnel builder and checkout optimizer for WooCommerce to sell more, faster v1.5.1
2.7.0 2.6.0 trunk 1.1.0 1.1.4 1.2.1 1.2.2 1.2.3 1.2.5 1.2.9 1.3.1 1.3.2 1.5.0 1.5.1 1.5.4 1.5.7 1.5.8 1.5.9 1.6.2 1.6.5 1.6.8 1.7.2 1.7.4 1.7.5 1.7.9 All 43 releases
sellkit / assets / dist / js / elementor-init.js

elementor-init.js in SellKit – Funnel builder and checkout optimizer for WooCommerce to sell more, faster 1.5.1, at assets/dist/js/elementor-init.js

4,782 lines 190.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2 "use strict";
3
4 Object.defineProperty(exports, "__esModule", {
5 value: true
6 });
7 exports["default"] = _default;
8
9 var _i18n = require("@wordpress/i18n");
10
11 /* eslint no-undef: 0 */
12 // Temporary turned off no undefined variable for localStorage
13 var $ = jQuery;
14 var wcCountries = JSON.parse(wc_country_select_params.countries);
15
16 function _default() {
17 $('body').addClass('contains-sellkit-checkout'); // General class to handle compatibility with other themes.
18
19 var parent = $('#sellkit-checkout-multistep-inner-wrap');
20 var sidebar = $('.sellkit-checkout-right-column');
21 var first = $('.sellkit-multistep-checkout-first');
22 var second = $('.sellkit-multistep-checkout-second');
23 var third = $('.sellkit-multistep-checkout-third');
24 var breadcrumb = $('.sellkit-checkout-widget-breadcrumb-desktop, .sellkit-checkout-widget-breadcrumb-mobile');
25
26 if ('1' !== sellkit_elementor.wcNeedShipping || typeof sellkitCheckoutShipping !== 'undefined' && true === sellkitCheckoutShipping) {
27 third.show();
28 $('.sellkit-one-page-checkout-place-order').css('justify-content', 'flex-end');
29 }
30
31 $('.go-to-shipping').on('click', function () {
32 // Checks if required fields are filled.
33 var requiredFieldsError = checkRequiredFields();
34
35 if (true === requiredFieldsError) {
36 return;
37 }
38
39 secondStepHeader();
40 var secondTrigger = true;
41 first.hide();
42
43 if ($('.sellkit-one-page-shipping-methods').children().length > 0) {
44 second.show();
45 } else {
46 third.show();
47 secondTrigger = false;
48 }
49
50 if ($(window).width() > 600 && secondTrigger) {
51 sidebar.css('background-color', '#effdf5');
52 } //Fix Header & wrapper height.
53
54
55 parent.css('height', 'auto');
56 second.css('height', 'auto');
57 second.css('min-height', $('.sellkit-checkout-left-column').height());
58 $('.multistep-headers').css('height', 'auto'); // Manage Breadcrumb.
59
60 breadcrumb.find('.information').removeClass('current').addClass('blue-line');
61 breadcrumb.find('.shipping').addClass('current').removeClass('inactive');
62 });
63 $('.go-to-first').on('click', function () {
64 first.show();
65 third.hide();
66 second.hide();
67 parent.css('height', 'auto');
68 first.css('height', 'auto');
69 sidebar.css('background-color', 'transparent'); // Manage Breadcrumb.
70
71 breadcrumb.find('.information').removeClass('blue-line').addClass('current');
72 breadcrumb.find('.shipping, .payment').removeClass('current').removeClass('blue-line').addClass('inactive');
73 });
74 $('.go-to-payment').on('click', function () {
75 // Checks if required fields are filled.
76 var requiredFieldsError = checkRequiredFields();
77
78 if (true === requiredFieldsError) {
79 return;
80 }
81
82 secondStepHeader();
83 second.hide();
84 first.hide();
85 third.show();
86 $('.sellkit-one-page-checkout-payment-heading').css('margin-top', '0px');
87 sidebar.css('background-color', 'transparent'); //Fix Header & wrapper height.
88
89 parent.css('height', 'auto');
90 third.css('height', 'auto');
91 $('.multistep-headers').css('height', 'auto'); // Manage Breadcrumb.
92
93 breadcrumb.find('.shipping').addClass('blue-line').removeClass('current');
94 breadcrumb.find('.payment').addClass('current').removeClass('inactive');
95 });
96 $('.go-to-second , .go-to-second-header').on('click', function () {
97 // Checks if required fields are filled.
98 var requiredFieldsError = checkRequiredFields();
99
100 if (true === requiredFieldsError) {
101 return;
102 }
103
104 var secondTrigger = true;
105
106 if ($('.sellkit-one-page-shipping-methods').children().length > 0) {
107 second.show();
108 first.hide();
109 } else {
110 second.hide();
111 first.show();
112 secondTrigger = false;
113 }
114
115 third.hide();
116 parent.css('height', 'auto');
117 second.css('height', 'auto');
118 second.css('height', $('.sellkit-checkout-left-column').height());
119 $('.multistep-headers').css('height', 'auto');
120
121 if ($(window).width() > 600 && secondTrigger) {
122 sidebar.css('background-color', '#effdf5');
123 } // Manage Breadcrumb.
124
125
126 breadcrumb.find('.shipping').addClass('current').removeClass('blue-line');
127 breadcrumb.find('.payment').removeClass('current').addClass('inactive');
128 }); //Inject login wrapper & functionality.
129
130 emailProcess();
131 LoginProcess(); // Billing method toggle.
132
133 manageBillingMethod(); // Mobile summary.
134
135 mobileSummary(); // Breadcrumb click management.
136
137 breadcrumbLinks(); // Fix shipping & billing fields space issue.
138
139 fixFieldSpaceIssue(); // Fields focus.
140
141 organizeFieldsonLoad();
142 fieldFocus();
143 jQuery(document).ajaxComplete(function () {
144 // Run after ajax
145 sellkitCheckoutUpdateCartItem();
146 applyCoupon();
147 couponToggle();
148 }); //Run when page loads.
149
150 sellkitCheckoutUpdateCartItem(); // Apply coupon.
151
152 applyCoupon(); // Coupon toggle.
153
154 couponToggle(); // Postal code autocomplete.
155
156 sellkitPostalCodeAutocomplete(); // Klarma checkout integration.
157
158 sellkitKlarmaIntegration(); // Fix state change issue on load.
159
160 fixStateIssueOnLoad(); // Shipping & billing country & state update on change
161
162 fixClientCountryOnReload(); // Configure bundled products.
163
164 sellkitCheckoutConfigureBundleProducts(); // Order bump.
165
166 sellkitCheckoutOrderBump(); // Sellkit after ajax call is completed.
167
168 sellkitAfterAjaxComplete();
169 }
170
171 var emailProcess = function emailProcess() {
172 var emailField = $('#billing_email');
173 var searchIcon = $('.jupiter-checkout-widget-email-search');
174 var errorText = $('.sellkit-checkout-widget-email-error');
175 var emptyError = $('.sellkit-checkout-widget-email-empty');
176 var passwordWrap = $('.sellkit-checkout-widget-password-field');
177 var passwordField = passwordWrap.find('#register_pass');
178 var usernameWrap = $('.sellkit-checkout-widget-username-field');
179 var usernameField = usernameWrap.find('input');
180 var loginBtn = $('.login-wrapper');
181 var createBox = $('.create-desc');
182 var createCheck = $('#createaccount');
183 emailField.on('keyup', function () {
184 var _this = this;
185
186 setTimeout(function () {
187 var emailAddress = $(_this).val();
188
189 if (_.isEmpty(emailAddress)) {
190 emptyError.show().css('display', 'inline-block');
191 errorText.hide();
192 createBox.css('display', 'none');
193 passwordWrap.addClass('login_hidden_section');
194 usernameWrap.addClass('login_hidden_section');
195 loginBtn.addClass('login_hidden_section');
196 searchIcon.hide();
197 return;
198 }
199
200 var check = validateEmailAddress(emailAddress);
201 $('#createaccount').prop('checked', false);
202
203 if (false === check) {
204 errorText.show().css('display', 'inline-block');
205 emptyError.hide();
206 createBox.css('display', 'none');
207 passwordWrap.addClass('login_hidden_section');
208 usernameWrap.addClass('login_hidden_section');
209 loginBtn.addClass('login_hidden_section');
210 searchIcon.hide();
211 return;
212 }
213
214 emptyError.hide();
215 errorText.hide();
216 searchIcon.show().css('display', 'inline-block');
217 wp.ajax.post({
218 action: 'sellkit_checkout_ajax_handler',
219 sub_action: 'search_for_email',
220 email: emailAddress,
221 dataType: 'json',
222 nonce: sellkit_elementor.nonce
223 }).done(function () {
224 successResultEmailCheck();
225 }).fail(function () {
226 errorResultEmailCheck();
227 });
228 }, 500);
229 });
230 usernameField.on('keyup', function () {
231 var _this2 = this;
232
233 setTimeout(function () {
234 var userValue = $(_this2).val();
235 wp.ajax.post({
236 action: 'sellkit_checkout_ajax_handler',
237 sub_action: 'search_for_username',
238 user: userValue,
239 dataType: 'json',
240 nonce: sellkit_elementor.nonce
241 }).done(function () {
242 $('.sellkit-checkout-widget-username-error').hide();
243 }).fail(function () {
244 $('.sellkit-checkout-widget-username-error').show();
245 });
246 }, 500);
247 }); // If user is going to create account show password and username fields if exists.
248
249 createCheck.on('click', function () {
250 if ($(this).is(':checked')) {
251 if (passwordField.length > 0) {
252 passwordWrap.removeClass('login_hidden_section');
253 }
254
255 if (usernameField.length > 0) {
256 usernameWrap.removeClass('login_hidden_section');
257 }
258 } else {
259 usernameWrap.addClass('login_hidden_section');
260 passwordWrap.addClass('login_hidden_section');
261 }
262 });
263
264 var successResultEmailCheck = function successResultEmailCheck() {
265 createBox.css('display', 'none');
266 passwordWrap.removeClass('login_hidden_section');
267 usernameWrap.addClass('login_hidden_section');
268 loginBtn.removeClass('login_hidden_section');
269 searchIcon.hide();
270 };
271
272 var errorResultEmailCheck = function errorResultEmailCheck() {
273 createBox.css('display', 'flex');
274 passwordWrap.addClass('login_hidden_section');
275 usernameWrap.addClass('login_hidden_section');
276 loginBtn.addClass('login_hidden_section');
277 searchIcon.hide();
278 };
279 };
280
281 var validateEmailAddress = function validateEmailAddress(emailAddress) {
282 var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
283 return pattern.test(emailAddress);
284 };
285
286 var LoginProcess = function LoginProcess() {
287 var submitBtn = $('.login-submit');
288 var email = $('.login-mail');
289 var pass = $('.login-pass');
290 var result = $('.login-result');
291 submitBtn.on('click', function () {
292 if ('' === email.val() || '' === pass.val()) {
293 result.text((0, _i18n.__)('Both Field required.', 'sellkit')).css({
294 color: 'red'
295 });
296 return;
297 }
298
299 wp.ajax.post({
300 beforeSend: function beforeSend() {
301 $('.login-submit').css('opacity', '0.5');
302 },
303 action: 'sellkit_checkout_ajax_handler',
304 sub_action: 'auth_user',
305 email: email.val(),
306 pass: pass.val(),
307 nonce: sellkit_elementor.nonce
308 }).done(function () {
309 location.reload();
310 }).fail(function (response) {
311 $('.login-submit').css('opacity', '1');
312 $('.login-result').html(response).css({
313 color: 'red'
314 });
315 });
316 });
317 };
318
319 var secondStepHeader = function secondStepHeader() {
320 var email = $('#billing_email');
321 $('.multistep-headers > .info-a > div > .mail').text(email.val());
322 var countryValue = $('#shipping_country option:selected').text();
323 var state = $('#sellkit-shipping_state');
324 var postcode = $('#shipping_postcode');
325 var city = $('#shipping_city');
326 var addressA = $('#shipping_address_1');
327 var addressB = $('#shipping_address_2');
328 var finalAddress = postcode.val() ? ', ' + postcode.val() : '';
329 finalAddress += addressB.val() ? ', ' + addressB.val() : '';
330 finalAddress += addressA.val() ? ', ' + addressA.val() : '';
331 finalAddress += city.val() ? ', ' + city.val() : '';
332 finalAddress += state.val() ? ', ' + state.val() : '';
333 finalAddress += countryValue && !countryValue.includes('/') ? ', ' + countryValue : '';
334
335 if (',' === finalAddress.charAt(0)) {
336 finalAddress = finalAddress.substring(1);
337 }
338
339 $('.multistep-headers > .info-b > div > .address').text(finalAddress);
340 var method = $('#shipping_method').find('input[type=radio]:checked');
341 var methodTxt = method.siblings('.labels').text();
342 $('.multistep-headers > .info-c > div > .method').text(methodTxt);
343 };
344
345 var manageBillingMethod = function manageBillingMethod() {
346 var billingWrap = $('.sellkit-one-page-checkout-billing');
347 var methodA = billingWrap.find('.method-a');
348 var methodB = billingWrap.find('.method-b'); // Get shipping values.
349
350 var name = $('#shipping_first_name');
351 var last = $('#shipping_last_name');
352 var addressA = $('#shipping_address_1');
353 var addressB = $('#shipping_address_2');
354 var country = $('#shipping_country');
355 var state = $('#sellkit-shipping_state');
356 var postcode = $('#shipping_postcode');
357 var city = $('#shipping_city');
358 methodA.on('click', function () {
359 billingWrap.find('.woocommerce-billing-fields__field-wrapper').hide();
360 $('#billing_first_name').val(name.val());
361 $('#billing_last_name').val(last.val());
362 $('#billing_address_1').val(addressA.val());
363 $('#billing_address_2').val(addressB.val());
364 $('#billing_country').val(country.val()).trigger('change');
365 $('#sellkit-billing_state').val(state.val()).trigger('change');
366 $('#billing_postcode').val(postcode.val());
367 $('#billing_city').val(city.val());
368 });
369 methodB.on('click', function () {
370 $('.inner_wrapper').css('height', 'auto');
371 billingWrap.find('.woocommerce-billing-fields__field-wrapper').show();
372 });
373 };
374
375 var mobileSummary = function mobileSummary() {
376 if ($(window).width() < 600) {
377 $('#order_review').addClass('sellkit-mobile-multistep-order-summary');
378 }
379
380 var toggleBtn = $('.summary_toggle > .title, .summary_toggle > i, .summary_toggle > .icon');
381 var wrap = $('.summary_toggle');
382 toggleBtn.on('click', function () {
383 $('#order_review').toggle();
384
385 if ('Hide order summary' === toggleBtn.text()) {
386 wrap.find('.title').text((0, _i18n.__)('Show order summary', 'sellkit'));
387 wrap.find('i').addClass('fa-chevron-down').removeClass('fa-chevron-up');
388 wrap.css('border-bottom-width', '0px');
389 } else {
390 wrap.find('.title').text((0, _i18n.__)('Hide order summary', 'sellkit'));
391 wrap.find('i').addClass('fa-chevron-up').removeClass('fa-chevron-down');
392 wrap.css('border-bottom-width', '1px');
393 }
394
395 var parent = $('#sellkit-checkout-multistep-inner-wrap');
396 parent.css('height', 'auto');
397 });
398 };
399
400 var fieldFocus = function fieldFocus() {
401 var $fields = $('.sellkit-checkout-local-fields').find('input, select, hidden, textarea, #sellkit-billing_state ,#sellkit-shipping_state, .validate-email');
402 $fields.each(function () {
403 var _this3 = this;
404
405 var miniTitle = $(this).parent().parent().parent().find('.mini-title');
406 var $thisValue = $(this).val(); // On load.
407
408 if (!_.isEmpty($thisValue)) {
409 $(this).addClass('filled').removeClass('empty');
410 miniTitle.css({
411 display: 'flex'
412 });
413 } // On change/focusOut
414
415
416 $(this).on('change input focusout', function (e) {
417 var changedValue = $(_this3).val();
418
419 if (changedValue || $(_this3).find('option').length) {
420 $(_this3).addClass('filled');
421 $(_this3).removeClass('empty');
422 $(_this3).parents('.sellkit-widget-checkout-fields').find('.mini-title').css('display', 'flex');
423 } else {
424 $(_this3).addClass('empty');
425 $(_this3).removeClass('filled');
426 $(_this3).parents('.sellkit-widget-checkout-fields').find('.mini-title').hide();
427 } // On focusout validate fields.
428
429
430 if ('focusout' === e.type) {
431 FieldsMiniTitles($(_this3), 'focusout');
432 var parent = $(_this3).parent().parent().parent(); // Required validation. return if required field rule is not followed.
433
434 if (parent.hasClass('validate-required')) {
435 if ('INPUT' === _this3.nodeName && 'checkbox' === $(_this3).attr('type')) {
436 if (!_this3.checked) {
437 parent.find('.sellkit-required-validation').css('display', 'inline-flex');
438 return;
439 }
440 }
441
442 if (_.isEmpty($(_this3).val())) {
443 parent.find('.sellkit-required-validation').css('display', 'inline-flex');
444 return;
445 }
446
447 parent.find('.sellkit-required-validation').css('display', 'none');
448 } // Required validation of this field if exists, passed successfully. now postcode validation.
449
450
451 if (parent.hasClass('sellkit-checkout-fields-validation-postcode')) {
452 var postcodeVal = $(_this3).val();
453
454 if (_.isEmpty(postcodeVal)) {
455 return;
456 } // Check field type to get related country value. we can't validate without country code.
457
458
459 var postcodeName = $(_this3).attr('name');
460 var postcodeCountry = $('#billing_country');
461
462 if (postcodeName.includes('shipping')) {
463 postcodeCountry = $('#shipping_country');
464 } // Keep validating only if country field is present.
465
466
467 if (!postcodeCountry.length) {
468 return;
469 }
470
471 var countryCode = postcodeCountry.val();
472
473 if (_.isEmpty(countryCode)) {
474 parent.find('.sellkit-checkout-field-global-errors').show().text((0, _i18n.__)('Please select a country.', 'sellkit'));
475 return;
476 } else {
477 // eslint-disable-line
478 parent.find('.sellkit-checkout-field-global-errors').hide().text('');
479 }
480
481 parent.find('.sellkit-checkout-field-global-errors').hide().text('');
482 postcodeValidation(postcodeVal, countryCode, $(_this3));
483 } // Phone validation using woocommerce way.
484
485
486 if (parent.hasClass('sellkit-checkout-fields-validation-phone')) {
487 var phone = $(_this3).val();
488
489 if (_.isEmpty(phone)) {
490 return;
491 }
492
493 phoneNumberValidation(phone, $(_this3));
494 }
495 }
496
497 if ('change' === e.type && ('billing_country' === $(_this3).attr('id') || 'shipping_country' === $(_this3).attr('id'))) {
498 var _countryCode = $(_this3).val();
499
500 var states = wcCountries[_countryCode];
501 var state = 'sellkit-shipping_state';
502
503 if ('billing_country' === $(_this3).attr('id')) {
504 state = 'sellkit-billing_state';
505 }
506
507 var stateField = document.getElementById(state);
508
509 if (_.isNull(stateField)) {
510 return;
511 }
512
513 $(stateField).empty();
514
515 for (var keys in states) {
516 var option = document.createElement('option');
517 option.value = keys;
518 option.innerHTML = states[keys];
519 stateField.appendChild(option);
520 }
521 }
522 });
523 });
524 };
525
526 var breadcrumbLinks = function breadcrumbLinks() {
527 var $parent = $('.sellkit-checkout-widget-breadcrumb-mobile, .sellkit-checkout-widget-breadcrumb-desktop');
528 var detector = $('.sellkit-multistep-checkout-first');
529 $parent.find('.information').on('click', function () {
530 $('.go-to-first').click();
531 });
532 $parent.find('.shipping').on('click', function () {
533 var display = detector.css('display');
534
535 if ('none' === display) {
536 $('.go-to-second').click();
537 } else {
538 $('.go-to-shipping').click();
539 }
540 });
541 $parent.find('.payment').on('click', function () {
542 $('.go-to-payment').click();
543 $('.information').removeClass('current').addClass('inactive, blue-line');
544 });
545 };
546
547 var fixFieldSpaceIssue = function fixFieldSpaceIssue() {
548 $(function () {
549 var shippingFields = $('#customer_details .sellkit-widget-checkout-fields');
550 shippingFields.each(function (index) {
551 if ($(shippingFields[index + 1]).length) {
552 var next = $(shippingFields[index + 1]).offset().top;
553 var current = $(shippingFields[index]).offset().top;
554
555 if (next > current) {
556 $(shippingFields[index]).addClass('sellkit-checkout-excluded-wrapper-fields');
557 }
558 } else {
559 $(shippingFields[index]).addClass('sellkit-checkout-excluded-wrapper-fields');
560 }
561 });
562 });
563 };
564
565 var organizeFieldsonLoad = function organizeFieldsonLoad() {
566 $(function () {
567 var fields = $('.sellkit-widget-checkout-fields').find('input, select, textarea');
568 fields.each(function () {
569 var tag = this.nodeName;
570
571 if ('SELECT' === tag) {
572 $(this).parent().parent().parent().addClass('sellkit-checkout-field-select');
573 }
574
575 FieldsMiniTitles($(this), 'load');
576 });
577 });
578 $(document).on('mousemove change', function (e) {
579 var fields = $('.sellkit-widget-checkout-fields').find('input, select, textarea');
580 fields.each(function () {
581 var tag = this.nodeName;
582
583 if ('SELECT' === tag) {
584 $(this).parent().parent().parent().addClass('sellkit-checkout-field-select');
585 }
586
587 FieldsMiniTitles($(this), e.type);
588 });
589 });
590 };
591
592 var FieldsMiniTitles = function FieldsMiniTitles(field, event) {
593 if (field.attr('multiple')) {
594 field.addClass('filled');
595 field.removeClass('empty');
596 field.parents('.sellkit-widget-checkout-fields').find('.mini-title').css('display', 'flex');
597 return;
598 }
599
600 if (_.isEmpty(field.val())) {
601 field.addClass('empty');
602 field.removeClass('filled');
603 field.parents('.sellkit-widget-checkout-fields').find('.mini-title').css('display', 'none');
604 } else {
605 field.addClass('filled');
606 field.removeClass('empty');
607 field.parents('.sellkit-widget-checkout-fields').find('.mini-title').css('display', 'flex');
608 } // Hide wrapper if field is hidden
609
610
611 if ('hidden' === field.attr('type')) {
612 field.parents('.sellkit-widget-checkout-fields').addClass('sellkit-hide-completely');
613 }
614
615 if ('change' !== event) {
616 return;
617 } // Hide Billing state wrapper when these fields are hidden.
618
619
620 if ('billing_country' === field.attr('id')) {
621 var $state = document.getElementById('sellkit-billing_state');
622
623 if (!_.isNull($state) && 'SELECT' === $state.nodeName && $('#sellkit-billing_state option').length < 1) {
624 var stateField = $('#sellkit-billing_state');
625 var parent = stateField.parent().parent().parent();
626 parent.removeClass('sellkit-checkout-field-select');
627 var placeholder = stateField.attr('placeholder');
628 var stateInput = document.createElement('input');
629 stateInput.setAttribute('type', 'text');
630 stateInput.setAttribute('id', 'sellkit-billing_state');
631 stateInput.setAttribute('name', 'billing_state');
632 stateInput.setAttribute('placeholder', placeholder); // Replace select field with text.
633
634 stateField.remove();
635 parent.find('.woocommerce-input-wrapper').append(stateInput);
636 }
637
638 var countryCode = field.val();
639 var states = wcCountries[countryCode];
640
641 if (!_.isNull($state) && 'INPUT' === $state.nodeName && !_.isEmpty(states)) {
642 var _stateField = $('#sellkit-billing_state');
643
644 var _placeholder = _stateField.attr('placeholder');
645
646 var _parent = _stateField.parent().parent().parent();
647
648 _parent.addClass('sellkit-checkout-field-select');
649
650 if (_.isUndefined(_placeholder) || _.isEmpty(_placeholder)) {
651 _placeholder = (0, _i18n.__)('State', 'sellkit');
652 } // Replace text field with select field.
653
654
655 _stateField.remove();
656
657 var stateSelect = document.createElement('select');
658 stateSelect.setAttribute('name', 'billing_state');
659 stateSelect.setAttribute('id', 'sellkit-billing_state');
660 stateSelect.setAttribute('placeholder', _placeholder);
661 stateSelect.addEventListener('change', function () {
662 sellkitSetAddressDetails();
663 });
664
665 for (var keys in states) {
666 var option = document.createElement('option');
667 option.value = keys;
668 option.innerHTML = states[keys];
669 stateSelect.appendChild(option);
670 }
671
672 _parent.find('.woocommerce-input-wrapper').append(stateSelect);
673 }
674 } // Remove select icon when field is text for the shipping/billing state fields.
675
676
677 if ('shipping_country' === field.attr('id')) {
678 var _$state = document.getElementById('sellkit-shipping_state');
679
680 if (!_.isNull(_$state) && 'SELECT' === _$state.nodeName && $('#sellkit-shipping_state option').length < 1) {
681 var _stateField2 = $('#sellkit-shipping_state');
682
683 var _parent2 = _stateField2.parent().parent().parent();
684
685 _parent2.removeClass('sellkit-checkout-field-select');
686
687 var _placeholder2 = _stateField2.attr('placeholder');
688
689 var _stateInput = document.createElement('input');
690
691 _stateInput.setAttribute('type', 'text');
692
693 _stateInput.setAttribute('id', 'sellkit-shipping_state');
694
695 _stateInput.setAttribute('name', 'shipping_state');
696
697 _stateInput.setAttribute('placeholder', _placeholder2); // Replace select field with text.
698
699
700 _stateField2.remove();
701
702 _parent2.find('.woocommerce-input-wrapper').append(_stateInput);
703 }
704
705 var _countryCode2 = field.val();
706
707 var _states = wcCountries[_countryCode2];
708
709 if (!_.isNull(_$state) && 'INPUT' === _$state.nodeName && !_.isEmpty(_states)) {
710 var _stateField3 = $('#sellkit-shipping_state');
711
712 var _placeholder3 = _stateField3.attr('placeholder');
713
714 var _parent3 = _stateField3.parent().parent().parent();
715
716 _parent3.addClass('sellkit-checkout-field-select');
717
718 if (_.isUndefined(_placeholder3) || _.isEmpty(_placeholder3)) {
719 _placeholder3 = (0, _i18n.__)('State', 'sellkit');
720 } // Replace text field with select field.
721
722
723 _stateField3.remove();
724
725 var _stateSelect = document.createElement('select');
726
727 _stateSelect.setAttribute('name', 'shipping_state');
728
729 _stateSelect.setAttribute('id', 'sellkit-shipping_state');
730
731 _stateSelect.setAttribute('placeholder', _placeholder3);
732
733 _stateSelect.addEventListener('change', function () {
734 sellkitSetAddressDetails();
735 });
736
737 for (var _keys in _states) {
738 var _option = document.createElement('option');
739
740 _option.value = _keys;
741 _option.innerHTML = _states[_keys];
742
743 _stateSelect.appendChild(_option);
744 }
745
746 _parent3.find('.woocommerce-input-wrapper').append(_stateSelect);
747 }
748 }
749 };
750 /**
751 * Change cart item quantity.
752 *
753 * @since 1.2.5
754 */
755
756
757 var sellkitCheckoutUpdateCartItem = function sellkitCheckoutUpdateCartItem() {
758 $('.sellkit-one-page-checkout-product-qty').off('change').on('change', function () {
759 $(this).attr('readonly', true);
760 wp.ajax.post({
761 action: 'sellkit_checkout_ajax_handler',
762 sub_action: 'change_cart_item_qty',
763 qty: $(this).val(),
764 id: $(this).attr('data-id'),
765 mode: 'edit',
766 related_checkout: $('#sellkit_current_page_id').val(),
767 nonce: sellkit_elementor.nonce
768 }).always(function () {
769 $(document.body).trigger('update_checkout');
770 $('.sellkit-one-page-checkout-product-qty').attr('readonly', false);
771 });
772 });
773 var paymentMethod = $('.sellkit-one-page-checkout-payment-methods').find('input[name=payment_method]:checked');
774 paymentMethod.parent().parent().next().show();
775 $('.sellkit-one-page-pay-method').on('click', function () {
776 $('.sellkit_payment_box').hide();
777 $(this).parent().parent().next().show();
778 });
779 var count = $('.sellkit-checkout-widget-order-summary-tfoot').children().length;
780
781 if (count <= 3) {
782 $('.cart-subtotal td').css('padding-bottom', '8px');
783 $('.cart-subtotal th').css('padding-bottom', '8px');
784 }
785 };
786 /**
787 * Apply a coupon.
788 *
789 * @since 1.2.5
790 */
791
792
793 var applyCoupon = function applyCoupon() {
794 $('.sellkit-apply-coupon').off('click').on('click', function () {
795 wp.ajax.post({
796 beforeSend: function beforeSend() {
797 $('.jx-apply-coupon').css('opacity', 0.5);
798 },
799 action: 'sellkit_checkout_ajax_handler',
800 sub_action: 'apply_coupon',
801 code: jQuery('.sellkit-custom-coupon-form').find('.jx-coupon').val(),
802 nonce: sellkit_elementor.nonce
803 }).done(function () {
804 $(document.body).trigger('update_checkout');
805 $('.jx-apply-coupon').css('opacity', 1);
806 }).fail(function () {
807 $('.jx-apply-coupon').css('opacity', 1);
808 });
809 });
810 };
811 /**
812 * Toggle coupon form on click event.
813 *
814 * @since 1.2.5
815 */
816
817
818 var couponToggle = function couponToggle() {
819 if ($('.sellkit-coupon-toggle').length) {
820 $('.sellkit-custom-coupon-form').css('display', 'none');
821 }
822
823 $('.sellkit-coupon-toggle').off('click').on('click', function () {
824 var direction = 'row';
825 var status = $('.sellkit-custom-coupon-form').css('display');
826 var displayValue = '';
827
828 if ($(window).width() < 600) {
829 direction = 'column';
830 }
831
832 if ('none' === status) {
833 displayValue = 'inline-flex';
834 } else {
835 displayValue = 'none';
836 }
837
838 $('.sellkit-custom-coupon-form').css({
839 display: displayValue,
840 flexDirection: direction
841 });
842 });
843 };
844 /**
845 * Validate postcode in WooCommerce way.
846 *
847 * @param {string} postcode
848 * @param {string} country
849 * @param {Object} element
850 */
851
852
853 var postcodeValidation = function postcodeValidation(postcode, country, element) {
854 var parentElement = element.attr('id');
855 wp.ajax.post({
856 action: 'sellkit_checkout_ajax_handler',
857 sub_action: 'validate_postcode',
858 post_code: postcode,
859 country_code: country,
860 parent: parentElement,
861 nonce: sellkit_elementor.nonce
862 }).done(function (response) {
863 var field = $('#' + response);
864 var parent = field.parent().parent().parent();
865 parent.find('.sellkit-checkout-field-global-errors').hide().text('');
866 }).fail(function (response) {
867 var field = $('#' + response);
868 var parent = field.parent().parent().parent();
869 parent.find('.sellkit-checkout-field-global-errors').show().text((0, _i18n.__)('Postcode is not valid.', 'sellkit'));
870 });
871 };
872 /**
873 * Validate phone number in WooCommerce way.
874 *
875 * @param {string} phone
876 * @param {Object} element
877 */
878
879
880 var phoneNumberValidation = function phoneNumberValidation(phone, element) {
881 var parentElement = element.attr('id');
882 wp.ajax.post({
883 action: 'sellkit_checkout_ajax_handler',
884 sub_action: 'validate_phone_number',
885 phone_number: phone,
886 parent: parentElement,
887 nonce: sellkit_elementor.nonce
888 }).done(function (response) {
889 var field = $('#' + response);
890 var parent = field.parent().parent().parent();
891 parent.find('.sellkit-checkout-field-global-errors').hide().text('');
892 }).fail(function (response) {
893 var field = $('#' + response);
894 var parent = field.parent().parent().parent();
895 parent.find('.sellkit-checkout-field-global-errors').show().text((0, _i18n.__)('Phone number is not valid.', 'sellkit'));
896 });
897 };
898 /**
899 * Auto populate city and state fields using postcode by getting information from third api : https://api.zippopotam.us/.
900 *
901 * @since 1.2.5
902 */
903
904
905 var sellkitPostalCodeAutocomplete = function sellkitPostalCodeAutocomplete() {
906 $('.post_code_autocomplete').find('input').on('paste focusout', function () {
907 var postcode = $(this).val();
908 var country = $('#shipping_country').val();
909 var state = $('#sellkit-shipping_state');
910 var city = $('#shipping_city');
911 var parent = $(this).parent().parent().parent();
912
913 if ('billing_postcode' === $(this).attr('id')) {
914 country = $('#billing_country').val();
915 state = $('#sellkit-billing_state');
916 city = $('#billing_city');
917 }
918
919 if (_.isEmpty(postcode) || _.isEmpty(country)) {
920 return;
921 }
922
923 wp.ajax.post({
924 action: 'sellkit_checkout_ajax_handler',
925 sub_action: 'sellkit_state_lookup_by_postcode',
926 country_value: country,
927 postcode_value: postcode,
928 nonce: sellkit_elementor.nonce
929 }).done(function (response) {
930 setError('');
931 var body = response;
932 var placeCity = body.places[0]['place name'];
933 var placeState = body.places[0]['state abbreviation'];
934 var countryResponse = body['country abbreviation'];
935
936 if (_.isEmpty(placeState)) {
937 placeState = body.places[0].state;
938 }
939
940 var countries = ['DE', 'TR', 'BD', 'DO', 'GB', 'GT', 'JP', 'TH', 'ZA'];
941
942 if (countries.includes(countryResponse)) {
943 placeState = fixConflictWooCommerceStatesWithApi(countryResponse, placeState, body);
944 }
945
946 setFields(placeCity, placeState);
947 }).fail(function (response) {
948 setError(response);
949 });
950
951 var setFields = function setFields(placeCity, placeState) {
952 state.val(placeState).addClass('filled');
953 city.val(placeCity).addClass('filled');
954
955 if (null === state.val() && 'SELECT' === state[0].nodeName) {
956 state.prop('selectedIndex', 0);
957 }
958 };
959
960 var setError = function setError(response) {
961 parent.find('.sellkit-checkout-field-global-errors').text(response);
962 };
963 });
964 };
965 /**
966 * Fix some countries states conflict between WooCommerce and https://api.zippopotam.us/.
967 *
968 * @param {string} country response country.
969 * @param {string} state response state.
970 * @param {Object} body response body.
971 * @return {string} state.
972 */
973
974
975 var fixConflictWooCommerceStatesWithApi = function fixConflictWooCommerceStatesWithApi(country, state, body) {
976 switch (country) {
977 case 'TR':
978 // Turkey.
979 state = 'TR' + state;
980 break;
981
982 case 'DE':
983 // Germany.
984 state = 'DE-' + state;
985 break;
986
987 case 'BD':
988 // Bangladesh.
989 state = sellkitCheckoutCountryFixAutoPopulate(state, country, body);
990 break;
991
992 case 'DO':
993 // Dominican Republic. Api has no proper response. we select first option
994 state = 'DO-01';
995 break;
996
997 case 'GB':
998 // United kingdom.
999 state = body.places[0].state;
1000 break;
1001
1002 case 'GT':
1003 // Guatemala.
1004 state = 'GT-AV';
1005 break;
1006
1007 case 'JP':
1008 // Japan.
1009 state = sellkitCheckoutCountryFixAutoPopulate(state, country, body);
1010 break;
1011
1012 case 'TH':
1013 // Thailand.
1014 state = sellkitCheckoutCountryFixAutoPopulate(state, country, body);
1015 break;
1016
1017 case 'ZA':
1018 // South Africa. API has no proper response. we select first option.
1019 state = 'EC';
1020 break;
1021
1022 default:
1023 return state;
1024 }
1025
1026 return state;
1027 };
1028 /**
1029 * Integration with Klarma checkout gateway.
1030 *
1031 * @since 1.2.5
1032 */
1033
1034
1035 var sellkitKlarmaIntegration = function sellkitKlarmaIntegration() {
1036 $(document).ready(function () {
1037 $('#sellkit-klarna-pay-button').on('click', function () {
1038 $('#payment_method_kco').trigger('click');
1039 });
1040 });
1041 };
1042 /**
1043 * Save client state and country on change event.
1044 *
1045 * @since 1.2.5
1046 */
1047
1048
1049 var fixClientCountryOnReload = function fixClientCountryOnReload() {
1050 $('#shipping_country, #billing_country, #sellkit-shipping_state, #sellkit-billing_state').on('change', function () {
1051 sellkitSetAddressDetails();
1052 });
1053 };
1054 /**
1055 * Ajax to save user state and country for both shipping and billing section if those fields are present.
1056 *
1057 * @since 1.2.5
1058 */
1059
1060
1061 var sellkitSetAddressDetails = function sellkitSetAddressDetails() {
1062 wp.ajax.post({
1063 action: 'sellkit_checkout_ajax_handler',
1064 sub_action: 'set_customer_details_ajax',
1065 country: document.querySelector('#billing_country') ? document.getElementById('billing_country').value : '',
1066 state: document.querySelector('#sellkit-billing_state') ? document.getElementById('sellkit-billing_state').value : '',
1067 shipping_country: document.querySelector('#shipping_country') ? document.getElementById('shipping_country').value : '',
1068 shipping_state: document.querySelector('#sellkit-shipping_state') ? document.getElementById('sellkit-shipping_state').value : '',
1069 nonce: sellkit_elementor.nonce
1070 }).always(function () {
1071 $(document.body).trigger('update_checkout');
1072 });
1073 };
1074 /**
1075 * On page load set shipping and billing state & country values.
1076 *
1077 * @since 1.2.5
1078 */
1079
1080
1081 var fixStateIssueOnLoad = function fixStateIssueOnLoad() {
1082 var primaryValue = '';
1083
1084 if (document.querySelector('#shipping_country')) {
1085 primaryValue = $('#shipping_country').val();
1086 $('#shipping_country').val($('#shipping_country option:eq(1)').val());
1087 $('#shipping_country').val(primaryValue).trigger('change');
1088 }
1089
1090 if (document.querySelector('#billing_country')) {
1091 primaryValue = $('#billing_country').val();
1092 $('#billing_country').val($('#billing_country option:eq(1)').val());
1093 $('#billing_country').val(primaryValue).trigger('change');
1094 }
1095 };
1096 /**
1097 * Modify cart items when bundle products are present.
1098 *
1099 * @since 1.2.5
1100 */
1101
1102
1103 var sellkitCheckoutConfigureBundleProducts = function sellkitCheckoutConfigureBundleProducts() {
1104 bundleProductOnQuantityChange();
1105 var radioProducts = $('.sellkit-checkout-bundle-item');
1106 radioProducts.off('change').on('change', function () {
1107 var addType = $(this).attr('type'); // On bundle product change, modify bump too.
1108
1109 $('.sellkit-checkout-bump-order-products').each(function () {
1110 if ($(this).is(':checked') && 'radio' === addType) {
1111 $(this).trigger('click');
1112 }
1113 });
1114 var product = $(this).val();
1115 var quantity = $(this).parent().parent().find('.sellkit-checkout-single-bundle-item-quantity').val();
1116 var checkout = $('#sellkit_current_page_id').val();
1117 var modifyType = 'add';
1118
1119 if (false === $(this).is(':checked')) {
1120 modifyType = 'remove';
1121 }
1122
1123 wp.ajax.post({
1124 action: 'sellkit_checkout_ajax_handler',
1125 sub_action: 'sellkit_checkout_modify_cart_by_bundle_products',
1126 id: product,
1127 qty: quantity,
1128 checkout_id: checkout,
1129 type: addType,
1130 modify: modifyType,
1131 nonce: sellkit_elementor.nonce
1132 }).always(function () {
1133 $(document.body).trigger('update_checkout');
1134 });
1135 });
1136 };
1137 /**
1138 * Change cart item quantity on bundle product quantity change.
1139 *
1140 * @since 1.3.1
1141 */
1142
1143
1144 var bundleProductOnQuantityChange = function bundleProductOnQuantityChange() {
1145 $('.sellkit-checkout-single-bundle-item-quantity').on('change', function () {
1146 var productCartKey = $(this).attr('data-id');
1147 var quantity = $(this).val();
1148
1149 if (false === $(this).parent().parent().find('.sellkit-checkout-bundle-item').is(':checked')) {
1150 return;
1151 }
1152
1153 wp.ajax.post({
1154 action: 'sellkit_checkout_ajax_handler',
1155 sub_action: 'sellkit_checkout_modify_cart_by_bundle_products',
1156 key: productCartKey,
1157 qty: quantity,
1158 nonce: sellkit_elementor.nonce
1159 }).always(function () {
1160 $(document.body).trigger('update_checkout');
1161 });
1162 });
1163 };
1164 /**
1165 * Manage to add or remove a bump product from cart.
1166 *
1167 * @since 1.2.5
1168 */
1169
1170
1171 var sellkitCheckoutOrderBump = function sellkitCheckoutOrderBump() {
1172 $('.sellkit-checkout-bump-order-products').on('click', function () {
1173 var subAction;
1174
1175 if ($(this).is(':checked')) {
1176 subAction = 'add';
1177 } else {
1178 subAction = 'remove';
1179 }
1180
1181 wp.ajax.post({
1182 action: 'sellkit_checkout_ajax_handler',
1183 sub_action: 'change_cart_item_qty',
1184 qty: $(this).attr('data-qty'),
1185 id: $(this).val(),
1186 mode: subAction,
1187 related_checkout: $('#sellkit_current_page_id').val(),
1188 nonce: sellkit_elementor.nonce
1189 }).always(function () {
1190 $(document.body).trigger('update_checkout');
1191 });
1192 });
1193 };
1194 /**
1195 * Checks if a required field is not filled.
1196 *
1197 * @return {boolean} state of error.
1198 * @since 1.2.5
1199 */
1200
1201
1202 var checkRequiredFields = function checkRequiredFields() {
1203 var fields = document.querySelectorAll('#sellkit-checkout-widget-shipping-fields > .validate-required');
1204 var error = false; // Let's check email field first.
1205
1206 if (_.isEmpty($('#billing_email').val())) {
1207 $('.sellkit-checkout-widget-email-empty').css('display', 'block');
1208 return true;
1209 } // Hide warning after filling email field.
1210
1211
1212 $('.sellkit-checkout-widget-email-empty').css('display', 'none');
1213
1214 if (fields.length < 1) {
1215 return error;
1216 }
1217
1218 fields.forEach(function (item) {
1219 var target = $(item).find('input, select, textarea').val();
1220
1221 if ('' === target) {
1222 error = true;
1223 $(item).find('.sellkit-required-validation').css('display', 'inline-flex');
1224 }
1225 });
1226 return error;
1227 };
1228 /**
1229 * Loop through WooCommerce states and replace api returned value.
1230 *
1231 * @param {string} state
1232 * @param {string} countryAbbreviated
1233 * @param {Object} body
1234 * @return {string} state value.
1235 * @since 1.2.5
1236 */
1237
1238
1239 var sellkitCheckoutCountryFixAutoPopulate = function sellkitCheckoutCountryFixAutoPopulate(state, countryAbbreviated, body) {
1240 var value = '';
1241 var country = '';
1242
1243 if ('BD' === countryAbbreviated) {
1244 country = wcCountries.BD;
1245 }
1246
1247 if ('JP' === countryAbbreviated) {
1248 country = wcCountries.JP;
1249 state = state.substring(0, state.length - 3);
1250 }
1251
1252 if ('TH' === countryAbbreviated) {
1253 value = 'TH-37';
1254 country = wcCountries.TH;
1255 state = body.places[0].state;
1256 }
1257
1258 for (var key in country) {
1259 if (state === country[key]) {
1260 value = key;
1261 }
1262 }
1263
1264 return value;
1265 };
1266
1267 var sellkitAfterAjaxComplete = function sellkitAfterAjaxComplete() {
1268 $('#place_order').on('click', function () {
1269 var count = 0;
1270 var transfer = setInterval(function () {
1271 count += 1;
1272
1273 if ($('.wc_payment_method > .woocommerce-NoticeGroup-checkout').length > 0) {
1274 var notice = $('.wc_payment_method').find('.woocommerce-NoticeGroup-checkout').html();
1275 $('.wc_payment_method').find('.woocommerce-NoticeGroup-checkout').remove();
1276 $('.woocommerce-notices-wrapper').first().append(notice);
1277 $(document.body).animate({
1278 scrollTop: $('.woocommerce-notices-wrapper').offset().top - 100
1279 }, 500);
1280 clearInterval(transfer);
1281 }
1282
1283 if (count > 20) {
1284 clearInterval(transfer);
1285 }
1286 }, 500);
1287 });
1288 };
1289
1290 },{"@wordpress/i18n":15}],2:[function(require,module,exports){
1291 "use strict";
1292
1293 (function ($) {
1294 var SellkitFrontend = function SellkitFrontend() {
1295 var widgets = {
1296 'sellkit-product-images.default': require('./product-images')["default"],
1297 'sellkit-checkout.default': require('./checkout')["default"],
1298 'sellkit-optin.default': require('./optin/optin')["default"]
1299 };
1300
1301 function elementorInit() {
1302 for (var widget in widgets) {
1303 elementorFrontend.hooks.addAction("frontend/element_ready/".concat(widget), widgets[widget]);
1304 }
1305 }
1306
1307 this.init = function () {
1308 $(window).on('elementor/frontend/init', elementorInit);
1309 };
1310
1311 this.init();
1312 };
1313
1314 window.sellkitFrontend = new SellkitFrontend();
1315 })(jQuery);
1316
1317 },{"./checkout":1,"./optin/optin":3,"./product-images":6}],3:[function(require,module,exports){
1318 "use strict";
1319
1320 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
1321
1322 Object.defineProperty(exports, "__esModule", {
1323 value: true
1324 });
1325 exports["default"] = _default;
1326
1327 var _intelligentTel = _interopRequireDefault(require("./submodules/intelligent-tel"));
1328
1329 var _fieldValidation = _interopRequireDefault(require("./submodules/field-validation"));
1330
1331 var _i18n = require("@wordpress/i18n");
1332
1333 var Optin = elementorModules.frontend.handlers.Base.extend({
1334 form: null,
1335 onInit: function onInit() {
1336 this.form = this.$element.find('form.sellkit-optin'); // Register submit listener.
1337
1338 this.form.on('submit', this.onSubmit.bind(this)); // Initialize ITI for tel fields.
1339
1340 _intelligentTel["default"].initializeITI(this.form); // AutoComplete address fields.
1341
1342
1343 jQuery(document).ready(this.autoCompleteAddress.bind(this)); // Initialize flatpickr for data and time fields.
1344
1345 this.initializeFlatpickr();
1346 },
1347 onSubmit: function onSubmit(event) {
1348 var _this = this;
1349
1350 event.preventDefault();
1351
1352 if (!this.checkSaveState()) {
1353 return;
1354 }
1355
1356 this.clearAllNotices();
1357 this.form.css('opacity', 0.5);
1358
1359 var validated = _fieldValidation["default"].validateFormFields(this.form);
1360
1361 if (!validated) {
1362 this.form.css('opacity', 1);
1363 return;
1364 }
1365
1366 wp.ajax.send('sellkit_optin_frontend', {
1367 data: this.prepareFormData(),
1368 type: 'POST',
1369 dataType: 'json',
1370 processData: false,
1371 contentType: false,
1372 success: this.onSuccess,
1373 error: this.onFailure,
1374 complete: function complete() {
1375 return _this.form.css('opacity', 1);
1376 }
1377 });
1378 },
1379 checkSaveState: function checkSaveState() {
1380 if (!this.isEdit) {
1381 return true;
1382 }
1383
1384 var btn = jQuery(elementor.panel.el).find('button#elementor-panel-saver-button-publish');
1385
1386 if (!btn.length || btn.hasClass('elementor-disabled')) {
1387 return true;
1388 }
1389
1390 var adminErrorsNode = "\n\t\t\t<div class=\"sellkit-optin-admin-alert\" role=\"alert\">\n\t\t\t\t<span class=\"title\">\n\t\t\t\t\tPlease first update/publish the changes.\n\t\t\t\t</span>\n\t\t\t</div>\n\t\t";
1391 this.form.before(adminErrorsNode);
1392 return false;
1393 },
1394 clearAllNotices: function clearAllNotices() {
1395 var form = this.form; // Reset everything.
1396
1397 form.parent().find('.sellkit-optin-response').remove();
1398 form.parent().find('.sellkit-optin-admin-alert').remove();
1399 form.parent().removeClass('sellkit-optin-error');
1400 form.parent().removeClass('sellkit-optin-success');
1401 },
1402 prepareFormData: function prepareFormData() {
1403 _intelligentTel["default"].fixTelBeforeSubmit(this.form);
1404
1405 var formData = new FormData(this.form[0]);
1406 var entries = Array.from(formData.entries()); // Unify nonsingular formData entries ( happens for checkbox or multiselection select fields ) .
1407
1408 entries.forEach(function (entry, i) {
1409 var value = entry[1];
1410 entries.forEach(function (_entry, _i) {
1411 if (_i !== i && _entry[0] === entry[0]) {
1412 value += ", ".concat(_entry[1]);
1413 formData["delete"](_entry[0]);
1414 }
1415 });
1416 formData.set(entry[0], value);
1417 });
1418 formData.append('referrer', location.toString());
1419 formData.append('action', 'sellkit_optin_frontend');
1420 formData.append('nonce', window.sellkit_elementor.nonce); // To make _POST content compatible with sellkit_funnel() functionality and let it find the funnel data.
1421
1422 formData.append('sellkit_current_page_id', formData.get('post_id'));
1423 return formData;
1424 },
1425 onSuccess: function onSuccess(response) {
1426 var form = this.form; // Success Message.
1427
1428 form.trigger('reset');
1429 form.parent().addClass('sellkit-optin-success');
1430 form.after("<div class=\"sellkit-optin-response\">".concat(response.message, "</div>")); // Admin Error Messages.
1431
1432 this.printAdminErrors(response.admin_errors); // Download.
1433
1434 if (response.downloadURL) {
1435 window.open(response.downloadURL, '_blank');
1436 } // Redirect.
1437
1438
1439 if (!jQuery.isEmptyObject(response.redirectURL)) {
1440 window.location.href = response.redirectURL;
1441 }
1442 },
1443 onFailure: function onFailure(response) {
1444 var form = this.form;
1445 form.parent().removeClass('sellkit-optin-success');
1446 form.parent().addClass('sellkit-optin-error'); // Handle user error messages.
1447
1448 if (!_.isEmpty(response.errors)) {
1449 _.each(response.errors, function (error) {
1450 form.after("<div class=\"sellkit-optin-response\">".concat(error, "</div>"));
1451 });
1452 } // Admin Error Messages.
1453
1454
1455 this.printAdminErrors(response.admin_errors);
1456 },
1457 printAdminErrors: function printAdminErrors(errors) {
1458 if (_.isEmpty(errors)) {
1459 return;
1460 }
1461
1462 var errorList = '';
1463
1464 _.each(errors, function (error) {
1465 errorList += "<li>".concat(error, "</li>");
1466 });
1467
1468 var adminErrorsNode = "\n\t\t\t<div class=\"sellkit-optin-admin-alert\" role=\"alert\">\n\t\t\t\t<span class=\"title\">\n\t\t\t\t\t".concat((0, _i18n.__)('Following messages are visible only for admin users.', 'sellkit'), "\n\t\t\t\t</span>\n\t\t\t\t<div class=\"description\">\n\t\t\t\t\t<ul> ").concat(errorList, " </ul>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t");
1469 this.form.before(adminErrorsNode);
1470 },
1471 initializeFlatpickr: function initializeFlatpickr() {
1472 var dateField = this.form.find('.flatpickr[type=text]');
1473 var customLocale = dateField.data('locale');
1474 var locale = {
1475 firstDayOfWeek: 1
1476 };
1477
1478 if (!_.isUndefined(customLocale) && 'default' !== customLocale) {
1479 locale = customLocale;
1480 }
1481
1482 dateField.flatpickr({
1483 locale: locale,
1484 minuteIncrement: 1
1485 });
1486 },
1487 autoCompleteAddress: function autoCompleteAddress() {
1488 var addressFields = this.form.find('input[data-type="address"]');
1489 var google = this.isEdit ? window.parent.google : window.google;
1490
1491 if (!addressFields.length || !google) {
1492 return;
1493 }
1494
1495 _.each(addressFields, function (input) {
1496 new google.maps.places.Autocomplete(input, {
1497 types: ['geocode'],
1498 fields: ['address_components']
1499 });
1500 });
1501 }
1502 });
1503
1504 function _default($scope) {
1505 new Optin({
1506 $element: $scope
1507 });
1508 }
1509
1510 },{"./submodules/field-validation":4,"./submodules/intelligent-tel":5,"@babel/runtime/helpers/interopRequireDefault":8,"@wordpress/i18n":15}],4:[function(require,module,exports){
1511 "use strict";
1512
1513 Object.defineProperty(exports, "__esModule", {
1514 value: true
1515 });
1516 exports["default"] = void 0;
1517 var _default = {
1518 messageRequired: '',
1519 messageError: '',
1520 validateFormFields: function validateFormFields(form) {
1521 var _this = this;
1522
1523 this.getCustomMessages(form);
1524 var formData = form.find('[name^="fields"]');
1525 var result = true;
1526
1527 _.each(formData, function (field) {
1528 var message = _this.getValidationMessage(field);
1529
1530 if (!_.isEmpty(message)) {
1531 result = false;
1532 }
1533
1534 _this.toggleFieldMessage(field, message);
1535 });
1536
1537 this.toggleFinalMessage(form, result);
1538 return result;
1539 },
1540 getValidationMessage: function getValidationMessage(target) {
1541 var type = target.dataset.type;
1542 var validity = target.validity;
1543 var i18n = window.sellkitOptinValidationsTranslations;
1544 var message = '';
1545
1546 if (validity.valueMissing || target.required && _.isEmpty(target.value)) {
1547 message = this.messageRequired;
1548 return message;
1549 }
1550
1551 switch (type) {
1552 case 'email':
1553 if (validity.typeMismatch || validity.patternMismatch) {
1554 message = i18n.general.invalidEmail;
1555 }
1556
1557 break;
1558
1559 case 'tel':
1560 var isITI = target.hasAttribute('data-iti-tel');
1561
1562 if (isITI) {
1563 var validationMessages = i18n.itiValidation;
1564 var inputItiInstance = window.intlTelInputGlobals.getInstance(target);
1565 var itiValidationCode = inputItiInstance.getValidationError();
1566 var areaCodeRequired = target.hasAttribute('data-iti-area-required');
1567 var mustBeTelType = target.getAttribute('data-iti-tel-type');
1568 var telType = "".concat(inputItiInstance.getNumberType());
1569
1570 switch (itiValidationCode) {
1571 case 1:
1572 message = validationMessages.invalidCountryCode;
1573 break;
1574
1575 case 2:
1576 message = validationMessages.tooShort;
1577 break;
1578
1579 case 3:
1580 message = validationMessages.tooLong;
1581 break;
1582
1583 case 4:
1584 message = areaCodeRequired ? validationMessages.areaCodeMissing : '';
1585 break;
1586
1587 case 5:
1588 message = validationMessages.invalidLength;
1589 break;
1590
1591 case -99:
1592 message = validationMessages.invalidGeneral;
1593 break;
1594
1595 case 0:
1596 default:
1597 if ('all' !== mustBeTelType && telType !== mustBeTelType) {
1598 message = validationMessages.typeMismatch[mustBeTelType];
1599 }
1600
1601 }
1602
1603 break;
1604 }
1605
1606 if (validity.typeMismatch || validity.patternMismatch) {
1607 message = i18n.general.invalidPhone;
1608 }
1609
1610 break;
1611
1612 case 'number':
1613 if (validity.typeMismatch || validity.patternMismatch) {
1614 message = i18n.general.invalidNumber;
1615 break;
1616 }
1617
1618 if (validity.rangeOverflow) {
1619 message = i18n.general.invalidMaxValue.replace('MAX_VALUE', target.max);
1620 break;
1621 }
1622
1623 if (validity.rangeUnderflow) {
1624 message = i18n.general.invalidMinValue.replace('MIN_VALUE', target.min);
1625 }
1626
1627 break;
1628 }
1629
1630 return message;
1631 },
1632 toggleFieldMessage: function toggleFieldMessage(field, message) {
1633 var fieldGroup = jQuery(field).closest('.sellkit-field-group');
1634 fieldGroup.removeClass('sellkit-field-invalid');
1635 fieldGroup.find('small').remove();
1636
1637 if (!_.isEmpty(message)) {
1638 fieldGroup.addClass('sellkit-field-invalid');
1639 fieldGroup.append("<small class=\"sellkit-optin-text\">".concat(message, "</small>"));
1640 }
1641 },
1642 toggleFinalMessage: function toggleFinalMessage(form, validationResult) {
1643 form.parent().toggleClass('sellkit-optin-error', !validationResult);
1644 form.parent().toggleClass('sellkit-optin-success', validationResult);
1645 form.parent().find('.sellkit-optin-response').remove();
1646
1647 if (true === validationResult) {
1648 return;
1649 }
1650
1651 form.after("<div class=\"sellkit-optin-response\">".concat(this.messageError, "</div>"));
1652 },
1653 getCustomMessages: function getCustomMessages(form) {
1654 var messagesRaw = form.attr('data-messages');
1655
1656 if (!_.isEmpty(messagesRaw)) {
1657 var messages = JSON.parse(messagesRaw);
1658 this.messageError = messages.error;
1659 this.messageRequired = messages.required;
1660 return;
1661 }
1662
1663 this.messageError = window.sellkitOptinValidationsTranslations.general.errorExists;
1664 this.messageRequired = window.sellkitOptinValidationsTranslations.general.required;
1665 }
1666 };
1667 exports["default"] = _default;
1668
1669 },{}],5:[function(require,module,exports){
1670 "use strict";
1671
1672 Object.defineProperty(exports, "__esModule", {
1673 value: true
1674 });
1675 exports["default"] = void 0;
1676 var _default = {
1677 initializeITI: function initializeITI(form) {
1678 var _this = this;
1679
1680 var itiTelFields = form.find('input[data-iti-tel]');
1681
1682 if (!itiTelFields.length) {
1683 return;
1684 }
1685
1686 if (!window.itiCountry) {
1687 jQuery.get('https://ipwho.is/', function () {}, 'json').always(function (response) {
1688 window.itiCountry = response && response.country_code ? response.country_code.toLowerCase() : 'us';
1689
1690 _this.setupTelFields(itiTelFields);
1691 });
1692 } else {
1693 this.setupTelFields(itiTelFields);
1694 }
1695 },
1696 setupTelFields: function setupTelFields(itiTelFields) {
1697 var iti = require('intl-tel-input');
1698
1699 if (!iti) {
1700 return;
1701 }
1702
1703 var allCountries = window.intlTelInputGlobals.getCountryData().map(function (item) {
1704 return item.iso2;
1705 });
1706 var numberTypes = ['FIXED_LINE', 'MOBILE', 'FIXED_LINE_OR_MOBILE', 'TOLL_FREE', 'PREMIUM_RATE', 'SHARED_COST', 'VOIP', 'PERSONAL_NUMBER', 'PAGER', 'UAN', 'VOICEMAIL'];
1707
1708 _.each(itiTelFields, function (input) {
1709 var allowDropdown = input.hasAttribute('data-iti-allow-dropdown');
1710 var countriesAttr = input.getAttribute('data-iti-country-include');
1711 var countries = countriesAttr ? countriesAttr.split(' ') : null;
1712 var isCountriesSet = countries && countries.length;
1713 var ipDetect = input.hasAttribute('data-iti-ip-detect');
1714 var placeHolderAttr = input.getAttribute('data-iti-tel-type');
1715 var args = {
1716 allowDropdown: allowDropdown,
1717 utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.16/js/utils.min.js',
1718 separateDialCode: true,
1719 placeholderNumberType: 'all' === placeHolderAttr ? 'MOBILE' : numberTypes[+placeHolderAttr],
1720 onlyCountries: isCountriesSet ? countries : allCountries,
1721 initialCountry: '',
1722 geoIpLookup: null
1723 };
1724
1725 if (ipDetect) {
1726 args.initialCountry = isCountriesSet && !countries.includes(window.itiCountry) ? countries[0] : 'auto';
1727
1728 args.geoIpLookup = function (success) {
1729 return success(window.itiCountry);
1730 };
1731 }
1732
1733 iti(input, args);
1734 });
1735 },
1736 fixTelBeforeSubmit: function fixTelBeforeSubmit(form) {
1737 var itiTelFields = form.find('input[data-iti-tel]');
1738
1739 _.each(itiTelFields, function (input) {
1740 var internationalize = input.hasAttribute('data-iti-internationalize');
1741
1742 if (internationalize) {
1743 var itiInstance = window.intlTelInputGlobals.getInstance(input);
1744 input.value = itiInstance.getNumber();
1745 }
1746 });
1747 }
1748 };
1749 exports["default"] = _default;
1750
1751 },{"intl-tel-input":19}],6:[function(require,module,exports){
1752 "use strict";
1753
1754 Object.defineProperty(exports, "__esModule", {
1755 value: true
1756 });
1757 exports["default"] = _default;
1758 var ProductImages = elementorModules.frontend.handlers.Base.extend({
1759 onInit: function onInit() {
1760 elementorModules.frontend.handlers.Base.prototype.onInit.apply(this, arguments);
1761
1762 if (document.body.classList.contains('elementor-editor-active')) {
1763 this.$element.find('.woocommerce-product-gallery').wc_product_gallery();
1764 }
1765
1766 var self = this;
1767
1768 if (typeof window.elementor === 'undefined') {
1769 return;
1770 }
1771
1772 window.elementor.channels.editor.on('change', function (controlView) {
1773 self.onElementChange(controlView.model.get('name'), controlView);
1774 });
1775 this.handleThumbnailBorderRadius(this.getElementSettings('thumbnail_border_radius'));
1776 },
1777 onElementChange: function onElementChange(propertyName, controlView) {
1778 if ('thumbnail_border_radius' === propertyName) {
1779 var borderRadius = controlView.container.settings.get('thumbnail_border_radius');
1780 this.handleThumbnailBorderRadius(borderRadius);
1781 }
1782 },
1783 handleThumbnailBorderRadius: function handleThumbnailBorderRadius(borderRadius) {
1784 var unit = borderRadius.unit;
1785 this.$element.find('.flex-control-nav li').css({
1786 'border-radius': borderRadius.top + unit + ' ' + borderRadius.right + unit + ' ' + borderRadius.bottom + unit + ' ' + borderRadius.left + unit
1787 });
1788 },
1789 bindEvents: function bindEvents() {
1790 this.$element.find('.woocommerce-product-gallery__image a').on('click', function (e) {
1791 e.stopImmediatePropagation();
1792 e.preventDefault();
1793 });
1794 }
1795 });
1796
1797 function _default($scope) {
1798 new ProductImages({
1799 $element: $scope
1800 });
1801 }
1802
1803 },{}],7:[function(require,module,exports){
1804 function _defineProperty(obj, key, value) {
1805 if (key in obj) {
1806 Object.defineProperty(obj, key, {
1807 value: value,
1808 enumerable: true,
1809 configurable: true,
1810 writable: true
1811 });
1812 } else {
1813 obj[key] = value;
1814 }
1815
1816 return obj;
1817 }
1818
1819 module.exports = _defineProperty;
1820 },{}],8:[function(require,module,exports){
1821 function _interopRequireDefault(obj) {
1822 return obj && obj.__esModule ? obj : {
1823 "default": obj
1824 };
1825 }
1826
1827 module.exports = _interopRequireDefault;
1828 },{}],9:[function(require,module,exports){
1829 'use strict';
1830
1831 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
1832
1833 var postfix = _interopDefault(require('@tannin/postfix'));
1834 var evaluate = _interopDefault(require('@tannin/evaluate'));
1835
1836 /**
1837 * Given a C expression, returns a function which can be called to evaluate its
1838 * result.
1839 *
1840 * @example
1841 *
1842 * ```js
1843 * import compile from '@tannin/compile';
1844 *
1845 * const evaluate = compile( 'n > 1' );
1846 *
1847 * evaluate( { n: 2 } );
1848 * // ⇒ true
1849 * ```
1850 *
1851 * @param {string} expression C expression.
1852 *
1853 * @return {(variables?:{[variable:string]:*})=>*} Compiled evaluator.
1854 */
1855 function compile( expression ) {
1856 var terms = postfix( expression );
1857
1858 return function( variables ) {
1859 return evaluate( terms, variables );
1860 };
1861 }
1862
1863 module.exports = compile;
1864
1865 },{"@tannin/evaluate":10,"@tannin/postfix":12}],10:[function(require,module,exports){
1866 'use strict';
1867
1868 /**
1869 * Operator callback functions.
1870 *
1871 * @type {Object}
1872 */
1873 var OPERATORS = {
1874 '!': function( a ) {
1875 return ! a;
1876 },
1877 '*': function( a, b ) {
1878 return a * b;
1879 },
1880 '/': function( a, b ) {
1881 return a / b;
1882 },
1883 '%': function( a, b ) {
1884 return a % b;
1885 },
1886 '+': function( a, b ) {
1887 return a + b;
1888 },
1889 '-': function( a, b ) {
1890 return a - b;
1891 },
1892 '<': function( a, b ) {
1893 return a < b;
1894 },
1895 '<=': function( a, b ) {
1896 return a <= b;
1897 },
1898 '>': function( a, b ) {
1899 return a > b;
1900 },
1901 '>=': function( a, b ) {
1902 return a >= b;
1903 },
1904 '==': function( a, b ) {
1905 return a === b;
1906 },
1907 '!=': function( a, b ) {
1908 return a !== b;
1909 },
1910 '&&': function( a, b ) {
1911 return a && b;
1912 },
1913 '||': function( a, b ) {
1914 return a || b;
1915 },
1916 '?:': function( a, b, c ) {
1917 if ( a ) {
1918 throw b;
1919 }
1920
1921 return c;
1922 },
1923 };
1924
1925 /**
1926 * Given an array of postfix terms and operand variables, returns the result of
1927 * the postfix evaluation.
1928 *
1929 * @example
1930 *
1931 * ```js
1932 * import evaluate from '@tannin/evaluate';
1933 *
1934 * // 3 + 4 * 5 / 6 ⇒ '3 4 5 * 6 / +'
1935 * const terms = [ '3', '4', '5', '*', '6', '/', '+' ];
1936 *
1937 * evaluate( terms, {} );
1938 * // ⇒ 6.333333333333334
1939 * ```
1940 *
1941 * @param {string[]} postfix Postfix terms.
1942 * @param {Object} variables Operand variables.
1943 *
1944 * @return {*} Result of evaluation.
1945 */
1946 function evaluate( postfix, variables ) {
1947 var stack = [],
1948 i, j, args, getOperatorResult, term, value;
1949
1950 for ( i = 0; i < postfix.length; i++ ) {
1951 term = postfix[ i ];
1952
1953 getOperatorResult = OPERATORS[ term ];
1954 if ( getOperatorResult ) {
1955 // Pop from stack by number of function arguments.
1956 j = getOperatorResult.length;
1957 args = Array( j );
1958 while ( j-- ) {
1959 args[ j ] = stack.pop();
1960 }
1961
1962 try {
1963 value = getOperatorResult.apply( null, args );
1964 } catch ( earlyReturn ) {
1965 return earlyReturn;
1966 }
1967 } else if ( variables.hasOwnProperty( term ) ) {
1968 value = variables[ term ];
1969 } else {
1970 value = +term;
1971 }
1972
1973 stack.push( value );
1974 }
1975
1976 return stack[ 0 ];
1977 }
1978
1979 module.exports = evaluate;
1980
1981 },{}],11:[function(require,module,exports){
1982 'use strict';
1983
1984 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
1985
1986 var compile = _interopDefault(require('@tannin/compile'));
1987
1988 /**
1989 * Given a C expression, returns a function which, when called with a value,
1990 * evaluates the result with the value assumed to be the "n" variable of the
1991 * expression. The result will be coerced to its numeric equivalent.
1992 *
1993 * @param {string} expression C expression.
1994 *
1995 * @return {Function} Evaluator function.
1996 */
1997 function pluralForms( expression ) {
1998 var evaluate = compile( expression );
1999
2000 return function( n ) {
2001 return +evaluate( { n: n } );
2002 };
2003 }
2004
2005 module.exports = pluralForms;
2006
2007 },{"@tannin/compile":9}],12:[function(require,module,exports){
2008 'use strict';
2009
2010 var PRECEDENCE, OPENERS, TERMINATORS, PATTERN;
2011
2012 /**
2013 * Operator precedence mapping.
2014 *
2015 * @type {Object}
2016 */
2017 PRECEDENCE = {
2018 '(': 9,
2019 '!': 8,
2020 '*': 7,
2021 '/': 7,
2022 '%': 7,
2023 '+': 6,
2024 '-': 6,
2025 '<': 5,
2026 '<=': 5,
2027 '>': 5,
2028 '>=': 5,
2029 '==': 4,
2030 '!=': 4,
2031 '&&': 3,
2032 '||': 2,
2033 '?': 1,
2034 '?:': 1,
2035 };
2036
2037 /**
2038 * Characters which signal pair opening, to be terminated by terminators.
2039 *
2040 * @type {string[]}
2041 */
2042 OPENERS = [ '(', '?' ];
2043
2044 /**
2045 * Characters which signal pair termination, the value an array with the
2046 * opener as its first member. The second member is an optional operator
2047 * replacement to push to the stack.
2048 *
2049 * @type {string[]}
2050 */
2051 TERMINATORS = {
2052 ')': [ '(' ],
2053 ':': [ '?', '?:' ],
2054 };
2055
2056 /**
2057 * Pattern matching operators and openers.
2058 *
2059 * @type {RegExp}
2060 */
2061 PATTERN = /<=|>=|==|!=|&&|\|\||\?:|\(|!|\*|\/|%|\+|-|<|>|\?|\)|:/;
2062
2063 /**
2064 * Given a C expression, returns the equivalent postfix (Reverse Polish)
2065 * notation terms as an array.
2066 *
2067 * If a postfix string is desired, simply `.join( ' ' )` the result.
2068 *
2069 * @example
2070 *
2071 * ```js
2072 * import postfix from '@tannin/postfix';
2073 *
2074 * postfix( 'n > 1' );
2075 * // ⇒ [ 'n', '1', '>' ]
2076 * ```
2077 *
2078 * @param {string} expression C expression.
2079 *
2080 * @return {string[]} Postfix terms.
2081 */
2082 function postfix( expression ) {
2083 var terms = [],
2084 stack = [],
2085 match, operator, term, element;
2086
2087 while ( ( match = expression.match( PATTERN ) ) ) {
2088 operator = match[ 0 ];
2089
2090 // Term is the string preceding the operator match. It may contain
2091 // whitespace, and may be empty (if operator is at beginning).
2092 term = expression.substr( 0, match.index ).trim();
2093 if ( term ) {
2094 terms.push( term );
2095 }
2096
2097 while ( ( element = stack.pop() ) ) {
2098 if ( TERMINATORS[ operator ] ) {
2099 if ( TERMINATORS[ operator ][ 0 ] === element ) {
2100 // Substitution works here under assumption that because
2101 // the assigned operator will no longer be a terminator, it
2102 // will be pushed to the stack during the condition below.
2103 operator = TERMINATORS[ operator ][ 1 ] || operator;
2104 break;
2105 }
2106 } else if ( OPENERS.indexOf( element ) >= 0 || PRECEDENCE[ element ] < PRECEDENCE[ operator ] ) {
2107 // Push to stack if either an opener or when pop reveals an
2108 // element of lower precedence.
2109 stack.push( element );
2110 break;
2111 }
2112
2113 // For each popped from stack, push to terms.
2114 terms.push( element );
2115 }
2116
2117 if ( ! TERMINATORS[ operator ] ) {
2118 stack.push( operator );
2119 }
2120
2121 // Slice matched fragment from expression to continue match.
2122 expression = expression.substr( match.index + operator.length );
2123 }
2124
2125 // Push remainder of operand, if exists, to terms.
2126 expression = expression.trim();
2127 if ( expression ) {
2128 terms.push( expression );
2129 }
2130
2131 // Pop remaining items from stack into terms.
2132 return terms.concat( stack.reverse() );
2133 }
2134
2135 module.exports = postfix;
2136
2137 },{}],13:[function(require,module,exports){
2138 "use strict";
2139
2140 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
2141
2142 Object.defineProperty(exports, "__esModule", {
2143 value: true
2144 });
2145 exports.createI18n = void 0;
2146
2147 var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
2148
2149 var _tannin = _interopRequireDefault(require("tannin"));
2150
2151 function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
2152
2153 function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
2154
2155 /**
2156 * @typedef {Record<string,any>} LocaleData
2157 */
2158
2159 /**
2160 * Default locale data to use for Tannin domain when not otherwise provided.
2161 * Assumes an English plural forms expression.
2162 *
2163 * @type {LocaleData}
2164 */
2165 var DEFAULT_LOCALE_DATA = {
2166 '': {
2167 /** @param {number} n */
2168 plural_forms: function plural_forms(n) {
2169 return n === 1 ? 0 : 1;
2170 }
2171 }
2172 };
2173 /**
2174 * An i18n instance
2175 *
2176 * @typedef {Object} I18n
2177 * @property {Function} setLocaleData Merges locale data into the Tannin instance by domain. Accepts data in a
2178 * Jed-formatted JSON object shape.
2179 * @property {Function} __ Retrieve the translation of text.
2180 * @property {Function} _x Retrieve translated string with gettext context.
2181 * @property {Function} _n Translates and retrieves the singular or plural form based on the supplied
2182 * number.
2183 * @property {Function} _nx Translates and retrieves the singular or plural form based on the supplied
2184 * number, with gettext context.
2185 * @property {Function} isRTL Check if current locale is RTL.
2186 */
2187
2188 /**
2189 * Create an i18n instance
2190 *
2191 * @param {LocaleData} [initialData] Locale data configuration.
2192 * @param {string} [initialDomain] Domain for which configuration applies.
2193 * @return {I18n} I18n instance
2194 */
2195
2196 var createI18n = function createI18n(initialData, initialDomain) {
2197 /**
2198 * The underlying instance of Tannin to which exported functions interface.
2199 *
2200 * @type {Tannin}
2201 */
2202 var tannin = new _tannin.default({});
2203 /**
2204 * Merges locale data into the Tannin instance by domain. Accepts data in a
2205 * Jed-formatted JSON object shape.
2206 *
2207 * @see http://messageformat.github.io/Jed/
2208 *
2209 * @param {LocaleData} [data] Locale data configuration.
2210 * @param {string} [domain] Domain for which configuration applies.
2211 */
2212
2213 var setLocaleData = function setLocaleData(data) {
2214 var domain = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
2215 tannin.data[domain] = _objectSpread({}, DEFAULT_LOCALE_DATA, {}, tannin.data[domain], {}, data); // Populate default domain configuration (supported locale date which omits
2216 // a plural forms expression).
2217
2218 tannin.data[domain][''] = _objectSpread({}, DEFAULT_LOCALE_DATA[''], {}, tannin.data[domain]['']);
2219 };
2220 /**
2221 * Wrapper for Tannin's `dcnpgettext`. Populates default locale data if not
2222 * otherwise previously assigned.
2223 *
2224 * @param {string|undefined} domain Domain to retrieve the translated text.
2225 * @param {string|undefined} context Context information for the translators.
2226 * @param {string} single Text to translate if non-plural. Used as
2227 * fallback return value on a caught error.
2228 * @param {string} [plural] The text to be used if the number is
2229 * plural.
2230 * @param {number} [number] The number to compare against to use
2231 * either the singular or plural form.
2232 *
2233 * @return {string} The translated string.
2234 */
2235
2236
2237 var dcnpgettext = function dcnpgettext() {
2238 var domain = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';
2239 var context = arguments.length > 1 ? arguments[1] : undefined;
2240 var single = arguments.length > 2 ? arguments[2] : undefined;
2241 var plural = arguments.length > 3 ? arguments[3] : undefined;
2242 var number = arguments.length > 4 ? arguments[4] : undefined;
2243
2244 if (!tannin.data[domain]) {
2245 setLocaleData(undefined, domain);
2246 }
2247
2248 return tannin.dcnpgettext(domain, context, single, plural, number);
2249 };
2250 /**
2251 * Retrieve the translation of text.
2252 *
2253 * @see https://developer.wordpress.org/reference/functions/__/
2254 *
2255 * @param {string} text Text to translate.
2256 * @param {string} [domain] Domain to retrieve the translated text.
2257 *
2258 * @return {string} Translated text.
2259 */
2260
2261
2262 var __ = function __(text, domain) {
2263 return dcnpgettext(domain, undefined, text);
2264 };
2265 /**
2266 * Retrieve translated string with gettext context.
2267 *
2268 * @see https://developer.wordpress.org/reference/functions/_x/
2269 *
2270 * @param {string} text Text to translate.
2271 * @param {string} context Context information for the translators.
2272 * @param {string} [domain] Domain to retrieve the translated text.
2273 *
2274 * @return {string} Translated context string without pipe.
2275 */
2276
2277
2278 var _x = function _x(text, context, domain) {
2279 return dcnpgettext(domain, context, text);
2280 };
2281 /**
2282 * Translates and retrieves the singular or plural form based on the supplied
2283 * number.
2284 *
2285 * @see https://developer.wordpress.org/reference/functions/_n/
2286 *
2287 * @param {string} single The text to be used if the number is singular.
2288 * @param {string} plural The text to be used if the number is plural.
2289 * @param {number} number The number to compare against to use either the
2290 * singular or plural form.
2291 * @param {string} [domain] Domain to retrieve the translated text.
2292 *
2293 * @return {string} The translated singular or plural form.
2294 */
2295
2296
2297 var _n = function _n(single, plural, number, domain) {
2298 return dcnpgettext(domain, undefined, single, plural, number);
2299 };
2300 /**
2301 * Translates and retrieves the singular or plural form based on the supplied
2302 * number, with gettext context.
2303 *
2304 * @see https://developer.wordpress.org/reference/functions/_nx/
2305 *
2306 * @param {string} single The text to be used if the number is singular.
2307 * @param {string} plural The text to be used if the number is plural.
2308 * @param {number} number The number to compare against to use either the
2309 * singular or plural form.
2310 * @param {string} context Context information for the translators.
2311 * @param {string} [domain] Domain to retrieve the translated text.
2312 *
2313 * @return {string} The translated singular or plural form.
2314 */
2315
2316
2317 var _nx = function _nx(single, plural, number, context, domain) {
2318 return dcnpgettext(domain, context, single, plural, number);
2319 };
2320 /**
2321 * Check if current locale is RTL.
2322 *
2323 * **RTL (Right To Left)** is a locale property indicating that text is written from right to left.
2324 * For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common
2325 * language written RTL. The opposite of RTL, LTR (Left To Right) is used in other languages,
2326 * including English (`en`, `en-US`, `en-GB`, etc.), Spanish (`es`), and French (`fr`).
2327 *
2328 * @return {boolean} Whether locale is RTL.
2329 */
2330
2331
2332 var isRTL = function isRTL() {
2333 return 'rtl' === _x('ltr', 'text direction');
2334 };
2335
2336 if (initialData) {
2337 setLocaleData(initialData, initialDomain);
2338 }
2339
2340 return {
2341 setLocaleData: setLocaleData,
2342 __: __,
2343 _x: _x,
2344 _n: _n,
2345 _nx: _nx,
2346 isRTL: isRTL
2347 };
2348 };
2349
2350 exports.createI18n = createI18n;
2351
2352 },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":8,"tannin":22}],14:[function(require,module,exports){
2353 "use strict";
2354
2355 Object.defineProperty(exports, "__esModule", {
2356 value: true
2357 });
2358 exports.isRTL = exports._nx = exports._n = exports._x = exports.__ = exports.setLocaleData = void 0;
2359
2360 var _createI18n = require("./create-i18n");
2361
2362 /**
2363 * Internal dependencies
2364 */
2365 var i18n = (0, _createI18n.createI18n)();
2366 /*
2367 * Comments in this file are duplicated from ./i18n due to
2368 * https://github.com/WordPress/gutenberg/pull/20318#issuecomment-590837722
2369 */
2370
2371 /**
2372 * @typedef {import('./create-i18n').LocaleData} LocaleData
2373 */
2374
2375 /**
2376 * Merges locale data into the Tannin instance by domain. Accepts data in a
2377 * Jed-formatted JSON object shape.
2378 *
2379 * @see http://messageformat.github.io/Jed/
2380 *
2381 * @param {LocaleData} [data] Locale data configuration.
2382 * @param {string} [domain] Domain for which configuration applies.
2383 */
2384
2385 var setLocaleData = i18n.setLocaleData.bind(i18n);
2386 /**
2387 * Retrieve the translation of text.
2388 *
2389 * @see https://developer.wordpress.org/reference/functions/__/
2390 *
2391 * @param {string} text Text to translate.
2392 * @param {string} [domain] Domain to retrieve the translated text.
2393 *
2394 * @return {string} Translated text.
2395 */
2396
2397 exports.setLocaleData = setLocaleData;
2398
2399 var __ = i18n.__.bind(i18n);
2400 /**
2401 * Retrieve translated string with gettext context.
2402 *
2403 * @see https://developer.wordpress.org/reference/functions/_x/
2404 *
2405 * @param {string} text Text to translate.
2406 * @param {string} context Context information for the translators.
2407 * @param {string} [domain] Domain to retrieve the translated text.
2408 *
2409 * @return {string} Translated context string without pipe.
2410 */
2411
2412
2413 exports.__ = __;
2414
2415 var _x = i18n._x.bind(i18n);
2416 /**
2417 * Translates and retrieves the singular or plural form based on the supplied
2418 * number.
2419 *
2420 * @see https://developer.wordpress.org/reference/functions/_n/
2421 *
2422 * @param {string} single The text to be used if the number is singular.
2423 * @param {string} plural The text to be used if the number is plural.
2424 * @param {number} number The number to compare against to use either the
2425 * singular or plural form.
2426 * @param {string} [domain] Domain to retrieve the translated text.
2427 *
2428 * @return {string} The translated singular or plural form.
2429 */
2430
2431
2432 exports._x = _x;
2433
2434 var _n = i18n._n.bind(i18n);
2435 /**
2436 * Translates and retrieves the singular or plural form based on the supplied
2437 * number, with gettext context.
2438 *
2439 * @see https://developer.wordpress.org/reference/functions/_nx/
2440 *
2441 * @param {string} single The text to be used if the number is singular.
2442 * @param {string} plural The text to be used if the number is plural.
2443 * @param {number} number The number to compare against to use either the
2444 * singular or plural form.
2445 * @param {string} context Context information for the translators.
2446 * @param {string} [domain] Domain to retrieve the translated text.
2447 *
2448 * @return {string} The translated singular or plural form.
2449 */
2450
2451
2452 exports._n = _n;
2453
2454 var _nx = i18n._nx.bind(i18n);
2455 /**
2456 * Check if current locale is RTL.
2457 *
2458 * **RTL (Right To Left)** is a locale property indicating that text is written from right to left.
2459 * For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common
2460 * language written RTL. The opposite of RTL, LTR (Left To Right) is used in other languages,
2461 * including English (`en`, `en-US`, `en-GB`, etc.), Spanish (`es`), and French (`fr`).
2462 *
2463 * @return {boolean} Whether locale is RTL.
2464 */
2465
2466
2467 exports._nx = _nx;
2468 var isRTL = i18n.isRTL.bind(i18n);
2469 exports.isRTL = isRTL;
2470
2471 },{"./create-i18n":13}],15:[function(require,module,exports){
2472 "use strict";
2473
2474 Object.defineProperty(exports, "__esModule", {
2475 value: true
2476 });
2477 var _exportNames = {
2478 sprintf: true,
2479 setLocaleData: true,
2480 __: true,
2481 _x: true,
2482 _n: true,
2483 _nx: true,
2484 isRTL: true
2485 };
2486 Object.defineProperty(exports, "sprintf", {
2487 enumerable: true,
2488 get: function get() {
2489 return _sprintf.sprintf;
2490 }
2491 });
2492 Object.defineProperty(exports, "setLocaleData", {
2493 enumerable: true,
2494 get: function get() {
2495 return _defaultI18n.setLocaleData;
2496 }
2497 });
2498 Object.defineProperty(exports, "__", {
2499 enumerable: true,
2500 get: function get() {
2501 return _defaultI18n.__;
2502 }
2503 });
2504 Object.defineProperty(exports, "_x", {
2505 enumerable: true,
2506 get: function get() {
2507 return _defaultI18n._x;
2508 }
2509 });
2510 Object.defineProperty(exports, "_n", {
2511 enumerable: true,
2512 get: function get() {
2513 return _defaultI18n._n;
2514 }
2515 });
2516 Object.defineProperty(exports, "_nx", {
2517 enumerable: true,
2518 get: function get() {
2519 return _defaultI18n._nx;
2520 }
2521 });
2522 Object.defineProperty(exports, "isRTL", {
2523 enumerable: true,
2524 get: function get() {
2525 return _defaultI18n.isRTL;
2526 }
2527 });
2528
2529 var _sprintf = require("./sprintf");
2530
2531 var _createI18n = require("./create-i18n");
2532
2533 Object.keys(_createI18n).forEach(function (key) {
2534 if (key === "default" || key === "__esModule") return;
2535 if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
2536 Object.defineProperty(exports, key, {
2537 enumerable: true,
2538 get: function get() {
2539 return _createI18n[key];
2540 }
2541 });
2542 });
2543
2544 var _defaultI18n = require("./default-i18n");
2545
2546 },{"./create-i18n":13,"./default-i18n":14,"./sprintf":16}],16:[function(require,module,exports){
2547 "use strict";
2548
2549 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
2550
2551 Object.defineProperty(exports, "__esModule", {
2552 value: true
2553 });
2554 exports.sprintf = sprintf;
2555
2556 var _memize = _interopRequireDefault(require("memize"));
2557
2558 var _sprintfJs = _interopRequireDefault(require("sprintf-js"));
2559
2560 /**
2561 * External dependencies
2562 */
2563
2564 /**
2565 * Log to console, once per message; or more precisely, per referentially equal
2566 * argument set. Because Jed throws errors, we log these to the console instead
2567 * to avoid crashing the application.
2568 *
2569 * @param {...*} args Arguments to pass to `console.error`
2570 */
2571 var logErrorOnce = (0, _memize.default)(console.error); // eslint-disable-line no-console
2572
2573 /**
2574 * Returns a formatted string. If an error occurs in applying the format, the
2575 * original format string is returned.
2576 *
2577 * @param {string} format The format of the string to generate.
2578 * @param {...*} args Arguments to apply to the format.
2579 *
2580 * @see http://www.diveintojavascript.com/projects/javascript-sprintf
2581 *
2582 * @return {string} The formatted string.
2583 */
2584
2585 function sprintf(format) {
2586 try {
2587 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2588 args[_key - 1] = arguments[_key];
2589 }
2590
2591 return _sprintfJs.default.sprintf.apply(_sprintfJs.default, [format].concat(args));
2592 } catch (error) {
2593 logErrorOnce('sprintf error: \n\n' + error.toString());
2594 return format;
2595 }
2596 }
2597
2598 },{"@babel/runtime/helpers/interopRequireDefault":8,"memize":20,"sprintf-js":17}],17:[function(require,module,exports){
2599 /* global window, exports, define */
2600
2601 !function() {
2602 'use strict'
2603
2604 var re = {
2605 not_string: /[^s]/,
2606 not_bool: /[^t]/,
2607 not_type: /[^T]/,
2608 not_primitive: /[^v]/,
2609 number: /[diefg]/,
2610 numeric_arg: /[bcdiefguxX]/,
2611 json: /[j]/,
2612 not_json: /[^j]/,
2613 text: /^[^\x25]+/,
2614 modulo: /^\x25{2}/,
2615 placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
2616 key: /^([a-z_][a-z_\d]*)/i,
2617 key_access: /^\.([a-z_][a-z_\d]*)/i,
2618 index_access: /^\[(\d+)\]/,
2619 sign: /^[+-]/
2620 }
2621
2622 function sprintf(key) {
2623 // `arguments` is not an array, but should be fine for this call
2624 return sprintf_format(sprintf_parse(key), arguments)
2625 }
2626
2627 function vsprintf(fmt, argv) {
2628 return sprintf.apply(null, [fmt].concat(argv || []))
2629 }
2630
2631 function sprintf_format(parse_tree, argv) {
2632 var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
2633 for (i = 0; i < tree_length; i++) {
2634 if (typeof parse_tree[i] === 'string') {
2635 output += parse_tree[i]
2636 }
2637 else if (typeof parse_tree[i] === 'object') {
2638 ph = parse_tree[i] // convenience purposes only
2639 if (ph.keys) { // keyword argument
2640 arg = argv[cursor]
2641 for (k = 0; k < ph.keys.length; k++) {
2642 if (arg == undefined) {
2643 throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
2644 }
2645 arg = arg[ph.keys[k]]
2646 }
2647 }
2648 else if (ph.param_no) { // positional argument (explicit)
2649 arg = argv[ph.param_no]
2650 }
2651 else { // positional argument (implicit)
2652 arg = argv[cursor++]
2653 }
2654
2655 if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
2656 arg = arg()
2657 }
2658
2659 if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
2660 throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
2661 }
2662
2663 if (re.number.test(ph.type)) {
2664 is_positive = arg >= 0
2665 }
2666
2667 switch (ph.type) {
2668 case 'b':
2669 arg = parseInt(arg, 10).toString(2)
2670 break
2671 case 'c':
2672 arg = String.fromCharCode(parseInt(arg, 10))
2673 break
2674 case 'd':
2675 case 'i':
2676 arg = parseInt(arg, 10)
2677 break
2678 case 'j':
2679 arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
2680 break
2681 case 'e':
2682 arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
2683 break
2684 case 'f':
2685 arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
2686 break
2687 case 'g':
2688 arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
2689 break
2690 case 'o':
2691 arg = (parseInt(arg, 10) >>> 0).toString(8)
2692 break
2693 case 's':
2694 arg = String(arg)
2695 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
2696 break
2697 case 't':
2698 arg = String(!!arg)
2699 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
2700 break
2701 case 'T':
2702 arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
2703 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
2704 break
2705 case 'u':
2706 arg = parseInt(arg, 10) >>> 0
2707 break
2708 case 'v':
2709 arg = arg.valueOf()
2710 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
2711 break
2712 case 'x':
2713 arg = (parseInt(arg, 10) >>> 0).toString(16)
2714 break
2715 case 'X':
2716 arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
2717 break
2718 }
2719 if (re.json.test(ph.type)) {
2720 output += arg
2721 }
2722 else {
2723 if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
2724 sign = is_positive ? '+' : '-'
2725 arg = arg.toString().replace(re.sign, '')
2726 }
2727 else {
2728 sign = ''
2729 }
2730 pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
2731 pad_length = ph.width - (sign + arg).length
2732 pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
2733 output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
2734 }
2735 }
2736 }
2737 return output
2738 }
2739
2740 var sprintf_cache = Object.create(null)
2741
2742 function sprintf_parse(fmt) {
2743 if (sprintf_cache[fmt]) {
2744 return sprintf_cache[fmt]
2745 }
2746
2747 var _fmt = fmt, match, parse_tree = [], arg_names = 0
2748 while (_fmt) {
2749 if ((match = re.text.exec(_fmt)) !== null) {
2750 parse_tree.push(match[0])
2751 }
2752 else if ((match = re.modulo.exec(_fmt)) !== null) {
2753 parse_tree.push('%')
2754 }
2755 else if ((match = re.placeholder.exec(_fmt)) !== null) {
2756 if (match[2]) {
2757 arg_names |= 1
2758 var field_list = [], replacement_field = match[2], field_match = []
2759 if ((field_match = re.key.exec(replacement_field)) !== null) {
2760 field_list.push(field_match[1])
2761 while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
2762 if ((field_match = re.key_access.exec(replacement_field)) !== null) {
2763 field_list.push(field_match[1])
2764 }
2765 else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
2766 field_list.push(field_match[1])
2767 }
2768 else {
2769 throw new SyntaxError('[sprintf] failed to parse named argument key')
2770 }
2771 }
2772 }
2773 else {
2774 throw new SyntaxError('[sprintf] failed to parse named argument key')
2775 }
2776 match[2] = field_list
2777 }
2778 else {
2779 arg_names |= 2
2780 }
2781 if (arg_names === 3) {
2782 throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
2783 }
2784
2785 parse_tree.push(
2786 {
2787 placeholder: match[0],
2788 param_no: match[1],
2789 keys: match[2],
2790 sign: match[3],
2791 pad_char: match[4],
2792 align: match[5],
2793 width: match[6],
2794 precision: match[7],
2795 type: match[8]
2796 }
2797 )
2798 }
2799 else {
2800 throw new SyntaxError('[sprintf] unexpected placeholder')
2801 }
2802 _fmt = _fmt.substring(match[0].length)
2803 }
2804 return sprintf_cache[fmt] = parse_tree
2805 }
2806
2807 /**
2808 * export to either browser or node.js
2809 */
2810 /* eslint-disable quote-props */
2811 if (typeof exports !== 'undefined') {
2812 exports['sprintf'] = sprintf
2813 exports['vsprintf'] = vsprintf
2814 }
2815 if (typeof window !== 'undefined') {
2816 window['sprintf'] = sprintf
2817 window['vsprintf'] = vsprintf
2818
2819 if (typeof define === 'function' && define['amd']) {
2820 define(function() {
2821 return {
2822 'sprintf': sprintf,
2823 'vsprintf': vsprintf
2824 }
2825 })
2826 }
2827 }
2828 /* eslint-enable quote-props */
2829 }(); // eslint-disable-line
2830
2831 },{}],18:[function(require,module,exports){
2832 /*
2833 * International Telephone Input v17.0.16
2834 * https://github.com/jackocnr/intl-tel-input.git
2835 * Licensed under the MIT license
2836 */
2837
2838 // wrap in UMD
2839 (function(factory) {
2840 if (typeof module === "object" && module.exports) module.exports = factory(); else window.intlTelInput = factory();
2841 })(function(undefined) {
2842 "use strict";
2843 return function() {
2844 // Array of country objects for the flag dropdown.
2845 // Here is the criteria for the plugin to support a given country/territory
2846 // - It has an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
2847 // - 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
2848 // - It has a flag in the region-flags project: https://github.com/behdad/region-flags/tree/gh-pages/png
2849 // - It is supported by libphonenumber (it must be listed on this page): https://github.com/googlei18n/libphonenumber/blob/master/resources/ShortNumberMetadata.xml
2850 // Each country array has the following information:
2851 // [
2852 // Country name,
2853 // iso2 code,
2854 // International dial code,
2855 // Order (if >1 country with same dial code),
2856 // Area codes
2857 // ]
2858 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", "289", "306", "343", "365", "387", "403", "416", "418", "431", "437", "438", "450", "506", "514", "519", "548", "579", "581", "587", "604", "613", "639", "647", "672", "705", "709", "742", "778", "780", "782", "807", "819", "825", "867", "873", "902", "905" ] ], [ "Cape Verde (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 (‫جزر الق�
2859 ر‬‎)", "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 (‫�
2860 صر‬‎)", "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 (Каза�
2861 стан)", "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" ], [ "North Macedonia (Македонија)", "mk", "389" ], [ "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 (‫�
2862 وريتانيا‬‎)", "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 (‫ال�
2863 غرب‬‎)", "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" ], [ "Northern Mariana Islands", "mp", "1", 17, [ "670" ] ], [ "Norway (Norge)", "no", "47", 0 ], [ "Oman (‫عُ�
2864 ان‬‎)", "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 (‫ال�
2865
2866 لكة العربية السعودية‬‎)", "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 (‫الإ�
2867 ارات العربية ال�
2868 تحدة‬‎)", "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 (‫الي�
2869 ن‬‎)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ], [ "�
2870 land Islands", "ax", "358", 1, [ "18" ] ] ];
2871 // loop over all of the countries above, restructuring the data to be objects with named keys
2872 for (var i = 0; i < allCountries.length; i++) {
2873 var c = allCountries[i];
2874 allCountries[i] = {
2875 name: c[0],
2876 iso2: c[1],
2877 dialCode: c[2],
2878 priority: c[3] || 0,
2879 areaCodes: c[4] || null
2880 };
2881 }
2882 "use strict";
2883 function _classCallCheck(instance, Constructor) {
2884 if (!(instance instanceof Constructor)) {
2885 throw new TypeError("Cannot call a class as a function");
2886 }
2887 }
2888 function _defineProperties(target, props) {
2889 for (var i = 0; i < props.length; i++) {
2890 var descriptor = props[i];
2891 descriptor.enumerable = descriptor.enumerable || false;
2892 descriptor.configurable = true;
2893 if ("value" in descriptor) descriptor.writable = true;
2894 Object.defineProperty(target, descriptor.key, descriptor);
2895 }
2896 }
2897 function _createClass(Constructor, protoProps, staticProps) {
2898 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
2899 if (staticProps) _defineProperties(Constructor, staticProps);
2900 return Constructor;
2901 }
2902 var intlTelInputGlobals = {
2903 getInstance: function getInstance(input) {
2904 var id = input.getAttribute("data-intl-tel-input-id");
2905 return window.intlTelInputGlobals.instances[id];
2906 },
2907 instances: {},
2908 // using a global like this allows us to mock it in the tests
2909 documentReady: function documentReady() {
2910 return document.readyState === "complete";
2911 }
2912 };
2913 if (typeof window === "object") window.intlTelInputGlobals = intlTelInputGlobals;
2914 // these vars persist through all instances of the plugin
2915 var id = 0;
2916 var defaults = {
2917 // whether or not to allow the dropdown
2918 allowDropdown: true,
2919 // if there is just a dial code in the input: remove it on blur
2920 autoHideDialCode: true,
2921 // add a placeholder in the input with an example number for the selected country
2922 autoPlaceholder: "polite",
2923 // modify the parentClass
2924 customContainer: "",
2925 // modify the auto placeholder
2926 customPlaceholder: null,
2927 // append menu to specified element
2928 dropdownContainer: null,
2929 // don't display these countries
2930 excludeCountries: [],
2931 // format the input value during initialisation and on setNumber
2932 formatOnDisplay: true,
2933 // geoIp lookup function
2934 geoIpLookup: null,
2935 // inject a hidden input with this name, and on submit, populate it with the result of getNumber
2936 hiddenInput: "",
2937 // initial country
2938 initialCountry: "",
2939 // localized country names e.g. { 'de': 'Deutschland' }
2940 localizedCountries: null,
2941 // don't insert international dial codes
2942 nationalMode: true,
2943 // display only these countries
2944 onlyCountries: [],
2945 // number type to use for placeholders
2946 placeholderNumberType: "MOBILE",
2947 // the countries at the top of the list. defaults to united states and united kingdom
2948 preferredCountries: [ "us", "gb" ],
2949 // display the country dial code next to the selected flag so it's not part of the typed number
2950 separateDialCode: false,
2951 // specify the path to the libphonenumber script to enable validation/formatting
2952 utilsScript: ""
2953 };
2954 // https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes#Non-geographic_area_codes
2955 var regionlessNanpNumbers = [ "800", "822", "833", "844", "855", "866", "877", "880", "881", "882", "883", "884", "885", "886", "887", "888", "889" ];
2956 // utility function to iterate over an object. can't use Object.entries or native forEach because
2957 // of IE11
2958 var forEachProp = function forEachProp(obj, callback) {
2959 var keys = Object.keys(obj);
2960 for (var i = 0; i < keys.length; i++) {
2961 callback(keys[i], obj[keys[i]]);
2962 }
2963 };
2964 // run a method on each instance of the plugin
2965 var forEachInstance = function forEachInstance(method) {
2966 forEachProp(window.intlTelInputGlobals.instances, function(key) {
2967 window.intlTelInputGlobals.instances[key][method]();
2968 });
2969 };
2970 // this is our plugin class that we will create an instance of
2971 // eslint-disable-next-line no-unused-vars
2972 var Iti = /*#__PURE__*/
2973 function() {
2974 function Iti(input, options) {
2975 var _this = this;
2976 _classCallCheck(this, Iti);
2977 this.id = id++;
2978 this.telInput = input;
2979 this.activeItem = null;
2980 this.highlightedItem = null;
2981 // process specified options / defaults
2982 // alternative to Object.assign, which isn't supported by IE11
2983 var customOptions = options || {};
2984 this.options = {};
2985 forEachProp(defaults, function(key, value) {
2986 _this.options[key] = customOptions.hasOwnProperty(key) ? customOptions[key] : value;
2987 });
2988 this.hadInitialPlaceholder = Boolean(input.getAttribute("placeholder"));
2989 }
2990 _createClass(Iti, [ {
2991 key: "_init",
2992 value: function _init() {
2993 var _this2 = this;
2994 // if in nationalMode, disable options relating to dial codes
2995 if (this.options.nationalMode) this.options.autoHideDialCode = false;
2996 // if separateDialCode then doesn't make sense to A) insert dial code into input
2997 // (autoHideDialCode), and B) display national numbers (because we're displaying the country
2998 // dial code next to them)
2999 if (this.options.separateDialCode) {
3000 this.options.autoHideDialCode = this.options.nationalMode = false;
3001 }
3002 // we cannot just test screen size as some smartphones/website meta tags will report desktop
3003 // resolutions
3004 // Note: for some reason jasmine breaks if you put this in the main Plugin function with the
3005 // rest of these declarations
3006 // Note: to target Android Mobiles (and not Tablets), we must find 'Android' and 'Mobile'
3007 this.isMobile = /Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
3008 if (this.isMobile) {
3009 // trigger the mobile dropdown css
3010 document.body.classList.add("iti-mobile");
3011 // on mobile, we want a full screen dropdown, so we must append it to the body
3012 if (!this.options.dropdownContainer) this.options.dropdownContainer = document.body;
3013 }
3014 // these promises get resolved when their individual requests complete
3015 // this way the dev can do something like iti.promise.then(...) to know when all requests are
3016 // complete
3017 if (typeof Promise !== "undefined") {
3018 var autoCountryPromise = new Promise(function(resolve, reject) {
3019 _this2.resolveAutoCountryPromise = resolve;
3020 _this2.rejectAutoCountryPromise = reject;
3021 });
3022 var utilsScriptPromise = new Promise(function(resolve, reject) {
3023 _this2.resolveUtilsScriptPromise = resolve;
3024 _this2.rejectUtilsScriptPromise = reject;
3025 });
3026 this.promise = Promise.all([ autoCountryPromise, utilsScriptPromise ]);
3027 } else {
3028 // prevent errors when Promise doesn't exist
3029 this.resolveAutoCountryPromise = this.rejectAutoCountryPromise = function() {};
3030 this.resolveUtilsScriptPromise = this.rejectUtilsScriptPromise = function() {};
3031 }
3032 // in various situations there could be no country selected initially, but we need to be able
3033 // to assume this variable exists
3034 this.selectedCountryData = {};
3035 // process all the data: onlyCountries, excludeCountries, preferredCountries etc
3036 this._processCountryData();
3037 // generate the markup
3038 this._generateMarkup();
3039 // set the initial state of the input value and the selected flag
3040 this._setInitialState();
3041 // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click
3042 this._initListeners();
3043 // utils script, and auto country
3044 this._initRequests();
3045 }
3046 }, {
3047 key: "_processCountryData",
3048 value: function _processCountryData() {
3049 // process onlyCountries or excludeCountries array if present
3050 this._processAllCountries();
3051 // process the countryCodes map
3052 this._processCountryCodes();
3053 // process the preferredCountries
3054 this._processPreferredCountries();
3055 // translate countries according to localizedCountries option
3056 if (this.options.localizedCountries) this._translateCountriesByLocale();
3057 // sort countries by name
3058 if (this.options.onlyCountries.length || this.options.localizedCountries) {
3059 this.countries.sort(this._countryNameSort);
3060 }
3061 }
3062 }, {
3063 key: "_addCountryCode",
3064 value: function _addCountryCode(iso2, countryCode, priority) {
3065 if (countryCode.length > this.countryCodeMaxLen) {
3066 this.countryCodeMaxLen = countryCode.length;
3067 }
3068 if (!this.countryCodes.hasOwnProperty(countryCode)) {
3069 this.countryCodes[countryCode] = [];
3070 }
3071 // bail if we already have this country for this countryCode
3072 for (var i = 0; i < this.countryCodes[countryCode].length; i++) {
3073 if (this.countryCodes[countryCode][i] === iso2) return;
3074 }
3075 // check for undefined as 0 is falsy
3076 var index = priority !== undefined ? priority : this.countryCodes[countryCode].length;
3077 this.countryCodes[countryCode][index] = iso2;
3078 }
3079 }, {
3080 key: "_processAllCountries",
3081 value: function _processAllCountries() {
3082 if (this.options.onlyCountries.length) {
3083 var lowerCaseOnlyCountries = this.options.onlyCountries.map(function(country) {
3084 return country.toLowerCase();
3085 });
3086 this.countries = allCountries.filter(function(country) {
3087 return lowerCaseOnlyCountries.indexOf(country.iso2) > -1;
3088 });
3089 } else if (this.options.excludeCountries.length) {
3090 var lowerCaseExcludeCountries = this.options.excludeCountries.map(function(country) {
3091 return country.toLowerCase();
3092 });
3093 this.countries = allCountries.filter(function(country) {
3094 return lowerCaseExcludeCountries.indexOf(country.iso2) === -1;
3095 });
3096 } else {
3097 this.countries = allCountries;
3098 }
3099 }
3100 }, {
3101 key: "_translateCountriesByLocale",
3102 value: function _translateCountriesByLocale() {
3103 for (var i = 0; i < this.countries.length; i++) {
3104 var iso = this.countries[i].iso2.toLowerCase();
3105 if (this.options.localizedCountries.hasOwnProperty(iso)) {
3106 this.countries[i].name = this.options.localizedCountries[iso];
3107 }
3108 }
3109 }
3110 }, {
3111 key: "_countryNameSort",
3112 value: function _countryNameSort(a, b) {
3113 return a.name.localeCompare(b.name);
3114 }
3115 }, {
3116 key: "_processCountryCodes",
3117 value: function _processCountryCodes() {
3118 this.countryCodeMaxLen = 0;
3119 // here we store just dial codes
3120 this.dialCodes = {};
3121 // here we store "country codes" (both dial codes and their area codes)
3122 this.countryCodes = {};
3123 // first: add dial codes
3124 for (var i = 0; i < this.countries.length; i++) {
3125 var c = this.countries[i];
3126 if (!this.dialCodes[c.dialCode]) this.dialCodes[c.dialCode] = true;
3127 this._addCountryCode(c.iso2, c.dialCode, c.priority);
3128 }
3129 // next: add area codes
3130 // this is a second loop over countries, to make sure we have all of the "root" countries
3131 // already in the map, so that we can access them, as each time we add an area code substring
3132 // to the map, we also need to include the "root" country's code, as that also matches
3133 for (var _i = 0; _i < this.countries.length; _i++) {
3134 var _c = this.countries[_i];
3135 // area codes
3136 if (_c.areaCodes) {
3137 var rootCountryCode = this.countryCodes[_c.dialCode][0];
3138 // for each area code
3139 for (var j = 0; j < _c.areaCodes.length; j++) {
3140 var areaCode = _c.areaCodes[j];
3141 // for each digit in the area code to add all partial matches as well
3142 for (var k = 1; k < areaCode.length; k++) {
3143 var partialDialCode = _c.dialCode + areaCode.substr(0, k);
3144 // start with the root country, as that also matches this dial code
3145 this._addCountryCode(rootCountryCode, partialDialCode);
3146 this._addCountryCode(_c.iso2, partialDialCode);
3147 }
3148 // add the full area code
3149 this._addCountryCode(_c.iso2, _c.dialCode + areaCode);
3150 }
3151 }
3152 }
3153 }
3154 }, {
3155 key: "_processPreferredCountries",
3156 value: function _processPreferredCountries() {
3157 this.preferredCountries = [];
3158 for (var i = 0; i < this.options.preferredCountries.length; i++) {
3159 var countryCode = this.options.preferredCountries[i].toLowerCase();
3160 var countryData = this._getCountryData(countryCode, false, true);
3161 if (countryData) this.preferredCountries.push(countryData);
3162 }
3163 }
3164 }, {
3165 key: "_createEl",
3166 value: function _createEl(name, attrs, container) {
3167 var el = document.createElement(name);
3168 if (attrs) forEachProp(attrs, function(key, value) {
3169 return el.setAttribute(key, value);
3170 });
3171 if (container) container.appendChild(el);
3172 return el;
3173 }
3174 }, {
3175 key: "_generateMarkup",
3176 value: function _generateMarkup() {
3177 // if autocomplete does not exist on the element and its form, then
3178 // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can
3179 // easily put the plugin in an inconsistent state e.g. the wrong flag selected for the
3180 // autocompleted number, which on submit could mean wrong number is saved (esp in nationalMode)
3181 if (!this.telInput.hasAttribute("autocomplete") && !(this.telInput.form && this.telInput.form.hasAttribute("autocomplete"))) {
3182 this.telInput.setAttribute("autocomplete", "off");
3183 }
3184 // containers (mostly for positioning)
3185 var parentClass = "iti";
3186 if (this.options.allowDropdown) parentClass += " iti--allow-dropdown";
3187 if (this.options.separateDialCode) parentClass += " iti--separate-dial-code";
3188 if (this.options.customContainer) {
3189 parentClass += " ";
3190 parentClass += this.options.customContainer;
3191 }
3192 var wrapper = this._createEl("div", {
3193 "class": parentClass
3194 });
3195 this.telInput.parentNode.insertBefore(wrapper, this.telInput);
3196 this.flagsContainer = this._createEl("div", {
3197 "class": "iti__flag-container"
3198 }, wrapper);
3199 wrapper.appendChild(this.telInput);
3200 // selected flag (displayed to left of input)
3201 this.selectedFlag = this._createEl("div", {
3202 "class": "iti__selected-flag",
3203 role: "combobox",
3204 "aria-controls": "iti-".concat(this.id, "__country-listbox"),
3205 "aria-owns": "iti-".concat(this.id, "__country-listbox"),
3206 "aria-expanded": "false"
3207 }, this.flagsContainer);
3208 this.selectedFlagInner = this._createEl("div", {
3209 "class": "iti__flag"
3210 }, this.selectedFlag);
3211 if (this.options.separateDialCode) {
3212 this.selectedDialCode = this._createEl("div", {
3213 "class": "iti__selected-dial-code"
3214 }, this.selectedFlag);
3215 }
3216 if (this.options.allowDropdown) {
3217 // make element focusable and tab navigable
3218 this.selectedFlag.setAttribute("tabindex", "0");
3219 this.dropdownArrow = this._createEl("div", {
3220 "class": "iti__arrow"
3221 }, this.selectedFlag);
3222 // country dropdown: preferred countries, then divider, then all countries
3223 this.countryList = this._createEl("ul", {
3224 "class": "iti__country-list iti__hide",
3225 id: "iti-".concat(this.id, "__country-listbox"),
3226 role: "listbox",
3227 "aria-label": "List of countries"
3228 });
3229 if (this.preferredCountries.length) {
3230 this._appendListItems(this.preferredCountries, "iti__preferred", true);
3231 this._createEl("li", {
3232 "class": "iti__divider",
3233 role: "separator",
3234 "aria-disabled": "true"
3235 }, this.countryList);
3236 }
3237 this._appendListItems(this.countries, "iti__standard");
3238 // create dropdownContainer markup
3239 if (this.options.dropdownContainer) {
3240 this.dropdown = this._createEl("div", {
3241 "class": "iti iti--container"
3242 });
3243 this.dropdown.appendChild(this.countryList);
3244 } else {
3245 this.flagsContainer.appendChild(this.countryList);
3246 }
3247 }
3248 if (this.options.hiddenInput) {
3249 var hiddenInputName = this.options.hiddenInput;
3250 var name = this.telInput.getAttribute("name");
3251 if (name) {
3252 var i = name.lastIndexOf("[");
3253 // if input name contains square brackets, then give the hidden input the same name,
3254 // replacing the contents of the last set of brackets with the given hiddenInput name
3255 if (i !== -1) hiddenInputName = "".concat(name.substr(0, i), "[").concat(hiddenInputName, "]");
3256 }
3257 this.hiddenInput = this._createEl("input", {
3258 type: "hidden",
3259 name: hiddenInputName
3260 });
3261 wrapper.appendChild(this.hiddenInput);
3262 }
3263 }
3264 }, {
3265 key: "_appendListItems",
3266 value: function _appendListItems(countries, className, preferred) {
3267 // we create so many DOM elements, it is faster to build a temp string
3268 // and then add everything to the DOM in one go at the end
3269 var tmp = "";
3270 // for each country
3271 for (var i = 0; i < countries.length; i++) {
3272 var c = countries[i];
3273 var idSuffix = preferred ? "-preferred" : "";
3274 // open the list item
3275 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'>");
3276 // add the flag
3277 tmp += "<div class='iti__flag-box'><div class='iti__flag iti__".concat(c.iso2, "'></div></div>");
3278 // and the country name and dial code
3279 tmp += "<span class='iti__country-name'>".concat(c.name, "</span>");
3280 tmp += "<span class='iti__dial-code'>+".concat(c.dialCode, "</span>");
3281 // close the list item
3282 tmp += "</li>";
3283 }
3284 this.countryList.insertAdjacentHTML("beforeend", tmp);
3285 }
3286 }, {
3287 key: "_setInitialState",
3288 value: function _setInitialState() {
3289 // fix firefox bug: when first load page (with input with value set to number with intl dial
3290 // code) and initialising plugin removes the dial code from the input, then refresh page,
3291 // and we try to init plugin again but this time on number without dial code so get grey flag
3292 var attributeValue = this.telInput.getAttribute("value");
3293 var inputValue = this.telInput.value;
3294 var useAttribute = attributeValue && attributeValue.charAt(0) === "+" && (!inputValue || inputValue.charAt(0) !== "+");
3295 var val = useAttribute ? attributeValue : inputValue;
3296 var dialCode = this._getDialCode(val);
3297 var isRegionlessNanp = this._isRegionlessNanp(val);
3298 var _this$options = this.options, initialCountry = _this$options.initialCountry, nationalMode = _this$options.nationalMode, autoHideDialCode = _this$options.autoHideDialCode, separateDialCode = _this$options.separateDialCode;
3299 // if we already have a dial code, and it's not a regionlessNanp, we can go ahead and set the
3300 // flag, else fall back to the default country
3301 if (dialCode && !isRegionlessNanp) {
3302 this._updateFlagFromNumber(val);
3303 } else if (initialCountry !== "auto") {
3304 // see if we should select a flag
3305 if (initialCountry) {
3306 this._setFlag(initialCountry.toLowerCase());
3307 } else {
3308 if (dialCode && isRegionlessNanp) {
3309 // has intl dial code, is regionless nanp, and no initialCountry, so default to US
3310 this._setFlag("us");
3311 } else {
3312 // no dial code and no initialCountry, so default to first in list
3313 this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2;
3314 if (!val) {
3315 this._setFlag(this.defaultCountry);
3316 }
3317 }
3318 }
3319 // if empty and no nationalMode and no autoHideDialCode then insert the default dial code
3320 if (!val && !nationalMode && !autoHideDialCode && !separateDialCode) {
3321 this.telInput.value = "+".concat(this.selectedCountryData.dialCode);
3322 }
3323 }
3324 // NOTE: if initialCountry is set to auto, that will be handled separately
3325 // format - note this wont be run after _updateDialCode as that's only called if no val
3326 if (val) this._updateValFromNumber(val);
3327 }
3328 }, {
3329 key: "_initListeners",
3330 value: function _initListeners() {
3331 this._initKeyListeners();
3332 if (this.options.autoHideDialCode) this._initBlurListeners();
3333 if (this.options.allowDropdown) this._initDropdownListeners();
3334 if (this.hiddenInput) this._initHiddenInputListener();
3335 }
3336 }, {
3337 key: "_initHiddenInputListener",
3338 value: function _initHiddenInputListener() {
3339 var _this3 = this;
3340 this._handleHiddenInputSubmit = function() {
3341 _this3.hiddenInput.value = _this3.getNumber();
3342 };
3343 if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleHiddenInputSubmit);
3344 }
3345 }, {
3346 key: "_getClosestLabel",
3347 value: function _getClosestLabel() {
3348 var el = this.telInput;
3349 while (el && el.tagName !== "LABEL") {
3350 el = el.parentNode;
3351 }
3352 return el;
3353 }
3354 }, {
3355 key: "_initDropdownListeners",
3356 value: function _initDropdownListeners() {
3357 var _this4 = this;
3358 // hack for input nested inside label (which is valid markup): clicking the selected-flag to
3359 // open the dropdown would then automatically trigger a 2nd click on the input which would
3360 // close it again
3361 this._handleLabelClick = function(e) {
3362 // if the dropdown is closed, then focus the input, else ignore the click
3363 if (_this4.countryList.classList.contains("iti__hide")) _this4.telInput.focus(); else e.preventDefault();
3364 };
3365 var label = this._getClosestLabel();
3366 if (label) label.addEventListener("click", this._handleLabelClick);
3367 // toggle country dropdown on click
3368 this._handleClickSelectedFlag = function() {
3369 // only intercept this event if we're opening the dropdown
3370 // else let it bubble up to the top ("click-off-to-close" listener)
3371 // we cannot just stopPropagation as it may be needed to close another instance
3372 if (_this4.countryList.classList.contains("iti__hide") && !_this4.telInput.disabled && !_this4.telInput.readOnly) {
3373 _this4._showDropdown();
3374 }
3375 };
3376 this.selectedFlag.addEventListener("click", this._handleClickSelectedFlag);
3377 // open dropdown list if currently focused
3378 this._handleFlagsContainerKeydown = function(e) {
3379 var isDropdownHidden = _this4.countryList.classList.contains("iti__hide");
3380 if (isDropdownHidden && [ "ArrowUp", "Up", "ArrowDown", "Down", " ", "Enter" ].indexOf(e.key) !== -1) {
3381 // prevent form from being submitted if "ENTER" was pressed
3382 e.preventDefault();
3383 // prevent event from being handled again by document
3384 e.stopPropagation();
3385 _this4._showDropdown();
3386 }
3387 // allow navigation from dropdown to input on TAB
3388 if (e.key === "Tab") _this4._closeDropdown();
3389 };
3390 this.flagsContainer.addEventListener("keydown", this._handleFlagsContainerKeydown);
3391 }
3392 }, {
3393 key: "_initRequests",
3394 value: function _initRequests() {
3395 var _this5 = this;
3396 // if the user has specified the path to the utils script, fetch it on window.load, else resolve
3397 if (this.options.utilsScript && !window.intlTelInputUtils) {
3398 // if the plugin is being initialised after the window.load event has already been fired
3399 if (window.intlTelInputGlobals.documentReady()) {
3400 window.intlTelInputGlobals.loadUtils(this.options.utilsScript);
3401 } else {
3402 // wait until the load event so we don't block any other requests e.g. the flags image
3403 window.addEventListener("load", function() {
3404 window.intlTelInputGlobals.loadUtils(_this5.options.utilsScript);
3405 });
3406 }
3407 } else this.resolveUtilsScriptPromise();
3408 if (this.options.initialCountry === "auto") this._loadAutoCountry(); else this.resolveAutoCountryPromise();
3409 }
3410 }, {
3411 key: "_loadAutoCountry",
3412 value: function _loadAutoCountry() {
3413 // 3 options:
3414 // 1) already loaded (we're done)
3415 // 2) not already started loading (start)
3416 // 3) already started loading (do nothing - just wait for loading callback to fire)
3417 if (window.intlTelInputGlobals.autoCountry) {
3418 this.handleAutoCountry();
3419 } else if (!window.intlTelInputGlobals.startedLoadingAutoCountry) {
3420 // don't do this twice!
3421 window.intlTelInputGlobals.startedLoadingAutoCountry = true;
3422 if (typeof this.options.geoIpLookup === "function") {
3423 this.options.geoIpLookup(function(countryCode) {
3424 window.intlTelInputGlobals.autoCountry = countryCode.toLowerCase();
3425 // tell all instances the auto country is ready
3426 // TODO: this should just be the current instances
3427 // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight
3428 // away (e.g. if they have already done the geo ip lookup somewhere else). Using
3429 // setTimeout means that the current thread of execution will finish before executing
3430 // this, which allows the plugin to finish initialising.
3431 setTimeout(function() {
3432 return forEachInstance("handleAutoCountry");
3433 });
3434 }, function() {
3435 return forEachInstance("rejectAutoCountryPromise");
3436 });
3437 }
3438 }
3439 }
3440 }, {
3441 key: "_initKeyListeners",
3442 value: function _initKeyListeners() {
3443 var _this6 = this;
3444 // update flag on keyup
3445 this._handleKeyupEvent = function() {
3446 if (_this6._updateFlagFromNumber(_this6.telInput.value)) {
3447 _this6._triggerCountryChange();
3448 }
3449 };
3450 this.telInput.addEventListener("keyup", this._handleKeyupEvent);
3451 // update flag on cut/paste events (now supported in all major browsers)
3452 this._handleClipboardEvent = function() {
3453 // hack because "paste" event is fired before input is updated
3454 setTimeout(_this6._handleKeyupEvent);
3455 };
3456 this.telInput.addEventListener("cut", this._handleClipboardEvent);
3457 this.telInput.addEventListener("paste", this._handleClipboardEvent);
3458 }
3459 }, {
3460 key: "_cap",
3461 value: function _cap(number) {
3462 var max = this.telInput.getAttribute("maxlength");
3463 return max && number.length > max ? number.substr(0, max) : number;
3464 }
3465 }, {
3466 key: "_initBlurListeners",
3467 value: function _initBlurListeners() {
3468 var _this7 = this;
3469 // on blur or form submit: if just a dial code then remove it
3470 this._handleSubmitOrBlurEvent = function() {
3471 _this7._removeEmptyDialCode();
3472 };
3473 if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleSubmitOrBlurEvent);
3474 this.telInput.addEventListener("blur", this._handleSubmitOrBlurEvent);
3475 }
3476 }, {
3477 key: "_removeEmptyDialCode",
3478 value: function _removeEmptyDialCode() {
3479 if (this.telInput.value.charAt(0) === "+") {
3480 var numeric = this._getNumeric(this.telInput.value);
3481 // if just a plus, or if just a dial code
3482 if (!numeric || this.selectedCountryData.dialCode === numeric) {
3483 this.telInput.value = "";
3484 }
3485 }
3486 }
3487 }, {
3488 key: "_getNumeric",
3489 value: function _getNumeric(s) {
3490 return s.replace(/\D/g, "");
3491 }
3492 }, {
3493 key: "_trigger",
3494 value: function _trigger(name) {
3495 // have to use old school document.createEvent as IE11 doesn't support `new Event()` syntax
3496 var e = document.createEvent("Event");
3497 e.initEvent(name, true, true);
3498 // can bubble, and is cancellable
3499 this.telInput.dispatchEvent(e);
3500 }
3501 }, {
3502 key: "_showDropdown",
3503 value: function _showDropdown() {
3504 this.countryList.classList.remove("iti__hide");
3505 this.selectedFlag.setAttribute("aria-expanded", "true");
3506 this._setDropdownPosition();
3507 // update highlighting and scroll to active list item
3508 if (this.activeItem) {
3509 this._highlightListItem(this.activeItem, false);
3510 this._scrollTo(this.activeItem, true);
3511 }
3512 // bind all the dropdown-related listeners: mouseover, click, click-off, keydown
3513 this._bindDropdownListeners();
3514 // update the arrow
3515 this.dropdownArrow.classList.add("iti__arrow--up");
3516 this._trigger("open:countrydropdown");
3517 }
3518 }, {
3519 key: "_toggleClass",
3520 value: function _toggleClass(el, className, shouldHaveClass) {
3521 if (shouldHaveClass && !el.classList.contains(className)) el.classList.add(className); else if (!shouldHaveClass && el.classList.contains(className)) el.classList.remove(className);
3522 }
3523 }, {
3524 key: "_setDropdownPosition",
3525 value: function _setDropdownPosition() {
3526 var _this8 = this;
3527 if (this.options.dropdownContainer) {
3528 this.options.dropdownContainer.appendChild(this.dropdown);
3529 }
3530 if (!this.isMobile) {
3531 var pos = this.telInput.getBoundingClientRect();
3532 // windowTop from https://stackoverflow.com/a/14384091/217866
3533 var windowTop = window.pageYOffset || document.documentElement.scrollTop;
3534 var inputTop = pos.top + windowTop;
3535 var dropdownHeight = this.countryList.offsetHeight;
3536 // dropdownFitsBelow = (dropdownBottom < windowBottom)
3537 var dropdownFitsBelow = inputTop + this.telInput.offsetHeight + dropdownHeight < windowTop + window.innerHeight;
3538 var dropdownFitsAbove = inputTop - dropdownHeight > windowTop;
3539 // by default, the dropdown will be below the input. If we want to position it above the
3540 // input, we add the dropup class.
3541 this._toggleClass(this.countryList, "iti__country-list--dropup", !dropdownFitsBelow && dropdownFitsAbove);
3542 // if dropdownContainer is enabled, calculate postion
3543 if (this.options.dropdownContainer) {
3544 // by default the dropdown will be directly over the input because it's not in the flow.
3545 // If we want to position it below, we need to add some extra top value.
3546 var extraTop = !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.offsetHeight;
3547 // calculate placement
3548 this.dropdown.style.top = "".concat(inputTop + extraTop, "px");
3549 this.dropdown.style.left = "".concat(pos.left + document.body.scrollLeft, "px");
3550 // close menu on window scroll
3551 this._handleWindowScroll = function() {
3552 return _this8._closeDropdown();
3553 };
3554 window.addEventListener("scroll", this._handleWindowScroll);
3555 }
3556 }
3557 }
3558 }, {
3559 key: "_getClosestListItem",
3560 value: function _getClosestListItem(target) {
3561 var el = target;
3562 while (el && el !== this.countryList && !el.classList.contains("iti__country")) {
3563 el = el.parentNode;
3564 }
3565 // if we reached the countryList element, then return null
3566 return el === this.countryList ? null : el;
3567 }
3568 }, {
3569 key: "_bindDropdownListeners",
3570 value: function _bindDropdownListeners() {
3571 var _this9 = this;
3572 // when mouse over a list item, just highlight that one
3573 // we add the class "highlight", so if they hit "enter" we know which one to select
3574 this._handleMouseoverCountryList = function(e) {
3575 // handle event delegation, as we're listening for this event on the countryList
3576 var listItem = _this9._getClosestListItem(e.target);
3577 if (listItem) _this9._highlightListItem(listItem, false);
3578 };
3579 this.countryList.addEventListener("mouseover", this._handleMouseoverCountryList);
3580 // listen for country selection
3581 this._handleClickCountryList = function(e) {
3582 var listItem = _this9._getClosestListItem(e.target);
3583 if (listItem) _this9._selectListItem(listItem);
3584 };
3585 this.countryList.addEventListener("click", this._handleClickCountryList);
3586 // click off to close
3587 // (except when this initial opening click is bubbling up)
3588 // we cannot just stopPropagation as it may be needed to close another instance
3589 var isOpening = true;
3590 this._handleClickOffToClose = function() {
3591 if (!isOpening) _this9._closeDropdown();
3592 isOpening = false;
3593 };
3594 document.documentElement.addEventListener("click", this._handleClickOffToClose);
3595 // listen for up/down scrolling, enter to select, or letters to jump to country name.
3596 // use keydown as keypress doesn't fire for non-char keys and we want to catch if they
3597 // just hit down and hold it to scroll down (no keyup event).
3598 // listen on the document because that's where key events are triggered if no input has focus
3599 var query = "";
3600 var queryTimer = null;
3601 this._handleKeydownOnDropdown = function(e) {
3602 // prevent down key from scrolling the whole page,
3603 // and enter key from submitting a form etc
3604 e.preventDefault();
3605 // up and down to navigate
3606 if (e.key === "ArrowUp" || e.key === "Up" || e.key === "ArrowDown" || e.key === "Down") _this9._handleUpDownKey(e.key); else if (e.key === "Enter") _this9._handleEnterKey(); else if (e.key === "Escape") _this9._closeDropdown(); else if (/^[a-zA-ZÀ-ÿа-яА-Я ]$/.test(e.key)) {
3607 // jump to countries that start with the query string
3608 if (queryTimer) clearTimeout(queryTimer);
3609 query += e.key.toLowerCase();
3610 _this9._searchForCountry(query);
3611 // if the timer hits 1 second, reset the query
3612 queryTimer = setTimeout(function() {
3613 query = "";
3614 }, 1e3);
3615 }
3616 };
3617 document.addEventListener("keydown", this._handleKeydownOnDropdown);
3618 }
3619 }, {
3620 key: "_handleUpDownKey",
3621 value: function _handleUpDownKey(key) {
3622 var next = key === "ArrowUp" || key === "Up" ? this.highlightedItem.previousElementSibling : this.highlightedItem.nextElementSibling;
3623 if (next) {
3624 // skip the divider
3625 if (next.classList.contains("iti__divider")) {
3626 next = key === "ArrowUp" || key === "Up" ? next.previousElementSibling : next.nextElementSibling;
3627 }
3628 this._highlightListItem(next, true);
3629 }
3630 }
3631 }, {
3632 key: "_handleEnterKey",
3633 value: function _handleEnterKey() {
3634 if (this.highlightedItem) this._selectListItem(this.highlightedItem);
3635 }
3636 }, {
3637 key: "_searchForCountry",
3638 value: function _searchForCountry(query) {
3639 for (var i = 0; i < this.countries.length; i++) {
3640 if (this._startsWith(this.countries[i].name, query)) {
3641 var listItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(this.countries[i].iso2));
3642 // update highlighting and scroll
3643 this._highlightListItem(listItem, false);
3644 this._scrollTo(listItem, true);
3645 break;
3646 }
3647 }
3648 }
3649 }, {
3650 key: "_startsWith",
3651 value: function _startsWith(a, b) {
3652 return a.substr(0, b.length).toLowerCase() === b;
3653 }
3654 }, {
3655 key: "_updateValFromNumber",
3656 value: function _updateValFromNumber(originalNumber) {
3657 var number = originalNumber;
3658 if (this.options.formatOnDisplay && window.intlTelInputUtils && this.selectedCountryData) {
3659 var useNational = !this.options.separateDialCode && (this.options.nationalMode || number.charAt(0) !== "+");
3660 var _intlTelInputUtils$nu = intlTelInputUtils.numberFormat, NATIONAL = _intlTelInputUtils$nu.NATIONAL, INTERNATIONAL = _intlTelInputUtils$nu.INTERNATIONAL;
3661 var format = useNational ? NATIONAL : INTERNATIONAL;
3662 number = intlTelInputUtils.formatNumber(number, this.selectedCountryData.iso2, format);
3663 }
3664 number = this._beforeSetNumber(number);
3665 this.telInput.value = number;
3666 }
3667 }, {
3668 key: "_updateFlagFromNumber",
3669 value: function _updateFlagFromNumber(originalNumber) {
3670 // if we're in nationalMode and we already have US/Canada selected, make sure the number starts
3671 // with a +1 so _getDialCode will be able to extract the area code
3672 // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag
3673 // from the number), that means we're initialising the plugin with a number that already has a
3674 // dial code, so fine to ignore this bit
3675 var number = originalNumber;
3676 var selectedDialCode = this.selectedCountryData.dialCode;
3677 var isNanp = selectedDialCode === "1";
3678 if (number && this.options.nationalMode && isNanp && number.charAt(0) !== "+") {
3679 if (number.charAt(0) !== "1") number = "1".concat(number);
3680 number = "+".concat(number);
3681 }
3682 // update flag if user types area code for another country
3683 if (this.options.separateDialCode && selectedDialCode && number.charAt(0) !== "+") {
3684 number = "+".concat(selectedDialCode).concat(number);
3685 }
3686 // try and extract valid dial code from input
3687 var dialCode = this._getDialCode(number, true);
3688 var numeric = this._getNumeric(number);
3689 var countryCode = null;
3690 if (dialCode) {
3691 var countryCodes = this.countryCodes[this._getNumeric(dialCode)];
3692 // check if the right country is already selected. this should be false if the number is
3693 // longer than the matched dial code because in this case we need to make sure that if
3694 // there are multiple country matches, that the first one is selected (note: we could
3695 // just check that here, but it requires the same loop that we already have later)
3696 var alreadySelected = countryCodes.indexOf(this.selectedCountryData.iso2) !== -1 && numeric.length <= dialCode.length - 1;
3697 var isRegionlessNanpNumber = selectedDialCode === "1" && this._isRegionlessNanp(numeric);
3698 // only update the flag if:
3699 // A) NOT (we currently have a NANP flag selected, and the number is a regionlessNanp)
3700 // AND
3701 // B) the right country is not already selected
3702 if (!isRegionlessNanpNumber && !alreadySelected) {
3703 // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first
3704 // non-empty index
3705 for (var j = 0; j < countryCodes.length; j++) {
3706 if (countryCodes[j]) {
3707 countryCode = countryCodes[j];
3708 break;
3709 }
3710 }
3711 }
3712 } else if (number.charAt(0) === "+" && numeric.length) {
3713 // invalid dial code, so empty
3714 // Note: use getNumeric here because the number has not been formatted yet, so could contain
3715 // bad chars
3716 countryCode = "";
3717 } else if (!number || number === "+") {
3718 // empty, or just a plus, so default
3719 countryCode = this.defaultCountry;
3720 }
3721 if (countryCode !== null) {
3722 return this._setFlag(countryCode);
3723 }
3724 return false;
3725 }
3726 }, {
3727 key: "_isRegionlessNanp",
3728 value: function _isRegionlessNanp(number) {
3729 var numeric = this._getNumeric(number);
3730 if (numeric.charAt(0) === "1") {
3731 var areaCode = numeric.substr(1, 3);
3732 return regionlessNanpNumbers.indexOf(areaCode) !== -1;
3733 }
3734 return false;
3735 }
3736 }, {
3737 key: "_highlightListItem",
3738 value: function _highlightListItem(listItem, shouldFocus) {
3739 var prevItem = this.highlightedItem;
3740 if (prevItem) prevItem.classList.remove("iti__highlight");
3741 this.highlightedItem = listItem;
3742 this.highlightedItem.classList.add("iti__highlight");
3743 if (shouldFocus) this.highlightedItem.focus();
3744 }
3745 }, {
3746 key: "_getCountryData",
3747 value: function _getCountryData(countryCode, ignoreOnlyCountriesOption, allowFail) {
3748 var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
3749 for (var i = 0; i < countryList.length; i++) {
3750 if (countryList[i].iso2 === countryCode) {
3751 return countryList[i];
3752 }
3753 }
3754 if (allowFail) {
3755 return null;
3756 }
3757 throw new Error("No country data for '".concat(countryCode, "'"));
3758 }
3759 }, {
3760 key: "_setFlag",
3761 value: function _setFlag(countryCode) {
3762 var prevCountry = this.selectedCountryData.iso2 ? this.selectedCountryData : {};
3763 // do this first as it will throw an error and stop if countryCode is invalid
3764 this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {};
3765 // update the defaultCountry - we only need the iso2 from now on, so just store that
3766 if (this.selectedCountryData.iso2) {
3767 this.defaultCountry = this.selectedCountryData.iso2;
3768 }
3769 this.selectedFlagInner.setAttribute("class", "iti__flag iti__".concat(countryCode));
3770 // update the selected country's title attribute
3771 var title = countryCode ? "".concat(this.selectedCountryData.name, ": +").concat(this.selectedCountryData.dialCode) : "Unknown";
3772 this.selectedFlag.setAttribute("title", title);
3773 if (this.options.separateDialCode) {
3774 var dialCode = this.selectedCountryData.dialCode ? "+".concat(this.selectedCountryData.dialCode) : "";
3775 this.selectedDialCode.innerHTML = dialCode;
3776 // offsetWidth is zero if input is in a hidden container during initialisation
3777 var selectedFlagWidth = this.selectedFlag.offsetWidth || this._getHiddenSelectedFlagWidth();
3778 // add 6px of padding after the grey selected-dial-code box, as this is what we use in the css
3779 this.telInput.style.paddingLeft = "".concat(selectedFlagWidth + 6, "px");
3780 }
3781 // and the input's placeholder
3782 this._updatePlaceholder();
3783 // update the active list item
3784 if (this.options.allowDropdown) {
3785 var prevItem = this.activeItem;
3786 if (prevItem) {
3787 prevItem.classList.remove("iti__active");
3788 prevItem.setAttribute("aria-selected", "false");
3789 }
3790 if (countryCode) {
3791 // check if there is a preferred item first, else fall back to standard
3792 var nextItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode, "-preferred")) || this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode));
3793 nextItem.setAttribute("aria-selected", "true");
3794 nextItem.classList.add("iti__active");
3795 this.activeItem = nextItem;
3796 this.selectedFlag.setAttribute("aria-activedescendant", nextItem.getAttribute("id"));
3797 }
3798 }
3799 // return if the flag has changed or not
3800 return prevCountry.iso2 !== countryCode;
3801 }
3802 }, {
3803 key: "_getHiddenSelectedFlagWidth",
3804 value: function _getHiddenSelectedFlagWidth() {
3805 // to get the right styling to apply, all we need is a shallow clone of the container,
3806 // and then to inject a deep clone of the selectedFlag element
3807 var containerClone = this.telInput.parentNode.cloneNode();
3808 containerClone.style.visibility = "hidden";
3809 document.body.appendChild(containerClone);
3810 var flagsContainerClone = this.flagsContainer.cloneNode();
3811 containerClone.appendChild(flagsContainerClone);
3812 var selectedFlagClone = this.selectedFlag.cloneNode(true);
3813 flagsContainerClone.appendChild(selectedFlagClone);
3814 var width = selectedFlagClone.offsetWidth;
3815 containerClone.parentNode.removeChild(containerClone);
3816 return width;
3817 }
3818 }, {
3819 key: "_updatePlaceholder",
3820 value: function _updatePlaceholder() {
3821 var shouldSetPlaceholder = this.options.autoPlaceholder === "aggressive" || !this.hadInitialPlaceholder && this.options.autoPlaceholder === "polite";
3822 if (window.intlTelInputUtils && shouldSetPlaceholder) {
3823 var numberType = intlTelInputUtils.numberType[this.options.placeholderNumberType];
3824 var placeholder = this.selectedCountryData.iso2 ? intlTelInputUtils.getExampleNumber(this.selectedCountryData.iso2, this.options.nationalMode, numberType) : "";
3825 placeholder = this._beforeSetNumber(placeholder);
3826 if (typeof this.options.customPlaceholder === "function") {
3827 placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData);
3828 }
3829 this.telInput.setAttribute("placeholder", placeholder);
3830 }
3831 }
3832 }, {
3833 key: "_selectListItem",
3834 value: function _selectListItem(listItem) {
3835 // update selected flag and active list item
3836 var flagChanged = this._setFlag(listItem.getAttribute("data-country-code"));
3837 this._closeDropdown();
3838 this._updateDialCode(listItem.getAttribute("data-dial-code"), true);
3839 // focus the input
3840 this.telInput.focus();
3841 // put cursor at end - this fix is required for FF and IE11 (with nationalMode=false i.e. auto
3842 // inserting dial code), who try to put the cursor at the beginning the first time
3843 var len = this.telInput.value.length;
3844 this.telInput.setSelectionRange(len, len);
3845 if (flagChanged) {
3846 this._triggerCountryChange();
3847 }
3848 }
3849 }, {
3850 key: "_closeDropdown",
3851 value: function _closeDropdown() {
3852 this.countryList.classList.add("iti__hide");
3853 this.selectedFlag.setAttribute("aria-expanded", "false");
3854 // update the arrow
3855 this.dropdownArrow.classList.remove("iti__arrow--up");
3856 // unbind key events
3857 document.removeEventListener("keydown", this._handleKeydownOnDropdown);
3858 document.documentElement.removeEventListener("click", this._handleClickOffToClose);
3859 this.countryList.removeEventListener("mouseover", this._handleMouseoverCountryList);
3860 this.countryList.removeEventListener("click", this._handleClickCountryList);
3861 // remove menu from container
3862 if (this.options.dropdownContainer) {
3863 if (!this.isMobile) window.removeEventListener("scroll", this._handleWindowScroll);
3864 if (this.dropdown.parentNode) this.dropdown.parentNode.removeChild(this.dropdown);
3865 }
3866 this._trigger("close:countrydropdown");
3867 }
3868 }, {
3869 key: "_scrollTo",
3870 value: function _scrollTo(element, middle) {
3871 var container = this.countryList;
3872 // windowTop from https://stackoverflow.com/a/14384091/217866
3873 var windowTop = window.pageYOffset || document.documentElement.scrollTop;
3874 var containerHeight = container.offsetHeight;
3875 var containerTop = container.getBoundingClientRect().top + windowTop;
3876 var containerBottom = containerTop + containerHeight;
3877 var elementHeight = element.offsetHeight;
3878 var elementTop = element.getBoundingClientRect().top + windowTop;
3879 var elementBottom = elementTop + elementHeight;
3880 var newScrollTop = elementTop - containerTop + container.scrollTop;
3881 var middleOffset = containerHeight / 2 - elementHeight / 2;
3882 if (elementTop < containerTop) {
3883 // scroll up
3884 if (middle) newScrollTop -= middleOffset;
3885 container.scrollTop = newScrollTop;
3886 } else if (elementBottom > containerBottom) {
3887 // scroll down
3888 if (middle) newScrollTop += middleOffset;
3889 var heightDifference = containerHeight - elementHeight;
3890 container.scrollTop = newScrollTop - heightDifference;
3891 }
3892 }
3893 }, {
3894 key: "_updateDialCode",
3895 value: function _updateDialCode(newDialCodeBare, hasSelectedListItem) {
3896 var inputVal = this.telInput.value;
3897 // save having to pass this every time
3898 var newDialCode = "+".concat(newDialCodeBare);
3899 var newNumber;
3900 if (inputVal.charAt(0) === "+") {
3901 // there's a plus so we're dealing with a replacement (doesn't matter if nationalMode or not)
3902 var prevDialCode = this._getDialCode(inputVal);
3903 if (prevDialCode) {
3904 // current number contains a valid dial code, so replace it
3905 newNumber = inputVal.replace(prevDialCode, newDialCode);
3906 } else {
3907 // current number contains an invalid dial code, so ditch it
3908 // (no way to determine where the invalid dial code ends and the rest of the number begins)
3909 newNumber = newDialCode;
3910 }
3911 } else if (this.options.nationalMode || this.options.separateDialCode) {
3912 // don't do anything
3913 return;
3914 } else {
3915 // nationalMode is disabled
3916 if (inputVal) {
3917 // there is an existing value with no dial code: prefix the new dial code
3918 newNumber = newDialCode + inputVal;
3919 } else if (hasSelectedListItem || !this.options.autoHideDialCode) {
3920 // no existing value and either they've just selected a list item, or autoHideDialCode is
3921 // disabled: insert new dial code
3922 newNumber = newDialCode;
3923 } else {
3924 return;
3925 }
3926 }
3927 this.telInput.value = newNumber;
3928 }
3929 }, {
3930 key: "_getDialCode",
3931 value: function _getDialCode(number, includeAreaCode) {
3932 var dialCode = "";
3933 // only interested in international numbers (starting with a plus)
3934 if (number.charAt(0) === "+") {
3935 var numericChars = "";
3936 // iterate over chars
3937 for (var i = 0; i < number.length; i++) {
3938 var c = number.charAt(i);
3939 // if char is number (https://stackoverflow.com/a/8935649/217866)
3940 if (!isNaN(parseInt(c, 10))) {
3941 numericChars += c;
3942 // if current numericChars make a valid dial code
3943 if (includeAreaCode) {
3944 if (this.countryCodes[numericChars]) {
3945 // store the actual raw string (useful for matching later)
3946 dialCode = number.substr(0, i + 1);
3947 }
3948 } else {
3949 if (this.dialCodes[numericChars]) {
3950 dialCode = number.substr(0, i + 1);
3951 // if we're just looking for a dial code, we can break as soon as we find one
3952 break;
3953 }
3954 }
3955 // stop searching as soon as we can - in this case when we hit max len
3956 if (numericChars.length === this.countryCodeMaxLen) {
3957 break;
3958 }
3959 }
3960 }
3961 }
3962 return dialCode;
3963 }
3964 }, {
3965 key: "_getFullNumber",
3966 value: function _getFullNumber() {
3967 var val = this.telInput.value.trim();
3968 var dialCode = this.selectedCountryData.dialCode;
3969 var prefix;
3970 var numericVal = this._getNumeric(val);
3971 if (this.options.separateDialCode && val.charAt(0) !== "+" && dialCode && numericVal) {
3972 // when using separateDialCode, it is visible so is effectively part of the typed number
3973 prefix = "+".concat(dialCode);
3974 } else {
3975 prefix = "";
3976 }
3977 return prefix + val;
3978 }
3979 }, {
3980 key: "_beforeSetNumber",
3981 value: function _beforeSetNumber(originalNumber) {
3982 var number = originalNumber;
3983 if (this.options.separateDialCode) {
3984 var dialCode = this._getDialCode(number);
3985 // if there is a valid dial code
3986 if (dialCode) {
3987 // in case _getDialCode returned an area code as well
3988 dialCode = "+".concat(this.selectedCountryData.dialCode);
3989 // a lot of numbers will have a space separating the dial code and the main number, and
3990 // some NANP numbers will have a hyphen e.g. +1 684-733-1234 - in both cases we want to get
3991 // rid of it
3992 // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc
3993 var start = number[dialCode.length] === " " || number[dialCode.length] === "-" ? dialCode.length + 1 : dialCode.length;
3994 number = number.substr(start);
3995 }
3996 }
3997 return this._cap(number);
3998 }
3999 }, {
4000 key: "_triggerCountryChange",
4001 value: function _triggerCountryChange() {
4002 this._trigger("countrychange");
4003 }
4004 }, {
4005 key: "handleAutoCountry",
4006 value: function handleAutoCountry() {
4007 if (this.options.initialCountry === "auto") {
4008 // we must set this even if there is an initial val in the input: in case the initial val is
4009 // invalid and they delete it - they should see their auto country
4010 this.defaultCountry = window.intlTelInputGlobals.autoCountry;
4011 // if there's no initial value in the input, then update the flag
4012 if (!this.telInput.value) {
4013 this.setCountry(this.defaultCountry);
4014 }
4015 this.resolveAutoCountryPromise();
4016 }
4017 }
4018 }, {
4019 key: "handleUtils",
4020 value: function handleUtils() {
4021 // if the request was successful
4022 if (window.intlTelInputUtils) {
4023 // if there's an initial value in the input, then format it
4024 if (this.telInput.value) {
4025 this._updateValFromNumber(this.telInput.value);
4026 }
4027 this._updatePlaceholder();
4028 }
4029 this.resolveUtilsScriptPromise();
4030 }
4031 }, {
4032 key: "destroy",
4033 value: function destroy() {
4034 var form = this.telInput.form;
4035 if (this.options.allowDropdown) {
4036 // make sure the dropdown is closed (and unbind listeners)
4037 this._closeDropdown();
4038 this.selectedFlag.removeEventListener("click", this._handleClickSelectedFlag);
4039 this.flagsContainer.removeEventListener("keydown", this._handleFlagsContainerKeydown);
4040 // label click hack
4041 var label = this._getClosestLabel();
4042 if (label) label.removeEventListener("click", this._handleLabelClick);
4043 }
4044 // unbind hiddenInput listeners
4045 if (this.hiddenInput && form) form.removeEventListener("submit", this._handleHiddenInputSubmit);
4046 // unbind autoHideDialCode listeners
4047 if (this.options.autoHideDialCode) {
4048 if (form) form.removeEventListener("submit", this._handleSubmitOrBlurEvent);
4049 this.telInput.removeEventListener("blur", this._handleSubmitOrBlurEvent);
4050 }
4051 // unbind key events, and cut/paste events
4052 this.telInput.removeEventListener("keyup", this._handleKeyupEvent);
4053 this.telInput.removeEventListener("cut", this._handleClipboardEvent);
4054 this.telInput.removeEventListener("paste", this._handleClipboardEvent);
4055 // remove attribute of id instance: data-intl-tel-input-id
4056 this.telInput.removeAttribute("data-intl-tel-input-id");
4057 // remove markup (but leave the original input)
4058 var wrapper = this.telInput.parentNode;
4059 wrapper.parentNode.insertBefore(this.telInput, wrapper);
4060 wrapper.parentNode.removeChild(wrapper);
4061 delete window.intlTelInputGlobals.instances[this.id];
4062 }
4063 }, {
4064 key: "getExtension",
4065 value: function getExtension() {
4066 if (window.intlTelInputUtils) {
4067 return intlTelInputUtils.getExtension(this._getFullNumber(), this.selectedCountryData.iso2);
4068 }
4069 return "";
4070 }
4071 }, {
4072 key: "getNumber",
4073 value: function getNumber(format) {
4074 if (window.intlTelInputUtils) {
4075 var iso2 = this.selectedCountryData.iso2;
4076 return intlTelInputUtils.formatNumber(this._getFullNumber(), iso2, format);
4077 }
4078 return "";
4079 }
4080 }, {
4081 key: "getNumberType",
4082 value: function getNumberType() {
4083 if (window.intlTelInputUtils) {
4084 return intlTelInputUtils.getNumberType(this._getFullNumber(), this.selectedCountryData.iso2);
4085 }
4086 return -99;
4087 }
4088 }, {
4089 key: "getSelectedCountryData",
4090 value: function getSelectedCountryData() {
4091 return this.selectedCountryData;
4092 }
4093 }, {
4094 key: "getValidationError",
4095 value: function getValidationError() {
4096 if (window.intlTelInputUtils) {
4097 var iso2 = this.selectedCountryData.iso2;
4098 return intlTelInputUtils.getValidationError(this._getFullNumber(), iso2);
4099 }
4100 return -99;
4101 }
4102 }, {
4103 key: "isValidNumber",
4104 value: function isValidNumber() {
4105 var val = this._getFullNumber().trim();
4106 var countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "";
4107 return window.intlTelInputUtils ? intlTelInputUtils.isValidNumber(val, countryCode) : null;
4108 }
4109 }, {
4110 key: "setCountry",
4111 value: function setCountry(originalCountryCode) {
4112 var countryCode = originalCountryCode.toLowerCase();
4113 // check if already selected
4114 if (!this.selectedFlagInner.classList.contains("iti__".concat(countryCode))) {
4115 this._setFlag(countryCode);
4116 this._updateDialCode(this.selectedCountryData.dialCode, false);
4117 this._triggerCountryChange();
4118 }
4119 }
4120 }, {
4121 key: "setNumber",
4122 value: function setNumber(number) {
4123 // we must update the flag first, which updates this.selectedCountryData, which is used for
4124 // formatting the number before displaying it
4125 var flagChanged = this._updateFlagFromNumber(number);
4126 this._updateValFromNumber(number);
4127 if (flagChanged) {
4128 this._triggerCountryChange();
4129 }
4130 }
4131 }, {
4132 key: "setPlaceholderNumberType",
4133 value: function setPlaceholderNumberType(type) {
4134 this.options.placeholderNumberType = type;
4135 this._updatePlaceholder();
4136 }
4137 } ]);
4138 return Iti;
4139 }();
4140 /********************
4141 * STATIC METHODS
4142 ********************/
4143 // get the country data object
4144 intlTelInputGlobals.getCountryData = function() {
4145 return allCountries;
4146 };
4147 // inject a <script> element to load utils.js
4148 var injectScript = function injectScript(path, handleSuccess, handleFailure) {
4149 // inject a new script element into the page
4150 var script = document.createElement("script");
4151 script.onload = function() {
4152 forEachInstance("handleUtils");
4153 if (handleSuccess) handleSuccess();
4154 };
4155 script.onerror = function() {
4156 forEachInstance("rejectUtilsScriptPromise");
4157 if (handleFailure) handleFailure();
4158 };
4159 script.className = "iti-load-utils";
4160 script.async = true;
4161 script.src = path;
4162 document.body.appendChild(script);
4163 };
4164 // load the utils script
4165 intlTelInputGlobals.loadUtils = function(path) {
4166 // 2 options:
4167 // 1) not already started loading (start)
4168 // 2) already started loading (do nothing - just wait for the onload callback to fire, which will
4169 // trigger handleUtils on all instances, invoking their resolveUtilsScriptPromise functions)
4170 if (!window.intlTelInputUtils && !window.intlTelInputGlobals.startedLoadingUtilsScript) {
4171 // only do this once
4172 window.intlTelInputGlobals.startedLoadingUtilsScript = true;
4173 // if we have promises, then return a promise
4174 if (typeof Promise !== "undefined") {
4175 return new Promise(function(resolve, reject) {
4176 return injectScript(path, resolve, reject);
4177 });
4178 }
4179 injectScript(path);
4180 }
4181 return null;
4182 };
4183 // default options
4184 intlTelInputGlobals.defaults = defaults;
4185 // version
4186 intlTelInputGlobals.version = "17.0.16";
4187 // convenience wrapper
4188 return function(input, options) {
4189 var iti = new Iti(input, options);
4190 iti._init();
4191 input.setAttribute("data-intl-tel-input-id", iti.id);
4192 window.intlTelInputGlobals.instances[iti.id] = iti;
4193 return iti;
4194 };
4195 }();
4196 });
4197 },{}],19:[function(require,module,exports){
4198 /**
4199 * Exposing intl-tel-input as a component
4200 */
4201 module.exports = require("./build/js/intlTelInput");
4202
4203 },{"./build/js/intlTelInput":18}],20:[function(require,module,exports){
4204 (function (process){
4205 /**
4206 * Memize options object.
4207 *
4208 * @typedef MemizeOptions
4209 *
4210 * @property {number} [maxSize] Maximum size of the cache.
4211 */
4212
4213 /**
4214 * Internal cache entry.
4215 *
4216 * @typedef MemizeCacheNode
4217 *
4218 * @property {?MemizeCacheNode|undefined} [prev] Previous node.
4219 * @property {?MemizeCacheNode|undefined} [next] Next node.
4220 * @property {Array<*>} args Function arguments for cache
4221 * entry.
4222 * @property {*} val Function result.
4223 */
4224
4225 /**
4226 * Properties of the enhanced function for controlling cache.
4227 *
4228 * @typedef MemizeMemoizedFunction
4229 *
4230 * @property {()=>void} clear Clear the cache.
4231 */
4232
4233 /**
4234 * Accepts a function to be memoized, and returns a new memoized function, with
4235 * optional options.
4236 *
4237 * @template {Function} F
4238 *
4239 * @param {F} fn Function to memoize.
4240 * @param {MemizeOptions} [options] Options object.
4241 *
4242 * @return {F & MemizeMemoizedFunction} Memoized function.
4243 */
4244 function memize( fn, options ) {
4245 var size = 0;
4246
4247 /** @type {?MemizeCacheNode|undefined} */
4248 var head;
4249
4250 /** @type {?MemizeCacheNode|undefined} */
4251 var tail;
4252
4253 options = options || {};
4254
4255 function memoized( /* ...args */ ) {
4256 var node = head,
4257 len = arguments.length,
4258 args, i;
4259
4260 searchCache: while ( node ) {
4261 // Perform a shallow equality test to confirm that whether the node
4262 // under test is a candidate for the arguments passed. Two arrays
4263 // are shallowly equal if their length matches and each entry is
4264 // strictly equal between the two sets. Avoid abstracting to a
4265 // function which could incur an arguments leaking deoptimization.
4266
4267 // Check whether node arguments match arguments length
4268 if ( node.args.length !== arguments.length ) {
4269 node = node.next;
4270 continue;
4271 }
4272
4273 // Check whether node arguments match arguments values
4274 for ( i = 0; i < len; i++ ) {
4275 if ( node.args[ i ] !== arguments[ i ] ) {
4276 node = node.next;
4277 continue searchCache;
4278 }
4279 }
4280
4281 // At this point we can assume we've found a match
4282
4283 // Surface matched node to head if not already
4284 if ( node !== head ) {
4285 // As tail, shift to previous. Must only shift if not also
4286 // head, since if both head and tail, there is no previous.
4287 if ( node === tail ) {
4288 tail = node.prev;
4289 }
4290
4291 // Adjust siblings to point to each other. If node was tail,
4292 // this also handles new tail's empty `next` assignment.
4293 /** @type {MemizeCacheNode} */ ( node.prev ).next = node.next;
4294 if ( node.next ) {
4295 node.next.prev = node.prev;
4296 }
4297
4298 node.next = head;
4299 node.prev = null;
4300 /** @type {MemizeCacheNode} */ ( head ).prev = node;
4301 head = node;
4302 }
4303
4304 // Return immediately
4305 return node.val;
4306 }
4307
4308 // No cached value found. Continue to insertion phase:
4309
4310 // Create a copy of arguments (avoid leaking deoptimization)
4311 args = new Array( len );
4312 for ( i = 0; i < len; i++ ) {
4313 args[ i ] = arguments[ i ];
4314 }
4315
4316 node = {
4317 args: args,
4318
4319 // Generate the result from original function
4320 val: fn.apply( null, args ),
4321 };
4322
4323 // Don't need to check whether node is already head, since it would
4324 // have been returned above already if it was
4325
4326 // Shift existing head down list
4327 if ( head ) {
4328 head.prev = node;
4329 node.next = head;
4330 } else {
4331 // If no head, follows that there's no tail (at initial or reset)
4332 tail = node;
4333 }
4334
4335 // Trim tail if we're reached max size and are pending cache insertion
4336 if ( size === /** @type {MemizeOptions} */ ( options ).maxSize ) {
4337 tail = /** @type {MemizeCacheNode} */ ( tail ).prev;
4338 /** @type {MemizeCacheNode} */ ( tail ).next = null;
4339 } else {
4340 size++;
4341 }
4342
4343 head = node;
4344
4345 return node.val;
4346 }
4347
4348 memoized.clear = function() {
4349 head = null;
4350 tail = null;
4351 size = 0;
4352 };
4353
4354 if ( process.env.NODE_ENV === 'test' ) {
4355 // Cache is not exposed in the public API, but used in tests to ensure
4356 // expected list progression
4357 memoized.getCache = function() {
4358 return [ head, tail, size ];
4359 };
4360 }
4361
4362 // Ignore reason: There's not a clear solution to create an intersection of
4363 // the function with additional properties, where the goal is to retain the
4364 // function signature of the incoming argument and add control properties
4365 // on the return value.
4366
4367 // @ts-ignore
4368 return memoized;
4369 }
4370
4371 module.exports = memize;
4372
4373 }).call(this,require('_process'))
4374 },{"_process":21}],21:[function(require,module,exports){
4375 // shim for using process in browser
4376 var process = module.exports = {};
4377
4378 // cached from whatever global is present so that test runners that stub it
4379 // don't break things. But we need to wrap it in a try catch in case it is
4380 // wrapped in strict mode code which doesn't define any globals. It's inside a
4381 // function because try/catches deoptimize in certain engines.
4382
4383 var cachedSetTimeout;
4384 var cachedClearTimeout;
4385
4386 function defaultSetTimout() {
4387 throw new Error('setTimeout has not been defined');
4388 }
4389 function defaultClearTimeout () {
4390 throw new Error('clearTimeout has not been defined');
4391 }
4392 (function () {
4393 try {
4394 if (typeof setTimeout === 'function') {
4395 cachedSetTimeout = setTimeout;
4396 } else {
4397 cachedSetTimeout = defaultSetTimout;
4398 }
4399 } catch (e) {
4400 cachedSetTimeout = defaultSetTimout;
4401 }
4402 try {
4403 if (typeof clearTimeout === 'function') {
4404 cachedClearTimeout = clearTimeout;
4405 } else {
4406 cachedClearTimeout = defaultClearTimeout;
4407 }
4408 } catch (e) {
4409 cachedClearTimeout = defaultClearTimeout;
4410 }
4411 } ())
4412 function runTimeout(fun) {
4413 if (cachedSetTimeout === setTimeout) {
4414 //normal enviroments in sane situations
4415 return setTimeout(fun, 0);
4416 }
4417 // if setTimeout wasn't available but was latter defined
4418 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
4419 cachedSetTimeout = setTimeout;
4420 return setTimeout(fun, 0);
4421 }
4422 try {
4423 // when when somebody has screwed with setTimeout but no I.E. maddness
4424 return cachedSetTimeout(fun, 0);
4425 } catch(e){
4426 try {
4427 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
4428 return cachedSetTimeout.call(null, fun, 0);
4429 } catch(e){
4430 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
4431 return cachedSetTimeout.call(this, fun, 0);
4432 }
4433 }
4434
4435
4436 }
4437 function runClearTimeout(marker) {
4438 if (cachedClearTimeout === clearTimeout) {
4439 //normal enviroments in sane situations
4440 return clearTimeout(marker);
4441 }
4442 // if clearTimeout wasn't available but was latter defined
4443 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
4444 cachedClearTimeout = clearTimeout;
4445 return clearTimeout(marker);
4446 }
4447 try {
4448 // when when somebody has screwed with setTimeout but no I.E. maddness
4449 return cachedClearTimeout(marker);
4450 } catch (e){
4451 try {
4452 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
4453 return cachedClearTimeout.call(null, marker);
4454 } catch (e){
4455 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
4456 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
4457 return cachedClearTimeout.call(this, marker);
4458 }
4459 }
4460
4461
4462
4463 }
4464 var queue = [];
4465 var draining = false;
4466 var currentQueue;
4467 var queueIndex = -1;
4468
4469 function cleanUpNextTick() {
4470 if (!draining || !currentQueue) {
4471 return;
4472 }
4473 draining = false;
4474 if (currentQueue.length) {
4475 queue = currentQueue.concat(queue);
4476 } else {
4477 queueIndex = -1;
4478 }
4479 if (queue.length) {
4480 drainQueue();
4481 }
4482 }
4483
4484 function drainQueue() {
4485 if (draining) {
4486 return;
4487 }
4488 var timeout = runTimeout(cleanUpNextTick);
4489 draining = true;
4490
4491 var len = queue.length;
4492 while(len) {
4493 currentQueue = queue;
4494 queue = [];
4495 while (++queueIndex < len) {
4496 if (currentQueue) {
4497 currentQueue[queueIndex].run();
4498 }
4499 }
4500 queueIndex = -1;
4501 len = queue.length;
4502 }
4503 currentQueue = null;
4504 draining = false;
4505 runClearTimeout(timeout);
4506 }
4507
4508 process.nextTick = function (fun) {
4509 var args = new Array(arguments.length - 1);
4510 if (arguments.length > 1) {
4511 for (var i = 1; i < arguments.length; i++) {
4512 args[i - 1] = arguments[i];
4513 }
4514 }
4515 queue.push(new Item(fun, args));
4516 if (queue.length === 1 && !draining) {
4517 runTimeout(drainQueue);
4518 }
4519 };
4520
4521 // v8 likes predictible objects
4522 function Item(fun, array) {
4523 this.fun = fun;
4524 this.array = array;
4525 }
4526 Item.prototype.run = function () {
4527 this.fun.apply(null, this.array);
4528 };
4529 process.title = 'browser';
4530 process.browser = true;
4531 process.env = {};
4532 process.argv = [];
4533 process.version = ''; // empty string to avoid regexp issues
4534 process.versions = {};
4535
4536 function noop() {}
4537
4538 process.on = noop;
4539 process.addListener = noop;
4540 process.once = noop;
4541 process.off = noop;
4542 process.removeListener = noop;
4543 process.removeAllListeners = noop;
4544 process.emit = noop;
4545 process.prependListener = noop;
4546 process.prependOnceListener = noop;
4547
4548 process.listeners = function (name) { return [] }
4549
4550 process.binding = function (name) {
4551 throw new Error('process.binding is not supported');
4552 };
4553
4554 process.cwd = function () { return '/' };
4555 process.chdir = function (dir) {
4556 throw new Error('process.chdir is not supported');
4557 };
4558 process.umask = function() { return 0; };
4559
4560 },{}],22:[function(require,module,exports){
4561 'use strict';
4562
4563 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
4564
4565 var pluralForms = _interopDefault(require('@tannin/plural-forms'));
4566
4567 /**
4568 * Tannin constructor options.
4569 *
4570 * @typedef {Object} TanninOptions
4571 *
4572 * @property {string} [contextDelimiter] Joiner in string lookup with context.
4573 * @property {Function} [onMissingKey] Callback to invoke when key missing.
4574 */
4575
4576 /**
4577 * Domain metadata.
4578 *
4579 * @typedef {Object} TanninDomainMetadata
4580 *
4581 * @property {string} [domain] Domain name.
4582 * @property {string} [lang] Language code.
4583 * @property {(string|Function)} [plural_forms] Plural forms expression or
4584 * function evaluator.
4585 */
4586
4587 /**
4588 * Domain translation pair respectively representing the singular and plural
4589 * translation.
4590 *
4591 * @typedef {[string,string]} TanninTranslation
4592 */
4593
4594 /**
4595 * Locale data domain. The key is used as reference for lookup, the value an
4596 * array of two string entries respectively representing the singular and plural
4597 * translation.
4598 *
4599 * @typedef {{[key:string]:TanninDomainMetadata|TanninTranslation,'':TanninDomainMetadata|TanninTranslation}} TanninLocaleDomain
4600 */
4601
4602 /**
4603 * Jed-formatted locale data.
4604 *
4605 * @see http://messageformat.github.io/Jed/
4606 *
4607 * @typedef {{[domain:string]:TanninLocaleDomain}} TanninLocaleData
4608 */
4609
4610 /**
4611 * Default Tannin constructor options.
4612 *
4613 * @type {TanninOptions}
4614 */
4615 var DEFAULT_OPTIONS = {
4616 contextDelimiter: '\u0004',
4617 onMissingKey: null,
4618 };
4619
4620 /**
4621 * Given a specific locale data's config `plural_forms` value, returns the
4622 * expression.
4623 *
4624 * @example
4625 *
4626 * ```
4627 * getPluralExpression( 'nplurals=2; plural=(n != 1);' ) === '(n != 1)'
4628 * ```
4629 *
4630 * @param {string} pf Locale data plural forms.
4631 *
4632 * @return {string} Plural forms expression.
4633 */
4634 function getPluralExpression( pf ) {
4635 var parts, i, part;
4636
4637 parts = pf.split( ';' );
4638
4639 for ( i = 0; i < parts.length; i++ ) {
4640 part = parts[ i ].trim();
4641 if ( part.indexOf( 'plural=' ) === 0 ) {
4642 return part.substr( 7 );
4643 }
4644 }
4645 }
4646
4647 /**
4648 * Tannin constructor.
4649 *
4650 * @class
4651 *
4652 * @param {TanninLocaleData} data Jed-formatted locale data.
4653 * @param {TanninOptions} [options] Tannin options.
4654 */
4655 function Tannin( data, options ) {
4656 var key;
4657
4658 /**
4659 * Jed-formatted locale data.
4660 *
4661 * @name Tannin#data
4662 * @type {TanninLocaleData}
4663 */
4664 this.data = data;
4665
4666 /**
4667 * Plural forms function cache, keyed by plural forms string.
4668 *
4669 * @name Tannin#pluralForms
4670 * @type {Object<string,Function>}
4671 */
4672 this.pluralForms = {};
4673
4674 /**
4675 * Effective options for instance, including defaults.
4676 *
4677 * @name Tannin#options
4678 * @type {TanninOptions}
4679 */
4680 this.options = {};
4681
4682 for ( key in DEFAULT_OPTIONS ) {
4683 this.options[ key ] = options !== undefined && key in options
4684 ? options[ key ]
4685 : DEFAULT_OPTIONS[ key ];
4686 }
4687 }
4688
4689 /**
4690 * Returns the plural form index for the given domain and value.
4691 *
4692 * @param {string} domain Domain on which to calculate plural form.
4693 * @param {number} n Value for which plural form is to be calculated.
4694 *
4695 * @return {number} Plural form index.
4696 */
4697 Tannin.prototype.getPluralForm = function( domain, n ) {
4698 var getPluralForm = this.pluralForms[ domain ],
4699 config, plural, pf;
4700
4701 if ( ! getPluralForm ) {
4702 config = this.data[ domain ][ '' ];
4703
4704 pf = (
4705 config[ 'Plural-Forms' ] ||
4706 config[ 'plural-forms' ] ||
4707 // Ignore reason: As known, there's no way to document the empty
4708 // string property on a key to guarantee this as metadata.
4709 // @ts-ignore
4710 config.plural_forms
4711 );
4712
4713 if ( typeof pf !== 'function' ) {
4714 plural = getPluralExpression(
4715 config[ 'Plural-Forms' ] ||
4716 config[ 'plural-forms' ] ||
4717 // Ignore reason: As known, there's no way to document the empty
4718 // string property on a key to guarantee this as metadata.
4719 // @ts-ignore
4720 config.plural_forms
4721 );
4722
4723 pf = pluralForms( plural );
4724 }
4725
4726 getPluralForm = this.pluralForms[ domain ] = pf;
4727 }
4728
4729 return getPluralForm( n );
4730 };
4731
4732 /**
4733 * Translate a string.
4734 *
4735 * @param {string} domain Translation domain.
4736 * @param {string|void} context Context distinguishing terms of the same name.
4737 * @param {string} singular Primary key for translation lookup.
4738 * @param {string=} plural Fallback value used for non-zero plural
4739 * form index.
4740 * @param {number=} n Value to use in calculating plural form.
4741 *
4742 * @return {string} Translated string.
4743 */
4744 Tannin.prototype.dcnpgettext = function( domain, context, singular, plural, n ) {
4745 var index, key, entry;
4746
4747 if ( n === undefined ) {
4748 // Default to singular.
4749 index = 0;
4750 } else {
4751 // Find index by evaluating plural form for value.
4752 index = this.getPluralForm( domain, n );
4753 }
4754
4755 key = singular;
4756
4757 // If provided, context is prepended to key with delimiter.
4758 if ( context ) {
4759 key = context + this.options.contextDelimiter + singular;
4760 }
4761
4762 entry = this.data[ domain ][ key ];
4763
4764 // Verify not only that entry exists, but that the intended index is within
4765 // range and non-empty.
4766 if ( entry && entry[ index ] ) {
4767 return entry[ index ];
4768 }
4769
4770 if ( this.options.onMissingKey ) {
4771 this.options.onMissingKey( singular, domain );
4772 }
4773
4774 // If entry not found, fall back to singular vs. plural with zero index
4775 // representing the singular value.
4776 return index === 0 ? singular : plural;
4777 };
4778
4779 module.exports = Tannin;
4780
4781 },{"@tannin/plural-forms":11}]},{},[2]);
4782