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

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

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