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

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

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