PluginProbe
SellKit – Funnel builder and checkout optimizer for WooCommerce to sell more, faster / 2.8.0
SellKit – Funnel builder and checkout optimizer for WooCommerce to sell more, faster v2.8.0
2.8.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 All 44 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.8.0, at assets/dist/js/elementor-init.js

5,260 lines 206.1 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 updateSellkitUpsellField(data.upsell_ids);
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 updateSellkitUpsellField = function updateSellkitUpsellField(data) {
1630 if (data === 'null' || data === null) {
1631 return;
1632 }
1633
1634 var current_val = $('input#sellkit_upsell_ids').val();
1635
1636 if (!current_val || current_val === '0') {
1637 $('input#sellkit_upsell_ids').val(data);
1638 } else {
1639 var val = current_val + ',' + data;
1640 $('input#sellkit_upsell_ids').val(val);
1641 }
1642 };
1643 /**
1644 * Toggle order notes.
1645 *
1646 * @since 1.8.9
1647 */
1648
1649
1650 var orderNotesToggle = function orderNotesToggle() {
1651 $('#sellkit-add-notes-to-order-box').on('change', function () {
1652 $(this).parent().next().toggle();
1653 });
1654 }; // --- Sellkit: Sync custom state fields to standard WooCommerce fields for gateway compatibility ---
1655
1656
1657 var ensureStandardWooFields = function ensureStandardWooFields() {
1658 try {
1659 var form = document.querySelector('form.checkout');
1660
1661 if (!form) {
1662 return;
1663 } // Billing state
1664
1665
1666 var sellkitBillingState = document.getElementById('sellkit-billing_state');
1667
1668 if (sellkitBillingState) {
1669 var billingState = document.getElementById('billing_state');
1670
1671 if (!billingState) {
1672 billingState = document.createElement('input');
1673 billingState.type = 'hidden';
1674 billingState.id = 'billing_state';
1675 billingState.name = 'billing_state';
1676 form.appendChild(billingState);
1677 }
1678
1679 billingState.value = sellkitBillingState.value;
1680 } // Shipping state
1681
1682
1683 var sellkitShippingState = document.getElementById('sellkit-shipping_state');
1684
1685 if (sellkitShippingState) {
1686 var shippingState = document.getElementById('shipping_state');
1687
1688 if (!shippingState) {
1689 shippingState = document.createElement('input');
1690 shippingState.type = 'hidden';
1691 shippingState.id = 'shipping_state';
1692 shippingState.name = 'shipping_state';
1693 form.appendChild(shippingState);
1694 }
1695
1696 shippingState.value = sellkitShippingState.value;
1697 }
1698 } catch (e) {
1699 // eslint-disable-next-line no-console
1700 console.error('[Sellkit] Error syncing state fields for gateway compatibility:', e);
1701 }
1702 }; // Attach to form submit and on state field change
1703
1704
1705 jQuery(document).ready(function (_$) {
1706 var form = _$('form.checkout');
1707
1708 if (form.length) {
1709 form.on('submit', function () {
1710 ensureStandardWooFields();
1711 }); // Also update on state field change
1712
1713 _$('#sellkit-billing_state, #sellkit-shipping_state').on('change input', function () {
1714 ensureStandardWooFields();
1715 });
1716 }
1717 });
1718
1719 },{"./checkout-settings":1,"@babel/runtime/helpers/interopRequireDefault":9,"@wordpress/i18n":16}],3:[function(require,module,exports){
1720 "use strict";
1721
1722 (function ($) {
1723 var SellkitFrontend = function SellkitFrontend() {
1724 var widgets = {
1725 'sellkit-product-images.default': require('./product-images')["default"],
1726 'sellkit-checkout.default': require('./checkout')["default"],
1727 'sellkit-optin.default': require('./optin/optin')["default"]
1728 };
1729
1730 function elementorInit() {
1731 for (var widget in widgets) {
1732 elementorFrontend.hooks.addAction("frontend/element_ready/".concat(widget), widgets[widget]);
1733 }
1734 }
1735
1736 this.init = function () {
1737 $(window).on('elementor/frontend/init', elementorInit);
1738 };
1739
1740 this.init();
1741 };
1742
1743 window.sellkitFrontend = new SellkitFrontend();
1744 })(jQuery);
1745
1746 },{"./checkout":2,"./optin/optin":4,"./product-images":7}],4:[function(require,module,exports){
1747 "use strict";
1748
1749 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
1750
1751 Object.defineProperty(exports, "__esModule", {
1752 value: true
1753 });
1754 exports["default"] = _default;
1755
1756 var _intelligentTel = _interopRequireDefault(require("./submodules/intelligent-tel"));
1757
1758 var _fieldValidation = _interopRequireDefault(require("./submodules/field-validation"));
1759
1760 var _i18n = require("@wordpress/i18n");
1761
1762 var Optin = elementorModules.frontend.handlers.Base.extend({
1763 form: null,
1764 onInit: function onInit() {
1765 this.form = this.$element.find('form.sellkit-optin'); // Register submit listener.
1766
1767 this.form.on('submit', this.onSubmit.bind(this)); // Initialize ITI for tel fields.
1768
1769 _intelligentTel["default"].initializeITI(this.form); // AutoComplete address fields.
1770
1771
1772 jQuery(document).ready(this.autoCompleteAddress.bind(this)); // Initialize flatpickr for data and time fields.
1773
1774 this.initializeFlatpickr();
1775 },
1776 onSubmit: function onSubmit(event) {
1777 var _this = this;
1778
1779 event.preventDefault();
1780
1781 if (!this.checkSaveState()) {
1782 return;
1783 }
1784
1785 this.clearAllNotices();
1786 this.form.css('opacity', 0.5);
1787
1788 var validated = _fieldValidation["default"].validateFormFields(this.form);
1789
1790 if (!validated) {
1791 this.form.css('opacity', 1);
1792 return;
1793 }
1794
1795 wp.ajax.send('sellkit_optin_frontend', {
1796 data: this.prepareFormData(),
1797 type: 'POST',
1798 dataType: 'json',
1799 processData: false,
1800 contentType: false,
1801 success: this.onSuccess,
1802 error: this.onFailure,
1803 complete: function complete() {
1804 return _this.form.css('opacity', 1);
1805 }
1806 });
1807 },
1808 checkSaveState: function checkSaveState() {
1809 if (!this.isEdit) {
1810 return true;
1811 }
1812
1813 var btn = jQuery(elementor.panel.el).find('button#elementor-panel-saver-button-publish');
1814
1815 if (!btn.length || btn.hasClass('elementor-disabled')) {
1816 return true;
1817 }
1818
1819 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";
1820 this.form.before(adminErrorsNode);
1821 return false;
1822 },
1823 clearAllNotices: function clearAllNotices() {
1824 var form = this.form; // Reset everything.
1825
1826 form.parent().find('.sellkit-optin-response').remove();
1827 form.parent().find('.sellkit-optin-admin-alert').remove();
1828 form.parent().removeClass('sellkit-optin-error');
1829 form.parent().removeClass('sellkit-optin-success');
1830 },
1831 prepareFormData: function prepareFormData() {
1832 _intelligentTel["default"].fixTelBeforeSubmit(this.form);
1833
1834 var formData = new FormData(this.form[0]);
1835 var entries = Array.from(formData.entries()); // Unify nonsingular formData entries ( happens for checkbox or multiselection select fields ) .
1836
1837 entries.forEach(function (entry, i) {
1838 var value = entry[1];
1839 entries.forEach(function (_entry, _i) {
1840 if (_i !== i && _entry[0] === entry[0]) {
1841 value += ", ".concat(_entry[1]);
1842 formData["delete"](_entry[0]);
1843 }
1844 });
1845 formData.set(entry[0], value);
1846 });
1847 formData.append('referrer', location.toString());
1848 formData.append('action', 'sellkit_optin_frontend');
1849 formData.append('nonce', window.sellkit_elementor.nonce); // To make _POST content compatible with sellkit_funnel() functionality and let it find the funnel data.
1850
1851 formData.append('sellkit_current_page_id', formData.get('post_id'));
1852 return formData;
1853 },
1854 onSuccess: function onSuccess(response) {
1855 var form = this.form; // Success Message.
1856
1857 form.trigger('reset');
1858 form.parent().addClass('sellkit-optin-success');
1859 form.after("<div class=\"sellkit-optin-response\">".concat(response.message, "</div>")); // Admin Error Messages.
1860
1861 this.printAdminErrors(response.admin_errors); // Download.
1862
1863 if (response.downloadURL) {
1864 window.open(response.downloadURL, '_blank');
1865 } // Redirect.
1866
1867
1868 if (!jQuery.isEmptyObject(response.redirectURL)) {
1869 window.location.href = response.redirectURL;
1870 }
1871 },
1872 onFailure: function onFailure(response) {
1873 var form = this.form;
1874 form.parent().removeClass('sellkit-optin-success');
1875 form.parent().addClass('sellkit-optin-error'); // Handle user error messages.
1876
1877 if (!_.isEmpty(response.errors)) {
1878 _.each(response.errors, function (error) {
1879 form.after("<div class=\"sellkit-optin-response\">".concat(error, "</div>"));
1880 });
1881 } // Admin Error Messages.
1882
1883
1884 this.printAdminErrors(response.admin_errors);
1885 },
1886 printAdminErrors: function printAdminErrors(errors) {
1887 if (_.isEmpty(errors)) {
1888 return;
1889 }
1890
1891 var errorList = '';
1892
1893 _.each(errors, function (error) {
1894 errorList += "<li>".concat(error, "</li>");
1895 });
1896
1897 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");
1898 this.form.before(adminErrorsNode);
1899 },
1900 initializeFlatpickr: function initializeFlatpickr() {
1901 var dateField = this.form.find('.flatpickr[type=text]');
1902 var customLocale = dateField.data('locale');
1903 var locale = {
1904 firstDayOfWeek: 1
1905 };
1906
1907 if (!_.isUndefined(customLocale) && 'default' !== customLocale) {
1908 locale = customLocale;
1909 }
1910
1911 dateField.flatpickr({
1912 locale: locale,
1913 minuteIncrement: 1
1914 });
1915 },
1916 autoCompleteAddress: function autoCompleteAddress() {
1917 var addressFields = this.form.find('input[data-type="address"]');
1918 var google = this.isEdit ? window.parent.google : window.google;
1919
1920 if (!addressFields.length || !google) {
1921 return;
1922 }
1923
1924 _.each(addressFields, function (input) {
1925 var autocomplete = new google.maps.places.Autocomplete(input, {
1926 types: ['geocode'],
1927 fields: ['address_components']
1928 });
1929 autocomplete.addListener('place_changed', function () {
1930 var place = autocomplete.getPlace(); // Extract address components
1931
1932 var address = {
1933 street_number: '',
1934 route: '',
1935 locality: '',
1936 administrative_area_level_1: '',
1937 country: '',
1938 postal_code: ''
1939 }; // Map Google Maps address components to your address object
1940
1941 place.address_components.forEach(function (component) {
1942 var componentType = component.types[0];
1943
1944 switch (componentType) {
1945 case 'street_number':
1946 address.street_number = component.long_name;
1947 break;
1948
1949 case 'route':
1950 address.route = component.long_name;
1951 break;
1952
1953 case 'locality':
1954 address.locality = component.long_name;
1955 break;
1956
1957 case 'administrative_area_level_1':
1958 address.administrative_area_level_1 = component.long_name;
1959 break;
1960
1961 case 'country':
1962 address.country = component.long_name;
1963 break;
1964
1965 case 'postal_code':
1966 address.postal_code = component.long_name;
1967 break;
1968 }
1969 }); // Combine street number and route for the full street address
1970
1971 var addressString = JSON.stringify(address);
1972 var addressHidenField = input.nextElementSibling;
1973
1974 if (addressHidenField && addressHidenField.type === 'hidden') {
1975 addressHidenField.value = addressString;
1976 }
1977 });
1978 });
1979 }
1980 });
1981
1982 function _default($scope) {
1983 new Optin({
1984 $element: $scope
1985 });
1986 }
1987
1988 },{"./submodules/field-validation":5,"./submodules/intelligent-tel":6,"@babel/runtime/helpers/interopRequireDefault":9,"@wordpress/i18n":16}],5:[function(require,module,exports){
1989 "use strict";
1990
1991 Object.defineProperty(exports, "__esModule", {
1992 value: true
1993 });
1994 exports["default"] = void 0;
1995 var _default = {
1996 messageRequired: '',
1997 messageError: '',
1998 validateFormFields: function validateFormFields(form) {
1999 var _this = this;
2000
2001 this.getCustomMessages(form);
2002 var formData = form.find('[name^="fields"]');
2003 var result = true;
2004
2005 _.each(formData, function (field) {
2006 var message = _this.getValidationMessage(field);
2007
2008 if (!_.isEmpty(message)) {
2009 result = false;
2010 }
2011
2012 _this.toggleFieldMessage(field, message);
2013 });
2014
2015 this.toggleFinalMessage(form, result);
2016 return result;
2017 },
2018 getValidationMessage: function getValidationMessage(target) {
2019 var type = target.dataset.type;
2020 var validity = target.validity;
2021 var i18n = window.sellkitOptinValidationsTranslations;
2022 var message = '';
2023
2024 if (validity.valueMissing || target.required && _.isEmpty(target.value)) {
2025 message = this.messageRequired;
2026 return message;
2027 }
2028
2029 switch (type) {
2030 case 'email':
2031 if (validity.typeMismatch || validity.patternMismatch) {
2032 message = i18n.general.invalidEmail;
2033 }
2034
2035 break;
2036
2037 case 'tel':
2038 var isITI = target.hasAttribute('data-iti-tel');
2039
2040 if (isITI) {
2041 var validationMessages = i18n.itiValidation;
2042 var inputItiInstance = window.intlTelInputGlobals.getInstance(target);
2043 var itiValidationCode = inputItiInstance.getValidationError();
2044 var areaCodeRequired = target.hasAttribute('data-iti-area-required');
2045 var mustBeTelType = target.getAttribute('data-iti-tel-type');
2046 var telType = "".concat(inputItiInstance.getNumberType());
2047
2048 switch (itiValidationCode) {
2049 case 1:
2050 message = validationMessages.invalidCountryCode;
2051 break;
2052
2053 case 2:
2054 message = validationMessages.tooShort;
2055 break;
2056
2057 case 3:
2058 message = validationMessages.tooLong;
2059 break;
2060
2061 case 4:
2062 message = areaCodeRequired ? validationMessages.areaCodeMissing : '';
2063 break;
2064
2065 case 5:
2066 message = validationMessages.invalidLength;
2067 break;
2068
2069 case -99:
2070 message = validationMessages.invalidGeneral;
2071 break;
2072
2073 case 0:
2074 default:
2075 if ('all' !== mustBeTelType && telType !== mustBeTelType) {
2076 message = validationMessages.typeMismatch[mustBeTelType];
2077 }
2078
2079 }
2080
2081 break;
2082 }
2083
2084 if (validity.typeMismatch || validity.patternMismatch) {
2085 message = i18n.general.invalidPhone;
2086 }
2087
2088 break;
2089
2090 case 'number':
2091 if (validity.typeMismatch || validity.patternMismatch) {
2092 message = i18n.general.invalidNumber;
2093 break;
2094 }
2095
2096 if (validity.rangeOverflow) {
2097 message = i18n.general.invalidMaxValue.replace('MAX_VALUE', target.max);
2098 break;
2099 }
2100
2101 if (validity.rangeUnderflow) {
2102 message = i18n.general.invalidMinValue.replace('MIN_VALUE', target.min);
2103 }
2104
2105 break;
2106 }
2107
2108 return message;
2109 },
2110 toggleFieldMessage: function toggleFieldMessage(field, message) {
2111 var fieldGroup = jQuery(field).closest('.sellkit-field-group');
2112 fieldGroup.removeClass('sellkit-field-invalid');
2113 fieldGroup.find('small').remove();
2114
2115 if (!_.isEmpty(message)) {
2116 fieldGroup.addClass('sellkit-field-invalid');
2117 fieldGroup.append("<small class=\"sellkit-optin-text\">".concat(message, "</small>"));
2118 }
2119 },
2120 toggleFinalMessage: function toggleFinalMessage(form, validationResult) {
2121 form.parent().toggleClass('sellkit-optin-error', !validationResult);
2122 form.parent().toggleClass('sellkit-optin-success', validationResult);
2123 form.parent().find('.sellkit-optin-response').remove();
2124
2125 if (true === validationResult) {
2126 return;
2127 }
2128
2129 form.after("<div class=\"sellkit-optin-response\">".concat(this.messageError, "</div>"));
2130 },
2131 getCustomMessages: function getCustomMessages(form) {
2132 var messagesRaw = form.attr('data-messages');
2133
2134 if (!_.isEmpty(messagesRaw)) {
2135 var messages = JSON.parse(messagesRaw);
2136 this.messageError = messages.error;
2137 this.messageRequired = messages.required;
2138 return;
2139 }
2140
2141 this.messageError = window.sellkitOptinValidationsTranslations.general.errorExists;
2142 this.messageRequired = window.sellkitOptinValidationsTranslations.general.required;
2143 }
2144 };
2145 exports["default"] = _default;
2146
2147 },{}],6:[function(require,module,exports){
2148 "use strict";
2149
2150 Object.defineProperty(exports, "__esModule", {
2151 value: true
2152 });
2153 exports["default"] = void 0;
2154 var _default = {
2155 initializeITI: function initializeITI(form) {
2156 var _this = this;
2157
2158 var itiTelFields = form.find('input[data-iti-tel]');
2159
2160 if (!itiTelFields.length) {
2161 return;
2162 }
2163
2164 if (!window.itiCountry) {
2165 jQuery.get('https://ipwho.is/', function () {}, 'json').always(function (response) {
2166 window.itiCountry = response && response.country_code ? response.country_code.toLowerCase() : 'us';
2167
2168 _this.setupTelFields(itiTelFields);
2169 });
2170 } else {
2171 this.setupTelFields(itiTelFields);
2172 }
2173 },
2174 setupTelFields: function setupTelFields(itiTelFields) {
2175 var iti = require('intl-tel-input');
2176
2177 if (!iti) {
2178 return;
2179 }
2180
2181 var allCountries = window.intlTelInputGlobals.getCountryData().map(function (item) {
2182 return item.iso2;
2183 });
2184 var numberTypes = ['FIXED_LINE', 'MOBILE', 'FIXED_LINE_OR_MOBILE', 'TOLL_FREE', 'PREMIUM_RATE', 'SHARED_COST', 'VOIP', 'PERSONAL_NUMBER', 'PAGER', 'UAN', 'VOICEMAIL'];
2185
2186 _.each(itiTelFields, function (input) {
2187 var allowDropdown = input.hasAttribute('data-iti-allow-dropdown');
2188 var countriesAttr = input.getAttribute('data-iti-country-include');
2189 var countries = countriesAttr ? countriesAttr.split(' ') : null;
2190 var isCountriesSet = countries && countries.length;
2191 var ipDetect = input.hasAttribute('data-iti-ip-detect');
2192 var placeHolderAttr = input.getAttribute('data-iti-tel-type');
2193 var args = {
2194 allowDropdown: allowDropdown,
2195 utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.16/js/utils.min.js',
2196 separateDialCode: true,
2197 placeholderNumberType: 'all' === placeHolderAttr ? 'MOBILE' : numberTypes[+placeHolderAttr],
2198 onlyCountries: isCountriesSet ? countries : allCountries,
2199 initialCountry: '',
2200 geoIpLookup: null
2201 };
2202
2203 if (ipDetect) {
2204 args.initialCountry = isCountriesSet && !countries.includes(window.itiCountry) ? countries[0] : 'auto';
2205
2206 args.geoIpLookup = function (success) {
2207 return success(window.itiCountry);
2208 };
2209 }
2210
2211 iti(input, args);
2212 });
2213 },
2214 fixTelBeforeSubmit: function fixTelBeforeSubmit(form) {
2215 var itiTelFields = form.find('input[data-iti-tel]');
2216
2217 _.each(itiTelFields, function (input) {
2218 var internationalize = input.hasAttribute('data-iti-internationalize');
2219
2220 if (internationalize) {
2221 var itiInstance = window.intlTelInputGlobals.getInstance(input);
2222 input.value = itiInstance.getNumber();
2223 }
2224 });
2225 }
2226 };
2227 exports["default"] = _default;
2228
2229 },{"intl-tel-input":20}],7:[function(require,module,exports){
2230 "use strict";
2231
2232 Object.defineProperty(exports, "__esModule", {
2233 value: true
2234 });
2235 exports["default"] = _default;
2236 var ProductImages = elementorModules.frontend.handlers.Base.extend({
2237 onInit: function onInit() {
2238 elementorModules.frontend.handlers.Base.prototype.onInit.apply(this, arguments);
2239
2240 if (document.body.classList.contains('elementor-editor-active')) {
2241 this.$element.find('.woocommerce-product-gallery').wc_product_gallery();
2242 }
2243
2244 var self = this;
2245
2246 if (typeof window.elementor === 'undefined') {
2247 return;
2248 }
2249
2250 window.elementor.channels.editor.on('change', function (controlView) {
2251 self.onElementChange(controlView.model.get('name'), controlView);
2252 });
2253 this.handleThumbnailBorderRadius(this.getElementSettings('thumbnail_border_radius'));
2254 },
2255 onElementChange: function onElementChange(propertyName, controlView) {
2256 if ('thumbnail_border_radius' === propertyName) {
2257 var borderRadius = controlView.container.settings.get('thumbnail_border_radius');
2258 this.handleThumbnailBorderRadius(borderRadius);
2259 }
2260 },
2261 handleThumbnailBorderRadius: function handleThumbnailBorderRadius(borderRadius) {
2262 var unit = borderRadius.unit;
2263 this.$element.find('.flex-control-nav li').css({
2264 'border-radius': borderRadius.top + unit + ' ' + borderRadius.right + unit + ' ' + borderRadius.bottom + unit + ' ' + borderRadius.left + unit
2265 });
2266 },
2267 bindEvents: function bindEvents() {
2268 this.$element.find('.woocommerce-product-gallery__image a').on('click', function (e) {
2269 e.stopImmediatePropagation();
2270 e.preventDefault();
2271 });
2272 }
2273 });
2274
2275 function _default($scope) {
2276 new ProductImages({
2277 $element: $scope
2278 });
2279 }
2280
2281 },{}],8:[function(require,module,exports){
2282 function _defineProperty(obj, key, value) {
2283 if (key in obj) {
2284 Object.defineProperty(obj, key, {
2285 value: value,
2286 enumerable: true,
2287 configurable: true,
2288 writable: true
2289 });
2290 } else {
2291 obj[key] = value;
2292 }
2293
2294 return obj;
2295 }
2296
2297 module.exports = _defineProperty;
2298 },{}],9:[function(require,module,exports){
2299 function _interopRequireDefault(obj) {
2300 return obj && obj.__esModule ? obj : {
2301 "default": obj
2302 };
2303 }
2304
2305 module.exports = _interopRequireDefault;
2306 },{}],10:[function(require,module,exports){
2307 'use strict';
2308
2309 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
2310
2311 var postfix = _interopDefault(require('@tannin/postfix'));
2312 var evaluate = _interopDefault(require('@tannin/evaluate'));
2313
2314 /**
2315 * Given a C expression, returns a function which can be called to evaluate its
2316 * result.
2317 *
2318 * @example
2319 *
2320 * ```js
2321 * import compile from '@tannin/compile';
2322 *
2323 * const evaluate = compile( 'n > 1' );
2324 *
2325 * evaluate( { n: 2 } );
2326 * // ⇒ true
2327 * ```
2328 *
2329 * @param {string} expression C expression.
2330 *
2331 * @return {(variables?:{[variable:string]:*})=>*} Compiled evaluator.
2332 */
2333 function compile( expression ) {
2334 var terms = postfix( expression );
2335
2336 return function( variables ) {
2337 return evaluate( terms, variables );
2338 };
2339 }
2340
2341 module.exports = compile;
2342
2343 },{"@tannin/evaluate":11,"@tannin/postfix":13}],11:[function(require,module,exports){
2344 'use strict';
2345
2346 /**
2347 * Operator callback functions.
2348 *
2349 * @type {Object}
2350 */
2351 var OPERATORS = {
2352 '!': function( a ) {
2353 return ! a;
2354 },
2355 '*': function( a, b ) {
2356 return a * b;
2357 },
2358 '/': function( a, b ) {
2359 return a / b;
2360 },
2361 '%': function( a, b ) {
2362 return a % b;
2363 },
2364 '+': function( a, b ) {
2365 return a + b;
2366 },
2367 '-': function( a, b ) {
2368 return a - b;
2369 },
2370 '<': function( a, b ) {
2371 return a < b;
2372 },
2373 '<=': function( a, b ) {
2374 return a <= b;
2375 },
2376 '>': function( a, b ) {
2377 return a > b;
2378 },
2379 '>=': function( a, b ) {
2380 return a >= b;
2381 },
2382 '==': function( a, b ) {
2383 return a === b;
2384 },
2385 '!=': function( a, b ) {
2386 return a !== b;
2387 },
2388 '&&': function( a, b ) {
2389 return a && b;
2390 },
2391 '||': function( a, b ) {
2392 return a || b;
2393 },
2394 '?:': function( a, b, c ) {
2395 if ( a ) {
2396 throw b;
2397 }
2398
2399 return c;
2400 },
2401 };
2402
2403 /**
2404 * Given an array of postfix terms and operand variables, returns the result of
2405 * the postfix evaluation.
2406 *
2407 * @example
2408 *
2409 * ```js
2410 * import evaluate from '@tannin/evaluate';
2411 *
2412 * // 3 + 4 * 5 / 6 ⇒ '3 4 5 * 6 / +'
2413 * const terms = [ '3', '4', '5', '*', '6', '/', '+' ];
2414 *
2415 * evaluate( terms, {} );
2416 * // ⇒ 6.333333333333334
2417 * ```
2418 *
2419 * @param {string[]} postfix Postfix terms.
2420 * @param {Object} variables Operand variables.
2421 *
2422 * @return {*} Result of evaluation.
2423 */
2424 function evaluate( postfix, variables ) {
2425 var stack = [],
2426 i, j, args, getOperatorResult, term, value;
2427
2428 for ( i = 0; i < postfix.length; i++ ) {
2429 term = postfix[ i ];
2430
2431 getOperatorResult = OPERATORS[ term ];
2432 if ( getOperatorResult ) {
2433 // Pop from stack by number of function arguments.
2434 j = getOperatorResult.length;
2435 args = Array( j );
2436 while ( j-- ) {
2437 args[ j ] = stack.pop();
2438 }
2439
2440 try {
2441 value = getOperatorResult.apply( null, args );
2442 } catch ( earlyReturn ) {
2443 return earlyReturn;
2444 }
2445 } else if ( variables.hasOwnProperty( term ) ) {
2446 value = variables[ term ];
2447 } else {
2448 value = +term;
2449 }
2450
2451 stack.push( value );
2452 }
2453
2454 return stack[ 0 ];
2455 }
2456
2457 module.exports = evaluate;
2458
2459 },{}],12:[function(require,module,exports){
2460 'use strict';
2461
2462 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
2463
2464 var compile = _interopDefault(require('@tannin/compile'));
2465
2466 /**
2467 * Given a C expression, returns a function which, when called with a value,
2468 * evaluates the result with the value assumed to be the "n" variable of the
2469 * expression. The result will be coerced to its numeric equivalent.
2470 *
2471 * @param {string} expression C expression.
2472 *
2473 * @return {Function} Evaluator function.
2474 */
2475 function pluralForms( expression ) {
2476 var evaluate = compile( expression );
2477
2478 return function( n ) {
2479 return +evaluate( { n: n } );
2480 };
2481 }
2482
2483 module.exports = pluralForms;
2484
2485 },{"@tannin/compile":10}],13:[function(require,module,exports){
2486 'use strict';
2487
2488 var PRECEDENCE, OPENERS, TERMINATORS, PATTERN;
2489
2490 /**
2491 * Operator precedence mapping.
2492 *
2493 * @type {Object}
2494 */
2495 PRECEDENCE = {
2496 '(': 9,
2497 '!': 8,
2498 '*': 7,
2499 '/': 7,
2500 '%': 7,
2501 '+': 6,
2502 '-': 6,
2503 '<': 5,
2504 '<=': 5,
2505 '>': 5,
2506 '>=': 5,
2507 '==': 4,
2508 '!=': 4,
2509 '&&': 3,
2510 '||': 2,
2511 '?': 1,
2512 '?:': 1,
2513 };
2514
2515 /**
2516 * Characters which signal pair opening, to be terminated by terminators.
2517 *
2518 * @type {string[]}
2519 */
2520 OPENERS = [ '(', '?' ];
2521
2522 /**
2523 * Characters which signal pair termination, the value an array with the
2524 * opener as its first member. The second member is an optional operator
2525 * replacement to push to the stack.
2526 *
2527 * @type {string[]}
2528 */
2529 TERMINATORS = {
2530 ')': [ '(' ],
2531 ':': [ '?', '?:' ],
2532 };
2533
2534 /**
2535 * Pattern matching operators and openers.
2536 *
2537 * @type {RegExp}
2538 */
2539 PATTERN = /<=|>=|==|!=|&&|\|\||\?:|\(|!|\*|\/|%|\+|-|<|>|\?|\)|:/;
2540
2541 /**
2542 * Given a C expression, returns the equivalent postfix (Reverse Polish)
2543 * notation terms as an array.
2544 *
2545 * If a postfix string is desired, simply `.join( ' ' )` the result.
2546 *
2547 * @example
2548 *
2549 * ```js
2550 * import postfix from '@tannin/postfix';
2551 *
2552 * postfix( 'n > 1' );
2553 * // ⇒ [ 'n', '1', '>' ]
2554 * ```
2555 *
2556 * @param {string} expression C expression.
2557 *
2558 * @return {string[]} Postfix terms.
2559 */
2560 function postfix( expression ) {
2561 var terms = [],
2562 stack = [],
2563 match, operator, term, element;
2564
2565 while ( ( match = expression.match( PATTERN ) ) ) {
2566 operator = match[ 0 ];
2567
2568 // Term is the string preceding the operator match. It may contain
2569 // whitespace, and may be empty (if operator is at beginning).
2570 term = expression.substr( 0, match.index ).trim();
2571 if ( term ) {
2572 terms.push( term );
2573 }
2574
2575 while ( ( element = stack.pop() ) ) {
2576 if ( TERMINATORS[ operator ] ) {
2577 if ( TERMINATORS[ operator ][ 0 ] === element ) {
2578 // Substitution works here under assumption that because
2579 // the assigned operator will no longer be a terminator, it
2580 // will be pushed to the stack during the condition below.
2581 operator = TERMINATORS[ operator ][ 1 ] || operator;
2582 break;
2583 }
2584 } else if ( OPENERS.indexOf( element ) >= 0 || PRECEDENCE[ element ] < PRECEDENCE[ operator ] ) {
2585 // Push to stack if either an opener or when pop reveals an
2586 // element of lower precedence.
2587 stack.push( element );
2588 break;
2589 }
2590
2591 // For each popped from stack, push to terms.
2592 terms.push( element );
2593 }
2594
2595 if ( ! TERMINATORS[ operator ] ) {
2596 stack.push( operator );
2597 }
2598
2599 // Slice matched fragment from expression to continue match.
2600 expression = expression.substr( match.index + operator.length );
2601 }
2602
2603 // Push remainder of operand, if exists, to terms.
2604 expression = expression.trim();
2605 if ( expression ) {
2606 terms.push( expression );
2607 }
2608
2609 // Pop remaining items from stack into terms.
2610 return terms.concat( stack.reverse() );
2611 }
2612
2613 module.exports = postfix;
2614
2615 },{}],14:[function(require,module,exports){
2616 "use strict";
2617
2618 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
2619
2620 Object.defineProperty(exports, "__esModule", {
2621 value: true
2622 });
2623 exports.createI18n = void 0;
2624
2625 var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
2626
2627 var _tannin = _interopRequireDefault(require("tannin"));
2628
2629 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; }
2630
2631 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; }
2632
2633 /**
2634 * @typedef {Record<string,any>} LocaleData
2635 */
2636
2637 /**
2638 * Default locale data to use for Tannin domain when not otherwise provided.
2639 * Assumes an English plural forms expression.
2640 *
2641 * @type {LocaleData}
2642 */
2643 var DEFAULT_LOCALE_DATA = {
2644 '': {
2645 /** @param {number} n */
2646 plural_forms: function plural_forms(n) {
2647 return n === 1 ? 0 : 1;
2648 }
2649 }
2650 };
2651 /**
2652 * An i18n instance
2653 *
2654 * @typedef {Object} I18n
2655 * @property {Function} setLocaleData Merges locale data into the Tannin instance by domain. Accepts data in a
2656 * Jed-formatted JSON object shape.
2657 * @property {Function} __ Retrieve the translation of text.
2658 * @property {Function} _x Retrieve translated string with gettext context.
2659 * @property {Function} _n Translates and retrieves the singular or plural form based on the supplied
2660 * number.
2661 * @property {Function} _nx Translates and retrieves the singular or plural form based on the supplied
2662 * number, with gettext context.
2663 * @property {Function} isRTL Check if current locale is RTL.
2664 */
2665
2666 /**
2667 * Create an i18n instance
2668 *
2669 * @param {LocaleData} [initialData] Locale data configuration.
2670 * @param {string} [initialDomain] Domain for which configuration applies.
2671 * @return {I18n} I18n instance
2672 */
2673
2674 var createI18n = function createI18n(initialData, initialDomain) {
2675 /**
2676 * The underlying instance of Tannin to which exported functions interface.
2677 *
2678 * @type {Tannin}
2679 */
2680 var tannin = new _tannin.default({});
2681 /**
2682 * Merges locale data into the Tannin instance by domain. Accepts data in a
2683 * Jed-formatted JSON object shape.
2684 *
2685 * @see http://messageformat.github.io/Jed/
2686 *
2687 * @param {LocaleData} [data] Locale data configuration.
2688 * @param {string} [domain] Domain for which configuration applies.
2689 */
2690
2691 var setLocaleData = function setLocaleData(data) {
2692 var domain = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
2693 tannin.data[domain] = _objectSpread({}, DEFAULT_LOCALE_DATA, {}, tannin.data[domain], {}, data); // Populate default domain configuration (supported locale date which omits
2694 // a plural forms expression).
2695
2696 tannin.data[domain][''] = _objectSpread({}, DEFAULT_LOCALE_DATA[''], {}, tannin.data[domain]['']);
2697 };
2698 /**
2699 * Wrapper for Tannin's `dcnpgettext`. Populates default locale data if not
2700 * otherwise previously assigned.
2701 *
2702 * @param {string|undefined} domain Domain to retrieve the translated text.
2703 * @param {string|undefined} context Context information for the translators.
2704 * @param {string} single Text to translate if non-plural. Used as
2705 * fallback return value on a caught error.
2706 * @param {string} [plural] The text to be used if the number is
2707 * plural.
2708 * @param {number} [number] The number to compare against to use
2709 * either the singular or plural form.
2710 *
2711 * @return {string} The translated string.
2712 */
2713
2714
2715 var dcnpgettext = function dcnpgettext() {
2716 var domain = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';
2717 var context = arguments.length > 1 ? arguments[1] : undefined;
2718 var single = arguments.length > 2 ? arguments[2] : undefined;
2719 var plural = arguments.length > 3 ? arguments[3] : undefined;
2720 var number = arguments.length > 4 ? arguments[4] : undefined;
2721
2722 if (!tannin.data[domain]) {
2723 setLocaleData(undefined, domain);
2724 }
2725
2726 return tannin.dcnpgettext(domain, context, single, plural, number);
2727 };
2728 /**
2729 * Retrieve the translation of text.
2730 *
2731 * @see https://developer.wordpress.org/reference/functions/__/
2732 *
2733 * @param {string} text Text to translate.
2734 * @param {string} [domain] Domain to retrieve the translated text.
2735 *
2736 * @return {string} Translated text.
2737 */
2738
2739
2740 var __ = function __(text, domain) {
2741 return dcnpgettext(domain, undefined, text);
2742 };
2743 /**
2744 * Retrieve translated string with gettext context.
2745 *
2746 * @see https://developer.wordpress.org/reference/functions/_x/
2747 *
2748 * @param {string} text Text to translate.
2749 * @param {string} context Context information for the translators.
2750 * @param {string} [domain] Domain to retrieve the translated text.
2751 *
2752 * @return {string} Translated context string without pipe.
2753 */
2754
2755
2756 var _x = function _x(text, context, domain) {
2757 return dcnpgettext(domain, context, text);
2758 };
2759 /**
2760 * Translates and retrieves the singular or plural form based on the supplied
2761 * number.
2762 *
2763 * @see https://developer.wordpress.org/reference/functions/_n/
2764 *
2765 * @param {string} single The text to be used if the number is singular.
2766 * @param {string} plural The text to be used if the number is plural.
2767 * @param {number} number The number to compare against to use either the
2768 * singular or plural form.
2769 * @param {string} [domain] Domain to retrieve the translated text.
2770 *
2771 * @return {string} The translated singular or plural form.
2772 */
2773
2774
2775 var _n = function _n(single, plural, number, domain) {
2776 return dcnpgettext(domain, undefined, single, plural, number);
2777 };
2778 /**
2779 * Translates and retrieves the singular or plural form based on the supplied
2780 * number, with gettext context.
2781 *
2782 * @see https://developer.wordpress.org/reference/functions/_nx/
2783 *
2784 * @param {string} single The text to be used if the number is singular.
2785 * @param {string} plural The text to be used if the number is plural.
2786 * @param {number} number The number to compare against to use either the
2787 * singular or plural form.
2788 * @param {string} context Context information for the translators.
2789 * @param {string} [domain] Domain to retrieve the translated text.
2790 *
2791 * @return {string} The translated singular or plural form.
2792 */
2793
2794
2795 var _nx = function _nx(single, plural, number, context, domain) {
2796 return dcnpgettext(domain, context, single, plural, number);
2797 };
2798 /**
2799 * Check if current locale is RTL.
2800 *
2801 * **RTL (Right To Left)** is a locale property indicating that text is written from right to left.
2802 * For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common
2803 * language written RTL. The opposite of RTL, LTR (Left To Right) is used in other languages,
2804 * including English (`en`, `en-US`, `en-GB`, etc.), Spanish (`es`), and French (`fr`).
2805 *
2806 * @return {boolean} Whether locale is RTL.
2807 */
2808
2809
2810 var isRTL = function isRTL() {
2811 return 'rtl' === _x('ltr', 'text direction');
2812 };
2813
2814 if (initialData) {
2815 setLocaleData(initialData, initialDomain);
2816 }
2817
2818 return {
2819 setLocaleData: setLocaleData,
2820 __: __,
2821 _x: _x,
2822 _n: _n,
2823 _nx: _nx,
2824 isRTL: isRTL
2825 };
2826 };
2827
2828 exports.createI18n = createI18n;
2829
2830 },{"@babel/runtime/helpers/defineProperty":8,"@babel/runtime/helpers/interopRequireDefault":9,"tannin":23}],15:[function(require,module,exports){
2831 "use strict";
2832
2833 Object.defineProperty(exports, "__esModule", {
2834 value: true
2835 });
2836 exports.isRTL = exports._nx = exports._n = exports._x = exports.__ = exports.setLocaleData = void 0;
2837
2838 var _createI18n = require("./create-i18n");
2839
2840 /**
2841 * Internal dependencies
2842 */
2843 var i18n = (0, _createI18n.createI18n)();
2844 /*
2845 * Comments in this file are duplicated from ./i18n due to
2846 * https://github.com/WordPress/gutenberg/pull/20318#issuecomment-590837722
2847 */
2848
2849 /**
2850 * @typedef {import('./create-i18n').LocaleData} LocaleData
2851 */
2852
2853 /**
2854 * Merges locale data into the Tannin instance by domain. Accepts data in a
2855 * Jed-formatted JSON object shape.
2856 *
2857 * @see http://messageformat.github.io/Jed/
2858 *
2859 * @param {LocaleData} [data] Locale data configuration.
2860 * @param {string} [domain] Domain for which configuration applies.
2861 */
2862
2863 var setLocaleData = i18n.setLocaleData.bind(i18n);
2864 /**
2865 * Retrieve the translation of text.
2866 *
2867 * @see https://developer.wordpress.org/reference/functions/__/
2868 *
2869 * @param {string} text Text to translate.
2870 * @param {string} [domain] Domain to retrieve the translated text.
2871 *
2872 * @return {string} Translated text.
2873 */
2874
2875 exports.setLocaleData = setLocaleData;
2876
2877 var __ = i18n.__.bind(i18n);
2878 /**
2879 * Retrieve translated string with gettext context.
2880 *
2881 * @see https://developer.wordpress.org/reference/functions/_x/
2882 *
2883 * @param {string} text Text to translate.
2884 * @param {string} context Context information for the translators.
2885 * @param {string} [domain] Domain to retrieve the translated text.
2886 *
2887 * @return {string} Translated context string without pipe.
2888 */
2889
2890
2891 exports.__ = __;
2892
2893 var _x = i18n._x.bind(i18n);
2894 /**
2895 * Translates and retrieves the singular or plural form based on the supplied
2896 * number.
2897 *
2898 * @see https://developer.wordpress.org/reference/functions/_n/
2899 *
2900 * @param {string} single The text to be used if the number is singular.
2901 * @param {string} plural The text to be used if the number is plural.
2902 * @param {number} number The number to compare against to use either the
2903 * singular or plural form.
2904 * @param {string} [domain] Domain to retrieve the translated text.
2905 *
2906 * @return {string} The translated singular or plural form.
2907 */
2908
2909
2910 exports._x = _x;
2911
2912 var _n = i18n._n.bind(i18n);
2913 /**
2914 * Translates and retrieves the singular or plural form based on the supplied
2915 * number, with gettext context.
2916 *
2917 * @see https://developer.wordpress.org/reference/functions/_nx/
2918 *
2919 * @param {string} single The text to be used if the number is singular.
2920 * @param {string} plural The text to be used if the number is plural.
2921 * @param {number} number The number to compare against to use either the
2922 * singular or plural form.
2923 * @param {string} context Context information for the translators.
2924 * @param {string} [domain] Domain to retrieve the translated text.
2925 *
2926 * @return {string} The translated singular or plural form.
2927 */
2928
2929
2930 exports._n = _n;
2931
2932 var _nx = i18n._nx.bind(i18n);
2933 /**
2934 * Check if current locale is RTL.
2935 *
2936 * **RTL (Right To Left)** is a locale property indicating that text is written from right to left.
2937 * For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common
2938 * language written RTL. The opposite of RTL, LTR (Left To Right) is used in other languages,
2939 * including English (`en`, `en-US`, `en-GB`, etc.), Spanish (`es`), and French (`fr`).
2940 *
2941 * @return {boolean} Whether locale is RTL.
2942 */
2943
2944
2945 exports._nx = _nx;
2946 var isRTL = i18n.isRTL.bind(i18n);
2947 exports.isRTL = isRTL;
2948
2949 },{"./create-i18n":14}],16:[function(require,module,exports){
2950 "use strict";
2951
2952 Object.defineProperty(exports, "__esModule", {
2953 value: true
2954 });
2955 var _exportNames = {
2956 sprintf: true,
2957 setLocaleData: true,
2958 __: true,
2959 _x: true,
2960 _n: true,
2961 _nx: true,
2962 isRTL: true
2963 };
2964 Object.defineProperty(exports, "sprintf", {
2965 enumerable: true,
2966 get: function get() {
2967 return _sprintf.sprintf;
2968 }
2969 });
2970 Object.defineProperty(exports, "setLocaleData", {
2971 enumerable: true,
2972 get: function get() {
2973 return _defaultI18n.setLocaleData;
2974 }
2975 });
2976 Object.defineProperty(exports, "__", {
2977 enumerable: true,
2978 get: function get() {
2979 return _defaultI18n.__;
2980 }
2981 });
2982 Object.defineProperty(exports, "_x", {
2983 enumerable: true,
2984 get: function get() {
2985 return _defaultI18n._x;
2986 }
2987 });
2988 Object.defineProperty(exports, "_n", {
2989 enumerable: true,
2990 get: function get() {
2991 return _defaultI18n._n;
2992 }
2993 });
2994 Object.defineProperty(exports, "_nx", {
2995 enumerable: true,
2996 get: function get() {
2997 return _defaultI18n._nx;
2998 }
2999 });
3000 Object.defineProperty(exports, "isRTL", {
3001 enumerable: true,
3002 get: function get() {
3003 return _defaultI18n.isRTL;
3004 }
3005 });
3006
3007 var _sprintf = require("./sprintf");
3008
3009 var _createI18n = require("./create-i18n");
3010
3011 Object.keys(_createI18n).forEach(function (key) {
3012 if (key === "default" || key === "__esModule") return;
3013 if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
3014 Object.defineProperty(exports, key, {
3015 enumerable: true,
3016 get: function get() {
3017 return _createI18n[key];
3018 }
3019 });
3020 });
3021
3022 var _defaultI18n = require("./default-i18n");
3023
3024 },{"./create-i18n":14,"./default-i18n":15,"./sprintf":17}],17:[function(require,module,exports){
3025 "use strict";
3026
3027 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
3028
3029 Object.defineProperty(exports, "__esModule", {
3030 value: true
3031 });
3032 exports.sprintf = sprintf;
3033
3034 var _memize = _interopRequireDefault(require("memize"));
3035
3036 var _sprintfJs = _interopRequireDefault(require("sprintf-js"));
3037
3038 /**
3039 * External dependencies
3040 */
3041
3042 /**
3043 * Log to console, once per message; or more precisely, per referentially equal
3044 * argument set. Because Jed throws errors, we log these to the console instead
3045 * to avoid crashing the application.
3046 *
3047 * @param {...*} args Arguments to pass to `console.error`
3048 */
3049 var logErrorOnce = (0, _memize.default)(console.error); // eslint-disable-line no-console
3050
3051 /**
3052 * Returns a formatted string. If an error occurs in applying the format, the
3053 * original format string is returned.
3054 *
3055 * @param {string} format The format of the string to generate.
3056 * @param {...*} args Arguments to apply to the format.
3057 *
3058 * @see http://www.diveintojavascript.com/projects/javascript-sprintf
3059 *
3060 * @return {string} The formatted string.
3061 */
3062
3063 function sprintf(format) {
3064 try {
3065 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
3066 args[_key - 1] = arguments[_key];
3067 }
3068
3069 return _sprintfJs.default.sprintf.apply(_sprintfJs.default, [format].concat(args));
3070 } catch (error) {
3071 logErrorOnce('sprintf error: \n\n' + error.toString());
3072 return format;
3073 }
3074 }
3075
3076 },{"@babel/runtime/helpers/interopRequireDefault":9,"memize":21,"sprintf-js":18}],18:[function(require,module,exports){
3077 /* global window, exports, define */
3078
3079 !function() {
3080 'use strict'
3081
3082 var re = {
3083 not_string: /[^s]/,
3084 not_bool: /[^t]/,
3085 not_type: /[^T]/,
3086 not_primitive: /[^v]/,
3087 number: /[diefg]/,
3088 numeric_arg: /[bcdiefguxX]/,
3089 json: /[j]/,
3090 not_json: /[^j]/,
3091 text: /^[^\x25]+/,
3092 modulo: /^\x25{2}/,
3093 placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
3094 key: /^([a-z_][a-z_\d]*)/i,
3095 key_access: /^\.([a-z_][a-z_\d]*)/i,
3096 index_access: /^\[(\d+)\]/,
3097 sign: /^[+-]/
3098 }
3099
3100 function sprintf(key) {
3101 // `arguments` is not an array, but should be fine for this call
3102 return sprintf_format(sprintf_parse(key), arguments)
3103 }
3104
3105 function vsprintf(fmt, argv) {
3106 return sprintf.apply(null, [fmt].concat(argv || []))
3107 }
3108
3109 function sprintf_format(parse_tree, argv) {
3110 var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
3111 for (i = 0; i < tree_length; i++) {
3112 if (typeof parse_tree[i] === 'string') {
3113 output += parse_tree[i]
3114 }
3115 else if (typeof parse_tree[i] === 'object') {
3116 ph = parse_tree[i] // convenience purposes only
3117 if (ph.keys) { // keyword argument
3118 arg = argv[cursor]
3119 for (k = 0; k < ph.keys.length; k++) {
3120 if (arg == undefined) {
3121 throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
3122 }
3123 arg = arg[ph.keys[k]]
3124 }
3125 }
3126 else if (ph.param_no) { // positional argument (explicit)
3127 arg = argv[ph.param_no]
3128 }
3129 else { // positional argument (implicit)
3130 arg = argv[cursor++]
3131 }
3132
3133 if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
3134 arg = arg()
3135 }
3136
3137 if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
3138 throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
3139 }
3140
3141 if (re.number.test(ph.type)) {
3142 is_positive = arg >= 0
3143 }
3144
3145 switch (ph.type) {
3146 case 'b':
3147 arg = parseInt(arg, 10).toString(2)
3148 break
3149 case 'c':
3150 arg = String.fromCharCode(parseInt(arg, 10))
3151 break
3152 case 'd':
3153 case 'i':
3154 arg = parseInt(arg, 10)
3155 break
3156 case 'j':
3157 arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
3158 break
3159 case 'e':
3160 arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
3161 break
3162 case 'f':
3163 arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
3164 break
3165 case 'g':
3166 arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
3167 break
3168 case 'o':
3169 arg = (parseInt(arg, 10) >>> 0).toString(8)
3170 break
3171 case 's':
3172 arg = String(arg)
3173 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
3174 break
3175 case 't':
3176 arg = String(!!arg)
3177 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
3178 break
3179 case 'T':
3180 arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
3181 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
3182 break
3183 case 'u':
3184 arg = parseInt(arg, 10) >>> 0
3185 break
3186 case 'v':
3187 arg = arg.valueOf()
3188 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
3189 break
3190 case 'x':
3191 arg = (parseInt(arg, 10) >>> 0).toString(16)
3192 break
3193 case 'X':
3194 arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
3195 break
3196 }
3197 if (re.json.test(ph.type)) {
3198 output += arg
3199 }
3200 else {
3201 if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
3202 sign = is_positive ? '+' : '-'
3203 arg = arg.toString().replace(re.sign, '')
3204 }
3205 else {
3206 sign = ''
3207 }
3208 pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
3209 pad_length = ph.width - (sign + arg).length
3210 pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
3211 output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
3212 }
3213 }
3214 }
3215 return output
3216 }
3217
3218 var sprintf_cache = Object.create(null)
3219
3220 function sprintf_parse(fmt) {
3221 if (sprintf_cache[fmt]) {
3222 return sprintf_cache[fmt]
3223 }
3224
3225 var _fmt = fmt, match, parse_tree = [], arg_names = 0
3226 while (_fmt) {
3227 if ((match = re.text.exec(_fmt)) !== null) {
3228 parse_tree.push(match[0])
3229 }
3230 else if ((match = re.modulo.exec(_fmt)) !== null) {
3231 parse_tree.push('%')
3232 }
3233 else if ((match = re.placeholder.exec(_fmt)) !== null) {
3234 if (match[2]) {
3235 arg_names |= 1
3236 var field_list = [], replacement_field = match[2], field_match = []
3237 if ((field_match = re.key.exec(replacement_field)) !== null) {
3238 field_list.push(field_match[1])
3239 while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
3240 if ((field_match = re.key_access.exec(replacement_field)) !== null) {
3241 field_list.push(field_match[1])
3242 }
3243 else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
3244 field_list.push(field_match[1])
3245 }
3246 else {
3247 throw new SyntaxError('[sprintf] failed to parse named argument key')
3248 }
3249 }
3250 }
3251 else {
3252 throw new SyntaxError('[sprintf] failed to parse named argument key')
3253 }
3254 match[2] = field_list
3255 }
3256 else {
3257 arg_names |= 2
3258 }
3259 if (arg_names === 3) {
3260 throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
3261 }
3262
3263 parse_tree.push(
3264 {
3265 placeholder: match[0],
3266 param_no: match[1],
3267 keys: match[2],
3268 sign: match[3],
3269 pad_char: match[4],
3270 align: match[5],
3271 width: match[6],
3272 precision: match[7],
3273 type: match[8]
3274 }
3275 )
3276 }
3277 else {
3278 throw new SyntaxError('[sprintf] unexpected placeholder')
3279 }
3280 _fmt = _fmt.substring(match[0].length)
3281 }
3282 return sprintf_cache[fmt] = parse_tree
3283 }
3284
3285 /**
3286 * export to either browser or node.js
3287 */
3288 /* eslint-disable quote-props */
3289 if (typeof exports !== 'undefined') {
3290 exports['sprintf'] = sprintf
3291 exports['vsprintf'] = vsprintf
3292 }
3293 if (typeof window !== 'undefined') {
3294 window['sprintf'] = sprintf
3295 window['vsprintf'] = vsprintf
3296
3297 if (typeof define === 'function' && define['amd']) {
3298 define(function() {
3299 return {
3300 'sprintf': sprintf,
3301 'vsprintf': vsprintf
3302 }
3303 })
3304 }
3305 }
3306 /* eslint-enable quote-props */
3307 }(); // eslint-disable-line
3308
3309 },{}],19:[function(require,module,exports){
3310 /*
3311 * International Telephone Input v17.0.16
3312 * https://github.com/jackocnr/intl-tel-input.git
3313 * Licensed under the MIT license
3314 */
3315
3316 // wrap in UMD
3317 (function(factory) {
3318 if (typeof module === "object" && module.exports) module.exports = factory(); else window.intlTelInput = factory();
3319 })(function(undefined) {
3320 "use strict";
3321 return function() {
3322 // Array of country objects for the flag dropdown.
3323 // Here is the criteria for the plugin to support a given country/territory
3324 // - It has an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
3325 // - 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
3326 // - It has a flag in the region-flags project: https://github.com/behdad/region-flags/tree/gh-pages/png
3327 // - It is supported by libphonenumber (it must be listed on this page): https://github.com/googlei18n/libphonenumber/blob/master/resources/ShortNumberMetadata.xml
3328 // Each country array has the following information:
3329 // [
3330 // Country name,
3331 // iso2 code,
3332 // International dial code,
3333 // Order (if >1 country with same dial code),
3334 // Area codes
3335 // ]
3336 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 (‫جزر الق�
3337 ر‬‎)", "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 (‫�
3338 صر‬‎)", "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 (Каза�
3339 стан)", "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 (‫�
3340 وريتانيا‬‎)", "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 (‫ال�
3341 غرب‬‎)", "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 (‫عُ�
3342 ان‬‎)", "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 (‫ال�
3343 �
3344 لكة العربية السعودية‬‎)", "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 (‫الإ�
3345 ارات العربية ال�
3346 تحدة‬‎)", "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 (‫الي�
3347 ن‬‎)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ], [ "�
3348 land Islands", "ax", "358", 1, [ "18" ] ] ];
3349 // loop over all of the countries above, restructuring the data to be objects with named keys
3350 for (var i = 0; i < allCountries.length; i++) {
3351 var c = allCountries[i];
3352 allCountries[i] = {
3353 name: c[0],
3354 iso2: c[1],
3355 dialCode: c[2],
3356 priority: c[3] || 0,
3357 areaCodes: c[4] || null
3358 };
3359 }
3360 "use strict";
3361 function _classCallCheck(instance, Constructor) {
3362 if (!(instance instanceof Constructor)) {
3363 throw new TypeError("Cannot call a class as a function");
3364 }
3365 }
3366 function _defineProperties(target, props) {
3367 for (var i = 0; i < props.length; i++) {
3368 var descriptor = props[i];
3369 descriptor.enumerable = descriptor.enumerable || false;
3370 descriptor.configurable = true;
3371 if ("value" in descriptor) descriptor.writable = true;
3372 Object.defineProperty(target, descriptor.key, descriptor);
3373 }
3374 }
3375 function _createClass(Constructor, protoProps, staticProps) {
3376 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
3377 if (staticProps) _defineProperties(Constructor, staticProps);
3378 return Constructor;
3379 }
3380 var intlTelInputGlobals = {
3381 getInstance: function getInstance(input) {
3382 var id = input.getAttribute("data-intl-tel-input-id");
3383 return window.intlTelInputGlobals.instances[id];
3384 },
3385 instances: {},
3386 // using a global like this allows us to mock it in the tests
3387 documentReady: function documentReady() {
3388 return document.readyState === "complete";
3389 }
3390 };
3391 if (typeof window === "object") window.intlTelInputGlobals = intlTelInputGlobals;
3392 // these vars persist through all instances of the plugin
3393 var id = 0;
3394 var defaults = {
3395 // whether or not to allow the dropdown
3396 allowDropdown: true,
3397 // if there is just a dial code in the input: remove it on blur
3398 autoHideDialCode: true,
3399 // add a placeholder in the input with an example number for the selected country
3400 autoPlaceholder: "polite",
3401 // modify the parentClass
3402 customContainer: "",
3403 // modify the auto placeholder
3404 customPlaceholder: null,
3405 // append menu to specified element
3406 dropdownContainer: null,
3407 // don't display these countries
3408 excludeCountries: [],
3409 // format the input value during initialisation and on setNumber
3410 formatOnDisplay: true,
3411 // geoIp lookup function
3412 geoIpLookup: null,
3413 // inject a hidden input with this name, and on submit, populate it with the result of getNumber
3414 hiddenInput: "",
3415 // initial country
3416 initialCountry: "",
3417 // localized country names e.g. { 'de': 'Deutschland' }
3418 localizedCountries: null,
3419 // don't insert international dial codes
3420 nationalMode: true,
3421 // display only these countries
3422 onlyCountries: [],
3423 // number type to use for placeholders
3424 placeholderNumberType: "MOBILE",
3425 // the countries at the top of the list. defaults to united states and united kingdom
3426 preferredCountries: [ "us", "gb" ],
3427 // display the country dial code next to the selected flag so it's not part of the typed number
3428 separateDialCode: false,
3429 // specify the path to the libphonenumber script to enable validation/formatting
3430 utilsScript: ""
3431 };
3432 // https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes#Non-geographic_area_codes
3433 var regionlessNanpNumbers = [ "800", "822", "833", "844", "855", "866", "877", "880", "881", "882", "883", "884", "885", "886", "887", "888", "889" ];
3434 // utility function to iterate over an object. can't use Object.entries or native forEach because
3435 // of IE11
3436 var forEachProp = function forEachProp(obj, callback) {
3437 var keys = Object.keys(obj);
3438 for (var i = 0; i < keys.length; i++) {
3439 callback(keys[i], obj[keys[i]]);
3440 }
3441 };
3442 // run a method on each instance of the plugin
3443 var forEachInstance = function forEachInstance(method) {
3444 forEachProp(window.intlTelInputGlobals.instances, function(key) {
3445 window.intlTelInputGlobals.instances[key][method]();
3446 });
3447 };
3448 // this is our plugin class that we will create an instance of
3449 // eslint-disable-next-line no-unused-vars
3450 var Iti = /*#__PURE__*/
3451 function() {
3452 function Iti(input, options) {
3453 var _this = this;
3454 _classCallCheck(this, Iti);
3455 this.id = id++;
3456 this.telInput = input;
3457 this.activeItem = null;
3458 this.highlightedItem = null;
3459 // process specified options / defaults
3460 // alternative to Object.assign, which isn't supported by IE11
3461 var customOptions = options || {};
3462 this.options = {};
3463 forEachProp(defaults, function(key, value) {
3464 _this.options[key] = customOptions.hasOwnProperty(key) ? customOptions[key] : value;
3465 });
3466 this.hadInitialPlaceholder = Boolean(input.getAttribute("placeholder"));
3467 }
3468 _createClass(Iti, [ {
3469 key: "_init",
3470 value: function _init() {
3471 var _this2 = this;
3472 // if in nationalMode, disable options relating to dial codes
3473 if (this.options.nationalMode) this.options.autoHideDialCode = false;
3474 // if separateDialCode then doesn't make sense to A) insert dial code into input
3475 // (autoHideDialCode), and B) display national numbers (because we're displaying the country
3476 // dial code next to them)
3477 if (this.options.separateDialCode) {
3478 this.options.autoHideDialCode = this.options.nationalMode = false;
3479 }
3480 // we cannot just test screen size as some smartphones/website meta tags will report desktop
3481 // resolutions
3482 // Note: for some reason jasmine breaks if you put this in the main Plugin function with the
3483 // rest of these declarations
3484 // Note: to target Android Mobiles (and not Tablets), we must find 'Android' and 'Mobile'
3485 this.isMobile = /Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
3486 if (this.isMobile) {
3487 // trigger the mobile dropdown css
3488 document.body.classList.add("iti-mobile");
3489 // on mobile, we want a full screen dropdown, so we must append it to the body
3490 if (!this.options.dropdownContainer) this.options.dropdownContainer = document.body;
3491 }
3492 // these promises get resolved when their individual requests complete
3493 // this way the dev can do something like iti.promise.then(...) to know when all requests are
3494 // complete
3495 if (typeof Promise !== "undefined") {
3496 var autoCountryPromise = new Promise(function(resolve, reject) {
3497 _this2.resolveAutoCountryPromise = resolve;
3498 _this2.rejectAutoCountryPromise = reject;
3499 });
3500 var utilsScriptPromise = new Promise(function(resolve, reject) {
3501 _this2.resolveUtilsScriptPromise = resolve;
3502 _this2.rejectUtilsScriptPromise = reject;
3503 });
3504 this.promise = Promise.all([ autoCountryPromise, utilsScriptPromise ]);
3505 } else {
3506 // prevent errors when Promise doesn't exist
3507 this.resolveAutoCountryPromise = this.rejectAutoCountryPromise = function() {};
3508 this.resolveUtilsScriptPromise = this.rejectUtilsScriptPromise = function() {};
3509 }
3510 // in various situations there could be no country selected initially, but we need to be able
3511 // to assume this variable exists
3512 this.selectedCountryData = {};
3513 // process all the data: onlyCountries, excludeCountries, preferredCountries etc
3514 this._processCountryData();
3515 // generate the markup
3516 this._generateMarkup();
3517 // set the initial state of the input value and the selected flag
3518 this._setInitialState();
3519 // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click
3520 this._initListeners();
3521 // utils script, and auto country
3522 this._initRequests();
3523 }
3524 }, {
3525 key: "_processCountryData",
3526 value: function _processCountryData() {
3527 // process onlyCountries or excludeCountries array if present
3528 this._processAllCountries();
3529 // process the countryCodes map
3530 this._processCountryCodes();
3531 // process the preferredCountries
3532 this._processPreferredCountries();
3533 // translate countries according to localizedCountries option
3534 if (this.options.localizedCountries) this._translateCountriesByLocale();
3535 // sort countries by name
3536 if (this.options.onlyCountries.length || this.options.localizedCountries) {
3537 this.countries.sort(this._countryNameSort);
3538 }
3539 }
3540 }, {
3541 key: "_addCountryCode",
3542 value: function _addCountryCode(iso2, countryCode, priority) {
3543 if (countryCode.length > this.countryCodeMaxLen) {
3544 this.countryCodeMaxLen = countryCode.length;
3545 }
3546 if (!this.countryCodes.hasOwnProperty(countryCode)) {
3547 this.countryCodes[countryCode] = [];
3548 }
3549 // bail if we already have this country for this countryCode
3550 for (var i = 0; i < this.countryCodes[countryCode].length; i++) {
3551 if (this.countryCodes[countryCode][i] === iso2) return;
3552 }
3553 // check for undefined as 0 is falsy
3554 var index = priority !== undefined ? priority : this.countryCodes[countryCode].length;
3555 this.countryCodes[countryCode][index] = iso2;
3556 }
3557 }, {
3558 key: "_processAllCountries",
3559 value: function _processAllCountries() {
3560 if (this.options.onlyCountries.length) {
3561 var lowerCaseOnlyCountries = this.options.onlyCountries.map(function(country) {
3562 return country.toLowerCase();
3563 });
3564 this.countries = allCountries.filter(function(country) {
3565 return lowerCaseOnlyCountries.indexOf(country.iso2) > -1;
3566 });
3567 } else if (this.options.excludeCountries.length) {
3568 var lowerCaseExcludeCountries = this.options.excludeCountries.map(function(country) {
3569 return country.toLowerCase();
3570 });
3571 this.countries = allCountries.filter(function(country) {
3572 return lowerCaseExcludeCountries.indexOf(country.iso2) === -1;
3573 });
3574 } else {
3575 this.countries = allCountries;
3576 }
3577 }
3578 }, {
3579 key: "_translateCountriesByLocale",
3580 value: function _translateCountriesByLocale() {
3581 for (var i = 0; i < this.countries.length; i++) {
3582 var iso = this.countries[i].iso2.toLowerCase();
3583 if (this.options.localizedCountries.hasOwnProperty(iso)) {
3584 this.countries[i].name = this.options.localizedCountries[iso];
3585 }
3586 }
3587 }
3588 }, {
3589 key: "_countryNameSort",
3590 value: function _countryNameSort(a, b) {
3591 return a.name.localeCompare(b.name);
3592 }
3593 }, {
3594 key: "_processCountryCodes",
3595 value: function _processCountryCodes() {
3596 this.countryCodeMaxLen = 0;
3597 // here we store just dial codes
3598 this.dialCodes = {};
3599 // here we store "country codes" (both dial codes and their area codes)
3600 this.countryCodes = {};
3601 // first: add dial codes
3602 for (var i = 0; i < this.countries.length; i++) {
3603 var c = this.countries[i];
3604 if (!this.dialCodes[c.dialCode]) this.dialCodes[c.dialCode] = true;
3605 this._addCountryCode(c.iso2, c.dialCode, c.priority);
3606 }
3607 // next: add area codes
3608 // this is a second loop over countries, to make sure we have all of the "root" countries
3609 // already in the map, so that we can access them, as each time we add an area code substring
3610 // to the map, we also need to include the "root" country's code, as that also matches
3611 for (var _i = 0; _i < this.countries.length; _i++) {
3612 var _c = this.countries[_i];
3613 // area codes
3614 if (_c.areaCodes) {
3615 var rootCountryCode = this.countryCodes[_c.dialCode][0];
3616 // for each area code
3617 for (var j = 0; j < _c.areaCodes.length; j++) {
3618 var areaCode = _c.areaCodes[j];
3619 // for each digit in the area code to add all partial matches as well
3620 for (var k = 1; k < areaCode.length; k++) {
3621 var partialDialCode = _c.dialCode + areaCode.substr(0, k);
3622 // start with the root country, as that also matches this dial code
3623 this._addCountryCode(rootCountryCode, partialDialCode);
3624 this._addCountryCode(_c.iso2, partialDialCode);
3625 }
3626 // add the full area code
3627 this._addCountryCode(_c.iso2, _c.dialCode + areaCode);
3628 }
3629 }
3630 }
3631 }
3632 }, {
3633 key: "_processPreferredCountries",
3634 value: function _processPreferredCountries() {
3635 this.preferredCountries = [];
3636 for (var i = 0; i < this.options.preferredCountries.length; i++) {
3637 var countryCode = this.options.preferredCountries[i].toLowerCase();
3638 var countryData = this._getCountryData(countryCode, false, true);
3639 if (countryData) this.preferredCountries.push(countryData);
3640 }
3641 }
3642 }, {
3643 key: "_createEl",
3644 value: function _createEl(name, attrs, container) {
3645 var el = document.createElement(name);
3646 if (attrs) forEachProp(attrs, function(key, value) {
3647 return el.setAttribute(key, value);
3648 });
3649 if (container) container.appendChild(el);
3650 return el;
3651 }
3652 }, {
3653 key: "_generateMarkup",
3654 value: function _generateMarkup() {
3655 // if autocomplete does not exist on the element and its form, then
3656 // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can
3657 // easily put the plugin in an inconsistent state e.g. the wrong flag selected for the
3658 // autocompleted number, which on submit could mean wrong number is saved (esp in nationalMode)
3659 if (!this.telInput.hasAttribute("autocomplete") && !(this.telInput.form && this.telInput.form.hasAttribute("autocomplete"))) {
3660 this.telInput.setAttribute("autocomplete", "off");
3661 }
3662 // containers (mostly for positioning)
3663 var parentClass = "iti";
3664 if (this.options.allowDropdown) parentClass += " iti--allow-dropdown";
3665 if (this.options.separateDialCode) parentClass += " iti--separate-dial-code";
3666 if (this.options.customContainer) {
3667 parentClass += " ";
3668 parentClass += this.options.customContainer;
3669 }
3670 var wrapper = this._createEl("div", {
3671 "class": parentClass
3672 });
3673 this.telInput.parentNode.insertBefore(wrapper, this.telInput);
3674 this.flagsContainer = this._createEl("div", {
3675 "class": "iti__flag-container"
3676 }, wrapper);
3677 wrapper.appendChild(this.telInput);
3678 // selected flag (displayed to left of input)
3679 this.selectedFlag = this._createEl("div", {
3680 "class": "iti__selected-flag",
3681 role: "combobox",
3682 "aria-controls": "iti-".concat(this.id, "__country-listbox"),
3683 "aria-owns": "iti-".concat(this.id, "__country-listbox"),
3684 "aria-expanded": "false"
3685 }, this.flagsContainer);
3686 this.selectedFlagInner = this._createEl("div", {
3687 "class": "iti__flag"
3688 }, this.selectedFlag);
3689 if (this.options.separateDialCode) {
3690 this.selectedDialCode = this._createEl("div", {
3691 "class": "iti__selected-dial-code"
3692 }, this.selectedFlag);
3693 }
3694 if (this.options.allowDropdown) {
3695 // make element focusable and tab navigable
3696 this.selectedFlag.setAttribute("tabindex", "0");
3697 this.dropdownArrow = this._createEl("div", {
3698 "class": "iti__arrow"
3699 }, this.selectedFlag);
3700 // country dropdown: preferred countries, then divider, then all countries
3701 this.countryList = this._createEl("ul", {
3702 "class": "iti__country-list iti__hide",
3703 id: "iti-".concat(this.id, "__country-listbox"),
3704 role: "listbox",
3705 "aria-label": "List of countries"
3706 });
3707 if (this.preferredCountries.length) {
3708 this._appendListItems(this.preferredCountries, "iti__preferred", true);
3709 this._createEl("li", {
3710 "class": "iti__divider",
3711 role: "separator",
3712 "aria-disabled": "true"
3713 }, this.countryList);
3714 }
3715 this._appendListItems(this.countries, "iti__standard");
3716 // create dropdownContainer markup
3717 if (this.options.dropdownContainer) {
3718 this.dropdown = this._createEl("div", {
3719 "class": "iti iti--container"
3720 });
3721 this.dropdown.appendChild(this.countryList);
3722 } else {
3723 this.flagsContainer.appendChild(this.countryList);
3724 }
3725 }
3726 if (this.options.hiddenInput) {
3727 var hiddenInputName = this.options.hiddenInput;
3728 var name = this.telInput.getAttribute("name");
3729 if (name) {
3730 var i = name.lastIndexOf("[");
3731 // if input name contains square brackets, then give the hidden input the same name,
3732 // replacing the contents of the last set of brackets with the given hiddenInput name
3733 if (i !== -1) hiddenInputName = "".concat(name.substr(0, i), "[").concat(hiddenInputName, "]");
3734 }
3735 this.hiddenInput = this._createEl("input", {
3736 type: "hidden",
3737 name: hiddenInputName
3738 });
3739 wrapper.appendChild(this.hiddenInput);
3740 }
3741 }
3742 }, {
3743 key: "_appendListItems",
3744 value: function _appendListItems(countries, className, preferred) {
3745 // we create so many DOM elements, it is faster to build a temp string
3746 // and then add everything to the DOM in one go at the end
3747 var tmp = "";
3748 // for each country
3749 for (var i = 0; i < countries.length; i++) {
3750 var c = countries[i];
3751 var idSuffix = preferred ? "-preferred" : "";
3752 // open the list item
3753 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'>");
3754 // add the flag
3755 tmp += "<div class='iti__flag-box'><div class='iti__flag iti__".concat(c.iso2, "'></div></div>");
3756 // and the country name and dial code
3757 tmp += "<span class='iti__country-name'>".concat(c.name, "</span>");
3758 tmp += "<span class='iti__dial-code'>+".concat(c.dialCode, "</span>");
3759 // close the list item
3760 tmp += "</li>";
3761 }
3762 this.countryList.insertAdjacentHTML("beforeend", tmp);
3763 }
3764 }, {
3765 key: "_setInitialState",
3766 value: function _setInitialState() {
3767 // fix firefox bug: when first load page (with input with value set to number with intl dial
3768 // code) and initialising plugin removes the dial code from the input, then refresh page,
3769 // and we try to init plugin again but this time on number without dial code so get grey flag
3770 var attributeValue = this.telInput.getAttribute("value");
3771 var inputValue = this.telInput.value;
3772 var useAttribute = attributeValue && attributeValue.charAt(0) === "+" && (!inputValue || inputValue.charAt(0) !== "+");
3773 var val = useAttribute ? attributeValue : inputValue;
3774 var dialCode = this._getDialCode(val);
3775 var isRegionlessNanp = this._isRegionlessNanp(val);
3776 var _this$options = this.options, initialCountry = _this$options.initialCountry, nationalMode = _this$options.nationalMode, autoHideDialCode = _this$options.autoHideDialCode, separateDialCode = _this$options.separateDialCode;
3777 // if we already have a dial code, and it's not a regionlessNanp, we can go ahead and set the
3778 // flag, else fall back to the default country
3779 if (dialCode && !isRegionlessNanp) {
3780 this._updateFlagFromNumber(val);
3781 } else if (initialCountry !== "auto") {
3782 // see if we should select a flag
3783 if (initialCountry) {
3784 this._setFlag(initialCountry.toLowerCase());
3785 } else {
3786 if (dialCode && isRegionlessNanp) {
3787 // has intl dial code, is regionless nanp, and no initialCountry, so default to US
3788 this._setFlag("us");
3789 } else {
3790 // no dial code and no initialCountry, so default to first in list
3791 this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2;
3792 if (!val) {
3793 this._setFlag(this.defaultCountry);
3794 }
3795 }
3796 }
3797 // if empty and no nationalMode and no autoHideDialCode then insert the default dial code
3798 if (!val && !nationalMode && !autoHideDialCode && !separateDialCode) {
3799 this.telInput.value = "+".concat(this.selectedCountryData.dialCode);
3800 }
3801 }
3802 // NOTE: if initialCountry is set to auto, that will be handled separately
3803 // format - note this wont be run after _updateDialCode as that's only called if no val
3804 if (val) this._updateValFromNumber(val);
3805 }
3806 }, {
3807 key: "_initListeners",
3808 value: function _initListeners() {
3809 this._initKeyListeners();
3810 if (this.options.autoHideDialCode) this._initBlurListeners();
3811 if (this.options.allowDropdown) this._initDropdownListeners();
3812 if (this.hiddenInput) this._initHiddenInputListener();
3813 }
3814 }, {
3815 key: "_initHiddenInputListener",
3816 value: function _initHiddenInputListener() {
3817 var _this3 = this;
3818 this._handleHiddenInputSubmit = function() {
3819 _this3.hiddenInput.value = _this3.getNumber();
3820 };
3821 if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleHiddenInputSubmit);
3822 }
3823 }, {
3824 key: "_getClosestLabel",
3825 value: function _getClosestLabel() {
3826 var el = this.telInput;
3827 while (el && el.tagName !== "LABEL") {
3828 el = el.parentNode;
3829 }
3830 return el;
3831 }
3832 }, {
3833 key: "_initDropdownListeners",
3834 value: function _initDropdownListeners() {
3835 var _this4 = this;
3836 // hack for input nested inside label (which is valid markup): clicking the selected-flag to
3837 // open the dropdown would then automatically trigger a 2nd click on the input which would
3838 // close it again
3839 this._handleLabelClick = function(e) {
3840 // if the dropdown is closed, then focus the input, else ignore the click
3841 if (_this4.countryList.classList.contains("iti__hide")) _this4.telInput.focus(); else e.preventDefault();
3842 };
3843 var label = this._getClosestLabel();
3844 if (label) label.addEventListener("click", this._handleLabelClick);
3845 // toggle country dropdown on click
3846 this._handleClickSelectedFlag = function() {
3847 // only intercept this event if we're opening the dropdown
3848 // else let it bubble up to the top ("click-off-to-close" listener)
3849 // we cannot just stopPropagation as it may be needed to close another instance
3850 if (_this4.countryList.classList.contains("iti__hide") && !_this4.telInput.disabled && !_this4.telInput.readOnly) {
3851 _this4._showDropdown();
3852 }
3853 };
3854 this.selectedFlag.addEventListener("click", this._handleClickSelectedFlag);
3855 // open dropdown list if currently focused
3856 this._handleFlagsContainerKeydown = function(e) {
3857 var isDropdownHidden = _this4.countryList.classList.contains("iti__hide");
3858 if (isDropdownHidden && [ "ArrowUp", "Up", "ArrowDown", "Down", " ", "Enter" ].indexOf(e.key) !== -1) {
3859 // prevent form from being submitted if "ENTER" was pressed
3860 e.preventDefault();
3861 // prevent event from being handled again by document
3862 e.stopPropagation();
3863 _this4._showDropdown();
3864 }
3865 // allow navigation from dropdown to input on TAB
3866 if (e.key === "Tab") _this4._closeDropdown();
3867 };
3868 this.flagsContainer.addEventListener("keydown", this._handleFlagsContainerKeydown);
3869 }
3870 }, {
3871 key: "_initRequests",
3872 value: function _initRequests() {
3873 var _this5 = this;
3874 // if the user has specified the path to the utils script, fetch it on window.load, else resolve
3875 if (this.options.utilsScript && !window.intlTelInputUtils) {
3876 // if the plugin is being initialised after the window.load event has already been fired
3877 if (window.intlTelInputGlobals.documentReady()) {
3878 window.intlTelInputGlobals.loadUtils(this.options.utilsScript);
3879 } else {
3880 // wait until the load event so we don't block any other requests e.g. the flags image
3881 window.addEventListener("load", function() {
3882 window.intlTelInputGlobals.loadUtils(_this5.options.utilsScript);
3883 });
3884 }
3885 } else this.resolveUtilsScriptPromise();
3886 if (this.options.initialCountry === "auto") this._loadAutoCountry(); else this.resolveAutoCountryPromise();
3887 }
3888 }, {
3889 key: "_loadAutoCountry",
3890 value: function _loadAutoCountry() {
3891 // 3 options:
3892 // 1) already loaded (we're done)
3893 // 2) not already started loading (start)
3894 // 3) already started loading (do nothing - just wait for loading callback to fire)
3895 if (window.intlTelInputGlobals.autoCountry) {
3896 this.handleAutoCountry();
3897 } else if (!window.intlTelInputGlobals.startedLoadingAutoCountry) {
3898 // don't do this twice!
3899 window.intlTelInputGlobals.startedLoadingAutoCountry = true;
3900 if (typeof this.options.geoIpLookup === "function") {
3901 this.options.geoIpLookup(function(countryCode) {
3902 window.intlTelInputGlobals.autoCountry = countryCode.toLowerCase();
3903 // tell all instances the auto country is ready
3904 // TODO: this should just be the current instances
3905 // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight
3906 // away (e.g. if they have already done the geo ip lookup somewhere else). Using
3907 // setTimeout means that the current thread of execution will finish before executing
3908 // this, which allows the plugin to finish initialising.
3909 setTimeout(function() {
3910 return forEachInstance("handleAutoCountry");
3911 });
3912 }, function() {
3913 return forEachInstance("rejectAutoCountryPromise");
3914 });
3915 }
3916 }
3917 }
3918 }, {
3919 key: "_initKeyListeners",
3920 value: function _initKeyListeners() {
3921 var _this6 = this;
3922 // update flag on keyup
3923 this._handleKeyupEvent = function() {
3924 if (_this6._updateFlagFromNumber(_this6.telInput.value)) {
3925 _this6._triggerCountryChange();
3926 }
3927 };
3928 this.telInput.addEventListener("keyup", this._handleKeyupEvent);
3929 // update flag on cut/paste events (now supported in all major browsers)
3930 this._handleClipboardEvent = function() {
3931 // hack because "paste" event is fired before input is updated
3932 setTimeout(_this6._handleKeyupEvent);
3933 };
3934 this.telInput.addEventListener("cut", this._handleClipboardEvent);
3935 this.telInput.addEventListener("paste", this._handleClipboardEvent);
3936 }
3937 }, {
3938 key: "_cap",
3939 value: function _cap(number) {
3940 var max = this.telInput.getAttribute("maxlength");
3941 return max && number.length > max ? number.substr(0, max) : number;
3942 }
3943 }, {
3944 key: "_initBlurListeners",
3945 value: function _initBlurListeners() {
3946 var _this7 = this;
3947 // on blur or form submit: if just a dial code then remove it
3948 this._handleSubmitOrBlurEvent = function() {
3949 _this7._removeEmptyDialCode();
3950 };
3951 if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleSubmitOrBlurEvent);
3952 this.telInput.addEventListener("blur", this._handleSubmitOrBlurEvent);
3953 }
3954 }, {
3955 key: "_removeEmptyDialCode",
3956 value: function _removeEmptyDialCode() {
3957 if (this.telInput.value.charAt(0) === "+") {
3958 var numeric = this._getNumeric(this.telInput.value);
3959 // if just a plus, or if just a dial code
3960 if (!numeric || this.selectedCountryData.dialCode === numeric) {
3961 this.telInput.value = "";
3962 }
3963 }
3964 }
3965 }, {
3966 key: "_getNumeric",
3967 value: function _getNumeric(s) {
3968 return s.replace(/\D/g, "");
3969 }
3970 }, {
3971 key: "_trigger",
3972 value: function _trigger(name) {
3973 // have to use old school document.createEvent as IE11 doesn't support `new Event()` syntax
3974 var e = document.createEvent("Event");
3975 e.initEvent(name, true, true);
3976 // can bubble, and is cancellable
3977 this.telInput.dispatchEvent(e);
3978 }
3979 }, {
3980 key: "_showDropdown",
3981 value: function _showDropdown() {
3982 this.countryList.classList.remove("iti__hide");
3983 this.selectedFlag.setAttribute("aria-expanded", "true");
3984 this._setDropdownPosition();
3985 // update highlighting and scroll to active list item
3986 if (this.activeItem) {
3987 this._highlightListItem(this.activeItem, false);
3988 this._scrollTo(this.activeItem, true);
3989 }
3990 // bind all the dropdown-related listeners: mouseover, click, click-off, keydown
3991 this._bindDropdownListeners();
3992 // update the arrow
3993 this.dropdownArrow.classList.add("iti__arrow--up");
3994 this._trigger("open:countrydropdown");
3995 }
3996 }, {
3997 key: "_toggleClass",
3998 value: function _toggleClass(el, className, shouldHaveClass) {
3999 if (shouldHaveClass && !el.classList.contains(className)) el.classList.add(className); else if (!shouldHaveClass && el.classList.contains(className)) el.classList.remove(className);
4000 }
4001 }, {
4002 key: "_setDropdownPosition",
4003 value: function _setDropdownPosition() {
4004 var _this8 = this;
4005 if (this.options.dropdownContainer) {
4006 this.options.dropdownContainer.appendChild(this.dropdown);
4007 }
4008 if (!this.isMobile) {
4009 var pos = this.telInput.getBoundingClientRect();
4010 // windowTop from https://stackoverflow.com/a/14384091/217866
4011 var windowTop = window.pageYOffset || document.documentElement.scrollTop;
4012 var inputTop = pos.top + windowTop;
4013 var dropdownHeight = this.countryList.offsetHeight;
4014 // dropdownFitsBelow = (dropdownBottom < windowBottom)
4015 var dropdownFitsBelow = inputTop + this.telInput.offsetHeight + dropdownHeight < windowTop + window.innerHeight;
4016 var dropdownFitsAbove = inputTop - dropdownHeight > windowTop;
4017 // by default, the dropdown will be below the input. If we want to position it above the
4018 // input, we add the dropup class.
4019 this._toggleClass(this.countryList, "iti__country-list--dropup", !dropdownFitsBelow && dropdownFitsAbove);
4020 // if dropdownContainer is enabled, calculate postion
4021 if (this.options.dropdownContainer) {
4022 // by default the dropdown will be directly over the input because it's not in the flow.
4023 // If we want to position it below, we need to add some extra top value.
4024 var extraTop = !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.offsetHeight;
4025 // calculate placement
4026 this.dropdown.style.top = "".concat(inputTop + extraTop, "px");
4027 this.dropdown.style.left = "".concat(pos.left + document.body.scrollLeft, "px");
4028 // close menu on window scroll
4029 this._handleWindowScroll = function() {
4030 return _this8._closeDropdown();
4031 };
4032 window.addEventListener("scroll", this._handleWindowScroll);
4033 }
4034 }
4035 }
4036 }, {
4037 key: "_getClosestListItem",
4038 value: function _getClosestListItem(target) {
4039 var el = target;
4040 while (el && el !== this.countryList && !el.classList.contains("iti__country")) {
4041 el = el.parentNode;
4042 }
4043 // if we reached the countryList element, then return null
4044 return el === this.countryList ? null : el;
4045 }
4046 }, {
4047 key: "_bindDropdownListeners",
4048 value: function _bindDropdownListeners() {
4049 var _this9 = this;
4050 // when mouse over a list item, just highlight that one
4051 // we add the class "highlight", so if they hit "enter" we know which one to select
4052 this._handleMouseoverCountryList = function(e) {
4053 // handle event delegation, as we're listening for this event on the countryList
4054 var listItem = _this9._getClosestListItem(e.target);
4055 if (listItem) _this9._highlightListItem(listItem, false);
4056 };
4057 this.countryList.addEventListener("mouseover", this._handleMouseoverCountryList);
4058 // listen for country selection
4059 this._handleClickCountryList = function(e) {
4060 var listItem = _this9._getClosestListItem(e.target);
4061 if (listItem) _this9._selectListItem(listItem);
4062 };
4063 this.countryList.addEventListener("click", this._handleClickCountryList);
4064 // click off to close
4065 // (except when this initial opening click is bubbling up)
4066 // we cannot just stopPropagation as it may be needed to close another instance
4067 var isOpening = true;
4068 this._handleClickOffToClose = function() {
4069 if (!isOpening) _this9._closeDropdown();
4070 isOpening = false;
4071 };
4072 document.documentElement.addEventListener("click", this._handleClickOffToClose);
4073 // listen for up/down scrolling, enter to select, or letters to jump to country name.
4074 // use keydown as keypress doesn't fire for non-char keys and we want to catch if they
4075 // just hit down and hold it to scroll down (no keyup event).
4076 // listen on the document because that's where key events are triggered if no input has focus
4077 var query = "";
4078 var queryTimer = null;
4079 this._handleKeydownOnDropdown = function(e) {
4080 // prevent down key from scrolling the whole page,
4081 // and enter key from submitting a form etc
4082 e.preventDefault();
4083 // up and down to navigate
4084 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)) {
4085 // jump to countries that start with the query string
4086 if (queryTimer) clearTimeout(queryTimer);
4087 query += e.key.toLowerCase();
4088 _this9._searchForCountry(query);
4089 // if the timer hits 1 second, reset the query
4090 queryTimer = setTimeout(function() {
4091 query = "";
4092 }, 1e3);
4093 }
4094 };
4095 document.addEventListener("keydown", this._handleKeydownOnDropdown);
4096 }
4097 }, {
4098 key: "_handleUpDownKey",
4099 value: function _handleUpDownKey(key) {
4100 var next = key === "ArrowUp" || key === "Up" ? this.highlightedItem.previousElementSibling : this.highlightedItem.nextElementSibling;
4101 if (next) {
4102 // skip the divider
4103 if (next.classList.contains("iti__divider")) {
4104 next = key === "ArrowUp" || key === "Up" ? next.previousElementSibling : next.nextElementSibling;
4105 }
4106 this._highlightListItem(next, true);
4107 }
4108 }
4109 }, {
4110 key: "_handleEnterKey",
4111 value: function _handleEnterKey() {
4112 if (this.highlightedItem) this._selectListItem(this.highlightedItem);
4113 }
4114 }, {
4115 key: "_searchForCountry",
4116 value: function _searchForCountry(query) {
4117 for (var i = 0; i < this.countries.length; i++) {
4118 if (this._startsWith(this.countries[i].name, query)) {
4119 var listItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(this.countries[i].iso2));
4120 // update highlighting and scroll
4121 this._highlightListItem(listItem, false);
4122 this._scrollTo(listItem, true);
4123 break;
4124 }
4125 }
4126 }
4127 }, {
4128 key: "_startsWith",
4129 value: function _startsWith(a, b) {
4130 return a.substr(0, b.length).toLowerCase() === b;
4131 }
4132 }, {
4133 key: "_updateValFromNumber",
4134 value: function _updateValFromNumber(originalNumber) {
4135 var number = originalNumber;
4136 if (this.options.formatOnDisplay && window.intlTelInputUtils && this.selectedCountryData) {
4137 var useNational = !this.options.separateDialCode && (this.options.nationalMode || number.charAt(0) !== "+");
4138 var _intlTelInputUtils$nu = intlTelInputUtils.numberFormat, NATIONAL = _intlTelInputUtils$nu.NATIONAL, INTERNATIONAL = _intlTelInputUtils$nu.INTERNATIONAL;
4139 var format = useNational ? NATIONAL : INTERNATIONAL;
4140 number = intlTelInputUtils.formatNumber(number, this.selectedCountryData.iso2, format);
4141 }
4142 number = this._beforeSetNumber(number);
4143 this.telInput.value = number;
4144 }
4145 }, {
4146 key: "_updateFlagFromNumber",
4147 value: function _updateFlagFromNumber(originalNumber) {
4148 // if we're in nationalMode and we already have US/Canada selected, make sure the number starts
4149 // with a +1 so _getDialCode will be able to extract the area code
4150 // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag
4151 // from the number), that means we're initialising the plugin with a number that already has a
4152 // dial code, so fine to ignore this bit
4153 var number = originalNumber;
4154 var selectedDialCode = this.selectedCountryData.dialCode;
4155 var isNanp = selectedDialCode === "1";
4156 if (number && this.options.nationalMode && isNanp && number.charAt(0) !== "+") {
4157 if (number.charAt(0) !== "1") number = "1".concat(number);
4158 number = "+".concat(number);
4159 }
4160 // update flag if user types area code for another country
4161 if (this.options.separateDialCode && selectedDialCode && number.charAt(0) !== "+") {
4162 number = "+".concat(selectedDialCode).concat(number);
4163 }
4164 // try and extract valid dial code from input
4165 var dialCode = this._getDialCode(number, true);
4166 var numeric = this._getNumeric(number);
4167 var countryCode = null;
4168 if (dialCode) {
4169 var countryCodes = this.countryCodes[this._getNumeric(dialCode)];
4170 // check if the right country is already selected. this should be false if the number is
4171 // longer than the matched dial code because in this case we need to make sure that if
4172 // there are multiple country matches, that the first one is selected (note: we could
4173 // just check that here, but it requires the same loop that we already have later)
4174 var alreadySelected = countryCodes.indexOf(this.selectedCountryData.iso2) !== -1 && numeric.length <= dialCode.length - 1;
4175 var isRegionlessNanpNumber = selectedDialCode === "1" && this._isRegionlessNanp(numeric);
4176 // only update the flag if:
4177 // A) NOT (we currently have a NANP flag selected, and the number is a regionlessNanp)
4178 // AND
4179 // B) the right country is not already selected
4180 if (!isRegionlessNanpNumber && !alreadySelected) {
4181 // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first
4182 // non-empty index
4183 for (var j = 0; j < countryCodes.length; j++) {
4184 if (countryCodes[j]) {
4185 countryCode = countryCodes[j];
4186 break;
4187 }
4188 }
4189 }
4190 } else if (number.charAt(0) === "+" && numeric.length) {
4191 // invalid dial code, so empty
4192 // Note: use getNumeric here because the number has not been formatted yet, so could contain
4193 // bad chars
4194 countryCode = "";
4195 } else if (!number || number === "+") {
4196 // empty, or just a plus, so default
4197 countryCode = this.defaultCountry;
4198 }
4199 if (countryCode !== null) {
4200 return this._setFlag(countryCode);
4201 }
4202 return false;
4203 }
4204 }, {
4205 key: "_isRegionlessNanp",
4206 value: function _isRegionlessNanp(number) {
4207 var numeric = this._getNumeric(number);
4208 if (numeric.charAt(0) === "1") {
4209 var areaCode = numeric.substr(1, 3);
4210 return regionlessNanpNumbers.indexOf(areaCode) !== -1;
4211 }
4212 return false;
4213 }
4214 }, {
4215 key: "_highlightListItem",
4216 value: function _highlightListItem(listItem, shouldFocus) {
4217 var prevItem = this.highlightedItem;
4218 if (prevItem) prevItem.classList.remove("iti__highlight");
4219 this.highlightedItem = listItem;
4220 this.highlightedItem.classList.add("iti__highlight");
4221 if (shouldFocus) this.highlightedItem.focus();
4222 }
4223 }, {
4224 key: "_getCountryData",
4225 value: function _getCountryData(countryCode, ignoreOnlyCountriesOption, allowFail) {
4226 var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
4227 for (var i = 0; i < countryList.length; i++) {
4228 if (countryList[i].iso2 === countryCode) {
4229 return countryList[i];
4230 }
4231 }
4232 if (allowFail) {
4233 return null;
4234 }
4235 throw new Error("No country data for '".concat(countryCode, "'"));
4236 }
4237 }, {
4238 key: "_setFlag",
4239 value: function _setFlag(countryCode) {
4240 var prevCountry = this.selectedCountryData.iso2 ? this.selectedCountryData : {};
4241 // do this first as it will throw an error and stop if countryCode is invalid
4242 this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {};
4243 // update the defaultCountry - we only need the iso2 from now on, so just store that
4244 if (this.selectedCountryData.iso2) {
4245 this.defaultCountry = this.selectedCountryData.iso2;
4246 }
4247 this.selectedFlagInner.setAttribute("class", "iti__flag iti__".concat(countryCode));
4248 // update the selected country's title attribute
4249 var title = countryCode ? "".concat(this.selectedCountryData.name, ": +").concat(this.selectedCountryData.dialCode) : "Unknown";
4250 this.selectedFlag.setAttribute("title", title);
4251 if (this.options.separateDialCode) {
4252 var dialCode = this.selectedCountryData.dialCode ? "+".concat(this.selectedCountryData.dialCode) : "";
4253 this.selectedDialCode.innerHTML = dialCode;
4254 // offsetWidth is zero if input is in a hidden container during initialisation
4255 var selectedFlagWidth = this.selectedFlag.offsetWidth || this._getHiddenSelectedFlagWidth();
4256 // add 6px of padding after the grey selected-dial-code box, as this is what we use in the css
4257 this.telInput.style.paddingLeft = "".concat(selectedFlagWidth + 6, "px");
4258 }
4259 // and the input's placeholder
4260 this._updatePlaceholder();
4261 // update the active list item
4262 if (this.options.allowDropdown) {
4263 var prevItem = this.activeItem;
4264 if (prevItem) {
4265 prevItem.classList.remove("iti__active");
4266 prevItem.setAttribute("aria-selected", "false");
4267 }
4268 if (countryCode) {
4269 // check if there is a preferred item first, else fall back to standard
4270 var nextItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode, "-preferred")) || this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode));
4271 nextItem.setAttribute("aria-selected", "true");
4272 nextItem.classList.add("iti__active");
4273 this.activeItem = nextItem;
4274 this.selectedFlag.setAttribute("aria-activedescendant", nextItem.getAttribute("id"));
4275 }
4276 }
4277 // return if the flag has changed or not
4278 return prevCountry.iso2 !== countryCode;
4279 }
4280 }, {
4281 key: "_getHiddenSelectedFlagWidth",
4282 value: function _getHiddenSelectedFlagWidth() {
4283 // to get the right styling to apply, all we need is a shallow clone of the container,
4284 // and then to inject a deep clone of the selectedFlag element
4285 var containerClone = this.telInput.parentNode.cloneNode();
4286 containerClone.style.visibility = "hidden";
4287 document.body.appendChild(containerClone);
4288 var flagsContainerClone = this.flagsContainer.cloneNode();
4289 containerClone.appendChild(flagsContainerClone);
4290 var selectedFlagClone = this.selectedFlag.cloneNode(true);
4291 flagsContainerClone.appendChild(selectedFlagClone);
4292 var width = selectedFlagClone.offsetWidth;
4293 containerClone.parentNode.removeChild(containerClone);
4294 return width;
4295 }
4296 }, {
4297 key: "_updatePlaceholder",
4298 value: function _updatePlaceholder() {
4299 var shouldSetPlaceholder = this.options.autoPlaceholder === "aggressive" || !this.hadInitialPlaceholder && this.options.autoPlaceholder === "polite";
4300 if (window.intlTelInputUtils && shouldSetPlaceholder) {
4301 var numberType = intlTelInputUtils.numberType[this.options.placeholderNumberType];
4302 var placeholder = this.selectedCountryData.iso2 ? intlTelInputUtils.getExampleNumber(this.selectedCountryData.iso2, this.options.nationalMode, numberType) : "";
4303 placeholder = this._beforeSetNumber(placeholder);
4304 if (typeof this.options.customPlaceholder === "function") {
4305 placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData);
4306 }
4307 this.telInput.setAttribute("placeholder", placeholder);
4308 }
4309 }
4310 }, {
4311 key: "_selectListItem",
4312 value: function _selectListItem(listItem) {
4313 // update selected flag and active list item
4314 var flagChanged = this._setFlag(listItem.getAttribute("data-country-code"));
4315 this._closeDropdown();
4316 this._updateDialCode(listItem.getAttribute("data-dial-code"), true);
4317 // focus the input
4318 this.telInput.focus();
4319 // put cursor at end - this fix is required for FF and IE11 (with nationalMode=false i.e. auto
4320 // inserting dial code), who try to put the cursor at the beginning the first time
4321 var len = this.telInput.value.length;
4322 this.telInput.setSelectionRange(len, len);
4323 if (flagChanged) {
4324 this._triggerCountryChange();
4325 }
4326 }
4327 }, {
4328 key: "_closeDropdown",
4329 value: function _closeDropdown() {
4330 this.countryList.classList.add("iti__hide");
4331 this.selectedFlag.setAttribute("aria-expanded", "false");
4332 // update the arrow
4333 this.dropdownArrow.classList.remove("iti__arrow--up");
4334 // unbind key events
4335 document.removeEventListener("keydown", this._handleKeydownOnDropdown);
4336 document.documentElement.removeEventListener("click", this._handleClickOffToClose);
4337 this.countryList.removeEventListener("mouseover", this._handleMouseoverCountryList);
4338 this.countryList.removeEventListener("click", this._handleClickCountryList);
4339 // remove menu from container
4340 if (this.options.dropdownContainer) {
4341 if (!this.isMobile) window.removeEventListener("scroll", this._handleWindowScroll);
4342 if (this.dropdown.parentNode) this.dropdown.parentNode.removeChild(this.dropdown);
4343 }
4344 this._trigger("close:countrydropdown");
4345 }
4346 }, {
4347 key: "_scrollTo",
4348 value: function _scrollTo(element, middle) {
4349 var container = this.countryList;
4350 // windowTop from https://stackoverflow.com/a/14384091/217866
4351 var windowTop = window.pageYOffset || document.documentElement.scrollTop;
4352 var containerHeight = container.offsetHeight;
4353 var containerTop = container.getBoundingClientRect().top + windowTop;
4354 var containerBottom = containerTop + containerHeight;
4355 var elementHeight = element.offsetHeight;
4356 var elementTop = element.getBoundingClientRect().top + windowTop;
4357 var elementBottom = elementTop + elementHeight;
4358 var newScrollTop = elementTop - containerTop + container.scrollTop;
4359 var middleOffset = containerHeight / 2 - elementHeight / 2;
4360 if (elementTop < containerTop) {
4361 // scroll up
4362 if (middle) newScrollTop -= middleOffset;
4363 container.scrollTop = newScrollTop;
4364 } else if (elementBottom > containerBottom) {
4365 // scroll down
4366 if (middle) newScrollTop += middleOffset;
4367 var heightDifference = containerHeight - elementHeight;
4368 container.scrollTop = newScrollTop - heightDifference;
4369 }
4370 }
4371 }, {
4372 key: "_updateDialCode",
4373 value: function _updateDialCode(newDialCodeBare, hasSelectedListItem) {
4374 var inputVal = this.telInput.value;
4375 // save having to pass this every time
4376 var newDialCode = "+".concat(newDialCodeBare);
4377 var newNumber;
4378 if (inputVal.charAt(0) === "+") {
4379 // there's a plus so we're dealing with a replacement (doesn't matter if nationalMode or not)
4380 var prevDialCode = this._getDialCode(inputVal);
4381 if (prevDialCode) {
4382 // current number contains a valid dial code, so replace it
4383 newNumber = inputVal.replace(prevDialCode, newDialCode);
4384 } else {
4385 // current number contains an invalid dial code, so ditch it
4386 // (no way to determine where the invalid dial code ends and the rest of the number begins)
4387 newNumber = newDialCode;
4388 }
4389 } else if (this.options.nationalMode || this.options.separateDialCode) {
4390 // don't do anything
4391 return;
4392 } else {
4393 // nationalMode is disabled
4394 if (inputVal) {
4395 // there is an existing value with no dial code: prefix the new dial code
4396 newNumber = newDialCode + inputVal;
4397 } else if (hasSelectedListItem || !this.options.autoHideDialCode) {
4398 // no existing value and either they've just selected a list item, or autoHideDialCode is
4399 // disabled: insert new dial code
4400 newNumber = newDialCode;
4401 } else {
4402 return;
4403 }
4404 }
4405 this.telInput.value = newNumber;
4406 }
4407 }, {
4408 key: "_getDialCode",
4409 value: function _getDialCode(number, includeAreaCode) {
4410 var dialCode = "";
4411 // only interested in international numbers (starting with a plus)
4412 if (number.charAt(0) === "+") {
4413 var numericChars = "";
4414 // iterate over chars
4415 for (var i = 0; i < number.length; i++) {
4416 var c = number.charAt(i);
4417 // if char is number (https://stackoverflow.com/a/8935649/217866)
4418 if (!isNaN(parseInt(c, 10))) {
4419 numericChars += c;
4420 // if current numericChars make a valid dial code
4421 if (includeAreaCode) {
4422 if (this.countryCodes[numericChars]) {
4423 // store the actual raw string (useful for matching later)
4424 dialCode = number.substr(0, i + 1);
4425 }
4426 } else {
4427 if (this.dialCodes[numericChars]) {
4428 dialCode = number.substr(0, i + 1);
4429 // if we're just looking for a dial code, we can break as soon as we find one
4430 break;
4431 }
4432 }
4433 // stop searching as soon as we can - in this case when we hit max len
4434 if (numericChars.length === this.countryCodeMaxLen) {
4435 break;
4436 }
4437 }
4438 }
4439 }
4440 return dialCode;
4441 }
4442 }, {
4443 key: "_getFullNumber",
4444 value: function _getFullNumber() {
4445 var val = this.telInput.value.trim();
4446 var dialCode = this.selectedCountryData.dialCode;
4447 var prefix;
4448 var numericVal = this._getNumeric(val);
4449 if (this.options.separateDialCode && val.charAt(0) !== "+" && dialCode && numericVal) {
4450 // when using separateDialCode, it is visible so is effectively part of the typed number
4451 prefix = "+".concat(dialCode);
4452 } else {
4453 prefix = "";
4454 }
4455 return prefix + val;
4456 }
4457 }, {
4458 key: "_beforeSetNumber",
4459 value: function _beforeSetNumber(originalNumber) {
4460 var number = originalNumber;
4461 if (this.options.separateDialCode) {
4462 var dialCode = this._getDialCode(number);
4463 // if there is a valid dial code
4464 if (dialCode) {
4465 // in case _getDialCode returned an area code as well
4466 dialCode = "+".concat(this.selectedCountryData.dialCode);
4467 // a lot of numbers will have a space separating the dial code and the main number, and
4468 // some NANP numbers will have a hyphen e.g. +1 684-733-1234 - in both cases we want to get
4469 // rid of it
4470 // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc
4471 var start = number[dialCode.length] === " " || number[dialCode.length] === "-" ? dialCode.length + 1 : dialCode.length;
4472 number = number.substr(start);
4473 }
4474 }
4475 return this._cap(number);
4476 }
4477 }, {
4478 key: "_triggerCountryChange",
4479 value: function _triggerCountryChange() {
4480 this._trigger("countrychange");
4481 }
4482 }, {
4483 key: "handleAutoCountry",
4484 value: function handleAutoCountry() {
4485 if (this.options.initialCountry === "auto") {
4486 // we must set this even if there is an initial val in the input: in case the initial val is
4487 // invalid and they delete it - they should see their auto country
4488 this.defaultCountry = window.intlTelInputGlobals.autoCountry;
4489 // if there's no initial value in the input, then update the flag
4490 if (!this.telInput.value) {
4491 this.setCountry(this.defaultCountry);
4492 }
4493 this.resolveAutoCountryPromise();
4494 }
4495 }
4496 }, {
4497 key: "handleUtils",
4498 value: function handleUtils() {
4499 // if the request was successful
4500 if (window.intlTelInputUtils) {
4501 // if there's an initial value in the input, then format it
4502 if (this.telInput.value) {
4503 this._updateValFromNumber(this.telInput.value);
4504 }
4505 this._updatePlaceholder();
4506 }
4507 this.resolveUtilsScriptPromise();
4508 }
4509 }, {
4510 key: "destroy",
4511 value: function destroy() {
4512 var form = this.telInput.form;
4513 if (this.options.allowDropdown) {
4514 // make sure the dropdown is closed (and unbind listeners)
4515 this._closeDropdown();
4516 this.selectedFlag.removeEventListener("click", this._handleClickSelectedFlag);
4517 this.flagsContainer.removeEventListener("keydown", this._handleFlagsContainerKeydown);
4518 // label click hack
4519 var label = this._getClosestLabel();
4520 if (label) label.removeEventListener("click", this._handleLabelClick);
4521 }
4522 // unbind hiddenInput listeners
4523 if (this.hiddenInput && form) form.removeEventListener("submit", this._handleHiddenInputSubmit);
4524 // unbind autoHideDialCode listeners
4525 if (this.options.autoHideDialCode) {
4526 if (form) form.removeEventListener("submit", this._handleSubmitOrBlurEvent);
4527 this.telInput.removeEventListener("blur", this._handleSubmitOrBlurEvent);
4528 }
4529 // unbind key events, and cut/paste events
4530 this.telInput.removeEventListener("keyup", this._handleKeyupEvent);
4531 this.telInput.removeEventListener("cut", this._handleClipboardEvent);
4532 this.telInput.removeEventListener("paste", this._handleClipboardEvent);
4533 // remove attribute of id instance: data-intl-tel-input-id
4534 this.telInput.removeAttribute("data-intl-tel-input-id");
4535 // remove markup (but leave the original input)
4536 var wrapper = this.telInput.parentNode;
4537 wrapper.parentNode.insertBefore(this.telInput, wrapper);
4538 wrapper.parentNode.removeChild(wrapper);
4539 delete window.intlTelInputGlobals.instances[this.id];
4540 }
4541 }, {
4542 key: "getExtension",
4543 value: function getExtension() {
4544 if (window.intlTelInputUtils) {
4545 return intlTelInputUtils.getExtension(this._getFullNumber(), this.selectedCountryData.iso2);
4546 }
4547 return "";
4548 }
4549 }, {
4550 key: "getNumber",
4551 value: function getNumber(format) {
4552 if (window.intlTelInputUtils) {
4553 var iso2 = this.selectedCountryData.iso2;
4554 return intlTelInputUtils.formatNumber(this._getFullNumber(), iso2, format);
4555 }
4556 return "";
4557 }
4558 }, {
4559 key: "getNumberType",
4560 value: function getNumberType() {
4561 if (window.intlTelInputUtils) {
4562 return intlTelInputUtils.getNumberType(this._getFullNumber(), this.selectedCountryData.iso2);
4563 }
4564 return -99;
4565 }
4566 }, {
4567 key: "getSelectedCountryData",
4568 value: function getSelectedCountryData() {
4569 return this.selectedCountryData;
4570 }
4571 }, {
4572 key: "getValidationError",
4573 value: function getValidationError() {
4574 if (window.intlTelInputUtils) {
4575 var iso2 = this.selectedCountryData.iso2;
4576 return intlTelInputUtils.getValidationError(this._getFullNumber(), iso2);
4577 }
4578 return -99;
4579 }
4580 }, {
4581 key: "isValidNumber",
4582 value: function isValidNumber() {
4583 var val = this._getFullNumber().trim();
4584 var countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "";
4585 return window.intlTelInputUtils ? intlTelInputUtils.isValidNumber(val, countryCode) : null;
4586 }
4587 }, {
4588 key: "setCountry",
4589 value: function setCountry(originalCountryCode) {
4590 var countryCode = originalCountryCode.toLowerCase();
4591 // check if already selected
4592 if (!this.selectedFlagInner.classList.contains("iti__".concat(countryCode))) {
4593 this._setFlag(countryCode);
4594 this._updateDialCode(this.selectedCountryData.dialCode, false);
4595 this._triggerCountryChange();
4596 }
4597 }
4598 }, {
4599 key: "setNumber",
4600 value: function setNumber(number) {
4601 // we must update the flag first, which updates this.selectedCountryData, which is used for
4602 // formatting the number before displaying it
4603 var flagChanged = this._updateFlagFromNumber(number);
4604 this._updateValFromNumber(number);
4605 if (flagChanged) {
4606 this._triggerCountryChange();
4607 }
4608 }
4609 }, {
4610 key: "setPlaceholderNumberType",
4611 value: function setPlaceholderNumberType(type) {
4612 this.options.placeholderNumberType = type;
4613 this._updatePlaceholder();
4614 }
4615 } ]);
4616 return Iti;
4617 }();
4618 /********************
4619 * STATIC METHODS
4620 ********************/
4621 // get the country data object
4622 intlTelInputGlobals.getCountryData = function() {
4623 return allCountries;
4624 };
4625 // inject a <script> element to load utils.js
4626 var injectScript = function injectScript(path, handleSuccess, handleFailure) {
4627 // inject a new script element into the page
4628 var script = document.createElement("script");
4629 script.onload = function() {
4630 forEachInstance("handleUtils");
4631 if (handleSuccess) handleSuccess();
4632 };
4633 script.onerror = function() {
4634 forEachInstance("rejectUtilsScriptPromise");
4635 if (handleFailure) handleFailure();
4636 };
4637 script.className = "iti-load-utils";
4638 script.async = true;
4639 script.src = path;
4640 document.body.appendChild(script);
4641 };
4642 // load the utils script
4643 intlTelInputGlobals.loadUtils = function(path) {
4644 // 2 options:
4645 // 1) not already started loading (start)
4646 // 2) already started loading (do nothing - just wait for the onload callback to fire, which will
4647 // trigger handleUtils on all instances, invoking their resolveUtilsScriptPromise functions)
4648 if (!window.intlTelInputUtils && !window.intlTelInputGlobals.startedLoadingUtilsScript) {
4649 // only do this once
4650 window.intlTelInputGlobals.startedLoadingUtilsScript = true;
4651 // if we have promises, then return a promise
4652 if (typeof Promise !== "undefined") {
4653 return new Promise(function(resolve, reject) {
4654 return injectScript(path, resolve, reject);
4655 });
4656 }
4657 injectScript(path);
4658 }
4659 return null;
4660 };
4661 // default options
4662 intlTelInputGlobals.defaults = defaults;
4663 // version
4664 intlTelInputGlobals.version = "17.0.16";
4665 // convenience wrapper
4666 return function(input, options) {
4667 var iti = new Iti(input, options);
4668 iti._init();
4669 input.setAttribute("data-intl-tel-input-id", iti.id);
4670 window.intlTelInputGlobals.instances[iti.id] = iti;
4671 return iti;
4672 };
4673 }();
4674 });
4675 },{}],20:[function(require,module,exports){
4676 /**
4677 * Exposing intl-tel-input as a component
4678 */
4679 module.exports = require("./build/js/intlTelInput");
4680
4681 },{"./build/js/intlTelInput":19}],21:[function(require,module,exports){
4682 (function (process){
4683 /**
4684 * Memize options object.
4685 *
4686 * @typedef MemizeOptions
4687 *
4688 * @property {number} [maxSize] Maximum size of the cache.
4689 */
4690
4691 /**
4692 * Internal cache entry.
4693 *
4694 * @typedef MemizeCacheNode
4695 *
4696 * @property {?MemizeCacheNode|undefined} [prev] Previous node.
4697 * @property {?MemizeCacheNode|undefined} [next] Next node.
4698 * @property {Array<*>} args Function arguments for cache
4699 * entry.
4700 * @property {*} val Function result.
4701 */
4702
4703 /**
4704 * Properties of the enhanced function for controlling cache.
4705 *
4706 * @typedef MemizeMemoizedFunction
4707 *
4708 * @property {()=>void} clear Clear the cache.
4709 */
4710
4711 /**
4712 * Accepts a function to be memoized, and returns a new memoized function, with
4713 * optional options.
4714 *
4715 * @template {Function} F
4716 *
4717 * @param {F} fn Function to memoize.
4718 * @param {MemizeOptions} [options] Options object.
4719 *
4720 * @return {F & MemizeMemoizedFunction} Memoized function.
4721 */
4722 function memize( fn, options ) {
4723 var size = 0;
4724
4725 /** @type {?MemizeCacheNode|undefined} */
4726 var head;
4727
4728 /** @type {?MemizeCacheNode|undefined} */
4729 var tail;
4730
4731 options = options || {};
4732
4733 function memoized( /* ...args */ ) {
4734 var node = head,
4735 len = arguments.length,
4736 args, i;
4737
4738 searchCache: while ( node ) {
4739 // Perform a shallow equality test to confirm that whether the node
4740 // under test is a candidate for the arguments passed. Two arrays
4741 // are shallowly equal if their length matches and each entry is
4742 // strictly equal between the two sets. Avoid abstracting to a
4743 // function which could incur an arguments leaking deoptimization.
4744
4745 // Check whether node arguments match arguments length
4746 if ( node.args.length !== arguments.length ) {
4747 node = node.next;
4748 continue;
4749 }
4750
4751 // Check whether node arguments match arguments values
4752 for ( i = 0; i < len; i++ ) {
4753 if ( node.args[ i ] !== arguments[ i ] ) {
4754 node = node.next;
4755 continue searchCache;
4756 }
4757 }
4758
4759 // At this point we can assume we've found a match
4760
4761 // Surface matched node to head if not already
4762 if ( node !== head ) {
4763 // As tail, shift to previous. Must only shift if not also
4764 // head, since if both head and tail, there is no previous.
4765 if ( node === tail ) {
4766 tail = node.prev;
4767 }
4768
4769 // Adjust siblings to point to each other. If node was tail,
4770 // this also handles new tail's empty `next` assignment.
4771 /** @type {MemizeCacheNode} */ ( node.prev ).next = node.next;
4772 if ( node.next ) {
4773 node.next.prev = node.prev;
4774 }
4775
4776 node.next = head;
4777 node.prev = null;
4778 /** @type {MemizeCacheNode} */ ( head ).prev = node;
4779 head = node;
4780 }
4781
4782 // Return immediately
4783 return node.val;
4784 }
4785
4786 // No cached value found. Continue to insertion phase:
4787
4788 // Create a copy of arguments (avoid leaking deoptimization)
4789 args = new Array( len );
4790 for ( i = 0; i < len; i++ ) {
4791 args[ i ] = arguments[ i ];
4792 }
4793
4794 node = {
4795 args: args,
4796
4797 // Generate the result from original function
4798 val: fn.apply( null, args ),
4799 };
4800
4801 // Don't need to check whether node is already head, since it would
4802 // have been returned above already if it was
4803
4804 // Shift existing head down list
4805 if ( head ) {
4806 head.prev = node;
4807 node.next = head;
4808 } else {
4809 // If no head, follows that there's no tail (at initial or reset)
4810 tail = node;
4811 }
4812
4813 // Trim tail if we're reached max size and are pending cache insertion
4814 if ( size === /** @type {MemizeOptions} */ ( options ).maxSize ) {
4815 tail = /** @type {MemizeCacheNode} */ ( tail ).prev;
4816 /** @type {MemizeCacheNode} */ ( tail ).next = null;
4817 } else {
4818 size++;
4819 }
4820
4821 head = node;
4822
4823 return node.val;
4824 }
4825
4826 memoized.clear = function() {
4827 head = null;
4828 tail = null;
4829 size = 0;
4830 };
4831
4832 if ( process.env.NODE_ENV === 'test' ) {
4833 // Cache is not exposed in the public API, but used in tests to ensure
4834 // expected list progression
4835 memoized.getCache = function() {
4836 return [ head, tail, size ];
4837 };
4838 }
4839
4840 // Ignore reason: There's not a clear solution to create an intersection of
4841 // the function with additional properties, where the goal is to retain the
4842 // function signature of the incoming argument and add control properties
4843 // on the return value.
4844
4845 // @ts-ignore
4846 return memoized;
4847 }
4848
4849 module.exports = memize;
4850
4851 }).call(this,require('_process'))
4852 },{"_process":22}],22:[function(require,module,exports){
4853 // shim for using process in browser
4854 var process = module.exports = {};
4855
4856 // cached from whatever global is present so that test runners that stub it
4857 // don't break things. But we need to wrap it in a try catch in case it is
4858 // wrapped in strict mode code which doesn't define any globals. It's inside a
4859 // function because try/catches deoptimize in certain engines.
4860
4861 var cachedSetTimeout;
4862 var cachedClearTimeout;
4863
4864 function defaultSetTimout() {
4865 throw new Error('setTimeout has not been defined');
4866 }
4867 function defaultClearTimeout () {
4868 throw new Error('clearTimeout has not been defined');
4869 }
4870 (function () {
4871 try {
4872 if (typeof setTimeout === 'function') {
4873 cachedSetTimeout = setTimeout;
4874 } else {
4875 cachedSetTimeout = defaultSetTimout;
4876 }
4877 } catch (e) {
4878 cachedSetTimeout = defaultSetTimout;
4879 }
4880 try {
4881 if (typeof clearTimeout === 'function') {
4882 cachedClearTimeout = clearTimeout;
4883 } else {
4884 cachedClearTimeout = defaultClearTimeout;
4885 }
4886 } catch (e) {
4887 cachedClearTimeout = defaultClearTimeout;
4888 }
4889 } ())
4890 function runTimeout(fun) {
4891 if (cachedSetTimeout === setTimeout) {
4892 //normal enviroments in sane situations
4893 return setTimeout(fun, 0);
4894 }
4895 // if setTimeout wasn't available but was latter defined
4896 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
4897 cachedSetTimeout = setTimeout;
4898 return setTimeout(fun, 0);
4899 }
4900 try {
4901 // when when somebody has screwed with setTimeout but no I.E. maddness
4902 return cachedSetTimeout(fun, 0);
4903 } catch(e){
4904 try {
4905 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
4906 return cachedSetTimeout.call(null, fun, 0);
4907 } catch(e){
4908 // 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
4909 return cachedSetTimeout.call(this, fun, 0);
4910 }
4911 }
4912
4913
4914 }
4915 function runClearTimeout(marker) {
4916 if (cachedClearTimeout === clearTimeout) {
4917 //normal enviroments in sane situations
4918 return clearTimeout(marker);
4919 }
4920 // if clearTimeout wasn't available but was latter defined
4921 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
4922 cachedClearTimeout = clearTimeout;
4923 return clearTimeout(marker);
4924 }
4925 try {
4926 // when when somebody has screwed with setTimeout but no I.E. maddness
4927 return cachedClearTimeout(marker);
4928 } catch (e){
4929 try {
4930 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
4931 return cachedClearTimeout.call(null, marker);
4932 } catch (e){
4933 // 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.
4934 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
4935 return cachedClearTimeout.call(this, marker);
4936 }
4937 }
4938
4939
4940
4941 }
4942 var queue = [];
4943 var draining = false;
4944 var currentQueue;
4945 var queueIndex = -1;
4946
4947 function cleanUpNextTick() {
4948 if (!draining || !currentQueue) {
4949 return;
4950 }
4951 draining = false;
4952 if (currentQueue.length) {
4953 queue = currentQueue.concat(queue);
4954 } else {
4955 queueIndex = -1;
4956 }
4957 if (queue.length) {
4958 drainQueue();
4959 }
4960 }
4961
4962 function drainQueue() {
4963 if (draining) {
4964 return;
4965 }
4966 var timeout = runTimeout(cleanUpNextTick);
4967 draining = true;
4968
4969 var len = queue.length;
4970 while(len) {
4971 currentQueue = queue;
4972 queue = [];
4973 while (++queueIndex < len) {
4974 if (currentQueue) {
4975 currentQueue[queueIndex].run();
4976 }
4977 }
4978 queueIndex = -1;
4979 len = queue.length;
4980 }
4981 currentQueue = null;
4982 draining = false;
4983 runClearTimeout(timeout);
4984 }
4985
4986 process.nextTick = function (fun) {
4987 var args = new Array(arguments.length - 1);
4988 if (arguments.length > 1) {
4989 for (var i = 1; i < arguments.length; i++) {
4990 args[i - 1] = arguments[i];
4991 }
4992 }
4993 queue.push(new Item(fun, args));
4994 if (queue.length === 1 && !draining) {
4995 runTimeout(drainQueue);
4996 }
4997 };
4998
4999 // v8 likes predictible objects
5000 function Item(fun, array) {
5001 this.fun = fun;
5002 this.array = array;
5003 }
5004 Item.prototype.run = function () {
5005 this.fun.apply(null, this.array);
5006 };
5007 process.title = 'browser';
5008 process.browser = true;
5009 process.env = {};
5010 process.argv = [];
5011 process.version = ''; // empty string to avoid regexp issues
5012 process.versions = {};
5013
5014 function noop() {}
5015
5016 process.on = noop;
5017 process.addListener = noop;
5018 process.once = noop;
5019 process.off = noop;
5020 process.removeListener = noop;
5021 process.removeAllListeners = noop;
5022 process.emit = noop;
5023 process.prependListener = noop;
5024 process.prependOnceListener = noop;
5025
5026 process.listeners = function (name) { return [] }
5027
5028 process.binding = function (name) {
5029 throw new Error('process.binding is not supported');
5030 };
5031
5032 process.cwd = function () { return '/' };
5033 process.chdir = function (dir) {
5034 throw new Error('process.chdir is not supported');
5035 };
5036 process.umask = function() { return 0; };
5037
5038 },{}],23:[function(require,module,exports){
5039 'use strict';
5040
5041 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
5042
5043 var pluralForms = _interopDefault(require('@tannin/plural-forms'));
5044
5045 /**
5046 * Tannin constructor options.
5047 *
5048 * @typedef {Object} TanninOptions
5049 *
5050 * @property {string} [contextDelimiter] Joiner in string lookup with context.
5051 * @property {Function} [onMissingKey] Callback to invoke when key missing.
5052 */
5053
5054 /**
5055 * Domain metadata.
5056 *
5057 * @typedef {Object} TanninDomainMetadata
5058 *
5059 * @property {string} [domain] Domain name.
5060 * @property {string} [lang] Language code.
5061 * @property {(string|Function)} [plural_forms] Plural forms expression or
5062 * function evaluator.
5063 */
5064
5065 /**
5066 * Domain translation pair respectively representing the singular and plural
5067 * translation.
5068 *
5069 * @typedef {[string,string]} TanninTranslation
5070 */
5071
5072 /**
5073 * Locale data domain. The key is used as reference for lookup, the value an
5074 * array of two string entries respectively representing the singular and plural
5075 * translation.
5076 *
5077 * @typedef {{[key:string]:TanninDomainMetadata|TanninTranslation,'':TanninDomainMetadata|TanninTranslation}} TanninLocaleDomain
5078 */
5079
5080 /**
5081 * Jed-formatted locale data.
5082 *
5083 * @see http://messageformat.github.io/Jed/
5084 *
5085 * @typedef {{[domain:string]:TanninLocaleDomain}} TanninLocaleData
5086 */
5087
5088 /**
5089 * Default Tannin constructor options.
5090 *
5091 * @type {TanninOptions}
5092 */
5093 var DEFAULT_OPTIONS = {
5094 contextDelimiter: '\u0004',
5095 onMissingKey: null,
5096 };
5097
5098 /**
5099 * Given a specific locale data's config `plural_forms` value, returns the
5100 * expression.
5101 *
5102 * @example
5103 *
5104 * ```
5105 * getPluralExpression( 'nplurals=2; plural=(n != 1);' ) === '(n != 1)'
5106 * ```
5107 *
5108 * @param {string} pf Locale data plural forms.
5109 *
5110 * @return {string} Plural forms expression.
5111 */
5112 function getPluralExpression( pf ) {
5113 var parts, i, part;
5114
5115 parts = pf.split( ';' );
5116
5117 for ( i = 0; i < parts.length; i++ ) {
5118 part = parts[ i ].trim();
5119 if ( part.indexOf( 'plural=' ) === 0 ) {
5120 return part.substr( 7 );
5121 }
5122 }
5123 }
5124
5125 /**
5126 * Tannin constructor.
5127 *
5128 * @class
5129 *
5130 * @param {TanninLocaleData} data Jed-formatted locale data.
5131 * @param {TanninOptions} [options] Tannin options.
5132 */
5133 function Tannin( data, options ) {
5134 var key;
5135
5136 /**
5137 * Jed-formatted locale data.
5138 *
5139 * @name Tannin#data
5140 * @type {TanninLocaleData}
5141 */
5142 this.data = data;
5143
5144 /**
5145 * Plural forms function cache, keyed by plural forms string.
5146 *
5147 * @name Tannin#pluralForms
5148 * @type {Object<string,Function>}
5149 */
5150 this.pluralForms = {};
5151
5152 /**
5153 * Effective options for instance, including defaults.
5154 *
5155 * @name Tannin#options
5156 * @type {TanninOptions}
5157 */
5158 this.options = {};
5159
5160 for ( key in DEFAULT_OPTIONS ) {
5161 this.options[ key ] = options !== undefined && key in options
5162 ? options[ key ]
5163 : DEFAULT_OPTIONS[ key ];
5164 }
5165 }
5166
5167 /**
5168 * Returns the plural form index for the given domain and value.
5169 *
5170 * @param {string} domain Domain on which to calculate plural form.
5171 * @param {number} n Value for which plural form is to be calculated.
5172 *
5173 * @return {number} Plural form index.
5174 */
5175 Tannin.prototype.getPluralForm = function( domain, n ) {
5176 var getPluralForm = this.pluralForms[ domain ],
5177 config, plural, pf;
5178
5179 if ( ! getPluralForm ) {
5180 config = this.data[ domain ][ '' ];
5181
5182 pf = (
5183 config[ 'Plural-Forms' ] ||
5184 config[ 'plural-forms' ] ||
5185 // Ignore reason: As known, there's no way to document the empty
5186 // string property on a key to guarantee this as metadata.
5187 // @ts-ignore
5188 config.plural_forms
5189 );
5190
5191 if ( typeof pf !== 'function' ) {
5192 plural = getPluralExpression(
5193 config[ 'Plural-Forms' ] ||
5194 config[ 'plural-forms' ] ||
5195 // Ignore reason: As known, there's no way to document the empty
5196 // string property on a key to guarantee this as metadata.
5197 // @ts-ignore
5198 config.plural_forms
5199 );
5200
5201 pf = pluralForms( plural );
5202 }
5203
5204 getPluralForm = this.pluralForms[ domain ] = pf;
5205 }
5206
5207 return getPluralForm( n );
5208 };
5209
5210 /**
5211 * Translate a string.
5212 *
5213 * @param {string} domain Translation domain.
5214 * @param {string|void} context Context distinguishing terms of the same name.
5215 * @param {string} singular Primary key for translation lookup.
5216 * @param {string=} plural Fallback value used for non-zero plural
5217 * form index.
5218 * @param {number=} n Value to use in calculating plural form.
5219 *
5220 * @return {string} Translated string.
5221 */
5222 Tannin.prototype.dcnpgettext = function( domain, context, singular, plural, n ) {
5223 var index, key, entry;
5224
5225 if ( n === undefined ) {
5226 // Default to singular.
5227 index = 0;
5228 } else {
5229 // Find index by evaluating plural form for value.
5230 index = this.getPluralForm( domain, n );
5231 }
5232
5233 key = singular;
5234
5235 // If provided, context is prepended to key with delimiter.
5236 if ( context ) {
5237 key = context + this.options.contextDelimiter + singular;
5238 }
5239
5240 entry = this.data[ domain ][ key ];
5241
5242 // Verify not only that entry exists, but that the intended index is within
5243 // range and non-empty.
5244 if ( entry && entry[ index ] ) {
5245 return entry[ index ];
5246 }
5247
5248 if ( this.options.onMissingKey ) {
5249 this.options.onMissingKey( singular, domain );
5250 }
5251
5252 // If entry not found, fall back to singular vs. plural with zero index
5253 // representing the singular value.
5254 return index === 0 ? singular : plural;
5255 };
5256
5257 module.exports = Tannin;
5258
5259 },{"@tannin/plural-forms":12}]},{},[3]);
5260