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
sellkit / assets / dist / js / elementor-init.js

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

5,262 lines 206.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2 "use strict";
3
4 Object.defineProperty(exports, "__esModule", {
5 value: true
6 });
7 exports["default"] = 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;
47 exports["default"] = _default;
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
59 var _i18n = require("@wordpress/i18n");
60
61 var _checkoutSettings = _interopRequireDefault(require("./checkout-settings"));
62
63 /* eslint no-undef: 0 */
64 // Temporary turned off no undefined variable for localStorage
65 var $ = jQuery;
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 */
73
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
82 var parent = $('#sellkit-checkout-multistep-inner-wrap');
83 var sidebar = $('.sellkit-checkout-right-column');
84 var first = $('.sellkit-multistep-checkout-first');
85 var second = $('.sellkit-multistep-checkout-second');
86 var third = $('.sellkit-multistep-checkout-third');
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
99 $('.go-to-shipping').on('click', function () {
100 // Checks if required fields are filled.
101 var requiredFieldsError = checkRequiredFields();
102
103 if (true === requiredFieldsError) {
104 return;
105 }
106
107 secondStepHeader();
108 first.hide();
109
110 if ($('.sellkit-one-page-shipping-methods').children().length > 0) {
111 second.show();
112 } else {
113 third.show();
114 } //Fix Header & wrapper height.
115
116
117 parent.css('height', 'auto');
118 second.css('height', 'auto');
119 second.css('min-height', $('.sellkit-checkout-left-column').height());
120 $('.multistep-headers').css('height', 'auto'); // Manage Breadcrumb.
121
122 breadcrumb.find('.information').removeClass('current').addClass('blue-line');
123 breadcrumb.find('.shipping').addClass('current').removeClass('inactive');
124 $('html, body').animate({
125 scrollTop: $('.sellkit-checkout-left-column').offset().top
126 }, 500);
127 });
128 $('.go-to-first').on('click', function () {
129 first.show();
130 third.hide();
131 second.hide();
132 parent.css('height', 'auto');
133 first.css('height', 'auto');
134 sidebar.css('background-color', 'transparent'); // Manage Breadcrumb.
135
136 breadcrumb.find('.information').removeClass('blue-line').addClass('current');
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);
141 });
142 $('.go-to-payment').on('click', function () {
143 // Checks if required fields are filled.
144 var requiredFieldsError = checkRequiredFields();
145
146 if (true === requiredFieldsError) {
147 return;
148 }
149
150 secondStepHeader();
151 second.hide();
152 first.hide();
153 third.show();
154 $('.sellkit-one-page-checkout-payment-heading').css('margin-top', '0px');
155 sidebar.css('background-color', 'transparent'); //Fix Header & wrapper height.
156
157 parent.css('height', 'auto');
158 third.css('height', 'auto');
159 $('.multistep-headers').css('height', 'auto'); // Manage Breadcrumb.
160
161 breadcrumb.find('.shipping').addClass('blue-line').removeClass('current');
162 breadcrumb.find('.payment').addClass('current').removeClass('inactive');
163 $('html, body').animate({
164 scrollTop: $('.sellkit-checkout-left-column').offset().top
165 }, 500);
166 });
167 $('.go-to-second , .go-to-second-header').on('click', function () {
168 // Checks if required fields are filled.
169 var requiredFieldsError = checkRequiredFields();
170
171 if (true === requiredFieldsError) {
172 return;
173 }
174
175 if ($('.sellkit-one-page-shipping-methods').children().length > 0) {
176 second.show();
177 first.hide();
178 } else {
179 second.hide();
180 first.show();
181 }
182
183 third.hide();
184 parent.css('height', 'auto');
185 second.css('height', 'auto');
186 second.css('height', $('.sellkit-checkout-left-column').height());
187 $('.multistep-headers').css('height', 'auto'); // Manage Breadcrumb.
188
189 breadcrumb.find('.shipping').addClass('current').removeClass('blue-line');
190 breadcrumb.find('.payment').removeClass('current').addClass('inactive');
191 $('html, body').animate({
192 scrollTop: $('.sellkit-checkout-left-column').offset().top
193 }, 500);
194 }); //Inject login wrapper & functionality.
195
196 emailProcess();
197 LoginProcess(); // Billing method toggle.
198
199 manageBillingMethod(); // Mobile summary.
200
201 mobileSummary(); // Breadcrumb click management.
202
203 breadcrumbLinks(); // Fix shipping & billing fields space issue.
204
205 fixFieldSpaceIssue(); // Fields focus.
206
207 organizeFieldsonLoad();
208 fieldFocus();
209 jQuery(document).ajaxComplete(function () {
210 // Run after ajax
211 sellkitCheckoutUpdateCartItem();
212 applyCoupon();
213 couponToggle();
214 fixGatewayListUi();
215 sellkitDetectShippingMethodChange();
216 }); // Fix the payment gateways divider issue.
217
218 fixGatewayListUi(); //Run when page loads.
219
220 sellkitCheckoutUpdateCartItem(); // Apply coupon.
221
222 applyCoupon(); // Coupon toggle.
223
224 couponToggle(); // Postal code autocomplete.
225
226 sellkitPostalCodeAutocomplete(); // Klarma checkout integration.
227
228 sellkitKlarmaIntegration(); // Fix state change issue on load.
229
230 fixStateIssueOnLoad(); // Shipping & billing country & state update on change
231
232 fixClientCountryOnReload(); // Configure bundled products.
233
234 sellkitCheckoutConfigureBundleProducts(); // Order bump.
235
236 sellkitCheckoutOrderBump(); // Sellkit after ajax call is completed.
237
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();
253 }
254
255 var emailProcess = function emailProcess() {
256 var emailField = $('#billing_email');
257 var searchIcon = $('.jupiter-checkout-widget-email-search');
258 var errorText = $('.sellkit-checkout-widget-email-error');
259 var emptyError = $('.sellkit-checkout-widget-email-empty');
260 var passwordWrap = $('.sellkit-checkout-widget-password-field');
261 var passwordField = passwordWrap.find('#register_pass');
262 var usernameWrap = $('.sellkit-checkout-widget-username-field');
263 var usernameField = usernameWrap.find('input');
264 var loginBtn = $('.login-wrapper');
265 var createBox = $('.create-desc');
266 var createCheck = $('#createaccount');
267 var emailCheckTimer = null;
268 var usernameCheckTimer = null;
269
270 var getCurrentEmailValue = function getCurrentEmailValue() {
271 return $('#billing_email').val();
272 };
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
285 if (_.isEmpty(emailAddress)) {
286 emptyError.show().css('display', 'inline-block');
287 errorText.hide();
288 createBox.css('display', 'none');
289 passwordWrap.addClass('login_hidden_section');
290 usernameWrap.addClass('login_hidden_section');
291 loginBtn.addClass('login_hidden_section');
292 searchIcon.hide();
293 return;
294 }
295
296 var check = validateEmailAddress(emailAddress);
297 $('#createaccount').prop('checked', false);
298
299 if (false === check) {
300 errorText.show().css('display', 'inline-block');
301 emptyError.hide();
302 createBox.css('display', 'none');
303 passwordWrap.addClass('login_hidden_section');
304 usernameWrap.addClass('login_hidden_section');
305 loginBtn.addClass('login_hidden_section');
306 searchIcon.hide();
307 return;
308 }
309
310 emptyError.hide();
311 errorText.hide();
312 searchIcon.show().css('display', 'inline-block');
313 wp.ajax.post({
314 action: 'sellkit_checkout_ajax_handler',
315 sub_action: 'search_for_email',
316 email: emailAddress,
317 dataType: 'json',
318 nonce: sellkit_elementor.nonce
319 }).done(function () {
320 if (emailAddress !== getCurrentEmailValue()) {
321 return;
322 }
323
324 successResultEmailCheck();
325 }).fail(function () {
326 if (emailAddress !== getCurrentEmailValue()) {
327 return;
328 }
329
330 errorResultEmailCheck();
331 });
332 }, 500);
333 });
334 usernameField.on('input change', function () {
335 var inputEl = this;
336 clearTimeout(usernameCheckTimer);
337 usernameCheckTimer = setTimeout(function () {
338 var userValue = $(inputEl).val();
339 wp.ajax.post({
340 action: 'sellkit_checkout_ajax_handler',
341 sub_action: 'search_for_username',
342 user: userValue,
343 dataType: 'json',
344 nonce: sellkit_elementor.nonce
345 }).done(function () {
346 if (userValue !== getCurrentUsernameValue()) {
347 return;
348 }
349
350 $('.sellkit-checkout-widget-username-error').hide();
351 }).fail(function () {
352 if (userValue !== getCurrentUsernameValue()) {
353 return;
354 }
355
356 $('.sellkit-checkout-widget-username-error').show();
357 });
358 }, 500);
359 }); // If user is going to create account show password and username fields if exists.
360
361 createCheck.on('click', function () {
362 if ($(this).is(':checked')) {
363 if (passwordField.length > 0) {
364 passwordWrap.removeClass('login_hidden_section');
365 }
366
367 if (usernameField.length > 0) {
368 usernameWrap.removeClass('login_hidden_section');
369 }
370 } else {
371 usernameWrap.addClass('login_hidden_section');
372 passwordWrap.addClass('login_hidden_section');
373 }
374 });
375
376 var successResultEmailCheck = function successResultEmailCheck() {
377 createBox.css('display', 'none');
378 passwordWrap.removeClass('login_hidden_section');
379 usernameWrap.addClass('login_hidden_section');
380 loginBtn.removeClass('login_hidden_section');
381 searchIcon.hide();
382 };
383
384 var errorResultEmailCheck = function errorResultEmailCheck() {
385 createBox.css('display', 'flex');
386 passwordWrap.addClass('login_hidden_section');
387 usernameWrap.addClass('login_hidden_section');
388 loginBtn.addClass('login_hidden_section');
389 searchIcon.hide();
390 };
391 };
392
393 var validateEmailAddress = function validateEmailAddress(emailAddress) {
394 var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
395 return pattern.test(emailAddress);
396 };
397
398 var LoginProcess = function LoginProcess() {
399 var submitBtn = $('.login-submit');
400 var email = $('.login-mail');
401 var pass = $('.login-pass');
402 var result = $('.login-result');
403 submitBtn.on('click', function () {
404 if ('' === email.val() || '' === pass.val()) {
405 result.text((0, _i18n.__)('Both Field required.', 'sellkit')).css({
406 color: 'red'
407 });
408 return;
409 }
410
411 wp.ajax.post({
412 beforeSend: function beforeSend() {
413 $('.login-submit').css('opacity', '0.5');
414 },
415 action: 'sellkit_checkout_ajax_handler',
416 sub_action: 'auth_user',
417 email: email.val(),
418 pass: pass.val(),
419 nonce: sellkit_elementor.nonce
420 }).done(function () {
421 location.reload();
422 }).fail(function (response) {
423 $('.login-submit').css('opacity', '1');
424 $('.login-result').html(response).css({
425 color: 'red'
426 });
427 });
428 });
429 };
430
431 var secondStepHeader = function secondStepHeader() {
432 var email = $('#billing_email');
433 $('.multistep-headers > .info-a > div > .mail').text(email.val());
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');
440 var finalAddress = postcode.val() ? ', ' + postcode.val() : '';
441 finalAddress += addressB.val() ? ', ' + addressB.val() : '';
442 finalAddress += addressA.val() ? ', ' + addressA.val() : '';
443 finalAddress += city.val() ? ', ' + city.val() : '';
444 finalAddress += state.val() ? ', ' + state.val() : '';
445 finalAddress += countryValue && !countryValue.includes('/') ? ', ' + countryValue : '';
446
447 if (',' === finalAddress.charAt(0)) {
448 finalAddress = finalAddress.substring(1);
449 }
450
451 $('.multistep-headers > .info-b > div > .address').text(finalAddress);
452 var method = $('#shipping_method').find('input[type=radio]:checked');
453 var methodTxt = method.siblings('.labels').text();
454 $('.multistep-headers > .info-c > div > .method').text(methodTxt);
455 };
456
457 var manageBillingMethod = function manageBillingMethod() {
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 */
468
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();
521 });
522 $(document.body).off('click.sellkitBillMethodDiff', '.sellkit-one-page-checkout-billing .method-b').on('click.sellkitBillMethodDiff', '.sellkit-one-page-checkout-billing .method-b', function () {
523 $('.inner_wrapper').css('height', 'auto');
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);
534 });
535 };
536
537 var mobileSummary = function mobileSummary() {
538 if ($(window).width() < 600) {
539 $('#order_review').addClass('sellkit-mobile-multistep-order-summary');
540 }
541
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');
543 var wrap = $('.summary_toggle');
544 toggleBtn.on('click', function () {
545 $('#order_review').toggle();
546
547 if ('Hide order summary' === wrap.find('.title').text()) {
548 wrap.find('.title').text((0, _i18n.__)('Show order summary', 'sellkit'));
549 wrap.find('.sellkit-checkout-summary-toggle-up').hide();
550 wrap.find('.sellkit-checkout-summary-toggle-down').show();
551 wrap.css('border-bottom-width', '0px');
552 } else {
553 wrap.find('.title').text((0, _i18n.__)('Hide order summary', 'sellkit'));
554 wrap.find('.sellkit-checkout-summary-toggle-up').show();
555 wrap.find('.sellkit-checkout-summary-toggle-down').hide();
556 wrap.css('border-bottom-width', '1px');
557 }
558
559 var parent = $('#sellkit-checkout-multistep-inner-wrap');
560 parent.css('height', 'auto');
561 });
562 };
563
564 var fieldFocus = function fieldFocus() {
565 var $fields = $('.sellkit-checkout-local-fields').find('input, select, hidden, textarea, #sellkit-billing_state ,#sellkit-shipping_state, .validate-email');
566 $fields.each(function () {
567 var _this = this;
568
569 var miniTitle = $(this).parent().parent().parent().find('.mini-title');
570 var $thisValue = $(this).val(); // On load.
571
572 if (!_.isEmpty($thisValue)) {
573 $(this).addClass('filled').removeClass('empty');
574 miniTitle.css({
575 display: 'flex'
576 });
577 } // On change/focusOut
578
579
580 $(this).on('change input focusout', function (e) {
581 var changedValue = $(_this).val();
582
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');
587 } else {
588 $(_this).addClass('empty');
589 $(_this).removeClass('filled');
590 $(_this).parents('.sellkit-widget-checkout-fields').find('.mini-title').hide();
591 } // On focusout validate fields.
592
593
594 if ('focusout' === e.type) {
595 FieldsMiniTitles($(_this), 'focusout');
596 var parent = $(_this).parent().parent().parent(); // Required validation. return if required field rule is not followed.
597
598 if (parent.hasClass('validate-required')) {
599 if ('INPUT' === _this.nodeName && 'checkbox' === $(_this).attr('type')) {
600 if (!_this.checked) {
601 parent.find('.sellkit-required-validation').css('display', 'inline-flex');
602 return;
603 }
604 }
605
606 if (_.isEmpty($(_this).val())) {
607 parent.find('.sellkit-required-validation').css('display', 'inline-flex');
608 return;
609 }
610
611 parent.find('.sellkit-required-validation').css('display', 'none');
612 } // Required validation of this field if exists, passed successfully. now postcode validation.
613
614
615 if (parent.hasClass('sellkit-checkout-fields-validation-postcode')) {
616 var postcodeVal = $(_this).val();
617
618 if (_.isEmpty(postcodeVal)) {
619 return;
620 } // Check field type to get related country value. we can't validate without country code.
621
622
623 var postcodeName = $(_this).attr('name');
624 var postcodeCountry = $('#billing_country');
625
626 if (postcodeName.includes('shipping')) {
627 postcodeCountry = $('#shipping_country');
628 } // Keep validating only if country field is present.
629
630
631 if (!postcodeCountry.length) {
632 return;
633 }
634
635 var countryCode = postcodeCountry.val();
636
637 if (_.isEmpty(countryCode)) {
638 parent.find('.sellkit-checkout-field-global-errors').show().text((0, _i18n.__)('Please select a country.', 'sellkit'));
639 return;
640 } else {
641 // eslint-disable-line
642 parent.find('.sellkit-checkout-field-global-errors').hide().text('');
643 }
644
645 parent.find('.sellkit-checkout-field-global-errors').hide().text('');
646 postcodeValidation(postcodeVal, countryCode, $(_this));
647 } // Phone validation using woocommerce way.
648
649
650 if (parent.hasClass('sellkit-checkout-fields-validation-phone')) {
651 var phone = $(_this).val();
652
653 if (_.isEmpty(phone)) {
654 return;
655 }
656
657 phoneNumberValidation(phone, $(_this));
658 }
659 }
660
661 if ('change' === e.type && ('billing_country' === $(_this).attr('id') || 'shipping_country' === $(_this).attr('id'))) {
662 var _countryCode = $(_this).val();
663
664 var states = wcCountries[_countryCode];
665 var state = 'sellkit-shipping_state';
666
667 if ('billing_country' === $(_this).attr('id')) {
668 state = 'sellkit-billing_state';
669 }
670
671 var stateField = document.getElementById(state);
672
673 if (_.isNull(stateField)) {
674 return;
675 }
676
677 if (!_.isObject(states)) {
678 return;
679 }
680
681 $(stateField).empty();
682
683 for (var keys in states) {
684 var option = document.createElement('option');
685 option.value = keys;
686 option.innerHTML = states[keys];
687 stateField.appendChild(option);
688 }
689 }
690 });
691 });
692 };
693
694 var breadcrumbLinks = function breadcrumbLinks() {
695 var $parent = $('.sellkit-checkout-widget-breadcrumb-mobile, .sellkit-checkout-widget-breadcrumb-desktop');
696 var detector = $('.sellkit-multistep-checkout-first');
697 $parent.find('.information').on('click', function () {
698 $('.go-to-first').click();
699 });
700 $parent.find('.shipping').on('click', function () {
701 var display = detector.css('display');
702
703 if ('none' === display) {
704 $('.go-to-second').click();
705 } else {
706 $('.go-to-shipping').click();
707 }
708 });
709 $parent.find('.payment').on('click', function () {
710 $('.go-to-payment').click();
711 $('.information').removeClass('current').addClass('inactive, blue-line');
712 });
713 };
714
715 var fixFieldSpaceIssue = function fixFieldSpaceIssue() {
716 $(function () {
717 var shippingFields = $('#customer_details .sellkit-widget-checkout-fields');
718 shippingFields.each(function (index) {
719 if ($(shippingFields[index + 1]).length) {
720 var next = $(shippingFields[index + 1]).offset().top;
721 var current = $(shippingFields[index]).offset().top;
722
723 if (next > current) {
724 $(shippingFields[index]).addClass('sellkit-checkout-excluded-wrapper-fields');
725 }
726 } else {
727 $(shippingFields[index]).addClass('sellkit-checkout-excluded-wrapper-fields');
728 }
729 });
730 });
731 };
732
733 var organizeFieldsonLoad = function organizeFieldsonLoad() {
734 $(function () {
735 var fields = $('.sellkit-widget-checkout-fields').find('input, select, textarea');
736 fields.each(function () {
737 var tag = this.nodeName;
738
739 if ('SELECT' === tag) {
740 $(this).parent().parent().parent().addClass('sellkit-checkout-field-select');
741 }
742
743 FieldsMiniTitles($(this), 'load');
744 });
745 });
746 $(document).on('mousemove change', function (e) {
747 var fields = $('.sellkit-widget-checkout-fields').find('input, select, textarea');
748 fields.each(function () {
749 var tag = this.nodeName;
750
751 if ('SELECT' === tag) {
752 $(this).parent().parent().parent().addClass('sellkit-checkout-field-select');
753 }
754
755 FieldsMiniTitles($(this), e.type);
756 });
757 });
758 };
759
760 var FieldsMiniTitles = function FieldsMiniTitles(field, event) {
761 if (field.attr('multiple')) {
762 field.addClass('filled');
763 field.removeClass('empty');
764 field.parents('.sellkit-widget-checkout-fields').find('.mini-title').css('display', 'flex');
765 return;
766 }
767
768 if (_.isEmpty(field.val())) {
769 field.addClass('empty');
770 field.removeClass('filled');
771 field.parents('.sellkit-widget-checkout-fields').find('.mini-title').css('display', 'none');
772 } else {
773 field.addClass('filled');
774 field.removeClass('empty');
775 field.parents('.sellkit-widget-checkout-fields').find('.mini-title').css('display', 'flex');
776 } // Hide wrapper if field is hidden
777
778
779 if ('hidden' === field.attr('type')) {
780 field.parents('.sellkit-widget-checkout-fields').addClass('sellkit-hide-completely');
781 }
782
783 if ('change' !== event) {
784 return;
785 } // Hide Billing state wrapper when these fields are hidden.
786
787
788 if ('billing_country' === field.attr('id')) {
789 var $state = document.getElementById('sellkit-billing_state');
790
791 if (!_.isNull($state) && 'SELECT' === $state.nodeName && $('#sellkit-billing_state option').length < 1) {
792 var stateField = $('#sellkit-billing_state');
793 var parent = stateField.parent().parent().parent();
794 parent.removeClass('sellkit-checkout-field-select');
795 var placeholder = stateField.attr('placeholder');
796 var stateInput = document.createElement('input');
797 stateInput.setAttribute('type', 'text');
798 stateInput.setAttribute('id', 'sellkit-billing_state');
799 stateInput.setAttribute('name', 'billing_state');
800 stateInput.setAttribute('placeholder', placeholder); // Replace select field with text.
801
802 stateField.remove();
803 parent.find('.woocommerce-input-wrapper').append(stateInput);
804 }
805
806 var countryCode = field.val();
807 var states = wcCountries[countryCode];
808
809 if (!_.isNull($state) && 'INPUT' === $state.nodeName && !_.isEmpty(states)) {
810 var _stateField = $('#sellkit-billing_state');
811
812 var _placeholder = _stateField.attr('placeholder');
813
814 var _parent = _stateField.parent().parent().parent();
815
816 _parent.addClass('sellkit-checkout-field-select');
817
818 if (_.isUndefined(_placeholder) || _.isEmpty(_placeholder)) {
819 _placeholder = (0, _i18n.__)('State', 'sellkit');
820 } // Replace text field with select field.
821
822
823 _stateField.remove();
824
825 var stateSelect = document.createElement('select');
826 stateSelect.setAttribute('name', 'billing_state');
827 stateSelect.setAttribute('id', 'sellkit-billing_state');
828 stateSelect.setAttribute('placeholder', _placeholder);
829 stateSelect.addEventListener('change', function () {
830 sellkitSetAddressDetails();
831 });
832
833 for (var keys in states) {
834 var option = document.createElement('option');
835 option.value = keys;
836 option.innerHTML = states[keys];
837 stateSelect.appendChild(option);
838 }
839
840 _parent.find('.woocommerce-input-wrapper').append(stateSelect);
841 }
842 } // Remove select icon when field is text for the shipping/billing state fields.
843
844
845 if ('shipping_country' === field.attr('id')) {
846 var _$state = document.getElementById('sellkit-shipping_state');
847
848 if (!_.isNull(_$state) && 'SELECT' === _$state.nodeName && $('#sellkit-shipping_state option').length < 1) {
849 var _stateField2 = $('#sellkit-shipping_state');
850
851 var _parent2 = _stateField2.parent().parent().parent();
852
853 _parent2.removeClass('sellkit-checkout-field-select');
854
855 var _placeholder2 = _stateField2.attr('placeholder');
856
857 var _stateInput = document.createElement('input');
858
859 _stateInput.setAttribute('type', 'text');
860
861 _stateInput.setAttribute('id', 'sellkit-shipping_state');
862
863 _stateInput.setAttribute('name', 'shipping_state');
864
865 _stateInput.setAttribute('placeholder', _placeholder2); // Replace select field with text.
866
867
868 _stateField2.remove();
869
870 _parent2.find('.woocommerce-input-wrapper').append(_stateInput);
871 }
872
873 var _countryCode2 = field.val();
874
875 var _states = wcCountries[_countryCode2];
876
877 if (!_.isNull(_$state) && 'INPUT' === _$state.nodeName && !_.isEmpty(_states)) {
878 var _stateField3 = $('#sellkit-shipping_state');
879
880 var _placeholder3 = _stateField3.attr('placeholder');
881
882 var _parent3 = _stateField3.parent().parent().parent();
883
884 _parent3.addClass('sellkit-checkout-field-select');
885
886 if (_.isUndefined(_placeholder3) || _.isEmpty(_placeholder3)) {
887 _placeholder3 = (0, _i18n.__)('State', 'sellkit');
888 } // Replace text field with select field.
889
890
891 _stateField3.remove();
892
893 var _stateSelect = document.createElement('select');
894
895 _stateSelect.setAttribute('name', 'shipping_state');
896
897 _stateSelect.setAttribute('id', 'sellkit-shipping_state');
898
899 _stateSelect.setAttribute('placeholder', _placeholder3);
900
901 _stateSelect.addEventListener('change', function () {
902 sellkitSetAddressDetails();
903 });
904
905 for (var _keys in _states) {
906 var _option = document.createElement('option');
907
908 _option.value = _keys;
909 _option.innerHTML = _states[_keys];
910
911 _stateSelect.appendChild(_option);
912 }
913
914 _parent3.find('.woocommerce-input-wrapper').append(_stateSelect);
915 }
916 }
917 };
918 /**
919 * Change cart item quantity.
920 *
921 * @since 1.2.5
922 */
923
924
925 var sellkitCheckoutUpdateCartItem = function sellkitCheckoutUpdateCartItem() {
926 $('.sellkit-one-page-checkout-product-qty').off('change').on('change', function () {
927 $(this).attr('readonly', true);
928 wp.ajax.post({
929 action: 'sellkit_checkout_ajax_handler',
930 sub_action: 'change_cart_item_qty',
931 qty: $(this).val(),
932 id: $(this).attr('data-id'),
933 mode: 'edit',
934 related_checkout: $('#sellkit_current_page_id').val(),
935 nonce: sellkit_elementor.nonce
936 }).always(function () {
937 $(document.body).trigger('update_checkout');
938 $('.sellkit-one-page-checkout-product-qty').attr('readonly', false);
939 });
940 });
941 var paymentMethod = $('.sellkit-one-page-checkout-payment-methods').find('input[name=payment_method]:checked');
942 paymentMethod.parent().parent().next().show();
943 $('.sellkit-one-page-pay-method').on('click', function () {
944 $('.sellkit_payment_box').hide();
945 $(this).parent().parent().next().show();
946 });
947 var count = $('.sellkit-checkout-widget-order-summary-tfoot').children().length;
948
949 if (count <= 3) {
950 $('.cart-subtotal td').css('padding-bottom', '8px');
951 $('.cart-subtotal th').css('padding-bottom', '8px');
952 }
953 };
954 /**
955 * Apply a coupon.
956 *
957 * @since 1.2.5
958 */
959
960
961 var applyCoupon = function applyCoupon() {
962 $('.sellkit-apply-coupon').off('click').on('click', function () {
963 wp.ajax.post({
964 beforeSend: function beforeSend() {
965 $('.jx-apply-coupon').css('opacity', 0.5);
966 },
967 action: 'sellkit_checkout_ajax_handler',
968 sub_action: 'apply_coupon',
969 code: jQuery('.sellkit-custom-coupon-form').find('.jx-coupon').val(),
970 nonce: sellkit_elementor.nonce
971 }).done(function () {
972 $(document.body).trigger('update_checkout');
973 $('.jx-apply-coupon').css('opacity', 1);
974 }).fail(function () {
975 $('.jx-apply-coupon').css('opacity', 1);
976 });
977 });
978 };
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 /**
1002 * Toggle coupon form on click event.
1003 *
1004 * @since 1.2.5
1005 */
1006
1007
1008 var couponToggle = function couponToggle() {
1009 if ($('.sellkit-coupon-toggle').length) {
1010 $('.sellkit-custom-coupon-form').css('display', 'none');
1011 }
1012
1013 $('.sellkit-coupon-toggle').off('click').on('click', function () {
1014 var direction = 'row';
1015 var status = $('.sellkit-custom-coupon-form').css('display');
1016 var displayValue = '';
1017
1018 if ($(window).width() < 600) {
1019 direction = 'column';
1020 }
1021
1022 if ('none' === status) {
1023 displayValue = 'inline-flex';
1024 } else {
1025 displayValue = 'none';
1026 }
1027
1028 $('.sellkit-custom-coupon-form').css({
1029 display: displayValue,
1030 flexDirection: direction
1031 });
1032 });
1033 };
1034 /**
1035 * Validate postcode in WooCommerce way.
1036 *
1037 * @param {string} postcode
1038 * @param {string} country
1039 * @param {Object} element
1040 */
1041
1042
1043 var postcodeValidation = function postcodeValidation(postcode, country, element) {
1044 var parentElement = element.attr('id');
1045 wp.ajax.post({
1046 action: 'sellkit_checkout_ajax_handler',
1047 sub_action: 'validate_postcode',
1048 post_code: postcode,
1049 country_code: country,
1050 parent: parentElement,
1051 nonce: sellkit_elementor.nonce
1052 }).done(function (response) {
1053 var field = $('#' + response);
1054 var parent = field.parent().parent().parent();
1055 parent.find('.sellkit-checkout-field-global-errors').hide().text('');
1056 }).fail(function (response) {
1057 var field = $('#' + response);
1058 var parent = field.parent().parent().parent();
1059 parent.find('.sellkit-checkout-field-global-errors').show().text((0, _i18n.__)('Postcode is not valid.', 'sellkit'));
1060 });
1061 };
1062 /**
1063 * Validate phone number in WooCommerce way.
1064 *
1065 * @param {string} phone
1066 * @param {Object} element
1067 */
1068
1069
1070 var phoneNumberValidation = function phoneNumberValidation(phone, element) {
1071 var parentElement = element.attr('id');
1072 wp.ajax.post({
1073 action: 'sellkit_checkout_ajax_handler',
1074 sub_action: 'validate_phone_number',
1075 phone_number: phone,
1076 parent: parentElement,
1077 nonce: sellkit_elementor.nonce
1078 }).done(function (response) {
1079 var field = $('#' + response);
1080 var parent = field.parent().parent().parent();
1081 parent.find('.sellkit-checkout-field-global-errors').hide().text('');
1082 }).fail(function (response) {
1083 var field = $('#' + response);
1084 var parent = field.parent().parent().parent();
1085 parent.find('.sellkit-checkout-field-global-errors').show().text((0, _i18n.__)('Phone number is not valid.', 'sellkit'));
1086 });
1087 };
1088 /**
1089 * Auto populate city and state fields using postcode by getting information from third api : https://api.zippopotam.us/.
1090 *
1091 * @since 1.2.5
1092 */
1093
1094
1095 var sellkitPostalCodeAutocomplete = function sellkitPostalCodeAutocomplete() {
1096 $('.post_code_autocomplete').find('input').on('paste focusout', function () {
1097 var postcode = $(this).val();
1098 var country = $('#shipping_country').val();
1099 var state = $('#sellkit-shipping_state');
1100 var city = $('#shipping_city');
1101 var parent = $(this).parent().parent().parent();
1102
1103 if ('billing_postcode' === $(this).attr('id')) {
1104 country = $('#billing_country').val();
1105 state = $('#sellkit-billing_state');
1106 city = $('#billing_city');
1107 }
1108
1109 if (_.isEmpty(postcode) || _.isEmpty(country)) {
1110 return;
1111 }
1112
1113 wp.ajax.post({
1114 action: 'sellkit_checkout_ajax_handler',
1115 sub_action: 'sellkit_state_lookup_by_postcode',
1116 country_value: country,
1117 postcode_value: postcode,
1118 nonce: sellkit_elementor.nonce
1119 }).done(function (response) {
1120 setError('');
1121 var body = response;
1122 var placeCity = body.places[0]['place name'];
1123 var placeState = body.places[0]['state abbreviation'];
1124 var countryResponse = body['country abbreviation'];
1125
1126 if (_.isEmpty(placeState)) {
1127 placeState = body.places[0].state;
1128 }
1129
1130 var countries = ['DE', 'TR', 'BD', 'DO', 'GB', 'GT', 'JP', 'TH', 'ZA'];
1131
1132 if (countries.includes(countryResponse)) {
1133 placeState = fixConflictWooCommerceStatesWithApi(countryResponse, placeState, body);
1134 }
1135
1136 setFields(placeCity, placeState);
1137 }).fail(function (response) {
1138 setError(response);
1139 });
1140
1141 var setFields = function setFields(placeCity, placeState) {
1142 state.val(placeState).addClass('filled');
1143 city.val(placeCity).addClass('filled');
1144
1145 if (null === state.val() && 'SELECT' === state[0].nodeName) {
1146 state.prop('selectedIndex', 0);
1147 }
1148 };
1149
1150 var setError = function setError(response) {
1151 parent.find('.sellkit-checkout-field-global-errors').text(response);
1152 };
1153 });
1154 };
1155 /**
1156 * Fix some countries states conflict between WooCommerce and https://api.zippopotam.us/.
1157 *
1158 * @param {string} country response country.
1159 * @param {string} state response state.
1160 * @param {Object} body response body.
1161 * @return {string} state.
1162 */
1163
1164
1165 var fixConflictWooCommerceStatesWithApi = function fixConflictWooCommerceStatesWithApi(country, state, body) {
1166 switch (country) {
1167 case 'TR':
1168 // Turkey.
1169 state = 'TR' + state;
1170 break;
1171
1172 case 'DE':
1173 // Germany.
1174 state = 'DE-' + state;
1175 break;
1176
1177 case 'BD':
1178 // Bangladesh.
1179 state = sellkitCheckoutCountryFixAutoPopulate(state, country, body);
1180 break;
1181
1182 case 'DO':
1183 // Dominican Republic. Api has no proper response. we select first option
1184 state = 'DO-01';
1185 break;
1186
1187 case 'GB':
1188 // United kingdom.
1189 state = body.places[0].state;
1190 break;
1191
1192 case 'GT':
1193 // Guatemala.
1194 state = 'GT-AV';
1195 break;
1196
1197 case 'JP':
1198 // Japan.
1199 state = sellkitCheckoutCountryFixAutoPopulate(state, country, body);
1200 break;
1201
1202 case 'TH':
1203 // Thailand.
1204 state = sellkitCheckoutCountryFixAutoPopulate(state, country, body);
1205 break;
1206
1207 case 'ZA':
1208 // South Africa. API has no proper response. we select first option.
1209 state = 'EC';
1210 break;
1211
1212 default:
1213 return state;
1214 }
1215
1216 return state;
1217 };
1218 /**
1219 * Integration with Klarma checkout gateway.
1220 *
1221 * @since 1.2.5
1222 */
1223
1224
1225 var sellkitKlarmaIntegration = function sellkitKlarmaIntegration() {
1226 $(document).ready(function () {
1227 $('#sellkit-klarna-pay-button').on('click', function () {
1228 $('#payment_method_kco').trigger('click');
1229 });
1230 });
1231 };
1232 /**
1233 * Save client state and country on change event.
1234 *
1235 * @since 1.2.5
1236 */
1237
1238
1239 var fixClientCountryOnReload = function fixClientCountryOnReload() {
1240 $('#shipping_country, #billing_country, #sellkit-shipping_state, #sellkit-billing_state').on('change', function () {
1241 sellkitSetAddressDetails();
1242 });
1243 };
1244 /**
1245 * Ajax to save user state and country for both shipping and billing section if those fields are present.
1246 *
1247 * @since 1.2.5
1248 */
1249
1250
1251 var sellkitSetAddressDetails = function sellkitSetAddressDetails() {
1252 if (window.sellkitSuppressBillingAddressAjax) {
1253 return;
1254 }
1255
1256 wp.ajax.post({
1257 action: 'sellkit_checkout_ajax_handler',
1258 sub_action: 'set_customer_details_ajax',
1259 country: document.querySelector('#billing_country') ? document.getElementById('billing_country').value : '',
1260 state: document.querySelector('#sellkit-billing_state') ? document.getElementById('sellkit-billing_state').value : '',
1261 shipping_country: document.querySelector('#shipping_country') ? document.getElementById('shipping_country').value : '',
1262 shipping_state: document.querySelector('#sellkit-shipping_state') ? document.getElementById('sellkit-shipping_state').value : '',
1263 nonce: sellkit_elementor.nonce
1264 }).always(function () {
1265 $(document.body).trigger('update_checkout');
1266 });
1267 };
1268 /**
1269 * On page load set shipping and billing state & country values.
1270 *
1271 * @since 1.2.5
1272 */
1273
1274
1275 var fixStateIssueOnLoad = function fixStateIssueOnLoad() {
1276 var primaryValue = '';
1277
1278 if (document.querySelector('#shipping_country')) {
1279 primaryValue = $('#shipping_country').val();
1280 $('#shipping_country').val($('#shipping_country option:eq(1)').val());
1281 $('#shipping_country').val(primaryValue).trigger('change');
1282 }
1283
1284 if (document.querySelector('#billing_country')) {
1285 primaryValue = $('#billing_country').val();
1286 $('#billing_country').val($('#billing_country option:eq(1)').val());
1287 $('#billing_country').val(primaryValue).trigger('change');
1288 }
1289 };
1290 /**
1291 * Modify cart items when bundle products are present.
1292 *
1293 * @since 1.2.5
1294 */
1295
1296
1297 var sellkitCheckoutConfigureBundleProducts = function sellkitCheckoutConfigureBundleProducts() {
1298 bundleProductOnQuantityChange();
1299 var radioProducts = $('.sellkit-checkout-bundle-item');
1300 radioProducts.off('change').on('change', function () {
1301 var addType = $(this).attr('type'); // On bundle product change, modify bump too.
1302
1303 $('.sellkit-checkout-bump-order-products').each(function () {
1304 if ($(this).is(':checked') && 'radio' === addType) {
1305 $(this).trigger('click');
1306 }
1307 });
1308 var product = $(this).val();
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
1317 wp.ajax.post({
1318 action: 'sellkit_checkout_ajax_handler',
1319 sub_action: 'sellkit_checkout_modify_cart_by_bundle_products',
1320 id: product,
1321 qty: quantity,
1322 checkout_id: checkout,
1323 type: addType,
1324 modify: modifyType,
1325 nonce: sellkit_elementor.nonce
1326 }).always(function () {
1327 $(document.body).trigger('update_checkout');
1328 });
1329 });
1330 };
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 /**
1359 * Manage to add or remove a bump product from cart.
1360 *
1361 * @since 1.2.5
1362 */
1363
1364
1365 var sellkitCheckoutOrderBump = function sellkitCheckoutOrderBump() {
1366 $('.sellkit-checkout-bump-order-products').on('click', function () {
1367 var subAction;
1368
1369 if ($(this).is(':checked')) {
1370 subAction = 'add';
1371 } else {
1372 subAction = 'remove';
1373 }
1374
1375 wp.ajax.post({
1376 action: 'sellkit_checkout_ajax_handler',
1377 sub_action: 'change_cart_item_qty',
1378 qty: $(this).attr('data-qty'),
1379 id: $(this).val(),
1380 mode: subAction,
1381 related_checkout: $('#sellkit_current_page_id').val(),
1382 nonce: sellkit_elementor.nonce
1383 }).always(function () {
1384 $(document.body).trigger('update_checkout');
1385 });
1386 });
1387 };
1388 /**
1389 * Checks if a required field is not filled.
1390 *
1391 * @return {boolean} state of error.
1392 * @since 1.2.5
1393 */
1394
1395
1396 var checkRequiredFields = function checkRequiredFields() {
1397 var fields = document.querySelectorAll('#sellkit-checkout-widget-shipping-fields > .validate-required');
1398 var error = false; // Let's check email field first.
1399
1400 if (_.isEmpty($('#billing_email').val())) {
1401 $('.sellkit-checkout-widget-email-empty').css('display', 'block');
1402 return true;
1403 } // Hide warning after filling email field.
1404
1405
1406 $('.sellkit-checkout-widget-email-empty').css('display', 'none');
1407
1408 if (fields.length < 1) {
1409 return error;
1410 }
1411
1412 fields.forEach(function (item) {
1413 var target = $(item).find('input, select, textarea').val();
1414
1415 if ('' === target) {
1416 error = true;
1417 $(item).find('.sellkit-required-validation').css('display', 'inline-flex');
1418 }
1419 });
1420 return error;
1421 };
1422 /**
1423 * Loop through WooCommerce states and replace api returned value.
1424 *
1425 * @param {string} state
1426 * @param {string} countryAbbreviated
1427 * @param {Object} body
1428 * @return {string} state value.
1429 * @since 1.2.5
1430 */
1431
1432
1433 var sellkitCheckoutCountryFixAutoPopulate = function sellkitCheckoutCountryFixAutoPopulate(state, countryAbbreviated, body) {
1434 var value = '';
1435 var country = '';
1436
1437 if ('BD' === countryAbbreviated) {
1438 country = wcCountries.BD;
1439 }
1440
1441 if ('JP' === countryAbbreviated) {
1442 country = wcCountries.JP;
1443 state = state.substring(0, state.length - 3);
1444 }
1445
1446 if ('TH' === countryAbbreviated) {
1447 value = 'TH-37';
1448 country = wcCountries.TH;
1449 state = body.places[0].state;
1450 }
1451
1452 for (var key in country) {
1453 if (state === country[key]) {
1454 value = key;
1455 }
1456 }
1457
1458 return value;
1459 };
1460
1461 var sellkitAfterAjaxComplete = function sellkitAfterAjaxComplete() {
1462 $('#place_order').on('click', function () {
1463 var count = 0;
1464 var transfer = setInterval(function () {
1465 count += 1;
1466
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 ).
1469 var notice = $('.wc_payment_method').find('.woocommerce-NoticeGroup-checkout').html();
1470 $('.wc_payment_method').find('.woocommerce-NoticeGroup-checkout').remove();
1471 $('.woocommerce-notices-wrapper').first().append(notice);
1472 $(document.body).animate({
1473 scrollTop: $('.woocommerce-notices-wrapper').offset().top - 100
1474 }, 500); // Stop interval.
1475
1476 clearInterval(transfer);
1477 }
1478
1479 if (count > 20) {
1480 clearInterval(transfer);
1481 }
1482 }, 500);
1483 });
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 */
1491
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){
1722 "use strict";
1723
1724 (function ($) {
1725 var SellkitFrontend = function SellkitFrontend() {
1726 var widgets = {
1727 'sellkit-product-images.default': require('./product-images')["default"],
1728 'sellkit-checkout.default': require('./checkout')["default"],
1729 'sellkit-optin.default': require('./optin/optin')["default"]
1730 };
1731
1732 function elementorInit() {
1733 for (var widget in widgets) {
1734 elementorFrontend.hooks.addAction("frontend/element_ready/".concat(widget), widgets[widget]);
1735 }
1736 }
1737
1738 this.init = function () {
1739 $(window).on('elementor/frontend/init', elementorInit);
1740 };
1741
1742 this.init();
1743 };
1744
1745 window.sellkitFrontend = new SellkitFrontend();
1746 })(jQuery);
1747
1748 },{"./checkout":2,"./optin/optin":4,"./product-images":7}],4:[function(require,module,exports){
1749 "use strict";
1750
1751 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
1752
1753 Object.defineProperty(exports, "__esModule", {
1754 value: true
1755 });
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;
2238 var ProductImages = elementorModules.frontend.handlers.Base.extend({
2239 onInit: function onInit() {
2240 elementorModules.frontend.handlers.Base.prototype.onInit.apply(this, arguments);
2241
2242 if (document.body.classList.contains('elementor-editor-active')) {
2243 this.$element.find('.woocommerce-product-gallery').wc_product_gallery();
2244 }
2245
2246 var self = this;
2247
2248 if (typeof window.elementor === 'undefined') {
2249 return;
2250 }
2251
2252 window.elementor.channels.editor.on('change', function (controlView) {
2253 self.onElementChange(controlView.model.get('name'), controlView);
2254 });
2255 this.handleThumbnailBorderRadius(this.getElementSettings('thumbnail_border_radius'));
2256 },
2257 onElementChange: function onElementChange(propertyName, controlView) {
2258 if ('thumbnail_border_radius' === propertyName) {
2259 var borderRadius = controlView.container.settings.get('thumbnail_border_radius');
2260 this.handleThumbnailBorderRadius(borderRadius);
2261 }
2262 },
2263 handleThumbnailBorderRadius: function handleThumbnailBorderRadius(borderRadius) {
2264 var unit = borderRadius.unit;
2265 this.$element.find('.flex-control-nav li').css({
2266 'border-radius': borderRadius.top + unit + ' ' + borderRadius.right + unit + ' ' + borderRadius.bottom + unit + ' ' + borderRadius.left + unit
2267 });
2268 },
2269 bindEvents: function bindEvents() {
2270 this.$element.find('.woocommerce-product-gallery__image a').on('click', function (e) {
2271 e.stopImmediatePropagation();
2272 e.preventDefault();
2273 });
2274 }
2275 });
2276
2277 function _default($scope) {
2278 new ProductImages({
2279 $element: $scope
2280 });
2281 }
2282
2283 },{}],8:[function(require,module,exports){
2284 function _defineProperty(obj, key, value) {
2285 if (key in obj) {
2286 Object.defineProperty(obj, key, {
2287 value: value,
2288 enumerable: true,
2289 configurable: true,
2290 writable: true
2291 });
2292 } else {
2293 obj[key] = value;
2294 }
2295
2296 return obj;
2297 }
2298
2299 module.exports = _defineProperty;
2300 },{}],9:[function(require,module,exports){
2301 function _interopRequireDefault(obj) {
2302 return obj && obj.__esModule ? obj : {
2303 "default": obj
2304 };
2305 }
2306
2307 module.exports = _interopRequireDefault;
2308 },{}],10:[function(require,module,exports){
2309 'use strict';
2310
2311 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
2312
2313 var postfix = _interopDefault(require('@tannin/postfix'));
2314 var evaluate = _interopDefault(require('@tannin/evaluate'));
2315
2316 /**
2317 * Given a C expression, returns a function which can be called to evaluate its
2318 * result.
2319 *
2320 * @example
2321 *
2322 * ```js
2323 * import compile from '@tannin/compile';
2324 *
2325 * const evaluate = compile( 'n > 1' );
2326 *
2327 * evaluate( { n: 2 } );
2328 * // ⇒ true
2329 * ```
2330 *
2331 * @param {string} expression C expression.
2332 *
2333 * @return {(variables?:{[variable:string]:*})=>*} Compiled evaluator.
2334 */
2335 function compile( expression ) {
2336 var terms = postfix( expression );
2337
2338 return function( variables ) {
2339 return evaluate( terms, variables );
2340 };
2341 }
2342
2343 module.exports = compile;
2344
2345 },{"@tannin/evaluate":11,"@tannin/postfix":13}],11:[function(require,module,exports){
2346 'use strict';
2347
2348 /**
2349 * Operator callback functions.
2350 *
2351 * @type {Object}
2352 */
2353 var OPERATORS = {
2354 '!': function( a ) {
2355 return ! a;
2356 },
2357 '*': function( a, b ) {
2358 return a * b;
2359 },
2360 '/': function( a, b ) {
2361 return a / b;
2362 },
2363 '%': function( a, b ) {
2364 return a % b;
2365 },
2366 '+': function( a, b ) {
2367 return a + b;
2368 },
2369 '-': function( a, b ) {
2370 return a - b;
2371 },
2372 '<': function( a, b ) {
2373 return a < b;
2374 },
2375 '<=': function( a, b ) {
2376 return a <= b;
2377 },
2378 '>': function( a, b ) {
2379 return a > b;
2380 },
2381 '>=': function( a, b ) {
2382 return a >= b;
2383 },
2384 '==': function( a, b ) {
2385 return a === b;
2386 },
2387 '!=': function( a, b ) {
2388 return a !== b;
2389 },
2390 '&&': function( a, b ) {
2391 return a && b;
2392 },
2393 '||': function( a, b ) {
2394 return a || b;
2395 },
2396 '?:': function( a, b, c ) {
2397 if ( a ) {
2398 throw b;
2399 }
2400
2401 return c;
2402 },
2403 };
2404
2405 /**
2406 * Given an array of postfix terms and operand variables, returns the result of
2407 * the postfix evaluation.
2408 *
2409 * @example
2410 *
2411 * ```js
2412 * import evaluate from '@tannin/evaluate';
2413 *
2414 * // 3 + 4 * 5 / 6 ⇒ '3 4 5 * 6 / +'
2415 * const terms = [ '3', '4', '5', '*', '6', '/', '+' ];
2416 *
2417 * evaluate( terms, {} );
2418 * // ⇒ 6.333333333333334
2419 * ```
2420 *
2421 * @param {string[]} postfix Postfix terms.
2422 * @param {Object} variables Operand variables.
2423 *
2424 * @return {*} Result of evaluation.
2425 */
2426 function evaluate( postfix, variables ) {
2427 var stack = [],
2428 i, j, args, getOperatorResult, term, value;
2429
2430 for ( i = 0; i < postfix.length; i++ ) {
2431 term = postfix[ i ];
2432
2433 getOperatorResult = OPERATORS[ term ];
2434 if ( getOperatorResult ) {
2435 // Pop from stack by number of function arguments.
2436 j = getOperatorResult.length;
2437 args = Array( j );
2438 while ( j-- ) {
2439 args[ j ] = stack.pop();
2440 }
2441
2442 try {
2443 value = getOperatorResult.apply( null, args );
2444 } catch ( earlyReturn ) {
2445 return earlyReturn;
2446 }
2447 } else if ( variables.hasOwnProperty( term ) ) {
2448 value = variables[ term ];
2449 } else {
2450 value = +term;
2451 }
2452
2453 stack.push( value );
2454 }
2455
2456 return stack[ 0 ];
2457 }
2458
2459 module.exports = evaluate;
2460
2461 },{}],12:[function(require,module,exports){
2462 'use strict';
2463
2464 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
2465
2466 var compile = _interopDefault(require('@tannin/compile'));
2467
2468 /**
2469 * Given a C expression, returns a function which, when called with a value,
2470 * evaluates the result with the value assumed to be the "n" variable of the
2471 * expression. The result will be coerced to its numeric equivalent.
2472 *
2473 * @param {string} expression C expression.
2474 *
2475 * @return {Function} Evaluator function.
2476 */
2477 function pluralForms( expression ) {
2478 var evaluate = compile( expression );
2479
2480 return function( n ) {
2481 return +evaluate( { n: n } );
2482 };
2483 }
2484
2485 module.exports = pluralForms;
2486
2487 },{"@tannin/compile":10}],13:[function(require,module,exports){
2488 'use strict';
2489
2490 var PRECEDENCE, OPENERS, TERMINATORS, PATTERN;
2491
2492 /**
2493 * Operator precedence mapping.
2494 *
2495 * @type {Object}
2496 */
2497 PRECEDENCE = {
2498 '(': 9,
2499 '!': 8,
2500 '*': 7,
2501 '/': 7,
2502 '%': 7,
2503 '+': 6,
2504 '-': 6,
2505 '<': 5,
2506 '<=': 5,
2507 '>': 5,
2508 '>=': 5,
2509 '==': 4,
2510 '!=': 4,
2511 '&&': 3,
2512 '||': 2,
2513 '?': 1,
2514 '?:': 1,
2515 };
2516
2517 /**
2518 * Characters which signal pair opening, to be terminated by terminators.
2519 *
2520 * @type {string[]}
2521 */
2522 OPENERS = [ '(', '?' ];
2523
2524 /**
2525 * Characters which signal pair termination, the value an array with the
2526 * opener as its first member. The second member is an optional operator
2527 * replacement to push to the stack.
2528 *
2529 * @type {string[]}
2530 */
2531 TERMINATORS = {
2532 ')': [ '(' ],
2533 ':': [ '?', '?:' ],
2534 };
2535
2536 /**
2537 * Pattern matching operators and openers.
2538 *
2539 * @type {RegExp}
2540 */
2541 PATTERN = /<=|>=|==|!=|&&|\|\||\?:|\(|!|\*|\/|%|\+|-|<|>|\?|\)|:/;
2542
2543 /**
2544 * Given a C expression, returns the equivalent postfix (Reverse Polish)
2545 * notation terms as an array.
2546 *
2547 * If a postfix string is desired, simply `.join( ' ' )` the result.
2548 *
2549 * @example
2550 *
2551 * ```js
2552 * import postfix from '@tannin/postfix';
2553 *
2554 * postfix( 'n > 1' );
2555 * // ⇒ [ 'n', '1', '>' ]
2556 * ```
2557 *
2558 * @param {string} expression C expression.
2559 *
2560 * @return {string[]} Postfix terms.
2561 */
2562 function postfix( expression ) {
2563 var terms = [],
2564 stack = [],
2565 match, operator, term, element;
2566
2567 while ( ( match = expression.match( PATTERN ) ) ) {
2568 operator = match[ 0 ];
2569
2570 // Term is the string preceding the operator match. It may contain
2571 // whitespace, and may be empty (if operator is at beginning).
2572 term = expression.substr( 0, match.index ).trim();
2573 if ( term ) {
2574 terms.push( term );
2575 }
2576
2577 while ( ( element = stack.pop() ) ) {
2578 if ( TERMINATORS[ operator ] ) {
2579 if ( TERMINATORS[ operator ][ 0 ] === element ) {
2580 // Substitution works here under assumption that because
2581 // the assigned operator will no longer be a terminator, it
2582 // will be pushed to the stack during the condition below.
2583 operator = TERMINATORS[ operator ][ 1 ] || operator;
2584 break;
2585 }
2586 } else if ( OPENERS.indexOf( element ) >= 0 || PRECEDENCE[ element ] < PRECEDENCE[ operator ] ) {
2587 // Push to stack if either an opener or when pop reveals an
2588 // element of lower precedence.
2589 stack.push( element );
2590 break;
2591 }
2592
2593 // For each popped from stack, push to terms.
2594 terms.push( element );
2595 }
2596
2597 if ( ! TERMINATORS[ operator ] ) {
2598 stack.push( operator );
2599 }
2600
2601 // Slice matched fragment from expression to continue match.
2602 expression = expression.substr( match.index + operator.length );
2603 }
2604
2605 // Push remainder of operand, if exists, to terms.
2606 expression = expression.trim();
2607 if ( expression ) {
2608 terms.push( expression );
2609 }
2610
2611 // Pop remaining items from stack into terms.
2612 return terms.concat( stack.reverse() );
2613 }
2614
2615 module.exports = postfix;
2616
2617 },{}],14:[function(require,module,exports){
2618 "use strict";
2619
2620 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
2621
2622 Object.defineProperty(exports, "__esModule", {
2623 value: true
2624 });
2625 exports.createI18n = void 0;
2626
2627 var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
2628
2629 var _tannin = _interopRequireDefault(require("tannin"));
2630
2631 function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
2632
2633 function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
2634
2635 /**
2636 * @typedef {Record<string,any>} LocaleData
2637 */
2638
2639 /**
2640 * Default locale data to use for Tannin domain when not otherwise provided.
2641 * Assumes an English plural forms expression.
2642 *
2643 * @type {LocaleData}
2644 */
2645 var DEFAULT_LOCALE_DATA = {
2646 '': {
2647 /** @param {number} n */
2648 plural_forms: function plural_forms(n) {
2649 return n === 1 ? 0 : 1;
2650 }
2651 }
2652 };
2653 /**
2654 * An i18n instance
2655 *
2656 * @typedef {Object} I18n
2657 * @property {Function} setLocaleData Merges locale data into the Tannin instance by domain. Accepts data in a
2658 * Jed-formatted JSON object shape.
2659 * @property {Function} __ Retrieve the translation of text.
2660 * @property {Function} _x Retrieve translated string with gettext context.
2661 * @property {Function} _n Translates and retrieves the singular or plural form based on the supplied
2662 * number.
2663 * @property {Function} _nx Translates and retrieves the singular or plural form based on the supplied
2664 * number, with gettext context.
2665 * @property {Function} isRTL Check if current locale is RTL.
2666 */
2667
2668 /**
2669 * Create an i18n instance
2670 *
2671 * @param {LocaleData} [initialData] Locale data configuration.
2672 * @param {string} [initialDomain] Domain for which configuration applies.
2673 * @return {I18n} I18n instance
2674 */
2675
2676 var createI18n = function createI18n(initialData, initialDomain) {
2677 /**
2678 * The underlying instance of Tannin to which exported functions interface.
2679 *
2680 * @type {Tannin}
2681 */
2682 var tannin = new _tannin.default({});
2683 /**
2684 * Merges locale data into the Tannin instance by domain. Accepts data in a
2685 * Jed-formatted JSON object shape.
2686 *
2687 * @see http://messageformat.github.io/Jed/
2688 *
2689 * @param {LocaleData} [data] Locale data configuration.
2690 * @param {string} [domain] Domain for which configuration applies.
2691 */
2692
2693 var setLocaleData = function setLocaleData(data) {
2694 var domain = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
2695 tannin.data[domain] = _objectSpread({}, DEFAULT_LOCALE_DATA, {}, tannin.data[domain], {}, data); // Populate default domain configuration (supported locale date which omits
2696 // a plural forms expression).
2697
2698 tannin.data[domain][''] = _objectSpread({}, DEFAULT_LOCALE_DATA[''], {}, tannin.data[domain]['']);
2699 };
2700 /**
2701 * Wrapper for Tannin's `dcnpgettext`. Populates default locale data if not
2702 * otherwise previously assigned.
2703 *
2704 * @param {string|undefined} domain Domain to retrieve the translated text.
2705 * @param {string|undefined} context Context information for the translators.
2706 * @param {string} single Text to translate if non-plural. Used as
2707 * fallback return value on a caught error.
2708 * @param {string} [plural] The text to be used if the number is
2709 * plural.
2710 * @param {number} [number] The number to compare against to use
2711 * either the singular or plural form.
2712 *
2713 * @return {string} The translated string.
2714 */
2715
2716
2717 var dcnpgettext = function dcnpgettext() {
2718 var domain = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';
2719 var context = arguments.length > 1 ? arguments[1] : undefined;
2720 var single = arguments.length > 2 ? arguments[2] : undefined;
2721 var plural = arguments.length > 3 ? arguments[3] : undefined;
2722 var number = arguments.length > 4 ? arguments[4] : undefined;
2723
2724 if (!tannin.data[domain]) {
2725 setLocaleData(undefined, domain);
2726 }
2727
2728 return tannin.dcnpgettext(domain, context, single, plural, number);
2729 };
2730 /**
2731 * Retrieve the translation of text.
2732 *
2733 * @see https://developer.wordpress.org/reference/functions/__/
2734 *
2735 * @param {string} text Text to translate.
2736 * @param {string} [domain] Domain to retrieve the translated text.
2737 *
2738 * @return {string} Translated text.
2739 */
2740
2741
2742 var __ = function __(text, domain) {
2743 return dcnpgettext(domain, undefined, text);
2744 };
2745 /**
2746 * Retrieve translated string with gettext context.
2747 *
2748 * @see https://developer.wordpress.org/reference/functions/_x/
2749 *
2750 * @param {string} text Text to translate.
2751 * @param {string} context Context information for the translators.
2752 * @param {string} [domain] Domain to retrieve the translated text.
2753 *
2754 * @return {string} Translated context string without pipe.
2755 */
2756
2757
2758 var _x = function _x(text, context, domain) {
2759 return dcnpgettext(domain, context, text);
2760 };
2761 /**
2762 * Translates and retrieves the singular or plural form based on the supplied
2763 * number.
2764 *
2765 * @see https://developer.wordpress.org/reference/functions/_n/
2766 *
2767 * @param {string} single The text to be used if the number is singular.
2768 * @param {string} plural The text to be used if the number is plural.
2769 * @param {number} number The number to compare against to use either the
2770 * singular or plural form.
2771 * @param {string} [domain] Domain to retrieve the translated text.
2772 *
2773 * @return {string} The translated singular or plural form.
2774 */
2775
2776
2777 var _n = function _n(single, plural, number, domain) {
2778 return dcnpgettext(domain, undefined, single, plural, number);
2779 };
2780 /**
2781 * Translates and retrieves the singular or plural form based on the supplied
2782 * number, with gettext context.
2783 *
2784 * @see https://developer.wordpress.org/reference/functions/_nx/
2785 *
2786 * @param {string} single The text to be used if the number is singular.
2787 * @param {string} plural The text to be used if the number is plural.
2788 * @param {number} number The number to compare against to use either the
2789 * singular or plural form.
2790 * @param {string} context Context information for the translators.
2791 * @param {string} [domain] Domain to retrieve the translated text.
2792 *
2793 * @return {string} The translated singular or plural form.
2794 */
2795
2796
2797 var _nx = function _nx(single, plural, number, context, domain) {
2798 return dcnpgettext(domain, context, single, plural, number);
2799 };
2800 /**
2801 * Check if current locale is RTL.
2802 *
2803 * **RTL (Right To Left)** is a locale property indicating that text is written from right to left.
2804 * For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common
2805 * language written RTL. The opposite of RTL, LTR (Left To Right) is used in other languages,
2806 * including English (`en`, `en-US`, `en-GB`, etc.), Spanish (`es`), and French (`fr`).
2807 *
2808 * @return {boolean} Whether locale is RTL.
2809 */
2810
2811
2812 var isRTL = function isRTL() {
2813 return 'rtl' === _x('ltr', 'text direction');
2814 };
2815
2816 if (initialData) {
2817 setLocaleData(initialData, initialDomain);
2818 }
2819
2820 return {
2821 setLocaleData: setLocaleData,
2822 __: __,
2823 _x: _x,
2824 _n: _n,
2825 _nx: _nx,
2826 isRTL: isRTL
2827 };
2828 };
2829
2830 exports.createI18n = createI18n;
2831
2832 },{"@babel/runtime/helpers/defineProperty":8,"@babel/runtime/helpers/interopRequireDefault":9,"tannin":23}],15:[function(require,module,exports){
2833 "use strict";
2834
2835 Object.defineProperty(exports, "__esModule", {
2836 value: true
2837 });
2838 exports.isRTL = exports._nx = exports._n = exports._x = exports.__ = exports.setLocaleData = void 0;
2839
2840 var _createI18n = require("./create-i18n");
2841
2842 /**
2843 * Internal dependencies
2844 */
2845 var i18n = (0, _createI18n.createI18n)();
2846 /*
2847 * Comments in this file are duplicated from ./i18n due to
2848 * https://github.com/WordPress/gutenberg/pull/20318#issuecomment-590837722
2849 */
2850
2851 /**
2852 * @typedef {import('./create-i18n').LocaleData} LocaleData
2853 */
2854
2855 /**
2856 * Merges locale data into the Tannin instance by domain. Accepts data in a
2857 * Jed-formatted JSON object shape.
2858 *
2859 * @see http://messageformat.github.io/Jed/
2860 *
2861 * @param {LocaleData} [data] Locale data configuration.
2862 * @param {string} [domain] Domain for which configuration applies.
2863 */
2864
2865 var setLocaleData = i18n.setLocaleData.bind(i18n);
2866 /**
2867 * Retrieve the translation of text.
2868 *
2869 * @see https://developer.wordpress.org/reference/functions/__/
2870 *
2871 * @param {string} text Text to translate.
2872 * @param {string} [domain] Domain to retrieve the translated text.
2873 *
2874 * @return {string} Translated text.
2875 */
2876
2877 exports.setLocaleData = setLocaleData;
2878
2879 var __ = i18n.__.bind(i18n);
2880 /**
2881 * Retrieve translated string with gettext context.
2882 *
2883 * @see https://developer.wordpress.org/reference/functions/_x/
2884 *
2885 * @param {string} text Text to translate.
2886 * @param {string} context Context information for the translators.
2887 * @param {string} [domain] Domain to retrieve the translated text.
2888 *
2889 * @return {string} Translated context string without pipe.
2890 */
2891
2892
2893 exports.__ = __;
2894
2895 var _x = i18n._x.bind(i18n);
2896 /**
2897 * Translates and retrieves the singular or plural form based on the supplied
2898 * number.
2899 *
2900 * @see https://developer.wordpress.org/reference/functions/_n/
2901 *
2902 * @param {string} single The text to be used if the number is singular.
2903 * @param {string} plural The text to be used if the number is plural.
2904 * @param {number} number The number to compare against to use either the
2905 * singular or plural form.
2906 * @param {string} [domain] Domain to retrieve the translated text.
2907 *
2908 * @return {string} The translated singular or plural form.
2909 */
2910
2911
2912 exports._x = _x;
2913
2914 var _n = i18n._n.bind(i18n);
2915 /**
2916 * Translates and retrieves the singular or plural form based on the supplied
2917 * number, with gettext context.
2918 *
2919 * @see https://developer.wordpress.org/reference/functions/_nx/
2920 *
2921 * @param {string} single The text to be used if the number is singular.
2922 * @param {string} plural The text to be used if the number is plural.
2923 * @param {number} number The number to compare against to use either the
2924 * singular or plural form.
2925 * @param {string} context Context information for the translators.
2926 * @param {string} [domain] Domain to retrieve the translated text.
2927 *
2928 * @return {string} The translated singular or plural form.
2929 */
2930
2931
2932 exports._n = _n;
2933
2934 var _nx = i18n._nx.bind(i18n);
2935 /**
2936 * Check if current locale is RTL.
2937 *
2938 * **RTL (Right To Left)** is a locale property indicating that text is written from right to left.
2939 * For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common
2940 * language written RTL. The opposite of RTL, LTR (Left To Right) is used in other languages,
2941 * including English (`en`, `en-US`, `en-GB`, etc.), Spanish (`es`), and French (`fr`).
2942 *
2943 * @return {boolean} Whether locale is RTL.
2944 */
2945
2946
2947 exports._nx = _nx;
2948 var isRTL = i18n.isRTL.bind(i18n);
2949 exports.isRTL = isRTL;
2950
2951 },{"./create-i18n":14}],16:[function(require,module,exports){
2952 "use strict";
2953
2954 Object.defineProperty(exports, "__esModule", {
2955 value: true
2956 });
2957 var _exportNames = {
2958 sprintf: true,
2959 setLocaleData: true,
2960 __: true,
2961 _x: true,
2962 _n: true,
2963 _nx: true,
2964 isRTL: true
2965 };
2966 Object.defineProperty(exports, "sprintf", {
2967 enumerable: true,
2968 get: function get() {
2969 return _sprintf.sprintf;
2970 }
2971 });
2972 Object.defineProperty(exports, "setLocaleData", {
2973 enumerable: true,
2974 get: function get() {
2975 return _defaultI18n.setLocaleData;
2976 }
2977 });
2978 Object.defineProperty(exports, "__", {
2979 enumerable: true,
2980 get: function get() {
2981 return _defaultI18n.__;
2982 }
2983 });
2984 Object.defineProperty(exports, "_x", {
2985 enumerable: true,
2986 get: function get() {
2987 return _defaultI18n._x;
2988 }
2989 });
2990 Object.defineProperty(exports, "_n", {
2991 enumerable: true,
2992 get: function get() {
2993 return _defaultI18n._n;
2994 }
2995 });
2996 Object.defineProperty(exports, "_nx", {
2997 enumerable: true,
2998 get: function get() {
2999 return _defaultI18n._nx;
3000 }
3001 });
3002 Object.defineProperty(exports, "isRTL", {
3003 enumerable: true,
3004 get: function get() {
3005 return _defaultI18n.isRTL;
3006 }
3007 });
3008
3009 var _sprintf = require("./sprintf");
3010
3011 var _createI18n = require("./create-i18n");
3012
3013 Object.keys(_createI18n).forEach(function (key) {
3014 if (key === "default" || key === "__esModule") return;
3015 if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
3016 Object.defineProperty(exports, key, {
3017 enumerable: true,
3018 get: function get() {
3019 return _createI18n[key];
3020 }
3021 });
3022 });
3023
3024 var _defaultI18n = require("./default-i18n");
3025
3026 },{"./create-i18n":14,"./default-i18n":15,"./sprintf":17}],17:[function(require,module,exports){
3027 "use strict";
3028
3029 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
3030
3031 Object.defineProperty(exports, "__esModule", {
3032 value: true
3033 });
3034 exports.sprintf = sprintf;
3035
3036 var _memize = _interopRequireDefault(require("memize"));
3037
3038 var _sprintfJs = _interopRequireDefault(require("sprintf-js"));
3039
3040 /**
3041 * External dependencies
3042 */
3043
3044 /**
3045 * Log to console, once per message; or more precisely, per referentially equal
3046 * argument set. Because Jed throws errors, we log these to the console instead
3047 * to avoid crashing the application.
3048 *
3049 * @param {...*} args Arguments to pass to `console.error`
3050 */
3051 var logErrorOnce = (0, _memize.default)(console.error); // eslint-disable-line no-console
3052
3053 /**
3054 * Returns a formatted string. If an error occurs in applying the format, the
3055 * original format string is returned.
3056 *
3057 * @param {string} format The format of the string to generate.
3058 * @param {...*} args Arguments to apply to the format.
3059 *
3060 * @see http://www.diveintojavascript.com/projects/javascript-sprintf
3061 *
3062 * @return {string} The formatted string.
3063 */
3064
3065 function sprintf(format) {
3066 try {
3067 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
3068 args[_key - 1] = arguments[_key];
3069 }
3070
3071 return _sprintfJs.default.sprintf.apply(_sprintfJs.default, [format].concat(args));
3072 } catch (error) {
3073 logErrorOnce('sprintf error: \n\n' + error.toString());
3074 return format;
3075 }
3076 }
3077
3078 },{"@babel/runtime/helpers/interopRequireDefault":9,"memize":21,"sprintf-js":18}],18:[function(require,module,exports){
3079 /* global window, exports, define */
3080
3081 !function() {
3082 'use strict'
3083
3084 var re = {
3085 not_string: /[^s]/,
3086 not_bool: /[^t]/,
3087 not_type: /[^T]/,
3088 not_primitive: /[^v]/,
3089 number: /[diefg]/,
3090 numeric_arg: /[bcdiefguxX]/,
3091 json: /[j]/,
3092 not_json: /[^j]/,
3093 text: /^[^\x25]+/,
3094 modulo: /^\x25{2}/,
3095 placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
3096 key: /^([a-z_][a-z_\d]*)/i,
3097 key_access: /^\.([a-z_][a-z_\d]*)/i,
3098 index_access: /^\[(\d+)\]/,
3099 sign: /^[+-]/
3100 }
3101
3102 function sprintf(key) {
3103 // `arguments` is not an array, but should be fine for this call
3104 return sprintf_format(sprintf_parse(key), arguments)
3105 }
3106
3107 function vsprintf(fmt, argv) {
3108 return sprintf.apply(null, [fmt].concat(argv || []))
3109 }
3110
3111 function sprintf_format(parse_tree, argv) {
3112 var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
3113 for (i = 0; i < tree_length; i++) {
3114 if (typeof parse_tree[i] === 'string') {
3115 output += parse_tree[i]
3116 }
3117 else if (typeof parse_tree[i] === 'object') {
3118 ph = parse_tree[i] // convenience purposes only
3119 if (ph.keys) { // keyword argument
3120 arg = argv[cursor]
3121 for (k = 0; k < ph.keys.length; k++) {
3122 if (arg == undefined) {
3123 throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
3124 }
3125 arg = arg[ph.keys[k]]
3126 }
3127 }
3128 else if (ph.param_no) { // positional argument (explicit)
3129 arg = argv[ph.param_no]
3130 }
3131 else { // positional argument (implicit)
3132 arg = argv[cursor++]
3133 }
3134
3135 if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
3136 arg = arg()
3137 }
3138
3139 if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
3140 throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
3141 }
3142
3143 if (re.number.test(ph.type)) {
3144 is_positive = arg >= 0
3145 }
3146
3147 switch (ph.type) {
3148 case 'b':
3149 arg = parseInt(arg, 10).toString(2)
3150 break
3151 case 'c':
3152 arg = String.fromCharCode(parseInt(arg, 10))
3153 break
3154 case 'd':
3155 case 'i':
3156 arg = parseInt(arg, 10)
3157 break
3158 case 'j':
3159 arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
3160 break
3161 case 'e':
3162 arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
3163 break
3164 case 'f':
3165 arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
3166 break
3167 case 'g':
3168 arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
3169 break
3170 case 'o':
3171 arg = (parseInt(arg, 10) >>> 0).toString(8)
3172 break
3173 case 's':
3174 arg = String(arg)
3175 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
3176 break
3177 case 't':
3178 arg = String(!!arg)
3179 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
3180 break
3181 case 'T':
3182 arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
3183 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
3184 break
3185 case 'u':
3186 arg = parseInt(arg, 10) >>> 0
3187 break
3188 case 'v':
3189 arg = arg.valueOf()
3190 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
3191 break
3192 case 'x':
3193 arg = (parseInt(arg, 10) >>> 0).toString(16)
3194 break
3195 case 'X':
3196 arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
3197 break
3198 }
3199 if (re.json.test(ph.type)) {
3200 output += arg
3201 }
3202 else {
3203 if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
3204 sign = is_positive ? '+' : '-'
3205 arg = arg.toString().replace(re.sign, '')
3206 }
3207 else {
3208 sign = ''
3209 }
3210 pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
3211 pad_length = ph.width - (sign + arg).length
3212 pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
3213 output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
3214 }
3215 }
3216 }
3217 return output
3218 }
3219
3220 var sprintf_cache = Object.create(null)
3221
3222 function sprintf_parse(fmt) {
3223 if (sprintf_cache[fmt]) {
3224 return sprintf_cache[fmt]
3225 }
3226
3227 var _fmt = fmt, match, parse_tree = [], arg_names = 0
3228 while (_fmt) {
3229 if ((match = re.text.exec(_fmt)) !== null) {
3230 parse_tree.push(match[0])
3231 }
3232 else if ((match = re.modulo.exec(_fmt)) !== null) {
3233 parse_tree.push('%')
3234 }
3235 else if ((match = re.placeholder.exec(_fmt)) !== null) {
3236 if (match[2]) {
3237 arg_names |= 1
3238 var field_list = [], replacement_field = match[2], field_match = []
3239 if ((field_match = re.key.exec(replacement_field)) !== null) {
3240 field_list.push(field_match[1])
3241 while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
3242 if ((field_match = re.key_access.exec(replacement_field)) !== null) {
3243 field_list.push(field_match[1])
3244 }
3245 else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
3246 field_list.push(field_match[1])
3247 }
3248 else {
3249 throw new SyntaxError('[sprintf] failed to parse named argument key')
3250 }
3251 }
3252 }
3253 else {
3254 throw new SyntaxError('[sprintf] failed to parse named argument key')
3255 }
3256 match[2] = field_list
3257 }
3258 else {
3259 arg_names |= 2
3260 }
3261 if (arg_names === 3) {
3262 throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
3263 }
3264
3265 parse_tree.push(
3266 {
3267 placeholder: match[0],
3268 param_no: match[1],
3269 keys: match[2],
3270 sign: match[3],
3271 pad_char: match[4],
3272 align: match[5],
3273 width: match[6],
3274 precision: match[7],
3275 type: match[8]
3276 }
3277 )
3278 }
3279 else {
3280 throw new SyntaxError('[sprintf] unexpected placeholder')
3281 }
3282 _fmt = _fmt.substring(match[0].length)
3283 }
3284 return sprintf_cache[fmt] = parse_tree
3285 }
3286
3287 /**
3288 * export to either browser or node.js
3289 */
3290 /* eslint-disable quote-props */
3291 if (typeof exports !== 'undefined') {
3292 exports['sprintf'] = sprintf
3293 exports['vsprintf'] = vsprintf
3294 }
3295 if (typeof window !== 'undefined') {
3296 window['sprintf'] = sprintf
3297 window['vsprintf'] = vsprintf
3298
3299 if (typeof define === 'function' && define['amd']) {
3300 define(function() {
3301 return {
3302 'sprintf': sprintf,
3303 'vsprintf': vsprintf
3304 }
3305 })
3306 }
3307 }
3308 /* eslint-enable quote-props */
3309 }(); // eslint-disable-line
3310
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 (‫جزر الق�
3339 ر‬‎)", "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 (‫�
3340 صر‬‎)", "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 (Каза�
3341 стан)", "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 (‫�
3342 وريتانيا‬‎)", "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 (‫ال�
3343 غرب‬‎)", "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 (‫عُ�
3344 ان‬‎)", "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 (‫ال�
3345
3346 لكة العربية السعودية‬‎)", "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 (‫الإ�
3347 ارات العربية ال�
3348 تحدة‬‎)", "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 (‫الي�
3349 ن‬‎)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ], [ "�
3350 land Islands", "ax", "358", 1, [ "18" ] ] ];
3351 // loop over all of the countries above, restructuring the data to be objects with named keys
3352 for (var i = 0; i < allCountries.length; i++) {
3353 var c = allCountries[i];
3354 allCountries[i] = {
3355 name: c[0],
3356 iso2: c[1],
3357 dialCode: c[2],
3358 priority: c[3] || 0,
3359 areaCodes: c[4] || null
3360 };
3361 }
3362 "use strict";
3363 function _classCallCheck(instance, Constructor) {
3364 if (!(instance instanceof Constructor)) {
3365 throw new TypeError("Cannot call a class as a function");
3366 }
3367 }
3368 function _defineProperties(target, props) {
3369 for (var i = 0; i < props.length; i++) {
3370 var descriptor = props[i];
3371 descriptor.enumerable = descriptor.enumerable || false;
3372 descriptor.configurable = true;
3373 if ("value" in descriptor) descriptor.writable = true;
3374 Object.defineProperty(target, descriptor.key, descriptor);
3375 }
3376 }
3377 function _createClass(Constructor, protoProps, staticProps) {
3378 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
3379 if (staticProps) _defineProperties(Constructor, staticProps);
3380 return Constructor;
3381 }
3382 var intlTelInputGlobals = {
3383 getInstance: function getInstance(input) {
3384 var id = input.getAttribute("data-intl-tel-input-id");
3385 return window.intlTelInputGlobals.instances[id];
3386 },
3387 instances: {},
3388 // using a global like this allows us to mock it in the tests
3389 documentReady: function documentReady() {
3390 return document.readyState === "complete";
3391 }
3392 };
3393 if (typeof window === "object") window.intlTelInputGlobals = intlTelInputGlobals;
3394 // these vars persist through all instances of the plugin
3395 var id = 0;
3396 var defaults = {
3397 // whether or not to allow the dropdown
3398 allowDropdown: true,
3399 // if there is just a dial code in the input: remove it on blur
3400 autoHideDialCode: true,
3401 // add a placeholder in the input with an example number for the selected country
3402 autoPlaceholder: "polite",
3403 // modify the parentClass
3404 customContainer: "",
3405 // modify the auto placeholder
3406 customPlaceholder: null,
3407 // append menu to specified element
3408 dropdownContainer: null,
3409 // don't display these countries
3410 excludeCountries: [],
3411 // format the input value during initialisation and on setNumber
3412 formatOnDisplay: true,
3413 // geoIp lookup function
3414 geoIpLookup: null,
3415 // inject a hidden input with this name, and on submit, populate it with the result of getNumber
3416 hiddenInput: "",
3417 // initial country
3418 initialCountry: "",
3419 // localized country names e.g. { 'de': 'Deutschland' }
3420 localizedCountries: null,
3421 // don't insert international dial codes
3422 nationalMode: true,
3423 // display only these countries
3424 onlyCountries: [],
3425 // number type to use for placeholders
3426 placeholderNumberType: "MOBILE",
3427 // the countries at the top of the list. defaults to united states and united kingdom
3428 preferredCountries: [ "us", "gb" ],
3429 // display the country dial code next to the selected flag so it's not part of the typed number
3430 separateDialCode: false,
3431 // specify the path to the libphonenumber script to enable validation/formatting
3432 utilsScript: ""
3433 };
3434 // https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes#Non-geographic_area_codes
3435 var regionlessNanpNumbers = [ "800", "822", "833", "844", "855", "866", "877", "880", "881", "882", "883", "884", "885", "886", "887", "888", "889" ];
3436 // utility function to iterate over an object. can't use Object.entries or native forEach because
3437 // of IE11
3438 var forEachProp = function forEachProp(obj, callback) {
3439 var keys = Object.keys(obj);
3440 for (var i = 0; i < keys.length; i++) {
3441 callback(keys[i], obj[keys[i]]);
3442 }
3443 };
3444 // run a method on each instance of the plugin
3445 var forEachInstance = function forEachInstance(method) {
3446 forEachProp(window.intlTelInputGlobals.instances, function(key) {
3447 window.intlTelInputGlobals.instances[key][method]();
3448 });
3449 };
3450 // this is our plugin class that we will create an instance of
3451 // eslint-disable-next-line no-unused-vars
3452 var Iti = /*#__PURE__*/
3453 function() {
3454 function Iti(input, options) {
3455 var _this = this;
3456 _classCallCheck(this, Iti);
3457 this.id = id++;
3458 this.telInput = input;
3459 this.activeItem = null;
3460 this.highlightedItem = null;
3461 // process specified options / defaults
3462 // alternative to Object.assign, which isn't supported by IE11
3463 var customOptions = options || {};
3464 this.options = {};
3465 forEachProp(defaults, function(key, value) {
3466 _this.options[key] = customOptions.hasOwnProperty(key) ? customOptions[key] : value;
3467 });
3468 this.hadInitialPlaceholder = Boolean(input.getAttribute("placeholder"));
3469 }
3470 _createClass(Iti, [ {
3471 key: "_init",
3472 value: function _init() {
3473 var _this2 = this;
3474 // if in nationalMode, disable options relating to dial codes
3475 if (this.options.nationalMode) this.options.autoHideDialCode = false;
3476 // if separateDialCode then doesn't make sense to A) insert dial code into input
3477 // (autoHideDialCode), and B) display national numbers (because we're displaying the country
3478 // dial code next to them)
3479 if (this.options.separateDialCode) {
3480 this.options.autoHideDialCode = this.options.nationalMode = false;
3481 }
3482 // we cannot just test screen size as some smartphones/website meta tags will report desktop
3483 // resolutions
3484 // Note: for some reason jasmine breaks if you put this in the main Plugin function with the
3485 // rest of these declarations
3486 // Note: to target Android Mobiles (and not Tablets), we must find 'Android' and 'Mobile'
3487 this.isMobile = /Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
3488 if (this.isMobile) {
3489 // trigger the mobile dropdown css
3490 document.body.classList.add("iti-mobile");
3491 // on mobile, we want a full screen dropdown, so we must append it to the body
3492 if (!this.options.dropdownContainer) this.options.dropdownContainer = document.body;
3493 }
3494 // these promises get resolved when their individual requests complete
3495 // this way the dev can do something like iti.promise.then(...) to know when all requests are
3496 // complete
3497 if (typeof Promise !== "undefined") {
3498 var autoCountryPromise = new Promise(function(resolve, reject) {
3499 _this2.resolveAutoCountryPromise = resolve;
3500 _this2.rejectAutoCountryPromise = reject;
3501 });
3502 var utilsScriptPromise = new Promise(function(resolve, reject) {
3503 _this2.resolveUtilsScriptPromise = resolve;
3504 _this2.rejectUtilsScriptPromise = reject;
3505 });
3506 this.promise = Promise.all([ autoCountryPromise, utilsScriptPromise ]);
3507 } else {
3508 // prevent errors when Promise doesn't exist
3509 this.resolveAutoCountryPromise = this.rejectAutoCountryPromise = function() {};
3510 this.resolveUtilsScriptPromise = this.rejectUtilsScriptPromise = function() {};
3511 }
3512 // in various situations there could be no country selected initially, but we need to be able
3513 // to assume this variable exists
3514 this.selectedCountryData = {};
3515 // process all the data: onlyCountries, excludeCountries, preferredCountries etc
3516 this._processCountryData();
3517 // generate the markup
3518 this._generateMarkup();
3519 // set the initial state of the input value and the selected flag
3520 this._setInitialState();
3521 // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click
3522 this._initListeners();
3523 // utils script, and auto country
3524 this._initRequests();
3525 }
3526 }, {
3527 key: "_processCountryData",
3528 value: function _processCountryData() {
3529 // process onlyCountries or excludeCountries array if present
3530 this._processAllCountries();
3531 // process the countryCodes map
3532 this._processCountryCodes();
3533 // process the preferredCountries
3534 this._processPreferredCountries();
3535 // translate countries according to localizedCountries option
3536 if (this.options.localizedCountries) this._translateCountriesByLocale();
3537 // sort countries by name
3538 if (this.options.onlyCountries.length || this.options.localizedCountries) {
3539 this.countries.sort(this._countryNameSort);
3540 }
3541 }
3542 }, {
3543 key: "_addCountryCode",
3544 value: function _addCountryCode(iso2, countryCode, priority) {
3545 if (countryCode.length > this.countryCodeMaxLen) {
3546 this.countryCodeMaxLen = countryCode.length;
3547 }
3548 if (!this.countryCodes.hasOwnProperty(countryCode)) {
3549 this.countryCodes[countryCode] = [];
3550 }
3551 // bail if we already have this country for this countryCode
3552 for (var i = 0; i < this.countryCodes[countryCode].length; i++) {
3553 if (this.countryCodes[countryCode][i] === iso2) return;
3554 }
3555 // check for undefined as 0 is falsy
3556 var index = priority !== undefined ? priority : this.countryCodes[countryCode].length;
3557 this.countryCodes[countryCode][index] = iso2;
3558 }
3559 }, {
3560 key: "_processAllCountries",
3561 value: function _processAllCountries() {
3562 if (this.options.onlyCountries.length) {
3563 var lowerCaseOnlyCountries = this.options.onlyCountries.map(function(country) {
3564 return country.toLowerCase();
3565 });
3566 this.countries = allCountries.filter(function(country) {
3567 return lowerCaseOnlyCountries.indexOf(country.iso2) > -1;
3568 });
3569 } else if (this.options.excludeCountries.length) {
3570 var lowerCaseExcludeCountries = this.options.excludeCountries.map(function(country) {
3571 return country.toLowerCase();
3572 });
3573 this.countries = allCountries.filter(function(country) {
3574 return lowerCaseExcludeCountries.indexOf(country.iso2) === -1;
3575 });
3576 } else {
3577 this.countries = allCountries;
3578 }
3579 }
3580 }, {
3581 key: "_translateCountriesByLocale",
3582 value: function _translateCountriesByLocale() {
3583 for (var i = 0; i < this.countries.length; i++) {
3584 var iso = this.countries[i].iso2.toLowerCase();
3585 if (this.options.localizedCountries.hasOwnProperty(iso)) {
3586 this.countries[i].name = this.options.localizedCountries[iso];
3587 }
3588 }
3589 }
3590 }, {
3591 key: "_countryNameSort",
3592 value: function _countryNameSort(a, b) {
3593 return a.name.localeCompare(b.name);
3594 }
3595 }, {
3596 key: "_processCountryCodes",
3597 value: function _processCountryCodes() {
3598 this.countryCodeMaxLen = 0;
3599 // here we store just dial codes
3600 this.dialCodes = {};
3601 // here we store "country codes" (both dial codes and their area codes)
3602 this.countryCodes = {};
3603 // first: add dial codes
3604 for (var i = 0; i < this.countries.length; i++) {
3605 var c = this.countries[i];
3606 if (!this.dialCodes[c.dialCode]) this.dialCodes[c.dialCode] = true;
3607 this._addCountryCode(c.iso2, c.dialCode, c.priority);
3608 }
3609 // next: add area codes
3610 // this is a second loop over countries, to make sure we have all of the "root" countries
3611 // already in the map, so that we can access them, as each time we add an area code substring
3612 // to the map, we also need to include the "root" country's code, as that also matches
3613 for (var _i = 0; _i < this.countries.length; _i++) {
3614 var _c = this.countries[_i];
3615 // area codes
3616 if (_c.areaCodes) {
3617 var rootCountryCode = this.countryCodes[_c.dialCode][0];
3618 // for each area code
3619 for (var j = 0; j < _c.areaCodes.length; j++) {
3620 var areaCode = _c.areaCodes[j];
3621 // for each digit in the area code to add all partial matches as well
3622 for (var k = 1; k < areaCode.length; k++) {
3623 var partialDialCode = _c.dialCode + areaCode.substr(0, k);
3624 // start with the root country, as that also matches this dial code
3625 this._addCountryCode(rootCountryCode, partialDialCode);
3626 this._addCountryCode(_c.iso2, partialDialCode);
3627 }
3628 // add the full area code
3629 this._addCountryCode(_c.iso2, _c.dialCode + areaCode);
3630 }
3631 }
3632 }
3633 }
3634 }, {
3635 key: "_processPreferredCountries",
3636 value: function _processPreferredCountries() {
3637 this.preferredCountries = [];
3638 for (var i = 0; i < this.options.preferredCountries.length; i++) {
3639 var countryCode = this.options.preferredCountries[i].toLowerCase();
3640 var countryData = this._getCountryData(countryCode, false, true);
3641 if (countryData) this.preferredCountries.push(countryData);
3642 }
3643 }
3644 }, {
3645 key: "_createEl",
3646 value: function _createEl(name, attrs, container) {
3647 var el = document.createElement(name);
3648 if (attrs) forEachProp(attrs, function(key, value) {
3649 return el.setAttribute(key, value);
3650 });
3651 if (container) container.appendChild(el);
3652 return el;
3653 }
3654 }, {
3655 key: "_generateMarkup",
3656 value: function _generateMarkup() {
3657 // if autocomplete does not exist on the element and its form, then
3658 // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can
3659 // easily put the plugin in an inconsistent state e.g. the wrong flag selected for the
3660 // autocompleted number, which on submit could mean wrong number is saved (esp in nationalMode)
3661 if (!this.telInput.hasAttribute("autocomplete") && !(this.telInput.form && this.telInput.form.hasAttribute("autocomplete"))) {
3662 this.telInput.setAttribute("autocomplete", "off");
3663 }
3664 // containers (mostly for positioning)
3665 var parentClass = "iti";
3666 if (this.options.allowDropdown) parentClass += " iti--allow-dropdown";
3667 if (this.options.separateDialCode) parentClass += " iti--separate-dial-code";
3668 if (this.options.customContainer) {
3669 parentClass += " ";
3670 parentClass += this.options.customContainer;
3671 }
3672 var wrapper = this._createEl("div", {
3673 "class": parentClass
3674 });
3675 this.telInput.parentNode.insertBefore(wrapper, this.telInput);
3676 this.flagsContainer = this._createEl("div", {
3677 "class": "iti__flag-container"
3678 }, wrapper);
3679 wrapper.appendChild(this.telInput);
3680 // selected flag (displayed to left of input)
3681 this.selectedFlag = this._createEl("div", {
3682 "class": "iti__selected-flag",
3683 role: "combobox",
3684 "aria-controls": "iti-".concat(this.id, "__country-listbox"),
3685 "aria-owns": "iti-".concat(this.id, "__country-listbox"),
3686 "aria-expanded": "false"
3687 }, this.flagsContainer);
3688 this.selectedFlagInner = this._createEl("div", {
3689 "class": "iti__flag"
3690 }, this.selectedFlag);
3691 if (this.options.separateDialCode) {
3692 this.selectedDialCode = this._createEl("div", {
3693 "class": "iti__selected-dial-code"
3694 }, this.selectedFlag);
3695 }
3696 if (this.options.allowDropdown) {
3697 // make element focusable and tab navigable
3698 this.selectedFlag.setAttribute("tabindex", "0");
3699 this.dropdownArrow = this._createEl("div", {
3700 "class": "iti__arrow"
3701 }, this.selectedFlag);
3702 // country dropdown: preferred countries, then divider, then all countries
3703 this.countryList = this._createEl("ul", {
3704 "class": "iti__country-list iti__hide",
3705 id: "iti-".concat(this.id, "__country-listbox"),
3706 role: "listbox",
3707 "aria-label": "List of countries"
3708 });
3709 if (this.preferredCountries.length) {
3710 this._appendListItems(this.preferredCountries, "iti__preferred", true);
3711 this._createEl("li", {
3712 "class": "iti__divider",
3713 role: "separator",
3714 "aria-disabled": "true"
3715 }, this.countryList);
3716 }
3717 this._appendListItems(this.countries, "iti__standard");
3718 // create dropdownContainer markup
3719 if (this.options.dropdownContainer) {
3720 this.dropdown = this._createEl("div", {
3721 "class": "iti iti--container"
3722 });
3723 this.dropdown.appendChild(this.countryList);
3724 } else {
3725 this.flagsContainer.appendChild(this.countryList);
3726 }
3727 }
3728 if (this.options.hiddenInput) {
3729 var hiddenInputName = this.options.hiddenInput;
3730 var name = this.telInput.getAttribute("name");
3731 if (name) {
3732 var i = name.lastIndexOf("[");
3733 // if input name contains square brackets, then give the hidden input the same name,
3734 // replacing the contents of the last set of brackets with the given hiddenInput name
3735 if (i !== -1) hiddenInputName = "".concat(name.substr(0, i), "[").concat(hiddenInputName, "]");
3736 }
3737 this.hiddenInput = this._createEl("input", {
3738 type: "hidden",
3739 name: hiddenInputName
3740 });
3741 wrapper.appendChild(this.hiddenInput);
3742 }
3743 }
3744 }, {
3745 key: "_appendListItems",
3746 value: function _appendListItems(countries, className, preferred) {
3747 // we create so many DOM elements, it is faster to build a temp string
3748 // and then add everything to the DOM in one go at the end
3749 var tmp = "";
3750 // for each country
3751 for (var i = 0; i < countries.length; i++) {
3752 var c = countries[i];
3753 var idSuffix = preferred ? "-preferred" : "";
3754 // open the list item
3755 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'>");
3756 // add the flag
3757 tmp += "<div class='iti__flag-box'><div class='iti__flag iti__".concat(c.iso2, "'></div></div>");
3758 // and the country name and dial code
3759 tmp += "<span class='iti__country-name'>".concat(c.name, "</span>");
3760 tmp += "<span class='iti__dial-code'>+".concat(c.dialCode, "</span>");
3761 // close the list item
3762 tmp += "</li>";
3763 }
3764 this.countryList.insertAdjacentHTML("beforeend", tmp);
3765 }
3766 }, {
3767 key: "_setInitialState",
3768 value: function _setInitialState() {
3769 // fix firefox bug: when first load page (with input with value set to number with intl dial
3770 // code) and initialising plugin removes the dial code from the input, then refresh page,
3771 // and we try to init plugin again but this time on number without dial code so get grey flag
3772 var attributeValue = this.telInput.getAttribute("value");
3773 var inputValue = this.telInput.value;
3774 var useAttribute = attributeValue && attributeValue.charAt(0) === "+" && (!inputValue || inputValue.charAt(0) !== "+");
3775 var val = useAttribute ? attributeValue : inputValue;
3776 var dialCode = this._getDialCode(val);
3777 var isRegionlessNanp = this._isRegionlessNanp(val);
3778 var _this$options = this.options, initialCountry = _this$options.initialCountry, nationalMode = _this$options.nationalMode, autoHideDialCode = _this$options.autoHideDialCode, separateDialCode = _this$options.separateDialCode;
3779 // if we already have a dial code, and it's not a regionlessNanp, we can go ahead and set the
3780 // flag, else fall back to the default country
3781 if (dialCode && !isRegionlessNanp) {
3782 this._updateFlagFromNumber(val);
3783 } else if (initialCountry !== "auto") {
3784 // see if we should select a flag
3785 if (initialCountry) {
3786 this._setFlag(initialCountry.toLowerCase());
3787 } else {
3788 if (dialCode && isRegionlessNanp) {
3789 // has intl dial code, is regionless nanp, and no initialCountry, so default to US
3790 this._setFlag("us");
3791 } else {
3792 // no dial code and no initialCountry, so default to first in list
3793 this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2;
3794 if (!val) {
3795 this._setFlag(this.defaultCountry);
3796 }
3797 }
3798 }
3799 // if empty and no nationalMode and no autoHideDialCode then insert the default dial code
3800 if (!val && !nationalMode && !autoHideDialCode && !separateDialCode) {
3801 this.telInput.value = "+".concat(this.selectedCountryData.dialCode);
3802 }
3803 }
3804 // NOTE: if initialCountry is set to auto, that will be handled separately
3805 // format - note this wont be run after _updateDialCode as that's only called if no val
3806 if (val) this._updateValFromNumber(val);
3807 }
3808 }, {
3809 key: "_initListeners",
3810 value: function _initListeners() {
3811 this._initKeyListeners();
3812 if (this.options.autoHideDialCode) this._initBlurListeners();
3813 if (this.options.allowDropdown) this._initDropdownListeners();
3814 if (this.hiddenInput) this._initHiddenInputListener();
3815 }
3816 }, {
3817 key: "_initHiddenInputListener",
3818 value: function _initHiddenInputListener() {
3819 var _this3 = this;
3820 this._handleHiddenInputSubmit = function() {
3821 _this3.hiddenInput.value = _this3.getNumber();
3822 };
3823 if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleHiddenInputSubmit);
3824 }
3825 }, {
3826 key: "_getClosestLabel",
3827 value: function _getClosestLabel() {
3828 var el = this.telInput;
3829 while (el && el.tagName !== "LABEL") {
3830 el = el.parentNode;
3831 }
3832 return el;
3833 }
3834 }, {
3835 key: "_initDropdownListeners",
3836 value: function _initDropdownListeners() {
3837 var _this4 = this;
3838 // hack for input nested inside label (which is valid markup): clicking the selected-flag to
3839 // open the dropdown would then automatically trigger a 2nd click on the input which would
3840 // close it again
3841 this._handleLabelClick = function(e) {
3842 // if the dropdown is closed, then focus the input, else ignore the click
3843 if (_this4.countryList.classList.contains("iti__hide")) _this4.telInput.focus(); else e.preventDefault();
3844 };
3845 var label = this._getClosestLabel();
3846 if (label) label.addEventListener("click", this._handleLabelClick);
3847 // toggle country dropdown on click
3848 this._handleClickSelectedFlag = function() {
3849 // only intercept this event if we're opening the dropdown
3850 // else let it bubble up to the top ("click-off-to-close" listener)
3851 // we cannot just stopPropagation as it may be needed to close another instance
3852 if (_this4.countryList.classList.contains("iti__hide") && !_this4.telInput.disabled && !_this4.telInput.readOnly) {
3853 _this4._showDropdown();
3854 }
3855 };
3856 this.selectedFlag.addEventListener("click", this._handleClickSelectedFlag);
3857 // open dropdown list if currently focused
3858 this._handleFlagsContainerKeydown = function(e) {
3859 var isDropdownHidden = _this4.countryList.classList.contains("iti__hide");
3860 if (isDropdownHidden && [ "ArrowUp", "Up", "ArrowDown", "Down", " ", "Enter" ].indexOf(e.key) !== -1) {
3861 // prevent form from being submitted if "ENTER" was pressed
3862 e.preventDefault();
3863 // prevent event from being handled again by document
3864 e.stopPropagation();
3865 _this4._showDropdown();
3866 }
3867 // allow navigation from dropdown to input on TAB
3868 if (e.key === "Tab") _this4._closeDropdown();
3869 };
3870 this.flagsContainer.addEventListener("keydown", this._handleFlagsContainerKeydown);
3871 }
3872 }, {
3873 key: "_initRequests",
3874 value: function _initRequests() {
3875 var _this5 = this;
3876 // if the user has specified the path to the utils script, fetch it on window.load, else resolve
3877 if (this.options.utilsScript && !window.intlTelInputUtils) {
3878 // if the plugin is being initialised after the window.load event has already been fired
3879 if (window.intlTelInputGlobals.documentReady()) {
3880 window.intlTelInputGlobals.loadUtils(this.options.utilsScript);
3881 } else {
3882 // wait until the load event so we don't block any other requests e.g. the flags image
3883 window.addEventListener("load", function() {
3884 window.intlTelInputGlobals.loadUtils(_this5.options.utilsScript);
3885 });
3886 }
3887 } else this.resolveUtilsScriptPromise();
3888 if (this.options.initialCountry === "auto") this._loadAutoCountry(); else this.resolveAutoCountryPromise();
3889 }
3890 }, {
3891 key: "_loadAutoCountry",
3892 value: function _loadAutoCountry() {
3893 // 3 options:
3894 // 1) already loaded (we're done)
3895 // 2) not already started loading (start)
3896 // 3) already started loading (do nothing - just wait for loading callback to fire)
3897 if (window.intlTelInputGlobals.autoCountry) {
3898 this.handleAutoCountry();
3899 } else if (!window.intlTelInputGlobals.startedLoadingAutoCountry) {
3900 // don't do this twice!
3901 window.intlTelInputGlobals.startedLoadingAutoCountry = true;
3902 if (typeof this.options.geoIpLookup === "function") {
3903 this.options.geoIpLookup(function(countryCode) {
3904 window.intlTelInputGlobals.autoCountry = countryCode.toLowerCase();
3905 // tell all instances the auto country is ready
3906 // TODO: this should just be the current instances
3907 // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight
3908 // away (e.g. if they have already done the geo ip lookup somewhere else). Using
3909 // setTimeout means that the current thread of execution will finish before executing
3910 // this, which allows the plugin to finish initialising.
3911 setTimeout(function() {
3912 return forEachInstance("handleAutoCountry");
3913 });
3914 }, function() {
3915 return forEachInstance("rejectAutoCountryPromise");
3916 });
3917 }
3918 }
3919 }
3920 }, {
3921 key: "_initKeyListeners",
3922 value: function _initKeyListeners() {
3923 var _this6 = this;
3924 // update flag on keyup
3925 this._handleKeyupEvent = function() {
3926 if (_this6._updateFlagFromNumber(_this6.telInput.value)) {
3927 _this6._triggerCountryChange();
3928 }
3929 };
3930 this.telInput.addEventListener("keyup", this._handleKeyupEvent);
3931 // update flag on cut/paste events (now supported in all major browsers)
3932 this._handleClipboardEvent = function() {
3933 // hack because "paste" event is fired before input is updated
3934 setTimeout(_this6._handleKeyupEvent);
3935 };
3936 this.telInput.addEventListener("cut", this._handleClipboardEvent);
3937 this.telInput.addEventListener("paste", this._handleClipboardEvent);
3938 }
3939 }, {
3940 key: "_cap",
3941 value: function _cap(number) {
3942 var max = this.telInput.getAttribute("maxlength");
3943 return max && number.length > max ? number.substr(0, max) : number;
3944 }
3945 }, {
3946 key: "_initBlurListeners",
3947 value: function _initBlurListeners() {
3948 var _this7 = this;
3949 // on blur or form submit: if just a dial code then remove it
3950 this._handleSubmitOrBlurEvent = function() {
3951 _this7._removeEmptyDialCode();
3952 };
3953 if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleSubmitOrBlurEvent);
3954 this.telInput.addEventListener("blur", this._handleSubmitOrBlurEvent);
3955 }
3956 }, {
3957 key: "_removeEmptyDialCode",
3958 value: function _removeEmptyDialCode() {
3959 if (this.telInput.value.charAt(0) === "+") {
3960 var numeric = this._getNumeric(this.telInput.value);
3961 // if just a plus, or if just a dial code
3962 if (!numeric || this.selectedCountryData.dialCode === numeric) {
3963 this.telInput.value = "";
3964 }
3965 }
3966 }
3967 }, {
3968 key: "_getNumeric",
3969 value: function _getNumeric(s) {
3970 return s.replace(/\D/g, "");
3971 }
3972 }, {
3973 key: "_trigger",
3974 value: function _trigger(name) {
3975 // have to use old school document.createEvent as IE11 doesn't support `new Event()` syntax
3976 var e = document.createEvent("Event");
3977 e.initEvent(name, true, true);
3978 // can bubble, and is cancellable
3979 this.telInput.dispatchEvent(e);
3980 }
3981 }, {
3982 key: "_showDropdown",
3983 value: function _showDropdown() {
3984 this.countryList.classList.remove("iti__hide");
3985 this.selectedFlag.setAttribute("aria-expanded", "true");
3986 this._setDropdownPosition();
3987 // update highlighting and scroll to active list item
3988 if (this.activeItem) {
3989 this._highlightListItem(this.activeItem, false);
3990 this._scrollTo(this.activeItem, true);
3991 }
3992 // bind all the dropdown-related listeners: mouseover, click, click-off, keydown
3993 this._bindDropdownListeners();
3994 // update the arrow
3995 this.dropdownArrow.classList.add("iti__arrow--up");
3996 this._trigger("open:countrydropdown");
3997 }
3998 }, {
3999 key: "_toggleClass",
4000 value: function _toggleClass(el, className, shouldHaveClass) {
4001 if (shouldHaveClass && !el.classList.contains(className)) el.classList.add(className); else if (!shouldHaveClass && el.classList.contains(className)) el.classList.remove(className);
4002 }
4003 }, {
4004 key: "_setDropdownPosition",
4005 value: function _setDropdownPosition() {
4006 var _this8 = this;
4007 if (this.options.dropdownContainer) {
4008 this.options.dropdownContainer.appendChild(this.dropdown);
4009 }
4010 if (!this.isMobile) {
4011 var pos = this.telInput.getBoundingClientRect();
4012 // windowTop from https://stackoverflow.com/a/14384091/217866
4013 var windowTop = window.pageYOffset || document.documentElement.scrollTop;
4014 var inputTop = pos.top + windowTop;
4015 var dropdownHeight = this.countryList.offsetHeight;
4016 // dropdownFitsBelow = (dropdownBottom < windowBottom)
4017 var dropdownFitsBelow = inputTop + this.telInput.offsetHeight + dropdownHeight < windowTop + window.innerHeight;
4018 var dropdownFitsAbove = inputTop - dropdownHeight > windowTop;
4019 // by default, the dropdown will be below the input. If we want to position it above the
4020 // input, we add the dropup class.
4021 this._toggleClass(this.countryList, "iti__country-list--dropup", !dropdownFitsBelow && dropdownFitsAbove);
4022 // if dropdownContainer is enabled, calculate postion
4023 if (this.options.dropdownContainer) {
4024 // by default the dropdown will be directly over the input because it's not in the flow.
4025 // If we want to position it below, we need to add some extra top value.
4026 var extraTop = !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.offsetHeight;
4027 // calculate placement
4028 this.dropdown.style.top = "".concat(inputTop + extraTop, "px");
4029 this.dropdown.style.left = "".concat(pos.left + document.body.scrollLeft, "px");
4030 // close menu on window scroll
4031 this._handleWindowScroll = function() {
4032 return _this8._closeDropdown();
4033 };
4034 window.addEventListener("scroll", this._handleWindowScroll);
4035 }
4036 }
4037 }
4038 }, {
4039 key: "_getClosestListItem",
4040 value: function _getClosestListItem(target) {
4041 var el = target;
4042 while (el && el !== this.countryList && !el.classList.contains("iti__country")) {
4043 el = el.parentNode;
4044 }
4045 // if we reached the countryList element, then return null
4046 return el === this.countryList ? null : el;
4047 }
4048 }, {
4049 key: "_bindDropdownListeners",
4050 value: function _bindDropdownListeners() {
4051 var _this9 = this;
4052 // when mouse over a list item, just highlight that one
4053 // we add the class "highlight", so if they hit "enter" we know which one to select
4054 this._handleMouseoverCountryList = function(e) {
4055 // handle event delegation, as we're listening for this event on the countryList
4056 var listItem = _this9._getClosestListItem(e.target);
4057 if (listItem) _this9._highlightListItem(listItem, false);
4058 };
4059 this.countryList.addEventListener("mouseover", this._handleMouseoverCountryList);
4060 // listen for country selection
4061 this._handleClickCountryList = function(e) {
4062 var listItem = _this9._getClosestListItem(e.target);
4063 if (listItem) _this9._selectListItem(listItem);
4064 };
4065 this.countryList.addEventListener("click", this._handleClickCountryList);
4066 // click off to close
4067 // (except when this initial opening click is bubbling up)
4068 // we cannot just stopPropagation as it may be needed to close another instance
4069 var isOpening = true;
4070 this._handleClickOffToClose = function() {
4071 if (!isOpening) _this9._closeDropdown();
4072 isOpening = false;
4073 };
4074 document.documentElement.addEventListener("click", this._handleClickOffToClose);
4075 // listen for up/down scrolling, enter to select, or letters to jump to country name.
4076 // use keydown as keypress doesn't fire for non-char keys and we want to catch if they
4077 // just hit down and hold it to scroll down (no keyup event).
4078 // listen on the document because that's where key events are triggered if no input has focus
4079 var query = "";
4080 var queryTimer = null;
4081 this._handleKeydownOnDropdown = function(e) {
4082 // prevent down key from scrolling the whole page,
4083 // and enter key from submitting a form etc
4084 e.preventDefault();
4085 // up and down to navigate
4086 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)) {
4087 // jump to countries that start with the query string
4088 if (queryTimer) clearTimeout(queryTimer);
4089 query += e.key.toLowerCase();
4090 _this9._searchForCountry(query);
4091 // if the timer hits 1 second, reset the query
4092 queryTimer = setTimeout(function() {
4093 query = "";
4094 }, 1e3);
4095 }
4096 };
4097 document.addEventListener("keydown", this._handleKeydownOnDropdown);
4098 }
4099 }, {
4100 key: "_handleUpDownKey",
4101 value: function _handleUpDownKey(key) {
4102 var next = key === "ArrowUp" || key === "Up" ? this.highlightedItem.previousElementSibling : this.highlightedItem.nextElementSibling;
4103 if (next) {
4104 // skip the divider
4105 if (next.classList.contains("iti__divider")) {
4106 next = key === "ArrowUp" || key === "Up" ? next.previousElementSibling : next.nextElementSibling;
4107 }
4108 this._highlightListItem(next, true);
4109 }
4110 }
4111 }, {
4112 key: "_handleEnterKey",
4113 value: function _handleEnterKey() {
4114 if (this.highlightedItem) this._selectListItem(this.highlightedItem);
4115 }
4116 }, {
4117 key: "_searchForCountry",
4118 value: function _searchForCountry(query) {
4119 for (var i = 0; i < this.countries.length; i++) {
4120 if (this._startsWith(this.countries[i].name, query)) {
4121 var listItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(this.countries[i].iso2));
4122 // update highlighting and scroll
4123 this._highlightListItem(listItem, false);
4124 this._scrollTo(listItem, true);
4125 break;
4126 }
4127 }
4128 }
4129 }, {
4130 key: "_startsWith",
4131 value: function _startsWith(a, b) {
4132 return a.substr(0, b.length).toLowerCase() === b;
4133 }
4134 }, {
4135 key: "_updateValFromNumber",
4136 value: function _updateValFromNumber(originalNumber) {
4137 var number = originalNumber;
4138 if (this.options.formatOnDisplay && window.intlTelInputUtils && this.selectedCountryData) {
4139 var useNational = !this.options.separateDialCode && (this.options.nationalMode || number.charAt(0) !== "+");
4140 var _intlTelInputUtils$nu = intlTelInputUtils.numberFormat, NATIONAL = _intlTelInputUtils$nu.NATIONAL, INTERNATIONAL = _intlTelInputUtils$nu.INTERNATIONAL;
4141 var format = useNational ? NATIONAL : INTERNATIONAL;
4142 number = intlTelInputUtils.formatNumber(number, this.selectedCountryData.iso2, format);
4143 }
4144 number = this._beforeSetNumber(number);
4145 this.telInput.value = number;
4146 }
4147 }, {
4148 key: "_updateFlagFromNumber",
4149 value: function _updateFlagFromNumber(originalNumber) {
4150 // if we're in nationalMode and we already have US/Canada selected, make sure the number starts
4151 // with a +1 so _getDialCode will be able to extract the area code
4152 // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag
4153 // from the number), that means we're initialising the plugin with a number that already has a
4154 // dial code, so fine to ignore this bit
4155 var number = originalNumber;
4156 var selectedDialCode = this.selectedCountryData.dialCode;
4157 var isNanp = selectedDialCode === "1";
4158 if (number && this.options.nationalMode && isNanp && number.charAt(0) !== "+") {
4159 if (number.charAt(0) !== "1") number = "1".concat(number);
4160 number = "+".concat(number);
4161 }
4162 // update flag if user types area code for another country
4163 if (this.options.separateDialCode && selectedDialCode && number.charAt(0) !== "+") {
4164 number = "+".concat(selectedDialCode).concat(number);
4165 }
4166 // try and extract valid dial code from input
4167 var dialCode = this._getDialCode(number, true);
4168 var numeric = this._getNumeric(number);
4169 var countryCode = null;
4170 if (dialCode) {
4171 var countryCodes = this.countryCodes[this._getNumeric(dialCode)];
4172 // check if the right country is already selected. this should be false if the number is
4173 // longer than the matched dial code because in this case we need to make sure that if
4174 // there are multiple country matches, that the first one is selected (note: we could
4175 // just check that here, but it requires the same loop that we already have later)
4176 var alreadySelected = countryCodes.indexOf(this.selectedCountryData.iso2) !== -1 && numeric.length <= dialCode.length - 1;
4177 var isRegionlessNanpNumber = selectedDialCode === "1" && this._isRegionlessNanp(numeric);
4178 // only update the flag if:
4179 // A) NOT (we currently have a NANP flag selected, and the number is a regionlessNanp)
4180 // AND
4181 // B) the right country is not already selected
4182 if (!isRegionlessNanpNumber && !alreadySelected) {
4183 // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first
4184 // non-empty index
4185 for (var j = 0; j < countryCodes.length; j++) {
4186 if (countryCodes[j]) {
4187 countryCode = countryCodes[j];
4188 break;
4189 }
4190 }
4191 }
4192 } else if (number.charAt(0) === "+" && numeric.length) {
4193 // invalid dial code, so empty
4194 // Note: use getNumeric here because the number has not been formatted yet, so could contain
4195 // bad chars
4196 countryCode = "";
4197 } else if (!number || number === "+") {
4198 // empty, or just a plus, so default
4199 countryCode = this.defaultCountry;
4200 }
4201 if (countryCode !== null) {
4202 return this._setFlag(countryCode);
4203 }
4204 return false;
4205 }
4206 }, {
4207 key: "_isRegionlessNanp",
4208 value: function _isRegionlessNanp(number) {
4209 var numeric = this._getNumeric(number);
4210 if (numeric.charAt(0) === "1") {
4211 var areaCode = numeric.substr(1, 3);
4212 return regionlessNanpNumbers.indexOf(areaCode) !== -1;
4213 }
4214 return false;
4215 }
4216 }, {
4217 key: "_highlightListItem",
4218 value: function _highlightListItem(listItem, shouldFocus) {
4219 var prevItem = this.highlightedItem;
4220 if (prevItem) prevItem.classList.remove("iti__highlight");
4221 this.highlightedItem = listItem;
4222 this.highlightedItem.classList.add("iti__highlight");
4223 if (shouldFocus) this.highlightedItem.focus();
4224 }
4225 }, {
4226 key: "_getCountryData",
4227 value: function _getCountryData(countryCode, ignoreOnlyCountriesOption, allowFail) {
4228 var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
4229 for (var i = 0; i < countryList.length; i++) {
4230 if (countryList[i].iso2 === countryCode) {
4231 return countryList[i];
4232 }
4233 }
4234 if (allowFail) {
4235 return null;
4236 }
4237 throw new Error("No country data for '".concat(countryCode, "'"));
4238 }
4239 }, {
4240 key: "_setFlag",
4241 value: function _setFlag(countryCode) {
4242 var prevCountry = this.selectedCountryData.iso2 ? this.selectedCountryData : {};
4243 // do this first as it will throw an error and stop if countryCode is invalid
4244 this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {};
4245 // update the defaultCountry - we only need the iso2 from now on, so just store that
4246 if (this.selectedCountryData.iso2) {
4247 this.defaultCountry = this.selectedCountryData.iso2;
4248 }
4249 this.selectedFlagInner.setAttribute("class", "iti__flag iti__".concat(countryCode));
4250 // update the selected country's title attribute
4251 var title = countryCode ? "".concat(this.selectedCountryData.name, ": +").concat(this.selectedCountryData.dialCode) : "Unknown";
4252 this.selectedFlag.setAttribute("title", title);
4253 if (this.options.separateDialCode) {
4254 var dialCode = this.selectedCountryData.dialCode ? "+".concat(this.selectedCountryData.dialCode) : "";
4255 this.selectedDialCode.innerHTML = dialCode;
4256 // offsetWidth is zero if input is in a hidden container during initialisation
4257 var selectedFlagWidth = this.selectedFlag.offsetWidth || this._getHiddenSelectedFlagWidth();
4258 // add 6px of padding after the grey selected-dial-code box, as this is what we use in the css
4259 this.telInput.style.paddingLeft = "".concat(selectedFlagWidth + 6, "px");
4260 }
4261 // and the input's placeholder
4262 this._updatePlaceholder();
4263 // update the active list item
4264 if (this.options.allowDropdown) {
4265 var prevItem = this.activeItem;
4266 if (prevItem) {
4267 prevItem.classList.remove("iti__active");
4268 prevItem.setAttribute("aria-selected", "false");
4269 }
4270 if (countryCode) {
4271 // check if there is a preferred item first, else fall back to standard
4272 var nextItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode, "-preferred")) || this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode));
4273 nextItem.setAttribute("aria-selected", "true");
4274 nextItem.classList.add("iti__active");
4275 this.activeItem = nextItem;
4276 this.selectedFlag.setAttribute("aria-activedescendant", nextItem.getAttribute("id"));
4277 }
4278 }
4279 // return if the flag has changed or not
4280 return prevCountry.iso2 !== countryCode;
4281 }
4282 }, {
4283 key: "_getHiddenSelectedFlagWidth",
4284 value: function _getHiddenSelectedFlagWidth() {
4285 // to get the right styling to apply, all we need is a shallow clone of the container,
4286 // and then to inject a deep clone of the selectedFlag element
4287 var containerClone = this.telInput.parentNode.cloneNode();
4288 containerClone.style.visibility = "hidden";
4289 document.body.appendChild(containerClone);
4290 var flagsContainerClone = this.flagsContainer.cloneNode();
4291 containerClone.appendChild(flagsContainerClone);
4292 var selectedFlagClone = this.selectedFlag.cloneNode(true);
4293 flagsContainerClone.appendChild(selectedFlagClone);
4294 var width = selectedFlagClone.offsetWidth;
4295 containerClone.parentNode.removeChild(containerClone);
4296 return width;
4297 }
4298 }, {
4299 key: "_updatePlaceholder",
4300 value: function _updatePlaceholder() {
4301 var shouldSetPlaceholder = this.options.autoPlaceholder === "aggressive" || !this.hadInitialPlaceholder && this.options.autoPlaceholder === "polite";
4302 if (window.intlTelInputUtils && shouldSetPlaceholder) {
4303 var numberType = intlTelInputUtils.numberType[this.options.placeholderNumberType];
4304 var placeholder = this.selectedCountryData.iso2 ? intlTelInputUtils.getExampleNumber(this.selectedCountryData.iso2, this.options.nationalMode, numberType) : "";
4305 placeholder = this._beforeSetNumber(placeholder);
4306 if (typeof this.options.customPlaceholder === "function") {
4307 placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData);
4308 }
4309 this.telInput.setAttribute("placeholder", placeholder);
4310 }
4311 }
4312 }, {
4313 key: "_selectListItem",
4314 value: function _selectListItem(listItem) {
4315 // update selected flag and active list item
4316 var flagChanged = this._setFlag(listItem.getAttribute("data-country-code"));
4317 this._closeDropdown();
4318 this._updateDialCode(listItem.getAttribute("data-dial-code"), true);
4319 // focus the input
4320 this.telInput.focus();
4321 // put cursor at end - this fix is required for FF and IE11 (with nationalMode=false i.e. auto
4322 // inserting dial code), who try to put the cursor at the beginning the first time
4323 var len = this.telInput.value.length;
4324 this.telInput.setSelectionRange(len, len);
4325 if (flagChanged) {
4326 this._triggerCountryChange();
4327 }
4328 }
4329 }, {
4330 key: "_closeDropdown",
4331 value: function _closeDropdown() {
4332 this.countryList.classList.add("iti__hide");
4333 this.selectedFlag.setAttribute("aria-expanded", "false");
4334 // update the arrow
4335 this.dropdownArrow.classList.remove("iti__arrow--up");
4336 // unbind key events
4337 document.removeEventListener("keydown", this._handleKeydownOnDropdown);
4338 document.documentElement.removeEventListener("click", this._handleClickOffToClose);
4339 this.countryList.removeEventListener("mouseover", this._handleMouseoverCountryList);
4340 this.countryList.removeEventListener("click", this._handleClickCountryList);
4341 // remove menu from container
4342 if (this.options.dropdownContainer) {
4343 if (!this.isMobile) window.removeEventListener("scroll", this._handleWindowScroll);
4344 if (this.dropdown.parentNode) this.dropdown.parentNode.removeChild(this.dropdown);
4345 }
4346 this._trigger("close:countrydropdown");
4347 }
4348 }, {
4349 key: "_scrollTo",
4350 value: function _scrollTo(element, middle) {
4351 var container = this.countryList;
4352 // windowTop from https://stackoverflow.com/a/14384091/217866
4353 var windowTop = window.pageYOffset || document.documentElement.scrollTop;
4354 var containerHeight = container.offsetHeight;
4355 var containerTop = container.getBoundingClientRect().top + windowTop;
4356 var containerBottom = containerTop + containerHeight;
4357 var elementHeight = element.offsetHeight;
4358 var elementTop = element.getBoundingClientRect().top + windowTop;
4359 var elementBottom = elementTop + elementHeight;
4360 var newScrollTop = elementTop - containerTop + container.scrollTop;
4361 var middleOffset = containerHeight / 2 - elementHeight / 2;
4362 if (elementTop < containerTop) {
4363 // scroll up
4364 if (middle) newScrollTop -= middleOffset;
4365 container.scrollTop = newScrollTop;
4366 } else if (elementBottom > containerBottom) {
4367 // scroll down
4368 if (middle) newScrollTop += middleOffset;
4369 var heightDifference = containerHeight - elementHeight;
4370 container.scrollTop = newScrollTop - heightDifference;
4371 }
4372 }
4373 }, {
4374 key: "_updateDialCode",
4375 value: function _updateDialCode(newDialCodeBare, hasSelectedListItem) {
4376 var inputVal = this.telInput.value;
4377 // save having to pass this every time
4378 var newDialCode = "+".concat(newDialCodeBare);
4379 var newNumber;
4380 if (inputVal.charAt(0) === "+") {
4381 // there's a plus so we're dealing with a replacement (doesn't matter if nationalMode or not)
4382 var prevDialCode = this._getDialCode(inputVal);
4383 if (prevDialCode) {
4384 // current number contains a valid dial code, so replace it
4385 newNumber = inputVal.replace(prevDialCode, newDialCode);
4386 } else {
4387 // current number contains an invalid dial code, so ditch it
4388 // (no way to determine where the invalid dial code ends and the rest of the number begins)
4389 newNumber = newDialCode;
4390 }
4391 } else if (this.options.nationalMode || this.options.separateDialCode) {
4392 // don't do anything
4393 return;
4394 } else {
4395 // nationalMode is disabled
4396 if (inputVal) {
4397 // there is an existing value with no dial code: prefix the new dial code
4398 newNumber = newDialCode + inputVal;
4399 } else if (hasSelectedListItem || !this.options.autoHideDialCode) {
4400 // no existing value and either they've just selected a list item, or autoHideDialCode is
4401 // disabled: insert new dial code
4402 newNumber = newDialCode;
4403 } else {
4404 return;
4405 }
4406 }
4407 this.telInput.value = newNumber;
4408 }
4409 }, {
4410 key: "_getDialCode",
4411 value: function _getDialCode(number, includeAreaCode) {
4412 var dialCode = "";
4413 // only interested in international numbers (starting with a plus)
4414 if (number.charAt(0) === "+") {
4415 var numericChars = "";
4416 // iterate over chars
4417 for (var i = 0; i < number.length; i++) {
4418 var c = number.charAt(i);
4419 // if char is number (https://stackoverflow.com/a/8935649/217866)
4420 if (!isNaN(parseInt(c, 10))) {
4421 numericChars += c;
4422 // if current numericChars make a valid dial code
4423 if (includeAreaCode) {
4424 if (this.countryCodes[numericChars]) {
4425 // store the actual raw string (useful for matching later)
4426 dialCode = number.substr(0, i + 1);
4427 }
4428 } else {
4429 if (this.dialCodes[numericChars]) {
4430 dialCode = number.substr(0, i + 1);
4431 // if we're just looking for a dial code, we can break as soon as we find one
4432 break;
4433 }
4434 }
4435 // stop searching as soon as we can - in this case when we hit max len
4436 if (numericChars.length === this.countryCodeMaxLen) {
4437 break;
4438 }
4439 }
4440 }
4441 }
4442 return dialCode;
4443 }
4444 }, {
4445 key: "_getFullNumber",
4446 value: function _getFullNumber() {
4447 var val = this.telInput.value.trim();
4448 var dialCode = this.selectedCountryData.dialCode;
4449 var prefix;
4450 var numericVal = this._getNumeric(val);
4451 if (this.options.separateDialCode && val.charAt(0) !== "+" && dialCode && numericVal) {
4452 // when using separateDialCode, it is visible so is effectively part of the typed number
4453 prefix = "+".concat(dialCode);
4454 } else {
4455 prefix = "";
4456 }
4457 return prefix + val;
4458 }
4459 }, {
4460 key: "_beforeSetNumber",
4461 value: function _beforeSetNumber(originalNumber) {
4462 var number = originalNumber;
4463 if (this.options.separateDialCode) {
4464 var dialCode = this._getDialCode(number);
4465 // if there is a valid dial code
4466 if (dialCode) {
4467 // in case _getDialCode returned an area code as well
4468 dialCode = "+".concat(this.selectedCountryData.dialCode);
4469 // a lot of numbers will have a space separating the dial code and the main number, and
4470 // some NANP numbers will have a hyphen e.g. +1 684-733-1234 - in both cases we want to get
4471 // rid of it
4472 // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc
4473 var start = number[dialCode.length] === " " || number[dialCode.length] === "-" ? dialCode.length + 1 : dialCode.length;
4474 number = number.substr(start);
4475 }
4476 }
4477 return this._cap(number);
4478 }
4479 }, {
4480 key: "_triggerCountryChange",
4481 value: function _triggerCountryChange() {
4482 this._trigger("countrychange");
4483 }
4484 }, {
4485 key: "handleAutoCountry",
4486 value: function handleAutoCountry() {
4487 if (this.options.initialCountry === "auto") {
4488 // we must set this even if there is an initial val in the input: in case the initial val is
4489 // invalid and they delete it - they should see their auto country
4490 this.defaultCountry = window.intlTelInputGlobals.autoCountry;
4491 // if there's no initial value in the input, then update the flag
4492 if (!this.telInput.value) {
4493 this.setCountry(this.defaultCountry);
4494 }
4495 this.resolveAutoCountryPromise();
4496 }
4497 }
4498 }, {
4499 key: "handleUtils",
4500 value: function handleUtils() {
4501 // if the request was successful
4502 if (window.intlTelInputUtils) {
4503 // if there's an initial value in the input, then format it
4504 if (this.telInput.value) {
4505 this._updateValFromNumber(this.telInput.value);
4506 }
4507 this._updatePlaceholder();
4508 }
4509 this.resolveUtilsScriptPromise();
4510 }
4511 }, {
4512 key: "destroy",
4513 value: function destroy() {
4514 var form = this.telInput.form;
4515 if (this.options.allowDropdown) {
4516 // make sure the dropdown is closed (and unbind listeners)
4517 this._closeDropdown();
4518 this.selectedFlag.removeEventListener("click", this._handleClickSelectedFlag);
4519 this.flagsContainer.removeEventListener("keydown", this._handleFlagsContainerKeydown);
4520 // label click hack
4521 var label = this._getClosestLabel();
4522 if (label) label.removeEventListener("click", this._handleLabelClick);
4523 }
4524 // unbind hiddenInput listeners
4525 if (this.hiddenInput && form) form.removeEventListener("submit", this._handleHiddenInputSubmit);
4526 // unbind autoHideDialCode listeners
4527 if (this.options.autoHideDialCode) {
4528 if (form) form.removeEventListener("submit", this._handleSubmitOrBlurEvent);
4529 this.telInput.removeEventListener("blur", this._handleSubmitOrBlurEvent);
4530 }
4531 // unbind key events, and cut/paste events
4532 this.telInput.removeEventListener("keyup", this._handleKeyupEvent);
4533 this.telInput.removeEventListener("cut", this._handleClipboardEvent);
4534 this.telInput.removeEventListener("paste", this._handleClipboardEvent);
4535 // remove attribute of id instance: data-intl-tel-input-id
4536 this.telInput.removeAttribute("data-intl-tel-input-id");
4537 // remove markup (but leave the original input)
4538 var wrapper = this.telInput.parentNode;
4539 wrapper.parentNode.insertBefore(this.telInput, wrapper);
4540 wrapper.parentNode.removeChild(wrapper);
4541 delete window.intlTelInputGlobals.instances[this.id];
4542 }
4543 }, {
4544 key: "getExtension",
4545 value: function getExtension() {
4546 if (window.intlTelInputUtils) {
4547 return intlTelInputUtils.getExtension(this._getFullNumber(), this.selectedCountryData.iso2);
4548 }
4549 return "";
4550 }
4551 }, {
4552 key: "getNumber",
4553 value: function getNumber(format) {
4554 if (window.intlTelInputUtils) {
4555 var iso2 = this.selectedCountryData.iso2;
4556 return intlTelInputUtils.formatNumber(this._getFullNumber(), iso2, format);
4557 }
4558 return "";
4559 }
4560 }, {
4561 key: "getNumberType",
4562 value: function getNumberType() {
4563 if (window.intlTelInputUtils) {
4564 return intlTelInputUtils.getNumberType(this._getFullNumber(), this.selectedCountryData.iso2);
4565 }
4566 return -99;
4567 }
4568 }, {
4569 key: "getSelectedCountryData",
4570 value: function getSelectedCountryData() {
4571 return this.selectedCountryData;
4572 }
4573 }, {
4574 key: "getValidationError",
4575 value: function getValidationError() {
4576 if (window.intlTelInputUtils) {
4577 var iso2 = this.selectedCountryData.iso2;
4578 return intlTelInputUtils.getValidationError(this._getFullNumber(), iso2);
4579 }
4580 return -99;
4581 }
4582 }, {
4583 key: "isValidNumber",
4584 value: function isValidNumber() {
4585 var val = this._getFullNumber().trim();
4586 var countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "";
4587 return window.intlTelInputUtils ? intlTelInputUtils.isValidNumber(val, countryCode) : null;
4588 }
4589 }, {
4590 key: "setCountry",
4591 value: function setCountry(originalCountryCode) {
4592 var countryCode = originalCountryCode.toLowerCase();
4593 // check if already selected
4594 if (!this.selectedFlagInner.classList.contains("iti__".concat(countryCode))) {
4595 this._setFlag(countryCode);
4596 this._updateDialCode(this.selectedCountryData.dialCode, false);
4597 this._triggerCountryChange();
4598 }
4599 }
4600 }, {
4601 key: "setNumber",
4602 value: function setNumber(number) {
4603 // we must update the flag first, which updates this.selectedCountryData, which is used for
4604 // formatting the number before displaying it
4605 var flagChanged = this._updateFlagFromNumber(number);
4606 this._updateValFromNumber(number);
4607 if (flagChanged) {
4608 this._triggerCountryChange();
4609 }
4610 }
4611 }, {
4612 key: "setPlaceholderNumberType",
4613 value: function setPlaceholderNumberType(type) {
4614 this.options.placeholderNumberType = type;
4615 this._updatePlaceholder();
4616 }
4617 } ]);
4618 return Iti;
4619 }();
4620 /********************
4621 * STATIC METHODS
4622 ********************/
4623 // get the country data object
4624 intlTelInputGlobals.getCountryData = function() {
4625 return allCountries;
4626 };
4627 // inject a <script> element to load utils.js
4628 var injectScript = function injectScript(path, handleSuccess, handleFailure) {
4629 // inject a new script element into the page
4630 var script = document.createElement("script");
4631 script.onload = function() {
4632 forEachInstance("handleUtils");
4633 if (handleSuccess) handleSuccess();
4634 };
4635 script.onerror = function() {
4636 forEachInstance("rejectUtilsScriptPromise");
4637 if (handleFailure) handleFailure();
4638 };
4639 script.className = "iti-load-utils";
4640 script.async = true;
4641 script.src = path;
4642 document.body.appendChild(script);
4643 };
4644 // load the utils script
4645 intlTelInputGlobals.loadUtils = function(path) {
4646 // 2 options:
4647 // 1) not already started loading (start)
4648 // 2) already started loading (do nothing - just wait for the onload callback to fire, which will
4649 // trigger handleUtils on all instances, invoking their resolveUtilsScriptPromise functions)
4650 if (!window.intlTelInputUtils && !window.intlTelInputGlobals.startedLoadingUtilsScript) {
4651 // only do this once
4652 window.intlTelInputGlobals.startedLoadingUtilsScript = true;
4653 // if we have promises, then return a promise
4654 if (typeof Promise !== "undefined") {
4655 return new Promise(function(resolve, reject) {
4656 return injectScript(path, resolve, reject);
4657 });
4658 }
4659 injectScript(path);
4660 }
4661 return null;
4662 };
4663 // default options
4664 intlTelInputGlobals.defaults = defaults;
4665 // version
4666 intlTelInputGlobals.version = "17.0.16";
4667 // convenience wrapper
4668 return function(input, options) {
4669 var iti = new Iti(input, options);
4670 iti._init();
4671 input.setAttribute("data-intl-tel-input-id", iti.id);
4672 window.intlTelInputGlobals.instances[iti.id] = iti;
4673 return iti;
4674 };
4675 }();
4676 });
4677 },{}],20:[function(require,module,exports){
4678 /**
4679 * Exposing intl-tel-input as a component
4680 */
4681 module.exports = require("./build/js/intlTelInput");
4682
4683 },{"./build/js/intlTelInput":19}],21:[function(require,module,exports){
4684 (function (process){
4685 /**
4686 * Memize options object.
4687 *
4688 * @typedef MemizeOptions
4689 *
4690 * @property {number} [maxSize] Maximum size of the cache.
4691 */
4692
4693 /**
4694 * Internal cache entry.
4695 *
4696 * @typedef MemizeCacheNode
4697 *
4698 * @property {?MemizeCacheNode|undefined} [prev] Previous node.
4699 * @property {?MemizeCacheNode|undefined} [next] Next node.
4700 * @property {Array<*>} args Function arguments for cache
4701 * entry.
4702 * @property {*} val Function result.
4703 */
4704
4705 /**
4706 * Properties of the enhanced function for controlling cache.
4707 *
4708 * @typedef MemizeMemoizedFunction
4709 *
4710 * @property {()=>void} clear Clear the cache.
4711 */
4712
4713 /**
4714 * Accepts a function to be memoized, and returns a new memoized function, with
4715 * optional options.
4716 *
4717 * @template {Function} F
4718 *
4719 * @param {F} fn Function to memoize.
4720 * @param {MemizeOptions} [options] Options object.
4721 *
4722 * @return {F & MemizeMemoizedFunction} Memoized function.
4723 */
4724 function memize( fn, options ) {
4725 var size = 0;
4726
4727 /** @type {?MemizeCacheNode|undefined} */
4728 var head;
4729
4730 /** @type {?MemizeCacheNode|undefined} */
4731 var tail;
4732
4733 options = options || {};
4734
4735 function memoized( /* ...args */ ) {
4736 var node = head,
4737 len = arguments.length,
4738 args, i;
4739
4740 searchCache: while ( node ) {
4741 // Perform a shallow equality test to confirm that whether the node
4742 // under test is a candidate for the arguments passed. Two arrays
4743 // are shallowly equal if their length matches and each entry is
4744 // strictly equal between the two sets. Avoid abstracting to a
4745 // function which could incur an arguments leaking deoptimization.
4746
4747 // Check whether node arguments match arguments length
4748 if ( node.args.length !== arguments.length ) {
4749 node = node.next;
4750 continue;
4751 }
4752
4753 // Check whether node arguments match arguments values
4754 for ( i = 0; i < len; i++ ) {
4755 if ( node.args[ i ] !== arguments[ i ] ) {
4756 node = node.next;
4757 continue searchCache;
4758 }
4759 }
4760
4761 // At this point we can assume we've found a match
4762
4763 // Surface matched node to head if not already
4764 if ( node !== head ) {
4765 // As tail, shift to previous. Must only shift if not also
4766 // head, since if both head and tail, there is no previous.
4767 if ( node === tail ) {
4768 tail = node.prev;
4769 }
4770
4771 // Adjust siblings to point to each other. If node was tail,
4772 // this also handles new tail's empty `next` assignment.
4773 /** @type {MemizeCacheNode} */ ( node.prev ).next = node.next;
4774 if ( node.next ) {
4775 node.next.prev = node.prev;
4776 }
4777
4778 node.next = head;
4779 node.prev = null;
4780 /** @type {MemizeCacheNode} */ ( head ).prev = node;
4781 head = node;
4782 }
4783
4784 // Return immediately
4785 return node.val;
4786 }
4787
4788 // No cached value found. Continue to insertion phase:
4789
4790 // Create a copy of arguments (avoid leaking deoptimization)
4791 args = new Array( len );
4792 for ( i = 0; i < len; i++ ) {
4793 args[ i ] = arguments[ i ];
4794 }
4795
4796 node = {
4797 args: args,
4798
4799 // Generate the result from original function
4800 val: fn.apply( null, args ),
4801 };
4802
4803 // Don't need to check whether node is already head, since it would
4804 // have been returned above already if it was
4805
4806 // Shift existing head down list
4807 if ( head ) {
4808 head.prev = node;
4809 node.next = head;
4810 } else {
4811 // If no head, follows that there's no tail (at initial or reset)
4812 tail = node;
4813 }
4814
4815 // Trim tail if we're reached max size and are pending cache insertion
4816 if ( size === /** @type {MemizeOptions} */ ( options ).maxSize ) {
4817 tail = /** @type {MemizeCacheNode} */ ( tail ).prev;
4818 /** @type {MemizeCacheNode} */ ( tail ).next = null;
4819 } else {
4820 size++;
4821 }
4822
4823 head = node;
4824
4825 return node.val;
4826 }
4827
4828 memoized.clear = function() {
4829 head = null;
4830 tail = null;
4831 size = 0;
4832 };
4833
4834 if ( process.env.NODE_ENV === 'test' ) {
4835 // Cache is not exposed in the public API, but used in tests to ensure
4836 // expected list progression
4837 memoized.getCache = function() {
4838 return [ head, tail, size ];
4839 };
4840 }
4841
4842 // Ignore reason: There's not a clear solution to create an intersection of
4843 // the function with additional properties, where the goal is to retain the
4844 // function signature of the incoming argument and add control properties
4845 // on the return value.
4846
4847 // @ts-ignore
4848 return memoized;
4849 }
4850
4851 module.exports = memize;
4852
4853 }).call(this,require('_process'))
4854 },{"_process":22}],22:[function(require,module,exports){
4855 // shim for using process in browser
4856 var process = module.exports = {};
4857
4858 // cached from whatever global is present so that test runners that stub it
4859 // don't break things. But we need to wrap it in a try catch in case it is
4860 // wrapped in strict mode code which doesn't define any globals. It's inside a
4861 // function because try/catches deoptimize in certain engines.
4862
4863 var cachedSetTimeout;
4864 var cachedClearTimeout;
4865
4866 function defaultSetTimout() {
4867 throw new Error('setTimeout has not been defined');
4868 }
4869 function defaultClearTimeout () {
4870 throw new Error('clearTimeout has not been defined');
4871 }
4872 (function () {
4873 try {
4874 if (typeof setTimeout === 'function') {
4875 cachedSetTimeout = setTimeout;
4876 } else {
4877 cachedSetTimeout = defaultSetTimout;
4878 }
4879 } catch (e) {
4880 cachedSetTimeout = defaultSetTimout;
4881 }
4882 try {
4883 if (typeof clearTimeout === 'function') {
4884 cachedClearTimeout = clearTimeout;
4885 } else {
4886 cachedClearTimeout = defaultClearTimeout;
4887 }
4888 } catch (e) {
4889 cachedClearTimeout = defaultClearTimeout;
4890 }
4891 } ())
4892 function runTimeout(fun) {
4893 if (cachedSetTimeout === setTimeout) {
4894 //normal enviroments in sane situations
4895 return setTimeout(fun, 0);
4896 }
4897 // if setTimeout wasn't available but was latter defined
4898 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
4899 cachedSetTimeout = setTimeout;
4900 return setTimeout(fun, 0);
4901 }
4902 try {
4903 // when when somebody has screwed with setTimeout but no I.E. maddness
4904 return cachedSetTimeout(fun, 0);
4905 } catch(e){
4906 try {
4907 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
4908 return cachedSetTimeout.call(null, fun, 0);
4909 } catch(e){
4910 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
4911 return cachedSetTimeout.call(this, fun, 0);
4912 }
4913 }
4914
4915
4916 }
4917 function runClearTimeout(marker) {
4918 if (cachedClearTimeout === clearTimeout) {
4919 //normal enviroments in sane situations
4920 return clearTimeout(marker);
4921 }
4922 // if clearTimeout wasn't available but was latter defined
4923 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
4924 cachedClearTimeout = clearTimeout;
4925 return clearTimeout(marker);
4926 }
4927 try {
4928 // when when somebody has screwed with setTimeout but no I.E. maddness
4929 return cachedClearTimeout(marker);
4930 } catch (e){
4931 try {
4932 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
4933 return cachedClearTimeout.call(null, marker);
4934 } catch (e){
4935 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
4936 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
4937 return cachedClearTimeout.call(this, marker);
4938 }
4939 }
4940
4941
4942
4943 }
4944 var queue = [];
4945 var draining = false;
4946 var currentQueue;
4947 var queueIndex = -1;
4948
4949 function cleanUpNextTick() {
4950 if (!draining || !currentQueue) {
4951 return;
4952 }
4953 draining = false;
4954 if (currentQueue.length) {
4955 queue = currentQueue.concat(queue);
4956 } else {
4957 queueIndex = -1;
4958 }
4959 if (queue.length) {
4960 drainQueue();
4961 }
4962 }
4963
4964 function drainQueue() {
4965 if (draining) {
4966 return;
4967 }
4968 var timeout = runTimeout(cleanUpNextTick);
4969 draining = true;
4970
4971 var len = queue.length;
4972 while(len) {
4973 currentQueue = queue;
4974 queue = [];
4975 while (++queueIndex < len) {
4976 if (currentQueue) {
4977 currentQueue[queueIndex].run();
4978 }
4979 }
4980 queueIndex = -1;
4981 len = queue.length;
4982 }
4983 currentQueue = null;
4984 draining = false;
4985 runClearTimeout(timeout);
4986 }
4987
4988 process.nextTick = function (fun) {
4989 var args = new Array(arguments.length - 1);
4990 if (arguments.length > 1) {
4991 for (var i = 1; i < arguments.length; i++) {
4992 args[i - 1] = arguments[i];
4993 }
4994 }
4995 queue.push(new Item(fun, args));
4996 if (queue.length === 1 && !draining) {
4997 runTimeout(drainQueue);
4998 }
4999 };
5000
5001 // v8 likes predictible objects
5002 function Item(fun, array) {
5003 this.fun = fun;
5004 this.array = array;
5005 }
5006 Item.prototype.run = function () {
5007 this.fun.apply(null, this.array);
5008 };
5009 process.title = 'browser';
5010 process.browser = true;
5011 process.env = {};
5012 process.argv = [];
5013 process.version = ''; // empty string to avoid regexp issues
5014 process.versions = {};
5015
5016 function noop() {}
5017
5018 process.on = noop;
5019 process.addListener = noop;
5020 process.once = noop;
5021 process.off = noop;
5022 process.removeListener = noop;
5023 process.removeAllListeners = noop;
5024 process.emit = noop;
5025 process.prependListener = noop;
5026 process.prependOnceListener = noop;
5027
5028 process.listeners = function (name) { return [] }
5029
5030 process.binding = function (name) {
5031 throw new Error('process.binding is not supported');
5032 };
5033
5034 process.cwd = function () { return '/' };
5035 process.chdir = function (dir) {
5036 throw new Error('process.chdir is not supported');
5037 };
5038 process.umask = function() { return 0; };
5039
5040 },{}],23:[function(require,module,exports){
5041 'use strict';
5042
5043 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
5044
5045 var pluralForms = _interopDefault(require('@tannin/plural-forms'));
5046
5047 /**
5048 * Tannin constructor options.
5049 *
5050 * @typedef {Object} TanninOptions
5051 *
5052 * @property {string} [contextDelimiter] Joiner in string lookup with context.
5053 * @property {Function} [onMissingKey] Callback to invoke when key missing.
5054 */
5055
5056 /**
5057 * Domain metadata.
5058 *
5059 * @typedef {Object} TanninDomainMetadata
5060 *
5061 * @property {string} [domain] Domain name.
5062 * @property {string} [lang] Language code.
5063 * @property {(string|Function)} [plural_forms] Plural forms expression or
5064 * function evaluator.
5065 */
5066
5067 /**
5068 * Domain translation pair respectively representing the singular and plural
5069 * translation.
5070 *
5071 * @typedef {[string,string]} TanninTranslation
5072 */
5073
5074 /**
5075 * Locale data domain. The key is used as reference for lookup, the value an
5076 * array of two string entries respectively representing the singular and plural
5077 * translation.
5078 *
5079 * @typedef {{[key:string]:TanninDomainMetadata|TanninTranslation,'':TanninDomainMetadata|TanninTranslation}} TanninLocaleDomain
5080 */
5081
5082 /**
5083 * Jed-formatted locale data.
5084 *
5085 * @see http://messageformat.github.io/Jed/
5086 *
5087 * @typedef {{[domain:string]:TanninLocaleDomain}} TanninLocaleData
5088 */
5089
5090 /**
5091 * Default Tannin constructor options.
5092 *
5093 * @type {TanninOptions}
5094 */
5095 var DEFAULT_OPTIONS = {
5096 contextDelimiter: '\u0004',
5097 onMissingKey: null,
5098 };
5099
5100 /**
5101 * Given a specific locale data's config `plural_forms` value, returns the
5102 * expression.
5103 *
5104 * @example
5105 *
5106 * ```
5107 * getPluralExpression( 'nplurals=2; plural=(n != 1);' ) === '(n != 1)'
5108 * ```
5109 *
5110 * @param {string} pf Locale data plural forms.
5111 *
5112 * @return {string} Plural forms expression.
5113 */
5114 function getPluralExpression( pf ) {
5115 var parts, i, part;
5116
5117 parts = pf.split( ';' );
5118
5119 for ( i = 0; i < parts.length; i++ ) {
5120 part = parts[ i ].trim();
5121 if ( part.indexOf( 'plural=' ) === 0 ) {
5122 return part.substr( 7 );
5123 }
5124 }
5125 }
5126
5127 /**
5128 * Tannin constructor.
5129 *
5130 * @class
5131 *
5132 * @param {TanninLocaleData} data Jed-formatted locale data.
5133 * @param {TanninOptions} [options] Tannin options.
5134 */
5135 function Tannin( data, options ) {
5136 var key;
5137
5138 /**
5139 * Jed-formatted locale data.
5140 *
5141 * @name Tannin#data
5142 * @type {TanninLocaleData}
5143 */
5144 this.data = data;
5145
5146 /**
5147 * Plural forms function cache, keyed by plural forms string.
5148 *
5149 * @name Tannin#pluralForms
5150 * @type {Object<string,Function>}
5151 */
5152 this.pluralForms = {};
5153
5154 /**
5155 * Effective options for instance, including defaults.
5156 *
5157 * @name Tannin#options
5158 * @type {TanninOptions}
5159 */
5160 this.options = {};
5161
5162 for ( key in DEFAULT_OPTIONS ) {
5163 this.options[ key ] = options !== undefined && key in options
5164 ? options[ key ]
5165 : DEFAULT_OPTIONS[ key ];
5166 }
5167 }
5168
5169 /**
5170 * Returns the plural form index for the given domain and value.
5171 *
5172 * @param {string} domain Domain on which to calculate plural form.
5173 * @param {number} n Value for which plural form is to be calculated.
5174 *
5175 * @return {number} Plural form index.
5176 */
5177 Tannin.prototype.getPluralForm = function( domain, n ) {
5178 var getPluralForm = this.pluralForms[ domain ],
5179 config, plural, pf;
5180
5181 if ( ! getPluralForm ) {
5182 config = this.data[ domain ][ '' ];
5183
5184 pf = (
5185 config[ 'Plural-Forms' ] ||
5186 config[ 'plural-forms' ] ||
5187 // Ignore reason: As known, there's no way to document the empty
5188 // string property on a key to guarantee this as metadata.
5189 // @ts-ignore
5190 config.plural_forms
5191 );
5192
5193 if ( typeof pf !== 'function' ) {
5194 plural = getPluralExpression(
5195 config[ 'Plural-Forms' ] ||
5196 config[ 'plural-forms' ] ||
5197 // Ignore reason: As known, there's no way to document the empty
5198 // string property on a key to guarantee this as metadata.
5199 // @ts-ignore
5200 config.plural_forms
5201 );
5202
5203 pf = pluralForms( plural );
5204 }
5205
5206 getPluralForm = this.pluralForms[ domain ] = pf;
5207 }
5208
5209 return getPluralForm( n );
5210 };
5211
5212 /**
5213 * Translate a string.
5214 *
5215 * @param {string} domain Translation domain.
5216 * @param {string|void} context Context distinguishing terms of the same name.
5217 * @param {string} singular Primary key for translation lookup.
5218 * @param {string=} plural Fallback value used for non-zero plural
5219 * form index.
5220 * @param {number=} n Value to use in calculating plural form.
5221 *
5222 * @return {string} Translated string.
5223 */
5224 Tannin.prototype.dcnpgettext = function( domain, context, singular, plural, n ) {
5225 var index, key, entry;
5226
5227 if ( n === undefined ) {
5228 // Default to singular.
5229 index = 0;
5230 } else {
5231 // Find index by evaluating plural form for value.
5232 index = this.getPluralForm( domain, n );
5233 }
5234
5235 key = singular;
5236
5237 // If provided, context is prepended to key with delimiter.
5238 if ( context ) {
5239 key = context + this.options.contextDelimiter + singular;
5240 }
5241
5242 entry = this.data[ domain ][ key ];
5243
5244 // Verify not only that entry exists, but that the intended index is within
5245 // range and non-empty.
5246 if ( entry && entry[ index ] ) {
5247 return entry[ index ];
5248 }
5249
5250 if ( this.options.onMissingKey ) {
5251 this.options.onMissingKey( singular, domain );
5252 }
5253
5254 // If entry not found, fall back to singular vs. plural with zero index
5255 // representing the singular value.
5256 return index === 0 ? singular : plural;
5257 };
5258
5259 module.exports = Tannin;
5260
5261 },{"@tannin/plural-forms":12}]},{},[3]);
5262