PluginProbe
SellKit – Funnel builder and checkout optimizer for WooCommerce to sell more, faster / 2.7.0
SellKit – Funnel builder and checkout optimizer for WooCommerce to sell more, faster v2.7.0
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
← All changes | assets/dist/js/elementor-init.js +2425 -103 1.2.92.7.0 View file →
@@ -3,18 +3,83 @@
3 3
4 4 Object.defineProperty(exports, "__esModule", {
5 5 value: true
6 6 });
7 +exports["default"] = void 0;
8 +var CheckoutSettings = elementorModules.frontend.handlers.Base.extend({
9 + getDefaultSettings: function getDefaultSettings() {
10 + return {
11 + selectors: {
12 + sticky: '.sellkit-multistep-checkout-sidebar-sticky'
13 + }
14 + };
15 + },
16 + getDefaultElements: function getDefaultElements() {
17 + var selectors = this.getSettings('selectors');
18 + return {
19 + $stickyContainer: this.$element.find(selectors.sticky)
20 + };
21 + },
22 + onInit: function onInit() {
23 + elementorModules.frontend.handlers.Base.prototype.onInit.apply(this, arguments);
24 + this.setOffset();
25 + },
26 + setOffset: function setOffset() {
27 + if (this.getElementSettings('show_sticky_cart_details') !== 'yes') {
28 + return;
29 + }
30 +
31 + var offset = this.getElementSettings('sticky_cart_offset') || 0;
32 +
33 + if (offset === 0) {
34 + return;
35 + }
36 +
37 + var adminbar = document.getElementById('wpadminbar');
38 +
39 + if (!_.isNull(adminbar)) {
40 + offset += adminbar.offsetHeight;
41 + }
42 +
43 + this.elements.$stickyContainer.css('top', "".concat(offset, "px"));
44 + }
45 +});
46 +var _default = CheckoutSettings;
7 47 exports["default"] = _default;
8 48
49 +},{}],2:[function(require,module,exports){
50 +"use strict";
51 +
52 +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
53 +
54 +Object.defineProperty(exports, "__esModule", {
55 + value: true
56 +});
57 +exports["default"] = _default;
58 +
9 59 var _i18n = require("@wordpress/i18n");
10 60
61 +var _checkoutSettings = _interopRequireDefault(require("./checkout-settings"));
62 +
11 63 /* eslint no-undef: 0 */
12 64 // Temporary turned off no undefined variable for localStorage
13 65 var $ = jQuery;
14 66 var wcCountries = JSON.parse(wc_country_select_params.countries);
67 +/**
68 + * When batching "same as shipping" billing sync, skip duplicate sellkit address AJAX
69 + * (avoids racing update_checkout / fragment refresh against hidden country/state fields).
70 + *
71 + * @type {boolean}
72 + */
15 73
16 -function _default() {
74 +window.sellkitSuppressBillingAddressAjax = false;
75 +
76 +function _default($scope) {
77 + new _checkoutSettings["default"]({
78 + $element: $scope
79 + });
80 + $('body').addClass('contains-sellkit-checkout'); // General class to handle compatibility with other themes.
81 +
17 82 var parent = $('#sellkit-checkout-multistep-inner-wrap');
18 83 var sidebar = $('.sellkit-checkout-right-column');
19 84 var first = $('.sellkit-multistep-checkout-first');
20 85 var second = $('.sellkit-multistep-checkout-second');
@@ -19,8 +84,19 @@
19 84 var first = $('.sellkit-multistep-checkout-first');
20 85 var second = $('.sellkit-multistep-checkout-second');
21 86 var third = $('.sellkit-multistep-checkout-third');
22 87 var breadcrumb = $('.sellkit-checkout-widget-breadcrumb-desktop, .sellkit-checkout-widget-breadcrumb-mobile');
88 + var billingMethodA = $('[name="billing-method"].sellkit-billing-method-a');
89 +
90 + if (billingMethodA.length > 0 && billingMethodA[0].checked) {
91 + billingMethodA[0].click();
92 + }
93 +
94 + if ('1' !== sellkit_elementor.wcNeedShipping || typeof sellkitCheckoutShipping !== 'undefined' && true === sellkitCheckoutShipping) {
95 + third.show();
96 + $('.sellkit-one-page-checkout-place-order').css('justify-content', 'flex-end');
97 + }
98 +
23 99 $('.go-to-shipping').on('click', function () {
24 100 // Checks if required fields are filled.
25 101 var requiredFieldsError = checkRequiredFields();
26 102
@@ -28,9 +104,8 @@
28 104 return;
29 105 }
30 106
31 107 secondStepHeader();
32 - var secondTrigger = true;
33 108 first.hide();
34 109
35 110 if ($('.sellkit-one-page-shipping-methods').children().length > 0) {
36 111 second.show();
@@ -35,13 +110,8 @@
35 110 if ($('.sellkit-one-page-shipping-methods').children().length > 0) {
36 111 second.show();
37 112 } else {
38 113 third.show();
39 - secondTrigger = false;
40 - }
41 -
42 - if ($(window).width() > 600 && secondTrigger) {
43 - sidebar.css('background-color', '#effdf5');
44 114 } //Fix Header & wrapper height.
45 115
46 116
47 117 parent.css('height', 'auto');
@@ -50,8 +120,11 @@
50 120 $('.multistep-headers').css('height', 'auto'); // Manage Breadcrumb.
51 121
52 122 breadcrumb.find('.information').removeClass('current').addClass('blue-line');
53 123 breadcrumb.find('.shipping').addClass('current').removeClass('inactive');
124 + $('html, body').animate({
125 + scrollTop: $('.sellkit-checkout-left-column').offset().top
126 + }, 500);
54 127 });
55 128 $('.go-to-first').on('click', function () {
56 129 first.show();
57 130 third.hide();
@@ -61,8 +134,11 @@
61 134 sidebar.css('background-color', 'transparent'); // Manage Breadcrumb.
62 135
63 136 breadcrumb.find('.information').removeClass('blue-line').addClass('current');
64 137 breadcrumb.find('.shipping, .payment').removeClass('current').removeClass('blue-line').addClass('inactive');
138 + $('html, body').animate({
139 + scrollTop: $('.sellkit-checkout-left-column').offset().top
140 + }, 500);
65 141 });
66 142 $('.go-to-payment').on('click', function () {
67 143 // Checks if required fields are filled.
68 144 var requiredFieldsError = checkRequiredFields();
@@ -83,8 +159,11 @@
83 159 $('.multistep-headers').css('height', 'auto'); // Manage Breadcrumb.
84 160
85 161 breadcrumb.find('.shipping').addClass('blue-line').removeClass('current');
86 162 breadcrumb.find('.payment').addClass('current').removeClass('inactive');
163 + $('html, body').animate({
164 + scrollTop: $('.sellkit-checkout-left-column').offset().top
165 + }, 500);
87 166 });
88 167 $('.go-to-second , .go-to-second-header').on('click', function () {
89 168 // Checks if required fields are filled.
90 169 var requiredFieldsError = checkRequiredFields();
@@ -92,10 +171,8 @@
92 171 if (true === requiredFieldsError) {
93 172 return;
94 173 }
95 174
96 - var secondTrigger = true;
97 -
98 175 if ($('.sellkit-one-page-shipping-methods').children().length > 0) {
99 176 second.show();
100 177 first.hide();
101 178 } else {
@@ -100,9 +177,8 @@
100 177 first.hide();
101 178 } else {
102 179 second.hide();
103 180 first.show();
104 - secondTrigger = false;
105 181 }
106 182
107 183 third.hide();
108 184 parent.css('height', 'auto');
@@ -107,17 +183,15 @@
107 183 third.hide();
108 184 parent.css('height', 'auto');
109 185 second.css('height', 'auto');
110 186 second.css('height', $('.sellkit-checkout-left-column').height());
111 - $('.multistep-headers').css('height', 'auto');
187 + $('.multistep-headers').css('height', 'auto'); // Manage Breadcrumb.
112 188
113 - if ($(window).width() > 600 && secondTrigger) {
114 - sidebar.css('background-color', '#effdf5');
115 - } // Manage Breadcrumb.
116 -
117 -
118 189 breadcrumb.find('.shipping').addClass('current').removeClass('blue-line');
119 190 breadcrumb.find('.payment').removeClass('current').addClass('inactive');
191 + $('html, body').animate({
192 + scrollTop: $('.sellkit-checkout-left-column').offset().top
193 + }, 500);
120 194 }); //Inject login wrapper & functionality.
121 195
122 196 emailProcess();
123 197 LoginProcess(); // Billing method toggle.
@@ -136,10 +210,14 @@
136 210 // Run after ajax
137 211 sellkitCheckoutUpdateCartItem();
138 212 applyCoupon();
139 213 couponToggle();
140 - }); //Run when page loads.
214 + fixGatewayListUi();
215 + sellkitDetectShippingMethodChange();
216 + }); // Fix the payment gateways divider issue.
141 217
218 + fixGatewayListUi(); //Run when page loads.
219 +
142 220 sellkitCheckoutUpdateCartItem(); // Apply coupon.
143 221
144 222 applyCoupon(); // Coupon toggle.
145 223
@@ -156,9 +234,23 @@
156 234 sellkitCheckoutConfigureBundleProducts(); // Order bump.
157 235
158 236 sellkitCheckoutOrderBump(); // Sellkit after ajax call is completed.
159 237
160 - sellkitAfterAjaxComplete();
238 + sellkitAfterAjaxComplete(); // Load upsell steps with popup.
239 +
240 + sellkitLoadUpsellSteps(); // send shipping method to backend after changed
241 +
242 + sellkitDetectShippingMethodChange(); // Run some functions on page load when WooCommerce doing early ajax.
243 +
244 + window.sellkitCheckoutMakeSureJsWorks = function () {
245 + sellkitCheckoutUpdateCartItem();
246 + applyCoupon();
247 + couponToggle();
248 + fixGatewayListUi();
249 + }; // Toggle order notes.
250 +
251 +
252 + orderNotesToggle();
161 253 }
162 254
163 255 var emailProcess = function emailProcess() {
164 256 var emailField = $('#billing_email');
@@ -171,14 +263,26 @@
171 263 var usernameField = usernameWrap.find('input');
172 264 var loginBtn = $('.login-wrapper');
173 265 var createBox = $('.create-desc');
174 266 var createCheck = $('#createaccount');
175 - emailField.on('keyup', function () {
176 - var _this = this;
267 + var emailCheckTimer = null;
268 + var usernameCheckTimer = null;
177 269
178 - setTimeout(function () {
179 - var emailAddress = $(_this).val();
270 + var getCurrentEmailValue = function getCurrentEmailValue() {
271 + return $('#billing_email').val();
272 + };
180 273
274 + var getCurrentUsernameValue = function getCurrentUsernameValue() {
275 + return $('.sellkit-checkout-widget-username-field').find('input').val();
276 + }; // Use input/change (not keyup): iOS Safari soft keyboard often omits or mishandles keyup.
277 +
278 +
279 + emailField.on('input change', function () {
280 + var inputEl = this;
281 + clearTimeout(emailCheckTimer);
282 + emailCheckTimer = setTimeout(function () {
283 + var emailAddress = $(inputEl).val();
284 +
181 285 if (_.isEmpty(emailAddress)) {
182 286 emptyError.show().css('display', 'inline-block');
183 287 errorText.hide();
184 288 createBox.css('display', 'none');
@@ -212,19 +316,27 @@
212 316 email: emailAddress,
213 317 dataType: 'json',
214 318 nonce: sellkit_elementor.nonce
215 319 }).done(function () {
320 + if (emailAddress !== getCurrentEmailValue()) {
321 + return;
322 + }
323 +
216 324 successResultEmailCheck();
217 325 }).fail(function () {
326 + if (emailAddress !== getCurrentEmailValue()) {
327 + return;
328 + }
329 +
218 330 errorResultEmailCheck();
219 331 });
220 332 }, 500);
221 333 });
222 - usernameField.on('keyup', function () {
223 - var _this2 = this;
224 -
225 - setTimeout(function () {
226 - var userValue = $(_this2).val();
334 + usernameField.on('input change', function () {
335 + var inputEl = this;
336 + clearTimeout(usernameCheckTimer);
337 + usernameCheckTimer = setTimeout(function () {
338 + var userValue = $(inputEl).val();
227 339 wp.ajax.post({
228 340 action: 'sellkit_checkout_ajax_handler',
229 341 sub_action: 'search_for_username',
230 342 user: userValue,
@@ -230,10 +342,18 @@
230 342 user: userValue,
231 343 dataType: 'json',
232 344 nonce: sellkit_elementor.nonce
233 345 }).done(function () {
346 + if (userValue !== getCurrentUsernameValue()) {
347 + return;
348 + }
349 +
234 350 $('.sellkit-checkout-widget-username-error').hide();
235 351 }).fail(function () {
352 + if (userValue !== getCurrentUsernameValue()) {
353 + return;
354 + }
355 +
236 356 $('.sellkit-checkout-widget-username-error').show();
237 357 });
238 358 }, 500);
239 359 }); // If user is going to create account show password and username fields if exists.
@@ -310,14 +430,14 @@
310 430
311 431 var secondStepHeader = function secondStepHeader() {
312 432 var email = $('#billing_email');
313 433 $('.multistep-headers > .info-a > div > .mail').text(email.val());
314 - var countryValue = $('#shipping_country option:selected').text();
315 - var state = $('#sellkit-shipping_state');
316 - var postcode = $('#shipping_postcode');
317 - var city = $('#shipping_city');
318 - var addressA = $('#shipping_address_1');
319 - var addressB = $('#shipping_address_2');
434 + var countryValue = $('#shipping_country option:selected').text() ? $('#shipping_country option:selected').text() : $('#billing_country option:selected').text();
435 + var state = $('#sellkit-shipping_state').val() ? $('#sellkit-shipping_state') : $('#sellkit-billing_state');
436 + var postcode = $('#shipping_postcode').val() ? $('#shipping_postcode') : $('#billing_postcode');
437 + var city = $('#shipping_city').val() ? $('#shipping_city') : $('#billing_city');
438 + var addressA = $('#shipping_address_1').val() ? $('#shipping_address_1') : $('#billing_address_1');
439 + var addressB = $('#shipping_address_2').val() ? $('#shipping_address_2') : $('#billing_address_2');
320 440 var finalAddress = postcode.val() ? ', ' + postcode.val() : '';
321 441 finalAddress += addressB.val() ? ', ' + addressB.val() : '';
322 442 finalAddress += addressA.val() ? ', ' + addressA.val() : '';
323 443 finalAddress += city.val() ? ', ' + city.val() : '';
@@ -334,34 +454,84 @@
334 454 $('.multistep-headers > .info-c > div > .method').text(methodTxt);
335 455 };
336 456
337 457 var manageBillingMethod = function manageBillingMethod() {
338 - var billingWrap = $('.sellkit-one-page-checkout-billing');
339 - var methodA = billingWrap.find('.method-a');
340 - var methodB = billingWrap.find('.method-b'); // Get shipping values.
458 + // Hide outer #wrapper-billing_* rows — not inner #billing_*_field <p> tags. Labels (.mini-title) sit
459 + // outside those <p> tags; hiding only the <p> left floating labels with no inputs.
460 + var mirroredSelectors = '#wrapper-billing_first_name, #wrapper-billing_last_name, #wrapper-billing_address_1, #wrapper-billing_address_2, #wrapper-billing_country, #wrapper-billing_state, #wrapper-billing_postcode, #wrapper-billing_city, #wrapper-billing_phone';
461 + /**
462 + * Always re-query the DOM. Checkout fragments replace nodes after update_checkout;
463 + * cached jQuery sets would point at detached elements and .hide() would not affect the live form.
464 + *
465 + * @param {boolean} shouldUseShippingAddress - Whether to use shipping address for billing
466 + *
467 + */
341 468
342 - var name = $('#shipping_first_name');
343 - var last = $('#shipping_last_name');
344 - var addressA = $('#shipping_address_1');
345 - var addressB = $('#shipping_address_2');
346 - var country = $('#shipping_country');
347 - var state = $('#sellkit-shipping_state');
348 - var postcode = $('#shipping_postcode');
349 - var city = $('#shipping_city');
350 - methodA.on('click', function () {
351 - billingWrap.find('.woocommerce-billing-fields__field-wrapper').hide();
352 - $('#billing_first_name').val(name.val());
353 - $('#billing_last_name').val(last.val());
354 - $('#billing_address_1').val(addressA.val());
355 - $('#billing_address_2').val(addressB.val());
356 - $('#billing_country').val(country.val()).trigger('change');
357 - $('#sellkit-billing_state').val(state.val()).trigger('change');
358 - $('#billing_postcode').val(postcode.val());
359 - $('#billing_city').val(city.val());
469 + var toggleBillingFields = function toggleBillingFields(shouldUseShippingAddress) {
470 + var billingWrap = $('.sellkit-one-page-checkout-billing');
471 +
472 + if (!billingWrap.length) {
473 + return;
474 + }
475 +
476 + var billingFieldWrapper = billingWrap.find('.woocommerce-billing-fields__field-wrapper');
477 + var mirroredBillingFields = billingFieldWrapper.find(mirroredSelectors);
478 + var billingOnlyFields = billingFieldWrapper.children().not(mirroredBillingFields);
479 +
480 + if (shouldUseShippingAddress) {
481 + mirroredBillingFields.hide();
482 +
483 + if (billingOnlyFields.length) {
484 + billingOnlyFields.show();
485 + billingFieldWrapper.show().css('display', 'inline-table');
486 + } else {
487 + billingFieldWrapper.hide();
488 + }
489 +
490 + return;
491 + }
492 +
493 + billingFieldWrapper.show().css('display', 'inline-table');
494 + mirroredBillingFields.show();
495 + billingOnlyFields.show();
496 + };
497 +
498 + var syncBillingFieldsFromShipping = function syncBillingFieldsFromShipping() {
499 + window.sellkitSuppressBillingAddressAjax = true;
500 + $('#billing_first_name').val($('#shipping_first_name').val());
501 + $('#billing_last_name').val($('#shipping_last_name').val());
502 + $('#billing_address_1').val($('#shipping_address_1').val());
503 + $('#billing_address_2').val($('#shipping_address_2').val());
504 + $('#billing_country').val($('#shipping_country').val()).trigger('change');
505 + $('#sellkit-billing_state').val($('#sellkit-shipping_state').val()).trigger('change');
506 + $('#billing_postcode').val($('#shipping_postcode').val());
507 + $('#billing_city').val($('#shipping_city').val());
508 +
509 + if ($('#billing_phone').length && $('#shipping_phone').length) {
510 + $('#billing_phone').val($('#shipping_phone').val());
511 + }
512 +
513 + window.sellkitSuppressBillingAddressAjax = false;
514 + }; // Delegated: billing markup can be replaced by WooCommerce checkout AJAX.
515 +
516 +
517 + $(document.body).off('click.sellkitBillMethod', '.sellkit-one-page-checkout-billing .method-a').on('click.sellkitBillMethod', '.sellkit-one-page-checkout-billing .method-a', function () {
518 + syncBillingFieldsFromShipping();
519 + toggleBillingFields(true);
520 + sellkitSetAddressDetails();
360 521 });
361 - methodB.on('click', function () {
522 + $(document.body).off('click.sellkitBillMethodDiff', '.sellkit-one-page-checkout-billing .method-b').on('click.sellkitBillMethodDiff', '.sellkit-one-page-checkout-billing .method-b', function () {
362 523 $('.inner_wrapper').css('height', 'auto');
363 - billingWrap.find('.woocommerce-billing-fields__field-wrapper').show();
524 + toggleBillingFields(false);
525 + }); // After fragments refresh, re-apply hide/show — otherwise mirrored rows show again and layout breaks.
526 +
527 + $(document.body).off('updated_checkout.sellkitBillingVis').on('updated_checkout.sellkitBillingVis', function () {
528 + if (!$('.sellkit-one-page-checkout-billing').length) {
529 + return;
530 + }
531 +
532 + var useSame = $('.sellkit-one-page-checkout-billing input[name="billing-method"]:checked').val() === 'same';
533 + toggleBillingFields(useSame);
364 534 });
365 535 };
366 536
367 537 var mobileSummary = function mobileSummary() {
@@ -368,20 +538,22 @@
368 538 if ($(window).width() < 600) {
369 539 $('#order_review').addClass('sellkit-mobile-multistep-order-summary');
370 540 }
371 541
372 - var toggleBtn = $('.summary_toggle > .title, .summary_toggle > i, .summary_toggle > .icon');
542 + var toggleBtn = $('.summary_toggle > .summery_toggle_link_wrapper > .title, .summary_toggle > .summery_toggle_link_wrapper > .sellkit-checkout-summary-toggle-up, .summary_toggle > .summery_toggle_link_wrapper > .icon, .summary_toggle > .summery_toggle_link_wrapper > .sellkit-checkout-summary-toggle-down');
373 543 var wrap = $('.summary_toggle');
374 544 toggleBtn.on('click', function () {
375 545 $('#order_review').toggle();
376 546
377 - if ('Hide order summary' === toggleBtn.text()) {
547 + if ('Hide order summary' === wrap.find('.title').text()) {
378 548 wrap.find('.title').text((0, _i18n.__)('Show order summary', 'sellkit'));
379 - wrap.find('i').addClass('fa-chevron-down').removeClass('fa-chevron-up');
549 + wrap.find('.sellkit-checkout-summary-toggle-up').hide();
550 + wrap.find('.sellkit-checkout-summary-toggle-down').show();
380 551 wrap.css('border-bottom-width', '0px');
381 552 } else {
382 553 wrap.find('.title').text((0, _i18n.__)('Hide order summary', 'sellkit'));
383 - wrap.find('i').addClass('fa-chevron-up').removeClass('fa-chevron-down');
554 + wrap.find('.sellkit-checkout-summary-toggle-up').show();
555 + wrap.find('.sellkit-checkout-summary-toggle-down').hide();
384 556 wrap.css('border-bottom-width', '1px');
385 557 }
386 558
387 559 var parent = $('#sellkit-checkout-multistep-inner-wrap');
@@ -391,9 +563,9 @@
391 563
392 564 var fieldFocus = function fieldFocus() {
393 565 var $fields = $('.sellkit-checkout-local-fields').find('input, select, hidden, textarea, #sellkit-billing_state ,#sellkit-shipping_state, .validate-email');
394 566 $fields.each(function () {
395 - var _this3 = this;
567 + var _this = this;
396 568
397 569 var miniTitle = $(this).parent().parent().parent().find('.mini-title');
398 570 var $thisValue = $(this).val(); // On load.
399 571
@@ -405,34 +577,34 @@
405 577 } // On change/focusOut
406 578
407 579
408 580 $(this).on('change input focusout', function (e) {
409 - var changedValue = $(_this3).val();
581 + var changedValue = $(_this).val();
410 582
411 - if (changedValue || $(_this3).find('option').length) {
412 - $(_this3).addClass('filled');
413 - $(_this3).removeClass('empty');
414 - $(_this3).parents('.sellkit-widget-checkout-fields').find('.mini-title').css('display', 'flex');
583 + if (changedValue || $(_this).find('option').length) {
584 + $(_this).addClass('filled');
585 + $(_this).removeClass('empty');
586 + $(_this).parents('.sellkit-widget-checkout-fields').find('.mini-title').css('display', 'flex');
415 587 } else {
416 - $(_this3).addClass('empty');
417 - $(_this3).removeClass('filled');
418 - $(_this3).parents('.sellkit-widget-checkout-fields').find('.mini-title').hide();
588 + $(_this).addClass('empty');
589 + $(_this).removeClass('filled');
590 + $(_this).parents('.sellkit-widget-checkout-fields').find('.mini-title').hide();
419 591 } // On focusout validate fields.
420 592
421 593
422 594 if ('focusout' === e.type) {
423 - FieldsMiniTitles($(_this3), 'focusout');
424 - var parent = $(_this3).parent().parent().parent(); // Required validation. return if required field rule is not followed.
595 + FieldsMiniTitles($(_this), 'focusout');
596 + var parent = $(_this).parent().parent().parent(); // Required validation. return if required field rule is not followed.
425 597
426 598 if (parent.hasClass('validate-required')) {
427 - if ('INPUT' === _this3.nodeName && 'checkbox' === $(_this3).attr('type')) {
428 - if (!_this3.checked) {
599 + if ('INPUT' === _this.nodeName && 'checkbox' === $(_this).attr('type')) {
600 + if (!_this.checked) {
429 601 parent.find('.sellkit-required-validation').css('display', 'inline-flex');
430 602 return;
431 603 }
432 604 }
433 605
434 - if (_.isEmpty($(_this3).val())) {
606 + if (_.isEmpty($(_this).val())) {
435 607 parent.find('.sellkit-required-validation').css('display', 'inline-flex');
436 608 return;
437 609 }
438 610
@@ -440,9 +612,9 @@
440 612 } // Required validation of this field if exists, passed successfully. now postcode validation.
441 613
442 614
443 615 if (parent.hasClass('sellkit-checkout-fields-validation-postcode')) {
444 - var postcodeVal = $(_this3).val();
616 + var postcodeVal = $(_this).val();
445 617
446 618 if (_.isEmpty(postcodeVal)) {
447 619 return;
448 620 } // Check field type to get related country value. we can't validate without country code.
@@ -447,9 +619,9 @@
447 619 return;
448 620 } // Check field type to get related country value. we can't validate without country code.
449 621
450 622
451 - var postcodeName = $(_this3).attr('name');
623 + var postcodeName = $(_this).attr('name');
452 624 var postcodeCountry = $('#billing_country');
453 625
454 626 if (postcodeName.includes('shipping')) {
455 627 postcodeCountry = $('#shipping_country');
@@ -470,30 +642,30 @@
470 642 parent.find('.sellkit-checkout-field-global-errors').hide().text('');
471 643 }
472 644
473 645 parent.find('.sellkit-checkout-field-global-errors').hide().text('');
474 - postcodeValidation(postcodeVal, countryCode, $(_this3));
646 + postcodeValidation(postcodeVal, countryCode, $(_this));
475 647 } // Phone validation using woocommerce way.
476 648
477 649
478 650 if (parent.hasClass('sellkit-checkout-fields-validation-phone')) {
479 - var phone = $(_this3).val();
651 + var phone = $(_this).val();
480 652
481 653 if (_.isEmpty(phone)) {
482 654 return;
483 655 }
484 656
485 - phoneNumberValidation(phone, $(_this3));
657 + phoneNumberValidation(phone, $(_this));
486 658 }
487 659 }
488 660
489 - if ('change' === e.type && ('billing_country' === $(_this3).attr('id') || 'shipping_country' === $(_this3).attr('id'))) {
490 - var _countryCode = $(_this3).val();
661 + if ('change' === e.type && ('billing_country' === $(_this).attr('id') || 'shipping_country' === $(_this).attr('id'))) {
662 + var _countryCode = $(_this).val();
491 663
492 664 var states = wcCountries[_countryCode];
493 665 var state = 'sellkit-shipping_state';
494 666
495 - if ('billing_country' === $(_this3).attr('id')) {
667 + if ('billing_country' === $(_this).attr('id')) {
496 668 state = 'sellkit-billing_state';
497 669 }
498 670
499 671 var stateField = document.getElementById(state);
@@ -501,8 +673,12 @@
501 673 if (_.isNull(stateField)) {
502 674 return;
503 675 }
504 676
677 + if (!_.isObject(states)) {
678 + return;
679 + }
680 +
505 681 $(stateField).empty();
506 682
507 683 for (var keys in states) {
508 684 var option = document.createElement('option');
@@ -800,8 +976,30 @@
800 976 });
801 977 });
802 978 };
803 979 /**
980 + * Send shipping method id to backend
981 + *
982 + * The click event used because change event, send shipping method id on page load to backend and make an issue.
983 + *
984 + * @since 2.6.0
985 + */
986 +
987 +
988 +var sellkitDetectShippingMethodChange = function sellkitDetectShippingMethodChange() {
989 + $('input.shipping_method').off('click').on('click', function () {
990 + var selectedMethod = $(this).val();
991 + wp.ajax.post({
992 + action: 'shipping_method_selected',
993 + nonce: sellkit_elementor.nonce,
994 + shipping_method: selectedMethod
995 + }).fail(function (data) {
996 + // eslint-disable-next-line
997 + console.error(data);
998 + });
999 + });
1000 +};
1001 +/**
804 1002 * Toggle coupon form on click event.
805 1003 *
806 1004 * @since 1.2.5
807 1005 */
@@ -1050,8 +1248,12 @@
1050 1248 */
1051 1249
1052 1250
1053 1251 var sellkitSetAddressDetails = function sellkitSetAddressDetails() {
1252 + if (window.sellkitSuppressBillingAddressAjax) {
1253 + return;
1254 + }
1255 +
1054 1256 wp.ajax.post({
1055 1257 action: 'sellkit_checkout_ajax_handler',
1056 1258 sub_action: 'set_customer_details_ajax',
1057 1259 country: document.querySelector('#billing_country') ? document.getElementById('billing_country').value : '',
@@ -1092,23 +1294,35 @@
1092 1294 */
1093 1295
1094 1296
1095 1297 var sellkitCheckoutConfigureBundleProducts = function sellkitCheckoutConfigureBundleProducts() {
1298 + bundleProductOnQuantityChange();
1096 1299 var radioProducts = $('.sellkit-checkout-bundle-item');
1097 1300 radioProducts.off('change').on('change', function () {
1301 + var addType = $(this).attr('type'); // On bundle product change, modify bump too.
1302 +
1098 1303 $('.sellkit-checkout-bump-order-products').each(function () {
1099 - if ($(this).is(':checked')) {
1304 + if ($(this).is(':checked') && 'radio' === addType) {
1100 1305 $(this).trigger('click');
1101 1306 }
1102 1307 });
1103 1308 var product = $(this).val();
1104 1309 var quantity = $(this).parent().parent().find('.sellkit-checkout-single-bundle-item-quantity').val();
1310 + var checkout = $('#sellkit_current_page_id').val();
1311 + var modifyType = 'add';
1312 +
1313 + if (false === $(this).is(':checked')) {
1314 + modifyType = 'remove';
1315 + }
1316 +
1105 1317 wp.ajax.post({
1106 1318 action: 'sellkit_checkout_ajax_handler',
1107 1319 sub_action: 'sellkit_checkout_modify_cart_by_bundle_products',
1108 1320 id: product,
1109 1321 qty: quantity,
1110 - type: 'radio',
1322 + checkout_id: checkout,
1323 + type: addType,
1324 + modify: modifyType,
1111 1325 nonce: sellkit_elementor.nonce
1112 1326 }).always(function () {
1113 1327 $(document.body).trigger('update_checkout');
1114 1328 });
@@ -1114,8 +1328,35 @@
1114 1328 });
1115 1329 });
1116 1330 };
1117 1331 /**
1332 + * Change cart item quantity on bundle product quantity change.
1333 + *
1334 + * @since 1.3.1
1335 + */
1336 +
1337 +
1338 +var bundleProductOnQuantityChange = function bundleProductOnQuantityChange() {
1339 + $('.sellkit-checkout-single-bundle-item-quantity').on('change', function () {
1340 + var productCartKey = $(this).attr('data-id');
1341 + var quantity = $(this).val();
1342 +
1343 + if (false === $(this).parent().parent().find('.sellkit-checkout-bundle-item').is(':checked')) {
1344 + return;
1345 + }
1346 +
1347 + wp.ajax.post({
1348 + action: 'sellkit_checkout_ajax_handler',
1349 + sub_action: 'sellkit_checkout_modify_cart_by_bundle_products',
1350 + key: productCartKey,
1351 + qty: quantity,
1352 + nonce: sellkit_elementor.nonce
1353 + }).always(function () {
1354 + $(document.body).trigger('update_checkout');
1355 + });
1356 + });
1357 +};
1358 +/**
1118 1359 * Manage to add or remove a bump product from cart.
1119 1360 *
1120 1361 * @since 1.2.5
1121 1362 */
@@ -1223,14 +1464,16 @@
1223 1464 var transfer = setInterval(function () {
1224 1465 count += 1;
1225 1466
1226 1467 if ($('.wc_payment_method > .woocommerce-NoticeGroup-checkout').length > 0) {
1468 + // Remove notice from payment area and move it to top of page( default error area ).
1227 1469 var notice = $('.wc_payment_method').find('.woocommerce-NoticeGroup-checkout').html();
1228 1470 $('.wc_payment_method').find('.woocommerce-NoticeGroup-checkout').remove();
1229 1471 $('.woocommerce-notices-wrapper').first().append(notice);
1230 1472 $(document.body).animate({
1231 1473 scrollTop: $('.woocommerce-notices-wrapper').offset().top - 100
1232 - }, 500);
1474 + }, 500); // Stop interval.
1475 +
1233 1476 clearInterval(transfer);
1234 1477 }
1235 1478
1236 1479 if (count > 20) {
@@ -1238,10 +1481,245 @@
1238 1481 }
1239 1482 }, 500);
1240 1483 });
1241 1484 };
1485 +/**
1486 + * Hide payment gateways <hr> divider properly after ajax calls.
1487 + * This could not be done with css.
1488 + *
1489 + * @since 1.5.4
1490 + */
1242 1491
1243 -},{"@wordpress/i18n":12}],2:[function(require,module,exports){
1492 +
1493 +var fixGatewayListUi = function fixGatewayListUi() {
1494 + $('.wc_payment_methods hr.sellkit-checkout-widget-divider').each(function (index, item) {
1495 + $(item).css('display', $(item).prevAll('li').first().css('display'));
1496 + });
1497 +};
1498 +/**
1499 + * Prevents checkout form from being submitted before checking upsell offers.
1500 + *
1501 + * @since 1.6.2
1502 + */
1503 +
1504 +
1505 +var sellkitLoadUpsellSteps = function sellkitLoadUpsellSteps() {
1506 + $('form.checkout').on('checkout_place_order', function () {
1507 + if ($('#sellkit_funnel_has_upsell').length > 0 && 'upsell' === $('#sellkit_funnel_has_upsell').val()) {
1508 + sellkitCallUpsell();
1509 + return false;
1510 + }
1511 +
1512 + return true;
1513 + });
1514 +};
1515 +/**
1516 + * After press place order button, call ajax to make decision for popups.
1517 + *
1518 + * @since 1.6.2
1519 + */
1520 +
1521 +
1522 +var sellkitCallUpsell = function sellkitCallUpsell() {
1523 + var loadingIcon = function loadingIcon() {
1524 + var icon = sellkit_elementor.url.assets + 'img/spinner.png',
1525 + img = document.createElement('img');
1526 + img.setAttribute('src', icon);
1527 + img.setAttribute('width', '35px');
1528 + img.setAttribute('class', 'sellkit-upsell-downsell-preloader');
1529 + return img;
1530 + };
1531 +
1532 + var onEmpty = function onEmpty() {
1533 + $('body').css('overflow', 'auto');
1534 + $('.sellkit_funnel_upsell_popup').css('display', 'none');
1535 + $('#sellkit_funnel_has_upsell').val('done');
1536 + $('#place_order').trigger('click');
1537 + };
1538 +
1539 + var loadNew = function loadNew(data) {
1540 + $('body').css('overflow', 'hidden');
1541 + $('.sellkit-upsell-popup').css('display', 'none');
1542 + $('#sellkit_funnel_popup_step_id').val(data.next_id);
1543 + $('.sellkit_funnel_upsell_popup').css({
1544 + 'z-index': '100',
1545 + display: 'none'
1546 + });
1547 + $('.sellkit_funnel_upsell_popup_' + data.next_id).css({
1548 + 'z-index': 101,
1549 + display: 'block'
1550 + });
1551 + };
1552 +
1553 + var onSuccess = function onSuccess(data) {
1554 + setTimeout(function () {
1555 + if ('thankyou' === data.next_type) {
1556 + onEmpty();
1557 + }
1558 +
1559 + if ('upsell' === data.next_type || 'downsell' === data.next_type) {
1560 + loadNew(data);
1561 + sellkitUpsellOperation();
1562 + }
1563 + }, 1000);
1564 + };
1565 +
1566 + var sellkitUpsellOperation = function sellkitUpsellOperation() {
1567 + $('.sellkit_funnel_upsell_popup .sellkit-upsell-accept-button').off().on('click', function () {
1568 + var parent = $(this).parents('.sellkit_funnel_upsell_popup'),
1569 + upsellId = parent.find('.identify').val(),
1570 + checkoutId = $('#sellkit_current_page_id').val();
1571 + $('.sellkit-upsell-popup').css('display', 'flex');
1572 + parent.find('.sellkit-upsell-updating').addClass('active');
1573 + wp.ajax.post({
1574 + action: 'sellkit_checkout_ajax_handler',
1575 + sub_action: 'perform_upsell_accept_button',
1576 + upsell_id: upsellId,
1577 + checkout_id: checkoutId,
1578 + nonce: sellkit_elementor.nonce
1579 + }).done(function (data) {
1580 + $(document.body).trigger('update_checkout');
1581 + parent.find('.sellkit-upsell-updating').removeClass('active');
1582 + parent.find('.sellkit-upsell-accepted').addClass('active');
1583 + updateSellkitPriceField(data.upsell_prices);
1584 + onSuccess(data);
1585 + }).fail(function (data) {
1586 + // eslint-disable-next-line no-console
1587 + console.error(data);
1588 + });
1589 + });
1590 + $('.sellkit_funnel_upsell_popup .sellkit-upsell-reject-button').off().on('click', function () {
1591 + var parent = $(this).parents('.sellkit_funnel_upsell_popup'),
1592 + upsellId = parent.find('.identify').val(),
1593 + icon = loadingIcon();
1594 + parent.find('.sellkit-upsell-downsell-preloader').remove();
1595 + $(icon).insertAfter(parent.find('.sellkit-accept-reject-button-widget .sellkit-upsell-reject-button'));
1596 + wp.ajax.post({
1597 + action: 'sellkit_checkout_ajax_handler',
1598 + sub_action: 'perform_upsell_reject_button',
1599 + upsell_id: upsellId,
1600 + nonce: sellkit_elementor.nonce
1601 + }).done(function (data) {
1602 + onSuccess(data);
1603 + }).fail(function (data) {
1604 + // eslint-disable-next-line no-console
1605 + console.error(data);
1606 + });
1607 + });
1608 + };
1609 +
1610 + var stepId = $('#sellkit_current_page_id').val(),
1611 + img = loadingIcon();
1612 + $('button[type=submit]').find('img').remove();
1613 + $('button[type=submit]').append(img);
1614 + wp.ajax.post({
1615 + action: 'sellkit_checkout_ajax_handler',
1616 + sub_action: 'call_funnel_popups',
1617 + step: stepId,
1618 + nonce: sellkit_elementor.nonce
1619 + }).done(function (data) {
1620 + onSuccess(data);
1621 + $('button[type=submit]').find('img').remove();
1622 + }).fail(function (data) {
1623 + // eslint-disable-next-line no-console
1624 + console.error(data);
1625 + $('button[type=submit]').find('img').remove();
1626 + });
1627 +};
1628 +
1629 +var updateSellkitPriceField = function updateSellkitPriceField(data) {
1630 + if (data === 'null' || data === null) {
1631 + return;
1632 + }
1633 +
1634 + var current_val = $('input#sellkit_product_prices').val();
1635 +
1636 + if (!current_val || current_val === '0') {
1637 + $('input#sellkit_product_prices').val(data);
1638 + } else {
1639 + var oldVal = JSON.parse(current_val);
1640 + var newVal = JSON.parse(data);
1641 + var val = JSON.stringify(Object.assign({}, oldVal, newVal));
1642 + $('input#sellkit_product_prices').val(val);
1643 + }
1644 +};
1645 +/**
1646 + * Toggle order notes.
1647 + *
1648 + * @since 1.8.9
1649 + */
1650 +
1651 +
1652 +var orderNotesToggle = function orderNotesToggle() {
1653 + $('#sellkit-add-notes-to-order-box').on('change', function () {
1654 + $(this).parent().next().toggle();
1655 + });
1656 +}; // --- Sellkit: Sync custom state fields to standard WooCommerce fields for gateway compatibility ---
1657 +
1658 +
1659 +var ensureStandardWooFields = function ensureStandardWooFields() {
1660 + try {
1661 + var form = document.querySelector('form.checkout');
1662 +
1663 + if (!form) {
1664 + return;
1665 + } // Billing state
1666 +
1667 +
1668 + var sellkitBillingState = document.getElementById('sellkit-billing_state');
1669 +
1670 + if (sellkitBillingState) {
1671 + var billingState = document.getElementById('billing_state');
1672 +
1673 + if (!billingState) {
1674 + billingState = document.createElement('input');
1675 + billingState.type = 'hidden';
1676 + billingState.id = 'billing_state';
1677 + billingState.name = 'billing_state';
1678 + form.appendChild(billingState);
1679 + }
1680 +
1681 + billingState.value = sellkitBillingState.value;
1682 + } // Shipping state
1683 +
1684 +
1685 + var sellkitShippingState = document.getElementById('sellkit-shipping_state');
1686 +
1687 + if (sellkitShippingState) {
1688 + var shippingState = document.getElementById('shipping_state');
1689 +
1690 + if (!shippingState) {
1691 + shippingState = document.createElement('input');
1692 + shippingState.type = 'hidden';
1693 + shippingState.id = 'shipping_state';
1694 + shippingState.name = 'shipping_state';
1695 + form.appendChild(shippingState);
1696 + }
1697 +
1698 + shippingState.value = sellkitShippingState.value;
1699 + }
1700 + } catch (e) {
1701 + // eslint-disable-next-line no-console
1702 + console.error('[Sellkit] Error syncing state fields for gateway compatibility:', e);
1703 + }
1704 +}; // Attach to form submit and on state field change
1705 +
1706 +
1707 +jQuery(document).ready(function (_$) {
1708 + var form = _$('form.checkout');
1709 +
1710 + if (form.length) {
1711 + form.on('submit', function () {
1712 + ensureStandardWooFields();
1713 + }); // Also update on state field change
1714 +
1715 + _$('#sellkit-billing_state, #sellkit-shipping_state').on('change input', function () {
1716 + ensureStandardWooFields();
1717 + });
1718 + }
1719 +});
1720 +
1721 +},{"./checkout-settings":1,"@babel/runtime/helpers/interopRequireDefault":9,"@wordpress/i18n":16}],3:[function(require,module,exports){
1244 1722 "use strict";
1245 1723
1246 1724 (function ($) {
1247 1725 var SellkitFrontend = function SellkitFrontend() {
@@ -1246,9 +1724,10 @@
1246 1724 (function ($) {
1247 1725 var SellkitFrontend = function SellkitFrontend() {
1248 1726 var widgets = {
1249 1727 'sellkit-product-images.default': require('./product-images')["default"],
1250 - 'sellkit-checkout.default': require('./checkout')["default"]
1728 + 'sellkit-checkout.default': require('./checkout')["default"],
1729 + 'sellkit-optin.default': require('./optin/optin')["default"]
1251 1730 };
1252 1731
1253 1732 function elementorInit() {
1254 1733 for (var widget in widgets) {
@@ -1265,15 +1744,498 @@
1265 1744
1266 1745 window.sellkitFrontend = new SellkitFrontend();
1267 1746 })(jQuery);
1268 1747
1269 -},{"./checkout":1,"./product-images":3}],3:[function(require,module,exports){
1748 +},{"./checkout":2,"./optin/optin":4,"./product-images":7}],4:[function(require,module,exports){
1270 1749 "use strict";
1271 1750
1751 +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
1752 +
1272 1753 Object.defineProperty(exports, "__esModule", {
1273 1754 value: true
1274 1755 });
1275 1756 exports["default"] = _default;
1757 +
1758 +var _intelligentTel = _interopRequireDefault(require("./submodules/intelligent-tel"));
1759 +
1760 +var _fieldValidation = _interopRequireDefault(require("./submodules/field-validation"));
1761 +
1762 +var _i18n = require("@wordpress/i18n");
1763 +
1764 +var Optin = elementorModules.frontend.handlers.Base.extend({
1765 + form: null,
1766 + onInit: function onInit() {
1767 + this.form = this.$element.find('form.sellkit-optin'); // Register submit listener.
1768 +
1769 + this.form.on('submit', this.onSubmit.bind(this)); // Initialize ITI for tel fields.
1770 +
1771 + _intelligentTel["default"].initializeITI(this.form); // AutoComplete address fields.
1772 +
1773 +
1774 + jQuery(document).ready(this.autoCompleteAddress.bind(this)); // Initialize flatpickr for data and time fields.
1775 +
1776 + this.initializeFlatpickr();
1777 + },
1778 + onSubmit: function onSubmit(event) {
1779 + var _this = this;
1780 +
1781 + event.preventDefault();
1782 +
1783 + if (!this.checkSaveState()) {
1784 + return;
1785 + }
1786 +
1787 + this.clearAllNotices();
1788 + this.form.css('opacity', 0.5);
1789 +
1790 + var validated = _fieldValidation["default"].validateFormFields(this.form);
1791 +
1792 + if (!validated) {
1793 + this.form.css('opacity', 1);
1794 + return;
1795 + }
1796 +
1797 + wp.ajax.send('sellkit_optin_frontend', {
1798 + data: this.prepareFormData(),
1799 + type: 'POST',
1800 + dataType: 'json',
1801 + processData: false,
1802 + contentType: false,
1803 + success: this.onSuccess,
1804 + error: this.onFailure,
1805 + complete: function complete() {
1806 + return _this.form.css('opacity', 1);
1807 + }
1808 + });
1809 + },
1810 + checkSaveState: function checkSaveState() {
1811 + if (!this.isEdit) {
1812 + return true;
1813 + }
1814 +
1815 + var btn = jQuery(elementor.panel.el).find('button#elementor-panel-saver-button-publish');
1816 +
1817 + if (!btn.length || btn.hasClass('elementor-disabled')) {
1818 + return true;
1819 + }
1820 +
1821 + 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";
1822 + this.form.before(adminErrorsNode);
1823 + return false;
1824 + },
1825 + clearAllNotices: function clearAllNotices() {
1826 + var form = this.form; // Reset everything.
1827 +
1828 + form.parent().find('.sellkit-optin-response').remove();
1829 + form.parent().find('.sellkit-optin-admin-alert').remove();
1830 + form.parent().removeClass('sellkit-optin-error');
1831 + form.parent().removeClass('sellkit-optin-success');
1832 + },
1833 + prepareFormData: function prepareFormData() {
1834 + _intelligentTel["default"].fixTelBeforeSubmit(this.form);
1835 +
1836 + var formData = new FormData(this.form[0]);
1837 + var entries = Array.from(formData.entries()); // Unify nonsingular formData entries ( happens for checkbox or multiselection select fields ) .
1838 +
1839 + entries.forEach(function (entry, i) {
1840 + var value = entry[1];
1841 + entries.forEach(function (_entry, _i) {
1842 + if (_i !== i && _entry[0] === entry[0]) {
1843 + value += ", ".concat(_entry[1]);
1844 + formData["delete"](_entry[0]);
1845 + }
1846 + });
1847 + formData.set(entry[0], value);
1848 + });
1849 + formData.append('referrer', location.toString());
1850 + formData.append('action', 'sellkit_optin_frontend');
1851 + formData.append('nonce', window.sellkit_elementor.nonce); // To make _POST content compatible with sellkit_funnel() functionality and let it find the funnel data.
1852 +
1853 + formData.append('sellkit_current_page_id', formData.get('post_id'));
1854 + return formData;
1855 + },
1856 + onSuccess: function onSuccess(response) {
1857 + var form = this.form; // Success Message.
1858 +
1859 + form.trigger('reset');
1860 + form.parent().addClass('sellkit-optin-success');
1861 + form.after("<div class=\"sellkit-optin-response\">".concat(response.message, "</div>")); // Admin Error Messages.
1862 +
1863 + this.printAdminErrors(response.admin_errors); // Download.
1864 +
1865 + if (response.downloadURL) {
1866 + window.open(response.downloadURL, '_blank');
1867 + } // Redirect.
1868 +
1869 +
1870 + if (!jQuery.isEmptyObject(response.redirectURL)) {
1871 + window.location.href = response.redirectURL;
1872 + }
1873 + },
1874 + onFailure: function onFailure(response) {
1875 + var form = this.form;
1876 + form.parent().removeClass('sellkit-optin-success');
1877 + form.parent().addClass('sellkit-optin-error'); // Handle user error messages.
1878 +
1879 + if (!_.isEmpty(response.errors)) {
1880 + _.each(response.errors, function (error) {
1881 + form.after("<div class=\"sellkit-optin-response\">".concat(error, "</div>"));
1882 + });
1883 + } // Admin Error Messages.
1884 +
1885 +
1886 + this.printAdminErrors(response.admin_errors);
1887 + },
1888 + printAdminErrors: function printAdminErrors(errors) {
1889 + if (_.isEmpty(errors)) {
1890 + return;
1891 + }
1892 +
1893 + var errorList = '';
1894 +
1895 + _.each(errors, function (error) {
1896 + errorList += "<li>".concat(error, "</li>");
1897 + });
1898 +
1899 + 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");
1900 + this.form.before(adminErrorsNode);
1901 + },
1902 + initializeFlatpickr: function initializeFlatpickr() {
1903 + var dateField = this.form.find('.flatpickr[type=text]');
1904 + var customLocale = dateField.data('locale');
1905 + var locale = {
1906 + firstDayOfWeek: 1
1907 + };
1908 +
1909 + if (!_.isUndefined(customLocale) && 'default' !== customLocale) {
1910 + locale = customLocale;
1911 + }
1912 +
1913 + dateField.flatpickr({
1914 + locale: locale,
1915 + minuteIncrement: 1
1916 + });
1917 + },
1918 + autoCompleteAddress: function autoCompleteAddress() {
1919 + var addressFields = this.form.find('input[data-type="address"]');
1920 + var google = this.isEdit ? window.parent.google : window.google;
1921 +
1922 + if (!addressFields.length || !google) {
1923 + return;
1924 + }
1925 +
1926 + _.each(addressFields, function (input) {
1927 + var autocomplete = new google.maps.places.Autocomplete(input, {
1928 + types: ['geocode'],
1929 + fields: ['address_components']
1930 + });
1931 + autocomplete.addListener('place_changed', function () {
1932 + var place = autocomplete.getPlace(); // Extract address components
1933 +
1934 + var address = {
1935 + street_number: '',
1936 + route: '',
1937 + locality: '',
1938 + administrative_area_level_1: '',
1939 + country: '',
1940 + postal_code: ''
1941 + }; // Map Google Maps address components to your address object
1942 +
1943 + place.address_components.forEach(function (component) {
1944 + var componentType = component.types[0];
1945 +
1946 + switch (componentType) {
1947 + case 'street_number':
1948 + address.street_number = component.long_name;
1949 + break;
1950 +
1951 + case 'route':
1952 + address.route = component.long_name;
1953 + break;
1954 +
1955 + case 'locality':
1956 + address.locality = component.long_name;
1957 + break;
1958 +
1959 + case 'administrative_area_level_1':
1960 + address.administrative_area_level_1 = component.long_name;
1961 + break;
1962 +
1963 + case 'country':
1964 + address.country = component.long_name;
1965 + break;
1966 +
1967 + case 'postal_code':
1968 + address.postal_code = component.long_name;
1969 + break;
1970 + }
1971 + }); // Combine street number and route for the full street address
1972 +
1973 + var addressString = JSON.stringify(address);
1974 + var addressHidenField = input.nextElementSibling;
1975 +
1976 + if (addressHidenField && addressHidenField.type === 'hidden') {
1977 + addressHidenField.value = addressString;
1978 + }
1979 + });
1980 + });
1981 + }
1982 +});
1983 +
1984 +function _default($scope) {
1985 + new Optin({
1986 + $element: $scope
1987 + });
1988 +}
1989 +
1990 +},{"./submodules/field-validation":5,"./submodules/intelligent-tel":6,"@babel/runtime/helpers/interopRequireDefault":9,"@wordpress/i18n":16}],5:[function(require,module,exports){
1991 +"use strict";
1992 +
1993 +Object.defineProperty(exports, "__esModule", {
1994 + value: true
1995 +});
1996 +exports["default"] = void 0;
1997 +var _default = {
1998 + messageRequired: '',
1999 + messageError: '',
2000 + validateFormFields: function validateFormFields(form) {
2001 + var _this = this;
2002 +
2003 + this.getCustomMessages(form);
2004 + var formData = form.find('[name^="fields"]');
2005 + var result = true;
2006 +
2007 + _.each(formData, function (field) {
2008 + var message = _this.getValidationMessage(field);
2009 +
2010 + if (!_.isEmpty(message)) {
2011 + result = false;
2012 + }
2013 +
2014 + _this.toggleFieldMessage(field, message);
2015 + });
2016 +
2017 + this.toggleFinalMessage(form, result);
2018 + return result;
2019 + },
2020 + getValidationMessage: function getValidationMessage(target) {
2021 + var type = target.dataset.type;
2022 + var validity = target.validity;
2023 + var i18n = window.sellkitOptinValidationsTranslations;
2024 + var message = '';
2025 +
2026 + if (validity.valueMissing || target.required && _.isEmpty(target.value)) {
2027 + message = this.messageRequired;
2028 + return message;
2029 + }
2030 +
2031 + switch (type) {
2032 + case 'email':
2033 + if (validity.typeMismatch || validity.patternMismatch) {
2034 + message = i18n.general.invalidEmail;
2035 + }
2036 +
2037 + break;
2038 +
2039 + case 'tel':
2040 + var isITI = target.hasAttribute('data-iti-tel');
2041 +
2042 + if (isITI) {
2043 + var validationMessages = i18n.itiValidation;
2044 + var inputItiInstance = window.intlTelInputGlobals.getInstance(target);
2045 + var itiValidationCode = inputItiInstance.getValidationError();
2046 + var areaCodeRequired = target.hasAttribute('data-iti-area-required');
2047 + var mustBeTelType = target.getAttribute('data-iti-tel-type');
2048 + var telType = "".concat(inputItiInstance.getNumberType());
2049 +
2050 + switch (itiValidationCode) {
2051 + case 1:
2052 + message = validationMessages.invalidCountryCode;
2053 + break;
2054 +
2055 + case 2:
2056 + message = validationMessages.tooShort;
2057 + break;
2058 +
2059 + case 3:
2060 + message = validationMessages.tooLong;
2061 + break;
2062 +
2063 + case 4:
2064 + message = areaCodeRequired ? validationMessages.areaCodeMissing : '';
2065 + break;
2066 +
2067 + case 5:
2068 + message = validationMessages.invalidLength;
2069 + break;
2070 +
2071 + case -99:
2072 + message = validationMessages.invalidGeneral;
2073 + break;
2074 +
2075 + case 0:
2076 + default:
2077 + if ('all' !== mustBeTelType && telType !== mustBeTelType) {
2078 + message = validationMessages.typeMismatch[mustBeTelType];
2079 + }
2080 +
2081 + }
2082 +
2083 + break;
2084 + }
2085 +
2086 + if (validity.typeMismatch || validity.patternMismatch) {
2087 + message = i18n.general.invalidPhone;
2088 + }
2089 +
2090 + break;
2091 +
2092 + case 'number':
2093 + if (validity.typeMismatch || validity.patternMismatch) {
2094 + message = i18n.general.invalidNumber;
2095 + break;
2096 + }
2097 +
2098 + if (validity.rangeOverflow) {
2099 + message = i18n.general.invalidMaxValue.replace('MAX_VALUE', target.max);
2100 + break;
2101 + }
2102 +
2103 + if (validity.rangeUnderflow) {
2104 + message = i18n.general.invalidMinValue.replace('MIN_VALUE', target.min);
2105 + }
2106 +
2107 + break;
2108 + }
2109 +
2110 + return message;
2111 + },
2112 + toggleFieldMessage: function toggleFieldMessage(field, message) {
2113 + var fieldGroup = jQuery(field).closest('.sellkit-field-group');
2114 + fieldGroup.removeClass('sellkit-field-invalid');
2115 + fieldGroup.find('small').remove();
2116 +
2117 + if (!_.isEmpty(message)) {
2118 + fieldGroup.addClass('sellkit-field-invalid');
2119 + fieldGroup.append("<small class=\"sellkit-optin-text\">".concat(message, "</small>"));
2120 + }
2121 + },
2122 + toggleFinalMessage: function toggleFinalMessage(form, validationResult) {
2123 + form.parent().toggleClass('sellkit-optin-error', !validationResult);
2124 + form.parent().toggleClass('sellkit-optin-success', validationResult);
2125 + form.parent().find('.sellkit-optin-response').remove();
2126 +
2127 + if (true === validationResult) {
2128 + return;
2129 + }
2130 +
2131 + form.after("<div class=\"sellkit-optin-response\">".concat(this.messageError, "</div>"));
2132 + },
2133 + getCustomMessages: function getCustomMessages(form) {
2134 + var messagesRaw = form.attr('data-messages');
2135 +
2136 + if (!_.isEmpty(messagesRaw)) {
2137 + var messages = JSON.parse(messagesRaw);
2138 + this.messageError = messages.error;
2139 + this.messageRequired = messages.required;
2140 + return;
2141 + }
2142 +
2143 + this.messageError = window.sellkitOptinValidationsTranslations.general.errorExists;
2144 + this.messageRequired = window.sellkitOptinValidationsTranslations.general.required;
2145 + }
2146 +};
2147 +exports["default"] = _default;
2148 +
2149 +},{}],6:[function(require,module,exports){
2150 +"use strict";
2151 +
2152 +Object.defineProperty(exports, "__esModule", {
2153 + value: true
2154 +});
2155 +exports["default"] = void 0;
2156 +var _default = {
2157 + initializeITI: function initializeITI(form) {
2158 + var _this = this;
2159 +
2160 + var itiTelFields = form.find('input[data-iti-tel]');
2161 +
2162 + if (!itiTelFields.length) {
2163 + return;
2164 + }
2165 +
2166 + if (!window.itiCountry) {
2167 + jQuery.get('https://ipwho.is/', function () {}, 'json').always(function (response) {
2168 + window.itiCountry = response && response.country_code ? response.country_code.toLowerCase() : 'us';
2169 +
2170 + _this.setupTelFields(itiTelFields);
2171 + });
2172 + } else {
2173 + this.setupTelFields(itiTelFields);
2174 + }
2175 + },
2176 + setupTelFields: function setupTelFields(itiTelFields) {
2177 + var iti = require('intl-tel-input');
2178 +
2179 + if (!iti) {
2180 + return;
2181 + }
2182 +
2183 + var allCountries = window.intlTelInputGlobals.getCountryData().map(function (item) {
2184 + return item.iso2;
2185 + });
2186 + var numberTypes = ['FIXED_LINE', 'MOBILE', 'FIXED_LINE_OR_MOBILE', 'TOLL_FREE', 'PREMIUM_RATE', 'SHARED_COST', 'VOIP', 'PERSONAL_NUMBER', 'PAGER', 'UAN', 'VOICEMAIL'];
2187 +
2188 + _.each(itiTelFields, function (input) {
2189 + var allowDropdown = input.hasAttribute('data-iti-allow-dropdown');
2190 + var countriesAttr = input.getAttribute('data-iti-country-include');
2191 + var countries = countriesAttr ? countriesAttr.split(' ') : null;
2192 + var isCountriesSet = countries && countries.length;
2193 + var ipDetect = input.hasAttribute('data-iti-ip-detect');
2194 + var placeHolderAttr = input.getAttribute('data-iti-tel-type');
2195 + var args = {
2196 + allowDropdown: allowDropdown,
2197 + utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.16/js/utils.min.js',
2198 + separateDialCode: true,
2199 + placeholderNumberType: 'all' === placeHolderAttr ? 'MOBILE' : numberTypes[+placeHolderAttr],
2200 + onlyCountries: isCountriesSet ? countries : allCountries,
2201 + initialCountry: '',
2202 + geoIpLookup: null
2203 + };
2204 +
2205 + if (ipDetect) {
2206 + args.initialCountry = isCountriesSet && !countries.includes(window.itiCountry) ? countries[0] : 'auto';
2207 +
2208 + args.geoIpLookup = function (success) {
2209 + return success(window.itiCountry);
2210 + };
2211 + }
2212 +
2213 + iti(input, args);
2214 + });
2215 + },
2216 + fixTelBeforeSubmit: function fixTelBeforeSubmit(form) {
2217 + var itiTelFields = form.find('input[data-iti-tel]');
2218 +
2219 + _.each(itiTelFields, function (input) {
2220 + var internationalize = input.hasAttribute('data-iti-internationalize');
2221 +
2222 + if (internationalize) {
2223 + var itiInstance = window.intlTelInputGlobals.getInstance(input);
2224 + input.value = itiInstance.getNumber();
2225 + }
2226 + });
2227 + }
2228 +};
2229 +exports["default"] = _default;
2230 +
2231 +},{"intl-tel-input":20}],7:[function(require,module,exports){
2232 +"use strict";
2233 +
2234 +Object.defineProperty(exports, "__esModule", {
2235 + value: true
2236 +});
2237 +exports["default"] = _default;
1276 2238 var ProductImages = elementorModules.frontend.handlers.Base.extend({
1277 2239 onInit: function onInit() {
1278 2240 elementorModules.frontend.handlers.Base.prototype.onInit.apply(this, arguments);
1279 2241
@@ -1317,9 +2279,9 @@
1317 2279 $element: $scope
1318 2280 });
1319 2281 }
1320 2282
1321 -},{}],4:[function(require,module,exports){
2283 +},{}],8:[function(require,module,exports){
1322 2284 function _defineProperty(obj, key, value) {
1323 2285 if (key in obj) {
1324 2286 Object.defineProperty(obj, key, {
1325 2287 value: value,
@@ -1334,9 +2296,9 @@
1334 2296 return obj;
1335 2297 }
1336 2298
1337 2299 module.exports = _defineProperty;
1338 -},{}],5:[function(require,module,exports){
2300 +},{}],9:[function(require,module,exports){
1339 2301 function _interopRequireDefault(obj) {
1340 2302 return obj && obj.__esModule ? obj : {
1341 2303 "default": obj
1342 2304 };
@@ -1342,9 +2304,9 @@
1342 2304 };
1343 2305 }
1344 2306
1345 2307 module.exports = _interopRequireDefault;
1346 -},{}],6:[function(require,module,exports){
2308 +},{}],10:[function(require,module,exports){
1347 2309 'use strict';
1348 2310
1349 2311 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
1350 2312
@@ -1379,9 +2341,9 @@
1379 2341 }
1380 2342
1381 2343 module.exports = compile;
1382 2344
1383 -},{"@tannin/evaluate":7,"@tannin/postfix":9}],7:[function(require,module,exports){
2345 +},{"@tannin/evaluate":11,"@tannin/postfix":13}],11:[function(require,module,exports){
1384 2346 'use strict';
1385 2347
1386 2348 /**
1387 2349 * Operator callback functions.
@@ -1495,9 +2457,9 @@
1495 2457 }
1496 2458
1497 2459 module.exports = evaluate;
1498 2460
1499 -},{}],8:[function(require,module,exports){
2461 +},{}],12:[function(require,module,exports){
1500 2462 'use strict';
1501 2463
1502 2464 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
1503 2465
@@ -1521,9 +2483,9 @@
1521 2483 }
1522 2484
1523 2485 module.exports = pluralForms;
1524 2486
1525 -},{"@tannin/compile":6}],9:[function(require,module,exports){
2487 +},{"@tannin/compile":10}],13:[function(require,module,exports){
1526 2488 'use strict';
1527 2489
1528 2490 var PRECEDENCE, OPENERS, TERMINATORS, PATTERN;
1529 2491
@@ -1651,9 +2613,9 @@
1651 2613 }
1652 2614
1653 2615 module.exports = postfix;
1654 2616
1655 -},{}],10:[function(require,module,exports){
2617 +},{}],14:[function(require,module,exports){
1656 2618 "use strict";
1657 2619
1658 2620 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
1659 2621
@@ -1866,9 +2828,9 @@
1866 2828 };
1867 2829
1868 2830 exports.createI18n = createI18n;
1869 2831
1870 -},{"@babel/runtime/helpers/defineProperty":4,"@babel/runtime/helpers/interopRequireDefault":5,"tannin":17}],11:[function(require,module,exports){
2832 +},{"@babel/runtime/helpers/defineProperty":8,"@babel/runtime/helpers/interopRequireDefault":9,"tannin":23}],15:[function(require,module,exports){
1871 2833 "use strict";
1872 2834
1873 2835 Object.defineProperty(exports, "__esModule", {
1874 2836 value: true
@@ -1985,9 +2947,9 @@
1985 2947 exports._nx = _nx;
1986 2948 var isRTL = i18n.isRTL.bind(i18n);
1987 2949 exports.isRTL = isRTL;
1988 2950
1989 -},{"./create-i18n":10}],12:[function(require,module,exports){
2951 +},{"./create-i18n":14}],16:[function(require,module,exports){
1990 2952 "use strict";
1991 2953
1992 2954 Object.defineProperty(exports, "__esModule", {
1993 2955 value: true
@@ -2060,9 +3022,9 @@
2060 3022 });
2061 3023
2062 3024 var _defaultI18n = require("./default-i18n");
2063 3025
2064 -},{"./create-i18n":10,"./default-i18n":11,"./sprintf":13}],13:[function(require,module,exports){
3026 +},{"./create-i18n":14,"./default-i18n":15,"./sprintf":17}],17:[function(require,module,exports){
2065 3027 "use strict";
2066 3028
2067 3029 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
2068 3030
@@ -2112,9 +3074,9 @@
2112 3074 return format;
2113 3075 }
2114 3076 }
2115 3077
2116 -},{"@babel/runtime/helpers/interopRequireDefault":5,"memize":15,"sprintf-js":14}],14:[function(require,module,exports){
3078 +},{"@babel/runtime/helpers/interopRequireDefault":9,"memize":21,"sprintf-js":18}],18:[function(require,module,exports){
2117 3079 /* global window, exports, define */
2118 3080
2119 3081 !function() {
2120 3082 'use strict'
@@ -2345,9 +3307,1369 @@
2345 3307 }
2346 3308 /* eslint-enable quote-props */
2347 3309 }(); // eslint-disable-line
2348 3310
2349 -},{}],15:[function(require,module,exports){
3311 +},{}],19:[function(require,module,exports){
3312 +/*
3313 + * International Telephone Input v17.0.16
3314 + * https://github.com/jackocnr/intl-tel-input.git
3315 + * Licensed under the MIT license
3316 + */
3317 +
3318 +// wrap in UMD
3319 +(function(factory) {
3320 + if (typeof module === "object" && module.exports) module.exports = factory(); else window.intlTelInput = factory();
3321 +})(function(undefined) {
3322 + "use strict";
3323 + return function() {
3324 + // Array of country objects for the flag dropdown.
3325 + // Here is the criteria for the plugin to support a given country/territory
3326 + // - It has an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
3327 + // - 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
3328 + // - It has a flag in the region-flags project: https://github.com/behdad/region-flags/tree/gh-pages/png
3329 + // - It is supported by libphonenumber (it must be listed on this page): https://github.com/googlei18n/libphonenumber/blob/master/resources/ShortNumberMetadata.xml
3330 + // Each country array has the following information:
3331 + // [
3332 + // Country name,
3333 + // iso2 code,
3334 + // International dial code,
3335 + // Order (if >1 country with same dial code),
3336 + // Area codes
3337 + // ]
3338 + 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 (‫جزر القمر‬‎)", "km", "269" ], [ "Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)", "cd", "243" ], [ "Congo (Republic) (Congo-Brazzaville)", "cg", "242" ], [ "Cook Islands", "ck", "682" ], [ "Costa Rica", "cr", "506" ], [ "Côte d’Ivoire", "ci", "225" ], [ "Croatia (Hrvatska)", "hr", "385" ], [ "Cuba", "cu", "53" ], [ "Curaçao", "cw", "599", 0 ], [ "Cyprus (Κύπρος)", "cy", "357" ], [ "Czech Republic (Česká republika)", "cz", "420" ], [ "Denmark (Danmark)", "dk", "45" ], [ "Djibouti", "dj", "253" ], [ "Dominica", "dm", "1", 13, [ "767" ] ], [ "Dominican Republic (República Dominicana)", "do", "1", 2, [ "809", "829", "849" ] ], [ "Ecuador", "ec", "593" ], [ "Egypt (‫مصر‬‎)", "eg", "20" ], [ "El Salvador", "sv", "503" ], [ "Equatorial Guinea (Guinea Ecuatorial)", "gq", "240" ], [ "Eritrea", "er", "291" ], [ "Estonia (Eesti)", "ee", "372" ], [ "Eswatini", "sz", "268" ], [ "Ethiopia", "et", "251" ], [ "Falkland Islands (Islas Malvinas)", "fk", "500" ], [ "Faroe Islands (Føroyar)", "fo", "298" ], [ "Fiji", "fj", "679" ], [ "Finland (Suomi)", "fi", "358", 0 ], [ "France", "fr", "33" ], [ "French Guiana (Guyane française)", "gf", "594" ], [ "French Polynesia (Polynésie française)", "pf", "689" ], [ "Gabon", "ga", "241" ], [ "Gambia", "gm", "220" ], [ "Georgia (საქართველო)", "ge", "995" ], [ "Germany (Deutschland)", "de", "49" ], [ "Ghana (Gaana)", "gh", "233" ], [ "Gibraltar", "gi", "350" ], [ "Greece (Ελλάδα)", "gr", "30" ], [ "Greenland (Kalaallit Nunaat)", "gl", "299" ], [ "Grenada", "gd", "1", 14, [ "473" ] ], [ "Guadeloupe", "gp", "590", 0 ], [ "Guam", "gu", "1", 15, [ "671" ] ], [ "Guatemala", "gt", "502" ], [ "Guernsey", "gg", "44", 1, [ "1481", "7781", "7839", "7911" ] ], [ "Guinea (Guinée)", "gn", "224" ], [ "Guinea-Bissau (Guiné Bissau)", "gw", "245" ], [ "Guyana", "gy", "592" ], [ "Haiti", "ht", "509" ], [ "Honduras", "hn", "504" ], [ "Hong Kong (香港)", "hk", "852" ], [ "Hungary (Magyarország)", "hu", "36" ], [ "Iceland (Ísland)", "is", "354" ], [ "India (भारत)", "in", "91" ], [ "Indonesia", "id", "62" ], [ "Iran (‫ایران‬‎)", "ir", "98" ], [ "Iraq (‫العراق‬‎)", "iq", "964" ], [ "Ireland", "ie", "353" ], [ "Isle of Man", "im", "44", 2, [ "1624", "74576", "7524", "7924", "7624" ] ], [ "Israel (‫ישראל‬‎)", "il", "972" ], [ "Italy (Italia)", "it", "39", 0 ], [ "Jamaica", "jm", "1", 4, [ "876", "658" ] ], [ "Japan (日本)", "jp", "81" ], [ "Jersey", "je", "44", 3, [ "1534", "7509", "7700", "7797", "7829", "7937" ] ], [ "Jordan (‫الأردن‬‎)", "jo", "962" ], [ "Kazakhstan (Казахстан)", "kz", "7", 1, [ "33", "7" ] ], [ "Kenya", "ke", "254" ], [ "Kiribati", "ki", "686" ], [ "Kosovo", "xk", "383" ], [ "Kuwait (‫الكويت‬‎)", "kw", "965" ], [ "Kyrgyzstan (Кыргызстан)", "kg", "996" ], [ "Laos (ລາວ)", "la", "856" ], [ "Latvia (Latvija)", "lv", "371" ], [ "Lebanon (‫لبنان‬‎)", "lb", "961" ], [ "Lesotho", "ls", "266" ], [ "Liberia", "lr", "231" ], [ "Libya (‫ليبيا‬‎)", "ly", "218" ], [ "Liechtenstein", "li", "423" ], [ "Lithuania (Lietuva)", "lt", "370" ], [ "Luxembourg", "lu", "352" ], [ "Macau (澳門)", "mo", "853" ], [ "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 (‫موريتانيا‬‎)", "mr", "222" ], [ "Mauritius (Moris)", "mu", "230" ], [ "Mayotte", "yt", "262", 1, [ "269", "639" ] ], [ "Mexico (México)", "mx", "52" ], [ "Micronesia", "fm", "691" ], [ "Moldova (Republica Moldova)", "md", "373" ], [ "Monaco", "mc", "377" ], [ "Mongolia (Монгол)", "mn", "976" ], [ "Montenegro (Crna Gora)", "me", "382" ], [ "Montserrat", "ms", "1", 16, [ "664" ] ], [ "Morocco (‫المغرب‬‎)", "ma", "212", 0 ], [ "Mozambique (Moçambique)", "mz", "258" ], [ "Myanmar (Burma) (မြန်မာ)", "mm", "95" ], [ "Namibia (Namibië)", "na", "264" ], [ "Nauru", "nr", "674" ], [ "Nepal (नेपाल)", "np", "977" ], [ "Netherlands (Nederland)", "nl", "31" ], [ "New Caledonia (Nouvelle-Calédonie)", "nc", "687" ], [ "New Zealand", "nz", "64" ], [ "Nicaragua", "ni", "505" ], [ "Niger (Nijar)", "ne", "227" ], [ "Nigeria", "ng", "234" ], [ "Niue", "nu", "683" ], [ "Norfolk Island", "nf", "672" ], [ "North Korea (조선 민주주의 인민 공화국)", "kp", "850" ], [ "Northern Mariana Islands", "mp", "1", 17, [ "670" ] ], [ "Norway (Norge)", "no", "47", 0 ], [ "Oman (‫عُمان‬‎)", "om", "968" ], [ "Pakistan (‫پاکستان‬‎)", "pk", "92" ], [ "Palau", "pw", "680" ], [ "Palestine (‫فلسطين‬‎)", "ps", "970" ], [ "Panama (Panamá)", "pa", "507" ], [ "Papua New Guinea", "pg", "675" ], [ "Paraguay", "py", "595" ], [ "Peru (Perú)", "pe", "51" ], [ "Philippines", "ph", "63" ], [ "Poland (Polska)", "pl", "48" ], [ "Portugal", "pt", "351" ], [ "Puerto Rico", "pr", "1", 3, [ "787", "939" ] ], [ "Qatar (‫قطر‬‎)", "qa", "974" ], [ "Réunion (La Réunion)", "re", "262", 0 ], [ "Romania (România)", "ro", "40" ], [ "Russia (Россия)", "ru", "7", 0 ], [ "Rwanda", "rw", "250" ], [ "Saint Barthélemy", "bl", "590", 1 ], [ "Saint Helena", "sh", "290" ], [ "Saint Kitts and Nevis", "kn", "1", 18, [ "869" ] ], [ "Saint Lucia", "lc", "1", 19, [ "758" ] ], [ "Saint Martin (Saint-Martin (partie française))", "mf", "590", 2 ], [ "Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)", "pm", "508" ], [ "Saint Vincent and the Grenadines", "vc", "1", 20, [ "784" ] ], [ "Samoa", "ws", "685" ], [ "San Marino", "sm", "378" ], [ "São Tomé and Príncipe (São Tomé e Príncipe)", "st", "239" ], [ "Saudi Arabia (‫المملكة العربية السعودية‬‎)", "sa", "966" ], [ "Senegal (Sénégal)", "sn", "221" ], [ "Serbia (Србија)", "rs", "381" ], [ "Seychelles", "sc", "248" ], [ "Sierra Leone", "sl", "232" ], [ "Singapore", "sg", "65" ], [ "Sint Maarten", "sx", "1", 21, [ "721" ] ], [ "Slovakia (Slovensko)", "sk", "421" ], [ "Slovenia (Slovenija)", "si", "386" ], [ "Solomon Islands", "sb", "677" ], [ "Somalia (Soomaaliya)", "so", "252" ], [ "South Africa", "za", "27" ], [ "South Korea (대한민국)", "kr", "82" ], [ "South Sudan (‫جنوب السودان‬‎)", "ss", "211" ], [ "Spain (España)", "es", "34" ], [ "Sri Lanka (ශ්‍රී ලංකාව)", "lk", "94" ], [ "Sudan (‫السودان‬‎)", "sd", "249" ], [ "Suriname", "sr", "597" ], [ "Svalbard and Jan Mayen", "sj", "47", 1, [ "79" ] ], [ "Sweden (Sverige)", "se", "46" ], [ "Switzerland (Schweiz)", "ch", "41" ], [ "Syria (‫سوريا‬‎)", "sy", "963" ], [ "Taiwan (台灣)", "tw", "886" ], [ "Tajikistan", "tj", "992" ], [ "Tanzania", "tz", "255" ], [ "Thailand (ไทย)", "th", "66" ], [ "Timor-Leste", "tl", "670" ], [ "Togo", "tg", "228" ], [ "Tokelau", "tk", "690" ], [ "Tonga", "to", "676" ], [ "Trinidad and Tobago", "tt", "1", 22, [ "868" ] ], [ "Tunisia (‫تونس‬‎)", "tn", "216" ], [ "Turkey (Türkiye)", "tr", "90" ], [ "Turkmenistan", "tm", "993" ], [ "Turks and Caicos Islands", "tc", "1", 23, [ "649" ] ], [ "Tuvalu", "tv", "688" ], [ "U.S. Virgin Islands", "vi", "1", 24, [ "340" ] ], [ "Uganda", "ug", "256" ], [ "Ukraine (Україна)", "ua", "380" ], [ "United Arab Emirates (‫الإمارات العربية المتحدة‬‎)", "ae", "971" ], [ "United Kingdom", "gb", "44", 0 ], [ "United States", "us", "1", 0 ], [ "Uruguay", "uy", "598" ], [ "Uzbekistan (Oʻzbekiston)", "uz", "998" ], [ "Vanuatu", "vu", "678" ], [ "Vatican City (Città del Vaticano)", "va", "39", 1, [ "06698" ] ], [ "Venezuela", "ve", "58" ], [ "Vietnam (Việt Nam)", "vn", "84" ], [ "Wallis and Futuna (Wallis-et-Futuna)", "wf", "681" ], [ "Western Sahara (‫الصحراء الغربية‬‎)", "eh", "212", 1, [ "5288", "5289" ] ], [ "Yemen (‫اليمن‬‎)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ], [ "Åland Islands", "ax", "358", 1, [ "18" ] ] ];
3339 + // loop over all of the countries above, restructuring the data to be objects with named keys
3340 + for (var i = 0; i < allCountries.length; i++) {
3341 + var c = allCountries[i];
3342 + allCountries[i] = {
3343 + name: c[0],
3344 + iso2: c[1],
3345 + dialCode: c[2],
3346 + priority: c[3] || 0,
3347 + areaCodes: c[4] || null
3348 + };
3349 + }
3350 + "use strict";
3351 + function _classCallCheck(instance, Constructor) {
3352 + if (!(instance instanceof Constructor)) {
3353 + throw new TypeError("Cannot call a class as a function");
3354 + }
3355 + }
3356 + function _defineProperties(target, props) {
3357 + for (var i = 0; i < props.length; i++) {
3358 + var descriptor = props[i];
3359 + descriptor.enumerable = descriptor.enumerable || false;
3360 + descriptor.configurable = true;
3361 + if ("value" in descriptor) descriptor.writable = true;
3362 + Object.defineProperty(target, descriptor.key, descriptor);
3363 + }
3364 + }
3365 + function _createClass(Constructor, protoProps, staticProps) {
3366 + if (protoProps) _defineProperties(Constructor.prototype, protoProps);
3367 + if (staticProps) _defineProperties(Constructor, staticProps);
3368 + return Constructor;
3369 + }
3370 + var intlTelInputGlobals = {
3371 + getInstance: function getInstance(input) {
3372 + var id = input.getAttribute("data-intl-tel-input-id");
3373 + return window.intlTelInputGlobals.instances[id];
3374 + },
3375 + instances: {},
3376 + // using a global like this allows us to mock it in the tests
3377 + documentReady: function documentReady() {
3378 + return document.readyState === "complete";
3379 + }
3380 + };
3381 + if (typeof window === "object") window.intlTelInputGlobals = intlTelInputGlobals;
3382 + // these vars persist through all instances of the plugin
3383 + var id = 0;
3384 + var defaults = {
3385 + // whether or not to allow the dropdown
3386 + allowDropdown: true,
3387 + // if there is just a dial code in the input: remove it on blur
3388 + autoHideDialCode: true,
3389 + // add a placeholder in the input with an example number for the selected country
3390 + autoPlaceholder: "polite",
3391 + // modify the parentClass
3392 + customContainer: "",
3393 + // modify the auto placeholder
3394 + customPlaceholder: null,
3395 + // append menu to specified element
3396 + dropdownContainer: null,
3397 + // don't display these countries
3398 + excludeCountries: [],
3399 + // format the input value during initialisation and on setNumber
3400 + formatOnDisplay: true,
3401 + // geoIp lookup function
3402 + geoIpLookup: null,
3403 + // inject a hidden input with this name, and on submit, populate it with the result of getNumber
3404 + hiddenInput: "",
3405 + // initial country
3406 + initialCountry: "",
3407 + // localized country names e.g. { 'de': 'Deutschland' }
3408 + localizedCountries: null,
3409 + // don't insert international dial codes
3410 + nationalMode: true,
3411 + // display only these countries
3412 + onlyCountries: [],
3413 + // number type to use for placeholders
3414 + placeholderNumberType: "MOBILE",
3415 + // the countries at the top of the list. defaults to united states and united kingdom
3416 + preferredCountries: [ "us", "gb" ],
3417 + // display the country dial code next to the selected flag so it's not part of the typed number
3418 + separateDialCode: false,
3419 + // specify the path to the libphonenumber script to enable validation/formatting
3420 + utilsScript: ""
3421 + };
3422 + // https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes#Non-geographic_area_codes
3423 + var regionlessNanpNumbers = [ "800", "822", "833", "844", "855", "866", "877", "880", "881", "882", "883", "884", "885", "886", "887", "888", "889" ];
3424 + // utility function to iterate over an object. can't use Object.entries or native forEach because
3425 + // of IE11
3426 + var forEachProp = function forEachProp(obj, callback) {
3427 + var keys = Object.keys(obj);
3428 + for (var i = 0; i < keys.length; i++) {
3429 + callback(keys[i], obj[keys[i]]);
3430 + }
3431 + };
3432 + // run a method on each instance of the plugin
3433 + var forEachInstance = function forEachInstance(method) {
3434 + forEachProp(window.intlTelInputGlobals.instances, function(key) {
3435 + window.intlTelInputGlobals.instances[key][method]();
3436 + });
3437 + };
3438 + // this is our plugin class that we will create an instance of
3439 + // eslint-disable-next-line no-unused-vars
3440 + var Iti = /*#__PURE__*/
3441 + function() {
3442 + function Iti(input, options) {
3443 + var _this = this;
3444 + _classCallCheck(this, Iti);
3445 + this.id = id++;
3446 + this.telInput = input;
3447 + this.activeItem = null;
3448 + this.highlightedItem = null;
3449 + // process specified options / defaults
3450 + // alternative to Object.assign, which isn't supported by IE11
3451 + var customOptions = options || {};
3452 + this.options = {};
3453 + forEachProp(defaults, function(key, value) {
3454 + _this.options[key] = customOptions.hasOwnProperty(key) ? customOptions[key] : value;
3455 + });
3456 + this.hadInitialPlaceholder = Boolean(input.getAttribute("placeholder"));
3457 + }
3458 + _createClass(Iti, [ {
3459 + key: "_init",
3460 + value: function _init() {
3461 + var _this2 = this;
3462 + // if in nationalMode, disable options relating to dial codes
3463 + if (this.options.nationalMode) this.options.autoHideDialCode = false;
3464 + // if separateDialCode then doesn't make sense to A) insert dial code into input
3465 + // (autoHideDialCode), and B) display national numbers (because we're displaying the country
3466 + // dial code next to them)
3467 + if (this.options.separateDialCode) {
3468 + this.options.autoHideDialCode = this.options.nationalMode = false;
3469 + }
3470 + // we cannot just test screen size as some smartphones/website meta tags will report desktop
3471 + // resolutions
3472 + // Note: for some reason jasmine breaks if you put this in the main Plugin function with the
3473 + // rest of these declarations
3474 + // Note: to target Android Mobiles (and not Tablets), we must find 'Android' and 'Mobile'
3475 + this.isMobile = /Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
3476 + if (this.isMobile) {
3477 + // trigger the mobile dropdown css
3478 + document.body.classList.add("iti-mobile");
3479 + // on mobile, we want a full screen dropdown, so we must append it to the body
3480 + if (!this.options.dropdownContainer) this.options.dropdownContainer = document.body;
3481 + }
3482 + // these promises get resolved when their individual requests complete
3483 + // this way the dev can do something like iti.promise.then(...) to know when all requests are
3484 + // complete
3485 + if (typeof Promise !== "undefined") {
3486 + var autoCountryPromise = new Promise(function(resolve, reject) {
3487 + _this2.resolveAutoCountryPromise = resolve;
3488 + _this2.rejectAutoCountryPromise = reject;
3489 + });
3490 + var utilsScriptPromise = new Promise(function(resolve, reject) {
3491 + _this2.resolveUtilsScriptPromise = resolve;
3492 + _this2.rejectUtilsScriptPromise = reject;
3493 + });
3494 + this.promise = Promise.all([ autoCountryPromise, utilsScriptPromise ]);
3495 + } else {
3496 + // prevent errors when Promise doesn't exist
3497 + this.resolveAutoCountryPromise = this.rejectAutoCountryPromise = function() {};
3498 + this.resolveUtilsScriptPromise = this.rejectUtilsScriptPromise = function() {};
3499 + }
3500 + // in various situations there could be no country selected initially, but we need to be able
3501 + // to assume this variable exists
3502 + this.selectedCountryData = {};
3503 + // process all the data: onlyCountries, excludeCountries, preferredCountries etc
3504 + this._processCountryData();
3505 + // generate the markup
3506 + this._generateMarkup();
3507 + // set the initial state of the input value and the selected flag
3508 + this._setInitialState();
3509 + // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click
3510 + this._initListeners();
3511 + // utils script, and auto country
3512 + this._initRequests();
3513 + }
3514 + }, {
3515 + key: "_processCountryData",
3516 + value: function _processCountryData() {
3517 + // process onlyCountries or excludeCountries array if present
3518 + this._processAllCountries();
3519 + // process the countryCodes map
3520 + this._processCountryCodes();
3521 + // process the preferredCountries
3522 + this._processPreferredCountries();
3523 + // translate countries according to localizedCountries option
3524 + if (this.options.localizedCountries) this._translateCountriesByLocale();
3525 + // sort countries by name
3526 + if (this.options.onlyCountries.length || this.options.localizedCountries) {
3527 + this.countries.sort(this._countryNameSort);
3528 + }
3529 + }
3530 + }, {
3531 + key: "_addCountryCode",
3532 + value: function _addCountryCode(iso2, countryCode, priority) {
3533 + if (countryCode.length > this.countryCodeMaxLen) {
3534 + this.countryCodeMaxLen = countryCode.length;
3535 + }
3536 + if (!this.countryCodes.hasOwnProperty(countryCode)) {
3537 + this.countryCodes[countryCode] = [];
3538 + }
3539 + // bail if we already have this country for this countryCode
3540 + for (var i = 0; i < this.countryCodes[countryCode].length; i++) {
3541 + if (this.countryCodes[countryCode][i] === iso2) return;
3542 + }
3543 + // check for undefined as 0 is falsy
3544 + var index = priority !== undefined ? priority : this.countryCodes[countryCode].length;
3545 + this.countryCodes[countryCode][index] = iso2;
3546 + }
3547 + }, {
3548 + key: "_processAllCountries",
3549 + value: function _processAllCountries() {
3550 + if (this.options.onlyCountries.length) {
3551 + var lowerCaseOnlyCountries = this.options.onlyCountries.map(function(country) {
3552 + return country.toLowerCase();
3553 + });
3554 + this.countries = allCountries.filter(function(country) {
3555 + return lowerCaseOnlyCountries.indexOf(country.iso2) > -1;
3556 + });
3557 + } else if (this.options.excludeCountries.length) {
3558 + var lowerCaseExcludeCountries = this.options.excludeCountries.map(function(country) {
3559 + return country.toLowerCase();
3560 + });
3561 + this.countries = allCountries.filter(function(country) {
3562 + return lowerCaseExcludeCountries.indexOf(country.iso2) === -1;
3563 + });
3564 + } else {
3565 + this.countries = allCountries;
3566 + }
3567 + }
3568 + }, {
3569 + key: "_translateCountriesByLocale",
3570 + value: function _translateCountriesByLocale() {
3571 + for (var i = 0; i < this.countries.length; i++) {
3572 + var iso = this.countries[i].iso2.toLowerCase();
3573 + if (this.options.localizedCountries.hasOwnProperty(iso)) {
3574 + this.countries[i].name = this.options.localizedCountries[iso];
3575 + }
3576 + }
3577 + }
3578 + }, {
3579 + key: "_countryNameSort",
3580 + value: function _countryNameSort(a, b) {
3581 + return a.name.localeCompare(b.name);
3582 + }
3583 + }, {
3584 + key: "_processCountryCodes",
3585 + value: function _processCountryCodes() {
3586 + this.countryCodeMaxLen = 0;
3587 + // here we store just dial codes
3588 + this.dialCodes = {};
3589 + // here we store "country codes" (both dial codes and their area codes)
3590 + this.countryCodes = {};
3591 + // first: add dial codes
3592 + for (var i = 0; i < this.countries.length; i++) {
3593 + var c = this.countries[i];
3594 + if (!this.dialCodes[c.dialCode]) this.dialCodes[c.dialCode] = true;
3595 + this._addCountryCode(c.iso2, c.dialCode, c.priority);
3596 + }
3597 + // next: add area codes
3598 + // this is a second loop over countries, to make sure we have all of the "root" countries
3599 + // already in the map, so that we can access them, as each time we add an area code substring
3600 + // to the map, we also need to include the "root" country's code, as that also matches
3601 + for (var _i = 0; _i < this.countries.length; _i++) {
3602 + var _c = this.countries[_i];
3603 + // area codes
3604 + if (_c.areaCodes) {
3605 + var rootCountryCode = this.countryCodes[_c.dialCode][0];
3606 + // for each area code
3607 + for (var j = 0; j < _c.areaCodes.length; j++) {
3608 + var areaCode = _c.areaCodes[j];
3609 + // for each digit in the area code to add all partial matches as well
3610 + for (var k = 1; k < areaCode.length; k++) {
3611 + var partialDialCode = _c.dialCode + areaCode.substr(0, k);
3612 + // start with the root country, as that also matches this dial code
3613 + this._addCountryCode(rootCountryCode, partialDialCode);
3614 + this._addCountryCode(_c.iso2, partialDialCode);
3615 + }
3616 + // add the full area code
3617 + this._addCountryCode(_c.iso2, _c.dialCode + areaCode);
3618 + }
3619 + }
3620 + }
3621 + }
3622 + }, {
3623 + key: "_processPreferredCountries",
3624 + value: function _processPreferredCountries() {
3625 + this.preferredCountries = [];
3626 + for (var i = 0; i < this.options.preferredCountries.length; i++) {
3627 + var countryCode = this.options.preferredCountries[i].toLowerCase();
3628 + var countryData = this._getCountryData(countryCode, false, true);
3629 + if (countryData) this.preferredCountries.push(countryData);
3630 + }
3631 + }
3632 + }, {
3633 + key: "_createEl",
3634 + value: function _createEl(name, attrs, container) {
3635 + var el = document.createElement(name);
3636 + if (attrs) forEachProp(attrs, function(key, value) {
3637 + return el.setAttribute(key, value);
3638 + });
3639 + if (container) container.appendChild(el);
3640 + return el;
3641 + }
3642 + }, {
3643 + key: "_generateMarkup",
3644 + value: function _generateMarkup() {
3645 + // if autocomplete does not exist on the element and its form, then
3646 + // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can
3647 + // easily put the plugin in an inconsistent state e.g. the wrong flag selected for the
3648 + // autocompleted number, which on submit could mean wrong number is saved (esp in nationalMode)
3649 + if (!this.telInput.hasAttribute("autocomplete") && !(this.telInput.form && this.telInput.form.hasAttribute("autocomplete"))) {
3650 + this.telInput.setAttribute("autocomplete", "off");
3651 + }
3652 + // containers (mostly for positioning)
3653 + var parentClass = "iti";
3654 + if (this.options.allowDropdown) parentClass += " iti--allow-dropdown";
3655 + if (this.options.separateDialCode) parentClass += " iti--separate-dial-code";
3656 + if (this.options.customContainer) {
3657 + parentClass += " ";
3658 + parentClass += this.options.customContainer;
3659 + }
3660 + var wrapper = this._createEl("div", {
3661 + "class": parentClass
3662 + });
3663 + this.telInput.parentNode.insertBefore(wrapper, this.telInput);
3664 + this.flagsContainer = this._createEl("div", {
3665 + "class": "iti__flag-container"
3666 + }, wrapper);
3667 + wrapper.appendChild(this.telInput);
3668 + // selected flag (displayed to left of input)
3669 + this.selectedFlag = this._createEl("div", {
3670 + "class": "iti__selected-flag",
3671 + role: "combobox",
3672 + "aria-controls": "iti-".concat(this.id, "__country-listbox"),
3673 + "aria-owns": "iti-".concat(this.id, "__country-listbox"),
3674 + "aria-expanded": "false"
3675 + }, this.flagsContainer);
3676 + this.selectedFlagInner = this._createEl("div", {
3677 + "class": "iti__flag"
3678 + }, this.selectedFlag);
3679 + if (this.options.separateDialCode) {
3680 + this.selectedDialCode = this._createEl("div", {
3681 + "class": "iti__selected-dial-code"
3682 + }, this.selectedFlag);
3683 + }
3684 + if (this.options.allowDropdown) {
3685 + // make element focusable and tab navigable
3686 + this.selectedFlag.setAttribute("tabindex", "0");
3687 + this.dropdownArrow = this._createEl("div", {
3688 + "class": "iti__arrow"
3689 + }, this.selectedFlag);
3690 + // country dropdown: preferred countries, then divider, then all countries
3691 + this.countryList = this._createEl("ul", {
3692 + "class": "iti__country-list iti__hide",
3693 + id: "iti-".concat(this.id, "__country-listbox"),
3694 + role: "listbox",
3695 + "aria-label": "List of countries"
3696 + });
3697 + if (this.preferredCountries.length) {
3698 + this._appendListItems(this.preferredCountries, "iti__preferred", true);
3699 + this._createEl("li", {
3700 + "class": "iti__divider",
3701 + role: "separator",
3702 + "aria-disabled": "true"
3703 + }, this.countryList);
3704 + }
3705 + this._appendListItems(this.countries, "iti__standard");
3706 + // create dropdownContainer markup
3707 + if (this.options.dropdownContainer) {
3708 + this.dropdown = this._createEl("div", {
3709 + "class": "iti iti--container"
3710 + });
3711 + this.dropdown.appendChild(this.countryList);
3712 + } else {
3713 + this.flagsContainer.appendChild(this.countryList);
3714 + }
3715 + }
3716 + if (this.options.hiddenInput) {
3717 + var hiddenInputName = this.options.hiddenInput;
3718 + var name = this.telInput.getAttribute("name");
3719 + if (name) {
3720 + var i = name.lastIndexOf("[");
3721 + // if input name contains square brackets, then give the hidden input the same name,
3722 + // replacing the contents of the last set of brackets with the given hiddenInput name
3723 + if (i !== -1) hiddenInputName = "".concat(name.substr(0, i), "[").concat(hiddenInputName, "]");
3724 + }
3725 + this.hiddenInput = this._createEl("input", {
3726 + type: "hidden",
3727 + name: hiddenInputName
3728 + });
3729 + wrapper.appendChild(this.hiddenInput);
3730 + }
3731 + }
3732 + }, {
3733 + key: "_appendListItems",
3734 + value: function _appendListItems(countries, className, preferred) {
3735 + // we create so many DOM elements, it is faster to build a temp string
3736 + // and then add everything to the DOM in one go at the end
3737 + var tmp = "";
3738 + // for each country
3739 + for (var i = 0; i < countries.length; i++) {
3740 + var c = countries[i];
3741 + var idSuffix = preferred ? "-preferred" : "";
3742 + // open the list item
3743 + 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'>");
3744 + // add the flag
3745 + tmp += "<div class='iti__flag-box'><div class='iti__flag iti__".concat(c.iso2, "'></div></div>");
3746 + // and the country name and dial code
3747 + tmp += "<span class='iti__country-name'>".concat(c.name, "</span>");
3748 + tmp += "<span class='iti__dial-code'>+".concat(c.dialCode, "</span>");
3749 + // close the list item
3750 + tmp += "</li>";
3751 + }
3752 + this.countryList.insertAdjacentHTML("beforeend", tmp);
3753 + }
3754 + }, {
3755 + key: "_setInitialState",
3756 + value: function _setInitialState() {
3757 + // fix firefox bug: when first load page (with input with value set to number with intl dial
3758 + // code) and initialising plugin removes the dial code from the input, then refresh page,
3759 + // and we try to init plugin again but this time on number without dial code so get grey flag
3760 + var attributeValue = this.telInput.getAttribute("value");
3761 + var inputValue = this.telInput.value;
3762 + var useAttribute = attributeValue && attributeValue.charAt(0) === "+" && (!inputValue || inputValue.charAt(0) !== "+");
3763 + var val = useAttribute ? attributeValue : inputValue;
3764 + var dialCode = this._getDialCode(val);
3765 + var isRegionlessNanp = this._isRegionlessNanp(val);
3766 + var _this$options = this.options, initialCountry = _this$options.initialCountry, nationalMode = _this$options.nationalMode, autoHideDialCode = _this$options.autoHideDialCode, separateDialCode = _this$options.separateDialCode;
3767 + // if we already have a dial code, and it's not a regionlessNanp, we can go ahead and set the
3768 + // flag, else fall back to the default country
3769 + if (dialCode && !isRegionlessNanp) {
3770 + this._updateFlagFromNumber(val);
3771 + } else if (initialCountry !== "auto") {
3772 + // see if we should select a flag
3773 + if (initialCountry) {
3774 + this._setFlag(initialCountry.toLowerCase());
3775 + } else {
3776 + if (dialCode && isRegionlessNanp) {
3777 + // has intl dial code, is regionless nanp, and no initialCountry, so default to US
3778 + this._setFlag("us");
3779 + } else {
3780 + // no dial code and no initialCountry, so default to first in list
3781 + this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2;
3782 + if (!val) {
3783 + this._setFlag(this.defaultCountry);
3784 + }
3785 + }
3786 + }
3787 + // if empty and no nationalMode and no autoHideDialCode then insert the default dial code
3788 + if (!val && !nationalMode && !autoHideDialCode && !separateDialCode) {
3789 + this.telInput.value = "+".concat(this.selectedCountryData.dialCode);
3790 + }
3791 + }
3792 + // NOTE: if initialCountry is set to auto, that will be handled separately
3793 + // format - note this wont be run after _updateDialCode as that's only called if no val
3794 + if (val) this._updateValFromNumber(val);
3795 + }
3796 + }, {
3797 + key: "_initListeners",
3798 + value: function _initListeners() {
3799 + this._initKeyListeners();
3800 + if (this.options.autoHideDialCode) this._initBlurListeners();
3801 + if (this.options.allowDropdown) this._initDropdownListeners();
3802 + if (this.hiddenInput) this._initHiddenInputListener();
3803 + }
3804 + }, {
3805 + key: "_initHiddenInputListener",
3806 + value: function _initHiddenInputListener() {
3807 + var _this3 = this;
3808 + this._handleHiddenInputSubmit = function() {
3809 + _this3.hiddenInput.value = _this3.getNumber();
3810 + };
3811 + if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleHiddenInputSubmit);
3812 + }
3813 + }, {
3814 + key: "_getClosestLabel",
3815 + value: function _getClosestLabel() {
3816 + var el = this.telInput;
3817 + while (el && el.tagName !== "LABEL") {
3818 + el = el.parentNode;
3819 + }
3820 + return el;
3821 + }
3822 + }, {
3823 + key: "_initDropdownListeners",
3824 + value: function _initDropdownListeners() {
3825 + var _this4 = this;
3826 + // hack for input nested inside label (which is valid markup): clicking the selected-flag to
3827 + // open the dropdown would then automatically trigger a 2nd click on the input which would
3828 + // close it again
3829 + this._handleLabelClick = function(e) {
3830 + // if the dropdown is closed, then focus the input, else ignore the click
3831 + if (_this4.countryList.classList.contains("iti__hide")) _this4.telInput.focus(); else e.preventDefault();
3832 + };
3833 + var label = this._getClosestLabel();
3834 + if (label) label.addEventListener("click", this._handleLabelClick);
3835 + // toggle country dropdown on click
3836 + this._handleClickSelectedFlag = function() {
3837 + // only intercept this event if we're opening the dropdown
3838 + // else let it bubble up to the top ("click-off-to-close" listener)
3839 + // we cannot just stopPropagation as it may be needed to close another instance
3840 + if (_this4.countryList.classList.contains("iti__hide") && !_this4.telInput.disabled && !_this4.telInput.readOnly) {
3841 + _this4._showDropdown();
3842 + }
3843 + };
3844 + this.selectedFlag.addEventListener("click", this._handleClickSelectedFlag);
3845 + // open dropdown list if currently focused
3846 + this._handleFlagsContainerKeydown = function(e) {
3847 + var isDropdownHidden = _this4.countryList.classList.contains("iti__hide");
3848 + if (isDropdownHidden && [ "ArrowUp", "Up", "ArrowDown", "Down", " ", "Enter" ].indexOf(e.key) !== -1) {
3849 + // prevent form from being submitted if "ENTER" was pressed
3850 + e.preventDefault();
3851 + // prevent event from being handled again by document
3852 + e.stopPropagation();
3853 + _this4._showDropdown();
3854 + }
3855 + // allow navigation from dropdown to input on TAB
3856 + if (e.key === "Tab") _this4._closeDropdown();
3857 + };
3858 + this.flagsContainer.addEventListener("keydown", this._handleFlagsContainerKeydown);
3859 + }
3860 + }, {
3861 + key: "_initRequests",
3862 + value: function _initRequests() {
3863 + var _this5 = this;
3864 + // if the user has specified the path to the utils script, fetch it on window.load, else resolve
3865 + if (this.options.utilsScript && !window.intlTelInputUtils) {
3866 + // if the plugin is being initialised after the window.load event has already been fired
3867 + if (window.intlTelInputGlobals.documentReady()) {
3868 + window.intlTelInputGlobals.loadUtils(this.options.utilsScript);
3869 + } else {
3870 + // wait until the load event so we don't block any other requests e.g. the flags image
3871 + window.addEventListener("load", function() {
3872 + window.intlTelInputGlobals.loadUtils(_this5.options.utilsScript);
3873 + });
3874 + }
3875 + } else this.resolveUtilsScriptPromise();
3876 + if (this.options.initialCountry === "auto") this._loadAutoCountry(); else this.resolveAutoCountryPromise();
3877 + }
3878 + }, {
3879 + key: "_loadAutoCountry",
3880 + value: function _loadAutoCountry() {
3881 + // 3 options:
3882 + // 1) already loaded (we're done)
3883 + // 2) not already started loading (start)
3884 + // 3) already started loading (do nothing - just wait for loading callback to fire)
3885 + if (window.intlTelInputGlobals.autoCountry) {
3886 + this.handleAutoCountry();
3887 + } else if (!window.intlTelInputGlobals.startedLoadingAutoCountry) {
3888 + // don't do this twice!
3889 + window.intlTelInputGlobals.startedLoadingAutoCountry = true;
3890 + if (typeof this.options.geoIpLookup === "function") {
3891 + this.options.geoIpLookup(function(countryCode) {
3892 + window.intlTelInputGlobals.autoCountry = countryCode.toLowerCase();
3893 + // tell all instances the auto country is ready
3894 + // TODO: this should just be the current instances
3895 + // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight
3896 + // away (e.g. if they have already done the geo ip lookup somewhere else). Using
3897 + // setTimeout means that the current thread of execution will finish before executing
3898 + // this, which allows the plugin to finish initialising.
3899 + setTimeout(function() {
3900 + return forEachInstance("handleAutoCountry");
3901 + });
3902 + }, function() {
3903 + return forEachInstance("rejectAutoCountryPromise");
3904 + });
3905 + }
3906 + }
3907 + }
3908 + }, {
3909 + key: "_initKeyListeners",
3910 + value: function _initKeyListeners() {
3911 + var _this6 = this;
3912 + // update flag on keyup
3913 + this._handleKeyupEvent = function() {
3914 + if (_this6._updateFlagFromNumber(_this6.telInput.value)) {
3915 + _this6._triggerCountryChange();
3916 + }
3917 + };
3918 + this.telInput.addEventListener("keyup", this._handleKeyupEvent);
3919 + // update flag on cut/paste events (now supported in all major browsers)
3920 + this._handleClipboardEvent = function() {
3921 + // hack because "paste" event is fired before input is updated
3922 + setTimeout(_this6._handleKeyupEvent);
3923 + };
3924 + this.telInput.addEventListener("cut", this._handleClipboardEvent);
3925 + this.telInput.addEventListener("paste", this._handleClipboardEvent);
3926 + }
3927 + }, {
3928 + key: "_cap",
3929 + value: function _cap(number) {
3930 + var max = this.telInput.getAttribute("maxlength");
3931 + return max && number.length > max ? number.substr(0, max) : number;
3932 + }
3933 + }, {
3934 + key: "_initBlurListeners",
3935 + value: function _initBlurListeners() {
3936 + var _this7 = this;
3937 + // on blur or form submit: if just a dial code then remove it
3938 + this._handleSubmitOrBlurEvent = function() {
3939 + _this7._removeEmptyDialCode();
3940 + };
3941 + if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleSubmitOrBlurEvent);
3942 + this.telInput.addEventListener("blur", this._handleSubmitOrBlurEvent);
3943 + }
3944 + }, {
3945 + key: "_removeEmptyDialCode",
3946 + value: function _removeEmptyDialCode() {
3947 + if (this.telInput.value.charAt(0) === "+") {
3948 + var numeric = this._getNumeric(this.telInput.value);
3949 + // if just a plus, or if just a dial code
3950 + if (!numeric || this.selectedCountryData.dialCode === numeric) {
3951 + this.telInput.value = "";
3952 + }
3953 + }
3954 + }
3955 + }, {
3956 + key: "_getNumeric",
3957 + value: function _getNumeric(s) {
3958 + return s.replace(/\D/g, "");
3959 + }
3960 + }, {
3961 + key: "_trigger",
3962 + value: function _trigger(name) {
3963 + // have to use old school document.createEvent as IE11 doesn't support `new Event()` syntax
3964 + var e = document.createEvent("Event");
3965 + e.initEvent(name, true, true);
3966 + // can bubble, and is cancellable
3967 + this.telInput.dispatchEvent(e);
3968 + }
3969 + }, {
3970 + key: "_showDropdown",
3971 + value: function _showDropdown() {
3972 + this.countryList.classList.remove("iti__hide");
3973 + this.selectedFlag.setAttribute("aria-expanded", "true");
3974 + this._setDropdownPosition();
3975 + // update highlighting and scroll to active list item
3976 + if (this.activeItem) {
3977 + this._highlightListItem(this.activeItem, false);
3978 + this._scrollTo(this.activeItem, true);
3979 + }
3980 + // bind all the dropdown-related listeners: mouseover, click, click-off, keydown
3981 + this._bindDropdownListeners();
3982 + // update the arrow
3983 + this.dropdownArrow.classList.add("iti__arrow--up");
3984 + this._trigger("open:countrydropdown");
3985 + }
3986 + }, {
3987 + key: "_toggleClass",
3988 + value: function _toggleClass(el, className, shouldHaveClass) {
3989 + if (shouldHaveClass && !el.classList.contains(className)) el.classList.add(className); else if (!shouldHaveClass && el.classList.contains(className)) el.classList.remove(className);
3990 + }
3991 + }, {
3992 + key: "_setDropdownPosition",
3993 + value: function _setDropdownPosition() {
3994 + var _this8 = this;
3995 + if (this.options.dropdownContainer) {
3996 + this.options.dropdownContainer.appendChild(this.dropdown);
3997 + }
3998 + if (!this.isMobile) {
3999 + var pos = this.telInput.getBoundingClientRect();
4000 + // windowTop from https://stackoverflow.com/a/14384091/217866
4001 + var windowTop = window.pageYOffset || document.documentElement.scrollTop;
4002 + var inputTop = pos.top + windowTop;
4003 + var dropdownHeight = this.countryList.offsetHeight;
4004 + // dropdownFitsBelow = (dropdownBottom < windowBottom)
4005 + var dropdownFitsBelow = inputTop + this.telInput.offsetHeight + dropdownHeight < windowTop + window.innerHeight;
4006 + var dropdownFitsAbove = inputTop - dropdownHeight > windowTop;
4007 + // by default, the dropdown will be below the input. If we want to position it above the
4008 + // input, we add the dropup class.
4009 + this._toggleClass(this.countryList, "iti__country-list--dropup", !dropdownFitsBelow && dropdownFitsAbove);
4010 + // if dropdownContainer is enabled, calculate postion
4011 + if (this.options.dropdownContainer) {
4012 + // by default the dropdown will be directly over the input because it's not in the flow.
4013 + // If we want to position it below, we need to add some extra top value.
4014 + var extraTop = !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.offsetHeight;
4015 + // calculate placement
4016 + this.dropdown.style.top = "".concat(inputTop + extraTop, "px");
4017 + this.dropdown.style.left = "".concat(pos.left + document.body.scrollLeft, "px");
4018 + // close menu on window scroll
4019 + this._handleWindowScroll = function() {
4020 + return _this8._closeDropdown();
4021 + };
4022 + window.addEventListener("scroll", this._handleWindowScroll);
4023 + }
4024 + }
4025 + }
4026 + }, {
4027 + key: "_getClosestListItem",
4028 + value: function _getClosestListItem(target) {
4029 + var el = target;
4030 + while (el && el !== this.countryList && !el.classList.contains("iti__country")) {
4031 + el = el.parentNode;
4032 + }
4033 + // if we reached the countryList element, then return null
4034 + return el === this.countryList ? null : el;
4035 + }
4036 + }, {
4037 + key: "_bindDropdownListeners",
4038 + value: function _bindDropdownListeners() {
4039 + var _this9 = this;
4040 + // when mouse over a list item, just highlight that one
4041 + // we add the class "highlight", so if they hit "enter" we know which one to select
4042 + this._handleMouseoverCountryList = function(e) {
4043 + // handle event delegation, as we're listening for this event on the countryList
4044 + var listItem = _this9._getClosestListItem(e.target);
4045 + if (listItem) _this9._highlightListItem(listItem, false);
4046 + };
4047 + this.countryList.addEventListener("mouseover", this._handleMouseoverCountryList);
4048 + // listen for country selection
4049 + this._handleClickCountryList = function(e) {
4050 + var listItem = _this9._getClosestListItem(e.target);
4051 + if (listItem) _this9._selectListItem(listItem);
4052 + };
4053 + this.countryList.addEventListener("click", this._handleClickCountryList);
4054 + // click off to close
4055 + // (except when this initial opening click is bubbling up)
4056 + // we cannot just stopPropagation as it may be needed to close another instance
4057 + var isOpening = true;
4058 + this._handleClickOffToClose = function() {
4059 + if (!isOpening) _this9._closeDropdown();
4060 + isOpening = false;
4061 + };
4062 + document.documentElement.addEventListener("click", this._handleClickOffToClose);
4063 + // listen for up/down scrolling, enter to select, or letters to jump to country name.
4064 + // use keydown as keypress doesn't fire for non-char keys and we want to catch if they
4065 + // just hit down and hold it to scroll down (no keyup event).
4066 + // listen on the document because that's where key events are triggered if no input has focus
4067 + var query = "";
4068 + var queryTimer = null;
4069 + this._handleKeydownOnDropdown = function(e) {
4070 + // prevent down key from scrolling the whole page,
4071 + // and enter key from submitting a form etc
4072 + e.preventDefault();
4073 + // up and down to navigate
4074 + 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)) {
4075 + // jump to countries that start with the query string
4076 + if (queryTimer) clearTimeout(queryTimer);
4077 + query += e.key.toLowerCase();
4078 + _this9._searchForCountry(query);
4079 + // if the timer hits 1 second, reset the query
4080 + queryTimer = setTimeout(function() {
4081 + query = "";
4082 + }, 1e3);
4083 + }
4084 + };
4085 + document.addEventListener("keydown", this._handleKeydownOnDropdown);
4086 + }
4087 + }, {
4088 + key: "_handleUpDownKey",
4089 + value: function _handleUpDownKey(key) {
4090 + var next = key === "ArrowUp" || key === "Up" ? this.highlightedItem.previousElementSibling : this.highlightedItem.nextElementSibling;
4091 + if (next) {
4092 + // skip the divider
4093 + if (next.classList.contains("iti__divider")) {
4094 + next = key === "ArrowUp" || key === "Up" ? next.previousElementSibling : next.nextElementSibling;
4095 + }
4096 + this._highlightListItem(next, true);
4097 + }
4098 + }
4099 + }, {
4100 + key: "_handleEnterKey",
4101 + value: function _handleEnterKey() {
4102 + if (this.highlightedItem) this._selectListItem(this.highlightedItem);
4103 + }
4104 + }, {
4105 + key: "_searchForCountry",
4106 + value: function _searchForCountry(query) {
4107 + for (var i = 0; i < this.countries.length; i++) {
4108 + if (this._startsWith(this.countries[i].name, query)) {
4109 + var listItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(this.countries[i].iso2));
4110 + // update highlighting and scroll
4111 + this._highlightListItem(listItem, false);
4112 + this._scrollTo(listItem, true);
4113 + break;
4114 + }
4115 + }
4116 + }
4117 + }, {
4118 + key: "_startsWith",
4119 + value: function _startsWith(a, b) {
4120 + return a.substr(0, b.length).toLowerCase() === b;
4121 + }
4122 + }, {
4123 + key: "_updateValFromNumber",
4124 + value: function _updateValFromNumber(originalNumber) {
4125 + var number = originalNumber;
4126 + if (this.options.formatOnDisplay && window.intlTelInputUtils && this.selectedCountryData) {
4127 + var useNational = !this.options.separateDialCode && (this.options.nationalMode || number.charAt(0) !== "+");
4128 + var _intlTelInputUtils$nu = intlTelInputUtils.numberFormat, NATIONAL = _intlTelInputUtils$nu.NATIONAL, INTERNATIONAL = _intlTelInputUtils$nu.INTERNATIONAL;
4129 + var format = useNational ? NATIONAL : INTERNATIONAL;
4130 + number = intlTelInputUtils.formatNumber(number, this.selectedCountryData.iso2, format);
4131 + }
4132 + number = this._beforeSetNumber(number);
4133 + this.telInput.value = number;
4134 + }
4135 + }, {
4136 + key: "_updateFlagFromNumber",
4137 + value: function _updateFlagFromNumber(originalNumber) {
4138 + // if we're in nationalMode and we already have US/Canada selected, make sure the number starts
4139 + // with a +1 so _getDialCode will be able to extract the area code
4140 + // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag
4141 + // from the number), that means we're initialising the plugin with a number that already has a
4142 + // dial code, so fine to ignore this bit
4143 + var number = originalNumber;
4144 + var selectedDialCode = this.selectedCountryData.dialCode;
4145 + var isNanp = selectedDialCode === "1";
4146 + if (number && this.options.nationalMode && isNanp && number.charAt(0) !== "+") {
4147 + if (number.charAt(0) !== "1") number = "1".concat(number);
4148 + number = "+".concat(number);
4149 + }
4150 + // update flag if user types area code for another country
4151 + if (this.options.separateDialCode && selectedDialCode && number.charAt(0) !== "+") {
4152 + number = "+".concat(selectedDialCode).concat(number);
4153 + }
4154 + // try and extract valid dial code from input
4155 + var dialCode = this._getDialCode(number, true);
4156 + var numeric = this._getNumeric(number);
4157 + var countryCode = null;
4158 + if (dialCode) {
4159 + var countryCodes = this.countryCodes[this._getNumeric(dialCode)];
4160 + // check if the right country is already selected. this should be false if the number is
4161 + // longer than the matched dial code because in this case we need to make sure that if
4162 + // there are multiple country matches, that the first one is selected (note: we could
4163 + // just check that here, but it requires the same loop that we already have later)
4164 + var alreadySelected = countryCodes.indexOf(this.selectedCountryData.iso2) !== -1 && numeric.length <= dialCode.length - 1;
4165 + var isRegionlessNanpNumber = selectedDialCode === "1" && this._isRegionlessNanp(numeric);
4166 + // only update the flag if:
4167 + // A) NOT (we currently have a NANP flag selected, and the number is a regionlessNanp)
4168 + // AND
4169 + // B) the right country is not already selected
4170 + if (!isRegionlessNanpNumber && !alreadySelected) {
4171 + // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first
4172 + // non-empty index
4173 + for (var j = 0; j < countryCodes.length; j++) {
4174 + if (countryCodes[j]) {
4175 + countryCode = countryCodes[j];
4176 + break;
4177 + }
4178 + }
4179 + }
4180 + } else if (number.charAt(0) === "+" && numeric.length) {
4181 + // invalid dial code, so empty
4182 + // Note: use getNumeric here because the number has not been formatted yet, so could contain
4183 + // bad chars
4184 + countryCode = "";
4185 + } else if (!number || number === "+") {
4186 + // empty, or just a plus, so default
4187 + countryCode = this.defaultCountry;
4188 + }
4189 + if (countryCode !== null) {
4190 + return this._setFlag(countryCode);
4191 + }
4192 + return false;
4193 + }
4194 + }, {
4195 + key: "_isRegionlessNanp",
4196 + value: function _isRegionlessNanp(number) {
4197 + var numeric = this._getNumeric(number);
4198 + if (numeric.charAt(0) === "1") {
4199 + var areaCode = numeric.substr(1, 3);
4200 + return regionlessNanpNumbers.indexOf(areaCode) !== -1;
4201 + }
4202 + return false;
4203 + }
4204 + }, {
4205 + key: "_highlightListItem",
4206 + value: function _highlightListItem(listItem, shouldFocus) {
4207 + var prevItem = this.highlightedItem;
4208 + if (prevItem) prevItem.classList.remove("iti__highlight");
4209 + this.highlightedItem = listItem;
4210 + this.highlightedItem.classList.add("iti__highlight");
4211 + if (shouldFocus) this.highlightedItem.focus();
4212 + }
4213 + }, {
4214 + key: "_getCountryData",
4215 + value: function _getCountryData(countryCode, ignoreOnlyCountriesOption, allowFail) {
4216 + var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
4217 + for (var i = 0; i < countryList.length; i++) {
4218 + if (countryList[i].iso2 === countryCode) {
4219 + return countryList[i];
4220 + }
4221 + }
4222 + if (allowFail) {
4223 + return null;
4224 + }
4225 + throw new Error("No country data for '".concat(countryCode, "'"));
4226 + }
4227 + }, {
4228 + key: "_setFlag",
4229 + value: function _setFlag(countryCode) {
4230 + var prevCountry = this.selectedCountryData.iso2 ? this.selectedCountryData : {};
4231 + // do this first as it will throw an error and stop if countryCode is invalid
4232 + this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {};
4233 + // update the defaultCountry - we only need the iso2 from now on, so just store that
4234 + if (this.selectedCountryData.iso2) {
4235 + this.defaultCountry = this.selectedCountryData.iso2;
4236 + }
4237 + this.selectedFlagInner.setAttribute("class", "iti__flag iti__".concat(countryCode));
4238 + // update the selected country's title attribute
4239 + var title = countryCode ? "".concat(this.selectedCountryData.name, ": +").concat(this.selectedCountryData.dialCode) : "Unknown";
4240 + this.selectedFlag.setAttribute("title", title);
4241 + if (this.options.separateDialCode) {
4242 + var dialCode = this.selectedCountryData.dialCode ? "+".concat(this.selectedCountryData.dialCode) : "";
4243 + this.selectedDialCode.innerHTML = dialCode;
4244 + // offsetWidth is zero if input is in a hidden container during initialisation
4245 + var selectedFlagWidth = this.selectedFlag.offsetWidth || this._getHiddenSelectedFlagWidth();
4246 + // add 6px of padding after the grey selected-dial-code box, as this is what we use in the css
4247 + this.telInput.style.paddingLeft = "".concat(selectedFlagWidth + 6, "px");
4248 + }
4249 + // and the input's placeholder
4250 + this._updatePlaceholder();
4251 + // update the active list item
4252 + if (this.options.allowDropdown) {
4253 + var prevItem = this.activeItem;
4254 + if (prevItem) {
4255 + prevItem.classList.remove("iti__active");
4256 + prevItem.setAttribute("aria-selected", "false");
4257 + }
4258 + if (countryCode) {
4259 + // check if there is a preferred item first, else fall back to standard
4260 + var nextItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode, "-preferred")) || this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode));
4261 + nextItem.setAttribute("aria-selected", "true");
4262 + nextItem.classList.add("iti__active");
4263 + this.activeItem = nextItem;
4264 + this.selectedFlag.setAttribute("aria-activedescendant", nextItem.getAttribute("id"));
4265 + }
4266 + }
4267 + // return if the flag has changed or not
4268 + return prevCountry.iso2 !== countryCode;
4269 + }
4270 + }, {
4271 + key: "_getHiddenSelectedFlagWidth",
4272 + value: function _getHiddenSelectedFlagWidth() {
4273 + // to get the right styling to apply, all we need is a shallow clone of the container,
4274 + // and then to inject a deep clone of the selectedFlag element
4275 + var containerClone = this.telInput.parentNode.cloneNode();
4276 + containerClone.style.visibility = "hidden";
4277 + document.body.appendChild(containerClone);
4278 + var flagsContainerClone = this.flagsContainer.cloneNode();
4279 + containerClone.appendChild(flagsContainerClone);
4280 + var selectedFlagClone = this.selectedFlag.cloneNode(true);
4281 + flagsContainerClone.appendChild(selectedFlagClone);
4282 + var width = selectedFlagClone.offsetWidth;
4283 + containerClone.parentNode.removeChild(containerClone);
4284 + return width;
4285 + }
4286 + }, {
4287 + key: "_updatePlaceholder",
4288 + value: function _updatePlaceholder() {
4289 + var shouldSetPlaceholder = this.options.autoPlaceholder === "aggressive" || !this.hadInitialPlaceholder && this.options.autoPlaceholder === "polite";
4290 + if (window.intlTelInputUtils && shouldSetPlaceholder) {
4291 + var numberType = intlTelInputUtils.numberType[this.options.placeholderNumberType];
4292 + var placeholder = this.selectedCountryData.iso2 ? intlTelInputUtils.getExampleNumber(this.selectedCountryData.iso2, this.options.nationalMode, numberType) : "";
4293 + placeholder = this._beforeSetNumber(placeholder);
4294 + if (typeof this.options.customPlaceholder === "function") {
4295 + placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData);
4296 + }
4297 + this.telInput.setAttribute("placeholder", placeholder);
4298 + }
4299 + }
4300 + }, {
4301 + key: "_selectListItem",
4302 + value: function _selectListItem(listItem) {
4303 + // update selected flag and active list item
4304 + var flagChanged = this._setFlag(listItem.getAttribute("data-country-code"));
4305 + this._closeDropdown();
4306 + this._updateDialCode(listItem.getAttribute("data-dial-code"), true);
4307 + // focus the input
4308 + this.telInput.focus();
4309 + // put cursor at end - this fix is required for FF and IE11 (with nationalMode=false i.e. auto
4310 + // inserting dial code), who try to put the cursor at the beginning the first time
4311 + var len = this.telInput.value.length;
4312 + this.telInput.setSelectionRange(len, len);
4313 + if (flagChanged) {
4314 + this._triggerCountryChange();
4315 + }
4316 + }
4317 + }, {
4318 + key: "_closeDropdown",
4319 + value: function _closeDropdown() {
4320 + this.countryList.classList.add("iti__hide");
4321 + this.selectedFlag.setAttribute("aria-expanded", "false");
4322 + // update the arrow
4323 + this.dropdownArrow.classList.remove("iti__arrow--up");
4324 + // unbind key events
4325 + document.removeEventListener("keydown", this._handleKeydownOnDropdown);
4326 + document.documentElement.removeEventListener("click", this._handleClickOffToClose);
4327 + this.countryList.removeEventListener("mouseover", this._handleMouseoverCountryList);
4328 + this.countryList.removeEventListener("click", this._handleClickCountryList);
4329 + // remove menu from container
4330 + if (this.options.dropdownContainer) {
4331 + if (!this.isMobile) window.removeEventListener("scroll", this._handleWindowScroll);
4332 + if (this.dropdown.parentNode) this.dropdown.parentNode.removeChild(this.dropdown);
4333 + }
4334 + this._trigger("close:countrydropdown");
4335 + }
4336 + }, {
4337 + key: "_scrollTo",
4338 + value: function _scrollTo(element, middle) {
4339 + var container = this.countryList;
4340 + // windowTop from https://stackoverflow.com/a/14384091/217866
4341 + var windowTop = window.pageYOffset || document.documentElement.scrollTop;
4342 + var containerHeight = container.offsetHeight;
4343 + var containerTop = container.getBoundingClientRect().top + windowTop;
4344 + var containerBottom = containerTop + containerHeight;
4345 + var elementHeight = element.offsetHeight;
4346 + var elementTop = element.getBoundingClientRect().top + windowTop;
4347 + var elementBottom = elementTop + elementHeight;
4348 + var newScrollTop = elementTop - containerTop + container.scrollTop;
4349 + var middleOffset = containerHeight / 2 - elementHeight / 2;
4350 + if (elementTop < containerTop) {
4351 + // scroll up
4352 + if (middle) newScrollTop -= middleOffset;
4353 + container.scrollTop = newScrollTop;
4354 + } else if (elementBottom > containerBottom) {
4355 + // scroll down
4356 + if (middle) newScrollTop += middleOffset;
4357 + var heightDifference = containerHeight - elementHeight;
4358 + container.scrollTop = newScrollTop - heightDifference;
4359 + }
4360 + }
4361 + }, {
4362 + key: "_updateDialCode",
4363 + value: function _updateDialCode(newDialCodeBare, hasSelectedListItem) {
4364 + var inputVal = this.telInput.value;
4365 + // save having to pass this every time
4366 + var newDialCode = "+".concat(newDialCodeBare);
4367 + var newNumber;
4368 + if (inputVal.charAt(0) === "+") {
4369 + // there's a plus so we're dealing with a replacement (doesn't matter if nationalMode or not)
4370 + var prevDialCode = this._getDialCode(inputVal);
4371 + if (prevDialCode) {
4372 + // current number contains a valid dial code, so replace it
4373 + newNumber = inputVal.replace(prevDialCode, newDialCode);
4374 + } else {
4375 + // current number contains an invalid dial code, so ditch it
4376 + // (no way to determine where the invalid dial code ends and the rest of the number begins)
4377 + newNumber = newDialCode;
4378 + }
4379 + } else if (this.options.nationalMode || this.options.separateDialCode) {
4380 + // don't do anything
4381 + return;
4382 + } else {
4383 + // nationalMode is disabled
4384 + if (inputVal) {
4385 + // there is an existing value with no dial code: prefix the new dial code
4386 + newNumber = newDialCode + inputVal;
4387 + } else if (hasSelectedListItem || !this.options.autoHideDialCode) {
4388 + // no existing value and either they've just selected a list item, or autoHideDialCode is
4389 + // disabled: insert new dial code
4390 + newNumber = newDialCode;
4391 + } else {
4392 + return;
4393 + }
4394 + }
4395 + this.telInput.value = newNumber;
4396 + }
4397 + }, {
4398 + key: "_getDialCode",
4399 + value: function _getDialCode(number, includeAreaCode) {
4400 + var dialCode = "";
4401 + // only interested in international numbers (starting with a plus)
4402 + if (number.charAt(0) === "+") {
4403 + var numericChars = "";
4404 + // iterate over chars
4405 + for (var i = 0; i < number.length; i++) {
4406 + var c = number.charAt(i);
4407 + // if char is number (https://stackoverflow.com/a/8935649/217866)
4408 + if (!isNaN(parseInt(c, 10))) {
4409 + numericChars += c;
4410 + // if current numericChars make a valid dial code
4411 + if (includeAreaCode) {
4412 + if (this.countryCodes[numericChars]) {
4413 + // store the actual raw string (useful for matching later)
4414 + dialCode = number.substr(0, i + 1);
4415 + }
4416 + } else {
4417 + if (this.dialCodes[numericChars]) {
4418 + dialCode = number.substr(0, i + 1);
4419 + // if we're just looking for a dial code, we can break as soon as we find one
4420 + break;
4421 + }
4422 + }
4423 + // stop searching as soon as we can - in this case when we hit max len
4424 + if (numericChars.length === this.countryCodeMaxLen) {
4425 + break;
4426 + }
4427 + }
4428 + }
4429 + }
4430 + return dialCode;
4431 + }
4432 + }, {
4433 + key: "_getFullNumber",
4434 + value: function _getFullNumber() {
4435 + var val = this.telInput.value.trim();
4436 + var dialCode = this.selectedCountryData.dialCode;
4437 + var prefix;
4438 + var numericVal = this._getNumeric(val);
4439 + if (this.options.separateDialCode && val.charAt(0) !== "+" && dialCode && numericVal) {
4440 + // when using separateDialCode, it is visible so is effectively part of the typed number
4441 + prefix = "+".concat(dialCode);
4442 + } else {
4443 + prefix = "";
4444 + }
4445 + return prefix + val;
4446 + }
4447 + }, {
4448 + key: "_beforeSetNumber",
4449 + value: function _beforeSetNumber(originalNumber) {
4450 + var number = originalNumber;
4451 + if (this.options.separateDialCode) {
4452 + var dialCode = this._getDialCode(number);
4453 + // if there is a valid dial code
4454 + if (dialCode) {
4455 + // in case _getDialCode returned an area code as well
4456 + dialCode = "+".concat(this.selectedCountryData.dialCode);
4457 + // a lot of numbers will have a space separating the dial code and the main number, and
4458 + // some NANP numbers will have a hyphen e.g. +1 684-733-1234 - in both cases we want to get
4459 + // rid of it
4460 + // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc
4461 + var start = number[dialCode.length] === " " || number[dialCode.length] === "-" ? dialCode.length + 1 : dialCode.length;
4462 + number = number.substr(start);
4463 + }
4464 + }
4465 + return this._cap(number);
4466 + }
4467 + }, {
4468 + key: "_triggerCountryChange",
4469 + value: function _triggerCountryChange() {
4470 + this._trigger("countrychange");
4471 + }
4472 + }, {
4473 + key: "handleAutoCountry",
4474 + value: function handleAutoCountry() {
4475 + if (this.options.initialCountry === "auto") {
4476 + // we must set this even if there is an initial val in the input: in case the initial val is
4477 + // invalid and they delete it - they should see their auto country
4478 + this.defaultCountry = window.intlTelInputGlobals.autoCountry;
4479 + // if there's no initial value in the input, then update the flag
4480 + if (!this.telInput.value) {
4481 + this.setCountry(this.defaultCountry);
4482 + }
4483 + this.resolveAutoCountryPromise();
4484 + }
4485 + }
4486 + }, {
4487 + key: "handleUtils",
4488 + value: function handleUtils() {
4489 + // if the request was successful
4490 + if (window.intlTelInputUtils) {
4491 + // if there's an initial value in the input, then format it
4492 + if (this.telInput.value) {
4493 + this._updateValFromNumber(this.telInput.value);
4494 + }
4495 + this._updatePlaceholder();
4496 + }
4497 + this.resolveUtilsScriptPromise();
4498 + }
4499 + }, {
4500 + key: "destroy",
4501 + value: function destroy() {
4502 + var form = this.telInput.form;
4503 + if (this.options.allowDropdown) {
4504 + // make sure the dropdown is closed (and unbind listeners)
4505 + this._closeDropdown();
4506 + this.selectedFlag.removeEventListener("click", this._handleClickSelectedFlag);
4507 + this.flagsContainer.removeEventListener("keydown", this._handleFlagsContainerKeydown);
4508 + // label click hack
4509 + var label = this._getClosestLabel();
4510 + if (label) label.removeEventListener("click", this._handleLabelClick);
4511 + }
4512 + // unbind hiddenInput listeners
4513 + if (this.hiddenInput && form) form.removeEventListener("submit", this._handleHiddenInputSubmit);
4514 + // unbind autoHideDialCode listeners
4515 + if (this.options.autoHideDialCode) {
4516 + if (form) form.removeEventListener("submit", this._handleSubmitOrBlurEvent);
4517 + this.telInput.removeEventListener("blur", this._handleSubmitOrBlurEvent);
4518 + }
4519 + // unbind key events, and cut/paste events
4520 + this.telInput.removeEventListener("keyup", this._handleKeyupEvent);
4521 + this.telInput.removeEventListener("cut", this._handleClipboardEvent);
4522 + this.telInput.removeEventListener("paste", this._handleClipboardEvent);
4523 + // remove attribute of id instance: data-intl-tel-input-id
4524 + this.telInput.removeAttribute("data-intl-tel-input-id");
4525 + // remove markup (but leave the original input)
4526 + var wrapper = this.telInput.parentNode;
4527 + wrapper.parentNode.insertBefore(this.telInput, wrapper);
4528 + wrapper.parentNode.removeChild(wrapper);
4529 + delete window.intlTelInputGlobals.instances[this.id];
4530 + }
4531 + }, {
4532 + key: "getExtension",
4533 + value: function getExtension() {
4534 + if (window.intlTelInputUtils) {
4535 + return intlTelInputUtils.getExtension(this._getFullNumber(), this.selectedCountryData.iso2);
4536 + }
4537 + return "";
4538 + }
4539 + }, {
4540 + key: "getNumber",
4541 + value: function getNumber(format) {
4542 + if (window.intlTelInputUtils) {
4543 + var iso2 = this.selectedCountryData.iso2;
4544 + return intlTelInputUtils.formatNumber(this._getFullNumber(), iso2, format);
4545 + }
4546 + return "";
4547 + }
4548 + }, {
4549 + key: "getNumberType",
4550 + value: function getNumberType() {
4551 + if (window.intlTelInputUtils) {
4552 + return intlTelInputUtils.getNumberType(this._getFullNumber(), this.selectedCountryData.iso2);
4553 + }
4554 + return -99;
4555 + }
4556 + }, {
4557 + key: "getSelectedCountryData",
4558 + value: function getSelectedCountryData() {
4559 + return this.selectedCountryData;
4560 + }
4561 + }, {
4562 + key: "getValidationError",
4563 + value: function getValidationError() {
4564 + if (window.intlTelInputUtils) {
4565 + var iso2 = this.selectedCountryData.iso2;
4566 + return intlTelInputUtils.getValidationError(this._getFullNumber(), iso2);
4567 + }
4568 + return -99;
4569 + }
4570 + }, {
4571 + key: "isValidNumber",
4572 + value: function isValidNumber() {
4573 + var val = this._getFullNumber().trim();
4574 + var countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "";
4575 + return window.intlTelInputUtils ? intlTelInputUtils.isValidNumber(val, countryCode) : null;
4576 + }
4577 + }, {
4578 + key: "setCountry",
4579 + value: function setCountry(originalCountryCode) {
4580 + var countryCode = originalCountryCode.toLowerCase();
4581 + // check if already selected
4582 + if (!this.selectedFlagInner.classList.contains("iti__".concat(countryCode))) {
4583 + this._setFlag(countryCode);
4584 + this._updateDialCode(this.selectedCountryData.dialCode, false);
4585 + this._triggerCountryChange();
4586 + }
4587 + }
4588 + }, {
4589 + key: "setNumber",
4590 + value: function setNumber(number) {
4591 + // we must update the flag first, which updates this.selectedCountryData, which is used for
4592 + // formatting the number before displaying it
4593 + var flagChanged = this._updateFlagFromNumber(number);
4594 + this._updateValFromNumber(number);
4595 + if (flagChanged) {
4596 + this._triggerCountryChange();
4597 + }
4598 + }
4599 + }, {
4600 + key: "setPlaceholderNumberType",
4601 + value: function setPlaceholderNumberType(type) {
4602 + this.options.placeholderNumberType = type;
4603 + this._updatePlaceholder();
4604 + }
4605 + } ]);
4606 + return Iti;
4607 + }();
4608 + /********************
4609 + * STATIC METHODS
4610 + ********************/
4611 + // get the country data object
4612 + intlTelInputGlobals.getCountryData = function() {
4613 + return allCountries;
4614 + };
4615 + // inject a <script> element to load utils.js
4616 + var injectScript = function injectScript(path, handleSuccess, handleFailure) {
4617 + // inject a new script element into the page
4618 + var script = document.createElement("script");
4619 + script.onload = function() {
4620 + forEachInstance("handleUtils");
4621 + if (handleSuccess) handleSuccess();
4622 + };
4623 + script.onerror = function() {
4624 + forEachInstance("rejectUtilsScriptPromise");
4625 + if (handleFailure) handleFailure();
4626 + };
4627 + script.className = "iti-load-utils";
4628 + script.async = true;
4629 + script.src = path;
4630 + document.body.appendChild(script);
4631 + };
4632 + // load the utils script
4633 + intlTelInputGlobals.loadUtils = function(path) {
4634 + // 2 options:
4635 + // 1) not already started loading (start)
4636 + // 2) already started loading (do nothing - just wait for the onload callback to fire, which will
4637 + // trigger handleUtils on all instances, invoking their resolveUtilsScriptPromise functions)
4638 + if (!window.intlTelInputUtils && !window.intlTelInputGlobals.startedLoadingUtilsScript) {
4639 + // only do this once
4640 + window.intlTelInputGlobals.startedLoadingUtilsScript = true;
4641 + // if we have promises, then return a promise
4642 + if (typeof Promise !== "undefined") {
4643 + return new Promise(function(resolve, reject) {
4644 + return injectScript(path, resolve, reject);
4645 + });
4646 + }
4647 + injectScript(path);
4648 + }
4649 + return null;
4650 + };
4651 + // default options
4652 + intlTelInputGlobals.defaults = defaults;
4653 + // version
4654 + intlTelInputGlobals.version = "17.0.16";
4655 + // convenience wrapper
4656 + return function(input, options) {
4657 + var iti = new Iti(input, options);
4658 + iti._init();
4659 + input.setAttribute("data-intl-tel-input-id", iti.id);
4660 + window.intlTelInputGlobals.instances[iti.id] = iti;
4661 + return iti;
4662 + };
4663 + }();
4664 +});
4665 +},{}],20:[function(require,module,exports){
4666 +/**
4667 + * Exposing intl-tel-input as a component
4668 + */
4669 +module.exports = require("./build/js/intlTelInput");
4670 +
4671 +},{"./build/js/intlTelInput":19}],21:[function(require,module,exports){
2350 4672 (function (process){
2351 4673 /**
2352 4674 * Memize options object.
2353 4675 *
@@ -2516,9 +4838,9 @@
2516 4838
2517 4839 module.exports = memize;
2518 4840
2519 4841 }).call(this,require('_process'))
2520 -},{"_process":16}],16:[function(require,module,exports){
4842 +},{"_process":22}],22:[function(require,module,exports){
2521 4843 // shim for using process in browser
2522 4844 var process = module.exports = {};
2523 4845
2524 4846 // cached from whatever global is present so that test runners that stub it
@@ -2702,9 +5024,9 @@
2702 5024 throw new Error('process.chdir is not supported');
2703 5025 };
2704 5026 process.umask = function() { return 0; };
2705 5027
2706 -},{}],17:[function(require,module,exports){
5028 +},{}],23:[function(require,module,exports){
2707 5029 'use strict';
2708 5030
2709 5031 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
2710 5032
@@ -2923,5 +5245,5 @@
2923 5245 };
2924 5246
2925 5247 module.exports = Tannin;
2926 5248
2927 -},{"@tannin/plural-forms":8}]},{},[2]);
5249 +},{"@tannin/plural-forms":12}]},{},[3]);