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

editor.js in SellKit – Funnel builder and checkout optimizer for WooCommerce to sell more, faster 1.6.2, at assets/dist/js/editor.js

3,973 lines 165.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2 "use strict";
3
4 Object.defineProperty(exports, "__esModule", {
5 value: true
6 });
7 exports["default"] = void 0;
8
9 var _i18n = require("@wordpress/i18n");
10
11 var FileUploader = elementor.modules.controls.BaseMultiple.extend({
12 ui: function ui() {
13 var ui = elementor.modules.controls.BaseMultiple.prototype.ui.apply(this, arguments);
14 return _.extend(ui, {
15 fileUploader: 'sellkit-control-file-uploader',
16 fileUploaderInput: '.sellkit-control-file-uploader-input',
17 fileUploaderBtn: '.sellkit-control-file-uploader-button',
18 fileUploaderValue: '.sellkit-control-file-uploader-value',
19 fileUploaderRemoveBtn: '.sellkit-control-file-uploader-value .fa',
20 fileUploaderProgress: '.sellkit-control-file-uploader-progress',
21 fileUploaderWarning: '.sellkit-control-file-uploader-warning',
22 fileUploaderSizeWarning: '.sellkit-control-file-uploader-warning-size'
23 });
24 },
25 events: function events() {
26 var events = elementor.modules.controls.BaseMultiple.prototype.events.apply(this, arguments);
27 return _.extend(events, {
28 'change @ui.fileUploaderInput': 'onFileInputChange',
29 'click @ui.fileUploaderRemoveBtn': 'onFileRemove'
30 });
31 },
32 onFileInputChange: function onFileInputChange(event) {
33 var self = this;
34 this.hideWarnings();
35
36 if (event.target.files.length === 0) {
37 return;
38 }
39
40 if (!this.checkFileSize(event.target.files[0])) {
41 return;
42 }
43
44 var formData = new FormData();
45 formData.append('action', 'sellkit_control_file_upload');
46 formData.append('file', event.target.files[0]);
47 formData.append('nonce', window.sellkitNonceEditorFileUploader[0]);
48 this.showUploadProgress();
49 jQuery.ajax(this.ui.fileUploaderInput.data('ajax-url'), {
50 method: 'POST',
51 processData: false,
52 contentType: false,
53 global: false,
54 data: formData,
55 success: function success(res) {
56 if (res.success) {
57 self.setValue('files', [res.data]);
58 self.showFile(res.data.name);
59 } else {
60 self.ui.fileUploaderInput.val('');
61 self.ui.fileUploaderWarning.find('ul').append("<li class=\"error\">".concat(res.data, "</li>"));
62 self.ui.fileUploaderWarning.show();
63 self.showUploadBtn();
64 }
65 },
66 error: function error() {
67 self.ui.fileUploaderInput.val('');
68 self.ui.fileUploaderWarning.find('ul').append("<li class=\"error\">".concat((0, _i18n.__)('Something went wrong please try again.', 'sellkit'), "</li>"));
69 self.ui.fileUploaderWarning.show();
70 self.showUploadBtn();
71 }
72 });
73 },
74 onFileRemove: function onFileRemove(event) {
75 event.stopPropagation();
76 this.setValue('files', []);
77 this.ui.fileUploaderValue.hide();
78 this.ui.fileUploaderBtn.show();
79 this.ui.fileUploaderInput.val('');
80 },
81 hideWarnings: function hideWarnings() {
82 this.ui.fileUploaderWarning.hide();
83 this.ui.fileUploaderWarning.find('li').hide();
84 this.ui.fileUploaderWarning.find('li.error').remove();
85 },
86 checkFileSize: function checkFileSize(file) {
87 var uploadLimit = parseFloat(this.ui.fileUploaderInput.data('max-upload-limit'));
88
89 if (file.size > uploadLimit) {
90 this.ui.fileUploaderWarning.show();
91 this.ui.fileUploaderSizeWarning.show();
92 return false;
93 }
94
95 return true;
96 },
97 stripHash: function stripHash(filename) {
98 var ext = filename.split('.').pop();
99 var name = filename.replace('.' + ext, '');
100 name = name.split('__').shift();
101 return name + '.' + ext;
102 },
103 shortenFilename: function shortenFilename(filename) {
104 return filename.length > 15 ? filename.substr(0, 15) + '...' : filename;
105 },
106 showFile: function showFile(filename) {
107 this.ui.fileUploaderProgress.hide();
108 this.ui.fileUploaderBtn.hide();
109 filename = this.stripHash(filename);
110 this.ui.fileUploaderValue.find('> span:first-child').attr('title', filename).text(this.shortenFilename(filename));
111 this.ui.fileUploaderValue.css('display', 'flex');
112 },
113 showUploadBtn: function showUploadBtn() {
114 this.ui.fileUploaderValue.hide();
115 this.ui.fileUploaderProgress.hide();
116 this.ui.fileUploaderBtn.show();
117 },
118 showUploadProgress: function showUploadProgress() {
119 this.ui.fileUploaderValue.hide();
120 this.ui.fileUploaderBtn.hide();
121 this.ui.fileUploaderProgress.show();
122 },
123 onRender: function onRender() {
124 _.extend(elementor.modules.controls.BaseMultiple.prototype.onRender.apply(this, arguments));
125
126 var files = this.getControlValue('files');
127
128 if (!files || files.length === 0) {
129 return;
130 }
131
132 this.showFile(files[0].name);
133 }
134 });
135 var _default = FileUploader;
136 exports["default"] = _default;
137
138 },{"@wordpress/i18n":23}],2:[function(require,module,exports){
139 "use strict";
140
141 (function ($, window) {
142 var sellkitEditor = function sellkitEditor() {
143 var onElementorReady = function onElementorReady() {
144 if (typeof elementor.settings.editorPreferences === 'undefined') {
145 return;
146 } // Manage dark & light icons.
147
148
149 if ('dark' === elementor.settings.editorPreferences.model.attributes.ui_theme) {
150 $('#elementor-editor-wrapper').addClass('sellkit-editor-ui-dark');
151 } else {
152 $('#elementor-editor-wrapper').removeClass('sellkit-editor-ui-dark');
153 }
154 };
155
156 var onSettingsChange = function onSettingsChange() {
157 elementor.settings.editorPreferences.model.on('change', onElementorReady);
158 }; // Initialize controls JS.
159
160
161 var initControls = function initControls() {
162 var controls = {
163 file_uploader: require('./controls/file-uploader')["default"]
164 };
165
166 for (var control in controls) {
167 elementor.addControlView("sellkit_".concat(control), controls[control]);
168 }
169 }; // Initialize widget JS.
170
171
172 var initWidgets = function initWidgets() {
173 var widgets = {
174 'sellkit-checkout': require('./widgets/checkout')["default"],
175 'sellkit-optin': require('./widgets/optin/optin')["default"]
176 };
177
178 for (var widget in widgets) {
179 elementor.hooks.addAction("panel/open_editor/widget/".concat(widget), widgets[widget]);
180 }
181 }; // Some widgets require a rerender after preview loaded,
182 // to fully sync with their ajaxed settings AND\OR displaying shortcode contents.
183
184
185 function rerenderWidgets() {
186 if (!elementor.previewView || !elementor.previewView._getNestedViews) {
187 return;
188 }
189
190 var widgets = ['sellkit-checkout'];
191
192 var _loop = function _loop(widget) {
193 var views = elementor.previewView._getNestedViews().filter(function (view) {
194 return 'widget' === view.model.get('elType') && widgets[widget] === view.model.get('widgetType');
195 });
196
197 _.each(views, function (view) {
198 return view.renderHTML();
199 });
200 };
201
202 for (var widget in widgets) {
203 _loop(widget);
204 }
205 }
206
207 function onDocumentLoaded() {
208 setTimeout(rerenderWidgets, 0);
209 }
210
211 var onElementorInit = function onElementorInit() {
212 onElementorReady();
213 onSettingsChange();
214 initControls();
215 elementor.on('frontend:init', initWidgets);
216 elementor.on('document:loaded', onDocumentLoaded);
217 };
218
219 $(window).on('elementor:init', onElementorInit);
220 };
221
222 window.sellkitEditor = new sellkitEditor();
223 })(jQuery, window);
224
225 },{"./controls/file-uploader":1,"./widgets/checkout":3,"./widgets/optin/optin":13}],3:[function(require,module,exports){
226 "use strict";
227
228 Object.defineProperty(exports, "__esModule", {
229 value: true
230 });
231 exports["default"] = _default;
232
233 function _default() {
234 var $ = jQuery;
235
236 var initializeChange = function initializeChange() {
237 var $element = $('input[data-setting="place_order_btn_txt"');
238 var value = $element.val();
239 $element.val('');
240 $element.val(value).trigger('input');
241 };
242
243 var disableExpressOnFree = function disableExpressOnFree() {
244 var promotionParent = $('.elementor-control-checkout-express-promotion');
245 promotionParent.find('input').attr('disabled', 'disabled');
246 promotionParent.find('.elementor-control-title').on('click', function () {
247 window.open('https://getsellkit.com/pricing/', '_blank');
248 });
249 };
250
251 var init = function init() {
252 initializeChange();
253 disableExpressOnFree();
254 };
255
256 init();
257 }
258
259 },{}],4:[function(require,module,exports){
260 "use strict";
261
262 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
263
264 Object.defineProperty(exports, "__esModule", {
265 value: true
266 });
267 exports["default"] = _default;
268
269 var _crmBase = _interopRequireDefault(require("./crm-base"));
270
271 function _default(panel, model, view) {
272 var ActiveCampaign = _crmBase["default"].extend({
273 panel: panel,
274 model: model,
275 action: 'activecampaign',
276 add_additional_api_data: function add_additional_api_data(params) {
277 params["".concat(this.action, "_custom_api_url")] = this.getControlValue("".concat(this.action, "_custom_api_url"));
278 },
279 updateAdditionalControls: function updateAdditionalControls() {
280 if (!this.additionalData.hasOwnProperty('tags')) {
281 return;
282 }
283
284 var tagsControl = this.getControlView("".concat(this.action, "_tags"));
285 tagsControl.model.set('options', this.additionalData.tags);
286 tagsControl.render();
287 },
288 // Override to reflect changes of "custom_api_url" control.
289 onElementChange: function onElementChange(controlView) {
290 var setting = controlView.model.get('name');
291
292 switch (setting) {
293 case "".concat(this.action, "_api_key_source"):
294 case "".concat(this.action, "_custom_api_key"):
295 case "".concat(this.action, "_custom_api_url"):
296 this.ajaxUpdateList();
297 break;
298
299 case "".concat(this.action, "_list"):
300 var listId = this.getListId();
301
302 if (listId && !this.listOptions.hasOwnProperty(listId)) {
303 this.ajaxUpdateAdditionalData();
304 }
305
306 break;
307 }
308 }
309 });
310
311 new ActiveCampaign({
312 $element: view.$el
313 });
314 }
315
316 },{"./crm-base":6,"@babel/runtime/helpers/interopRequireDefault":16}],5:[function(require,module,exports){
317 "use strict";
318
319 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
320
321 Object.defineProperty(exports, "__esModule", {
322 value: true
323 });
324 exports["default"] = _default;
325
326 var _crmBase = _interopRequireDefault(require("./crm-base"));
327
328 function _default(panel, model, view) {
329 var ConvertKit = _crmBase["default"].extend({
330 panel: panel,
331 model: model,
332 action: 'convertkit',
333 updateAdditionalControls: function updateAdditionalControls() {
334 if (!this.additionalData.hasOwnProperty('tags')) {
335 return;
336 }
337
338 var tagsControl = this.getControlView("".concat(this.action, "_tags"));
339 tagsControl.model.set('options', this.additionalData.tags);
340 tagsControl.render();
341 }
342 });
343
344 new ConvertKit({
345 $element: view.$el
346 });
347 }
348
349 },{"./crm-base":6,"@babel/runtime/helpers/interopRequireDefault":16}],6:[function(require,module,exports){
350 "use strict";
351
352 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
353
354 Object.defineProperty(exports, "__esModule", {
355 value: true
356 });
357 exports["default"] = void 0;
358
359 var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
360
361 var _util = _interopRequireDefault(require("../../util"));
362
363 var _i18n = require("@wordpress/i18n");
364
365 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; }
366
367 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; }
368
369 var _default = _util["default"].extend({
370 panel: null,
371 model: null,
372 action: null,
373 listView: null,
374 listOptions: {
375 none: {
376 none: (0, _i18n.__)('Select...', 'sellkit')
377 },
378 fetching: {
379 fetching: (0, _i18n.__)('Fetching...', 'sellkit')
380 },
381 noList: {
382 noList: (0, _i18n.__)('Nothing found!', 'sellkit')
383 }
384 },
385 fieldNoneOption: {
386 '': (0, _i18n.__)('-NONE-', 'sellkit')
387 },
388 mappingRepeater: null,
389 localFields: {},
390 additionalData: [],
391 onInit: function onInit() {
392 elementor.channels.editor.on('section:activated', this.onSectionActivated);
393 elementor.channels.editor.on('change', this.onElementChange);
394 },
395 onDestroy: function onDestroy() {
396 elementor.channels.editor.off('change', this.onElementChange);
397 },
398 onSectionActivated: function onSectionActivated(activeSection, section) {
399 if (activeSection !== "section_".concat(this.action) || section.model.id !== this.model.get('id')) {
400 return;
401 }
402
403 this.init();
404 },
405 init: function init() {
406 this.localFields = _objectSpread(_objectSpread({}, this.fieldNoneOption), this.getFormFields());
407 this.listView = this.getControlView("".concat(this.action, "_list"));
408 this.mappingRepeater = this.getControlView("".concat(this.action, "_fields_mapping"));
409 this.ajaxUpdateList();
410 this.updateControls();
411 this.mappingRepeater.on('add:child', this.updateControls);
412 this.mappingRepeater.on('childview:click:remove', this.updateControls);
413 },
414 ajaxUpdateList: function ajaxUpdateList() {
415 var _this = this;
416
417 var currentValue = this.getControlValue("".concat(this.action, "_list"));
418 this.setListOptions(this.listOptions.fetching);
419 this.setListSelection('fetching');
420 this.addControlSpinner("".concat(this.action, "_list"));
421 var params = {};
422 params["".concat(this.action, "_api_key_source")] = this.getControlValue("".concat(this.action, "_api_key_source")) || 'default';
423 params["".concat(this.action, "_custom_api_key")] = this.getControlValue("".concat(this.action, "_custom_api_key"));
424 this.add_additional_api_data(params);
425 wp.ajax.send('sellkit_optin_editor', {
426 cache: false,
427 data: {
428 params: params,
429 nonce: window.sellkitNonceEditorOptin[0],
430 service: this.action,
431 request: 'get_list'
432 },
433 success: function success(response) {
434 _this.removeControlSpinner("".concat(_this.action, "_list"));
435
436 var lists = {};
437
438 if (response.success[0].lists.length === 0) {
439 _this.setListOptions(_this.listOptions.noList);
440
441 _this.setListSelection('noList');
442
443 return;
444 }
445
446 _.each(response.success[0].lists, function (list, id) {
447 lists[id] = list;
448 });
449
450 var options = _objectSpread(_objectSpread({}, _this.listOptions.none), lists);
451
452 _this.setListOptions(options);
453
454 if (options[currentValue]) {
455 _this.setListSelection(currentValue);
456
457 return;
458 }
459
460 if (_.isEmpty(_this.listView.$el.val())) {
461 _this.setListSelection('none');
462 }
463 },
464 error: function error() {
465 _this.removeControlSpinner("".concat(_this.action, "_list"));
466
467 _this.listView.$el.find('option').text((0, _i18n.__)('Error! nonce mismatch', 'sellkit'));
468
469 _this.listView.$el.find('select').attr('disabled', 'disabled');
470 }
471 });
472 },
473 ajaxUpdateAdditionalData: function ajaxUpdateAdditionalData() {
474 var _this2 = this;
475
476 var params = {};
477 params["".concat(this.action, "_api_key_source")] = this.getControlValue("".concat(this.action, "_api_key_source")) || 'default';
478 params["".concat(this.action, "_custom_api_key")] = this.getControlValue("".concat(this.action, "_custom_api_key"));
479 params.list_id = this.getListId();
480 this.add_additional_api_data(params);
481 this.toggleSpinner(true);
482 wp.ajax.send('sellkit_optin_editor', {
483 data: {
484 params: params,
485 nonce: window.sellkitNonceEditorOptin[0],
486 service: this.action,
487 request: 'get_additional_data'
488 },
489 success: function success(response) {
490 _this2.additionalData = response.success[0];
491
492 _this2.updateControls();
493 },
494 complete: function complete() {
495 return _this2.toggleSpinner(false);
496 }
497 });
498 },
499 updateControls: function updateControls() {
500 var _this3 = this;
501
502 this.mappingRepeater.children.each(function (row) {
503 row.children.each(function (control) {
504 var fieldModel = control.model;
505 var fieldName = fieldModel.get('name');
506
507 switch (fieldName) {
508 case 'remote_field':
509 if (!_this3.additionalData.hasOwnProperty('custom_fields')) {
510 break;
511 }
512
513 var currentOptions = fieldModel.get('options');
514
515 var newOptions = _objectSpread(_objectSpread(_objectSpread({}, _this3.fieldNoneOption), currentOptions), _this3.additionalData.custom_fields);
516
517 fieldModel.set('options', newOptions);
518 break;
519
520 case 'local_field':
521 fieldModel.set('options', _this3.localFields);
522 break;
523
524 default:
525 break;
526 }
527
528 control.render();
529 });
530
531 _this3.fixTitleField(row);
532 });
533 this.sortSelectOptions();
534 this.lockRequiredRemoteFields();
535 this.updateAdditionalControls();
536 },
537 onElementChange: function onElementChange(controlView) {
538 var setting = controlView.model.get('name');
539
540 switch (setting) {
541 case "".concat(this.action, "_api_key_source"):
542 case "".concat(this.action, "_custom_api_key"):
543 this.ajaxUpdateList();
544 break;
545
546 case "".concat(this.action, "_list"):
547 var listId = this.getListId();
548
549 if (listId && !this.listOptions.hasOwnProperty(listId)) {
550 this.ajaxUpdateAdditionalData();
551 }
552
553 break;
554 }
555 },
556 getListId: function getListId() {
557 return this.getControlValue("".concat(this.action, "_list"));
558 },
559 // Set Options of the "List" select control.
560 setListOptions: function setListOptions(options) {
561 this.listView.model.set('options', options);
562 this.listView.render(); // Sort options so that the "Select..." option comes first.
563
564 var select = this.listView.$el.find('select');
565 var firstOption = select.find('option[value="none"]');
566
567 if (!firstOption.length) {
568 return;
569 }
570
571 var helper = firstOption[0];
572 firstOption.remove();
573 select.prepend(helper);
574 },
575 setListSelection: function setListSelection(option) {
576 this.listView.$el.find('select').val(option).change();
577 },
578 // Sort mapping fields options so that the "-NONE-" option comes first.
579 sortSelectOptions: function sortSelectOptions() {
580 var selects = this.mappingRepeater.$el.find('select');
581
582 _.each(selects, function (select) {
583 var firstOption = jQuery(select).find('option[value=""]');
584
585 if (!firstOption.length) {
586 return;
587 }
588
589 var helper = firstOption[0];
590 firstOption.remove();
591 select.prepend(helper);
592 });
593 },
594 getFormFields: function getFormFields() {
595 var items = {};
596 var formFieldsRepeater = this.getElementSettings(this.model, 'fields');
597
598 _.each(formFieldsRepeater, function (item) {
599 items[item._id] = item.label;
600 });
601
602 return items;
603 },
604 // Find required remote fields, lock them, remove their repeater row styles, and add a star next to them.
605 lockRequiredRemoteFields: function lockRequiredRemoteFields() {
606 this.mappingRepeater.children.each(function (row) {
607 if (row.model.get('is_required')) {
608 var toolbar = row.$el.find('div.elementor-repeater-row-tools');
609 var controlWrapper = row.$el.find('div.elementor-repeater-row-controls');
610 var remoteField = row.$el.find('div.elementor-control-remote_field');
611 var localField = row.$el.find('div.elementor-control-local_field');
612 var localLabel = localField.find('label');
613 var newLabel = remoteField.find('select option:selected').text();
614 var starMark = '<span style="color:red">*</span>';
615 toolbar.hide();
616 controlWrapper.show();
617 controlWrapper.css('border', 'none');
618 remoteField.hide();
619 localLabel.html(newLabel + starMark);
620 localField.css('padding', '0');
621 }
622 });
623 },
624 // Set titles of repeater rows so that they show "label" of remote fields instead of their "key".
625 fixTitleField: function fixTitleField(rowView) {
626 if (rowView.data) {
627 rowView = rowView.data.rowView;
628 }
629
630 var remoteFieldSelect = rowView.$el.find('select[data-setting="remote_field"]');
631 var label = remoteFieldSelect.find("option[value=\"".concat(remoteFieldSelect.val(), "\"]")).first().text();
632 rowView.$el.find('div.elementor-repeater-row-item-title').text(label);
633 remoteFieldSelect.off('change', this.fixTitleField).change({
634 rowView: rowView
635 }, this.fixTitleField);
636 },
637 // While additional data about the selected list is being recieved,
638 // toggle a spinner and opaque its corresopnding fields.
639 toggleSpinner: function toggleSpinner(state) {
640 var containers = jQuery(".elementor-control.elementor-control-".concat(this.action, "_list")).nextAll();
641 containers.css('opacity', state ? 0.5 : 1);
642
643 if (state) {
644 var spinner = "\n\t\t\t\t<span style=\"position: absolute; top: 15px; right: 15px;\" class=\"elementor-control-spinner\">\n\t\t\t\t\t<span style=\"font-size: 20px\" class=\"fa fa-spinner fa-spin\"></span>\n\t\t\t\t\t&nbsp;\n\t\t\t\t</span>\n\t\t\t";
645 containers.first().prepend(spinner);
646 return;
647 }
648
649 containers.first().find('span.elementor-control-spinner').remove();
650 },
651 // Placed to be overridden if needed.
652
653 /* eslint-disable no-unused-vars */
654 add_additional_api_data: function add_additional_api_data(params) {},
655
656 /* eslint-enable no-unused-vars */
657 // Placed to be overridden if needed.
658 updateAdditionalControls: function updateAdditionalControls() {}
659 });
660
661 exports["default"] = _default;
662
663 },{"../../util":14,"@babel/runtime/helpers/defineProperty":15,"@babel/runtime/helpers/interopRequireDefault":16,"@wordpress/i18n":23}],7:[function(require,module,exports){
664 "use strict";
665
666 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
667
668 Object.defineProperty(exports, "__esModule", {
669 value: true
670 });
671 exports["default"] = _default;
672
673 var _crmBase = _interopRequireDefault(require("./crm-base"));
674
675 function _default(panel, model, view) {
676 var Drip = _crmBase["default"].extend({
677 panel: panel,
678 model: model,
679 action: 'drip',
680 updateAdditionalControls: function updateAdditionalControls() {
681 if (!this.additionalData.hasOwnProperty('tags')) {
682 return;
683 }
684
685 var tagsControl = this.getControlView("".concat(this.action, "_tags"));
686 tagsControl.model.set('options', this.additionalData.tags);
687 tagsControl.render();
688 }
689 });
690
691 new Drip({
692 $element: view.$el
693 });
694 }
695
696 },{"./crm-base":6,"@babel/runtime/helpers/interopRequireDefault":16}],8:[function(require,module,exports){
697 "use strict";
698
699 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
700
701 Object.defineProperty(exports, "__esModule", {
702 value: true
703 });
704 exports["default"] = _default;
705
706 var _crmBase = _interopRequireDefault(require("./crm-base"));
707
708 function _default(panel, model, view) {
709 var GetResponse = _crmBase["default"].extend({
710 panel: panel,
711 model: model,
712 action: 'getresponse',
713 updateAdditionalControls: function updateAdditionalControls() {
714 if (!this.additionalData.hasOwnProperty('tags')) {
715 return;
716 }
717
718 var tagsControl = this.getControlView("".concat(this.action, "_tags"));
719 tagsControl.model.set('options', this.additionalData.tags);
720 tagsControl.render();
721 }
722 });
723
724 new GetResponse({
725 $element: view.$el
726 });
727 }
728
729 },{"./crm-base":6,"@babel/runtime/helpers/interopRequireDefault":16}],9:[function(require,module,exports){
730 "use strict";
731
732 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
733
734 Object.defineProperty(exports, "__esModule", {
735 value: true
736 });
737 exports["default"] = _default;
738
739 var _crmBase = _interopRequireDefault(require("./crm-base"));
740
741 function _default(panel, model, view) {
742 var Growmatic = _crmBase["default"].extend({
743 panel: panel,
744 model: model,
745 action: 'growmatik',
746 updateAdditionalControls: function updateAdditionalControls() {
747 if (!this.additionalData.hasOwnProperty('tags')) {
748 return;
749 }
750
751 var tagsControl = this.getControlView("".concat(this.action, "_tags"));
752 tagsControl.model.set('options', this.additionalData.tags);
753 tagsControl.render();
754 }
755 });
756
757 new Growmatic({
758 $element: view.$el
759 });
760 }
761
762 },{"./crm-base":6,"@babel/runtime/helpers/interopRequireDefault":16}],10:[function(require,module,exports){
763 "use strict";
764
765 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
766
767 Object.defineProperty(exports, "__esModule", {
768 value: true
769 });
770 exports["default"] = _default;
771
772 var _crmBase = _interopRequireDefault(require("./crm-base"));
773
774 function _default(panel, model, view) {
775 var ConvertKit = _crmBase["default"].extend({
776 panel: panel,
777 model: model,
778 action: 'mailchimp',
779 // Override just to add spinner, since the request time is little heavier than other actions.
780 ajaxUpdateAdditionalData: function ajaxUpdateAdditionalData() {
781 this.addControlSpinner("".concat(this.action, "_tags"));
782 this.addControlSpinner("".concat(this.action, "_groups"));
783
784 _crmBase["default"].prototype.ajaxUpdateAdditionalData.apply(this, arguments);
785 },
786 updateAdditionalControls: function updateAdditionalControls() {
787 var _this = this;
788
789 this.removeControlSpinner("".concat(this.action, "_tags"));
790 this.removeControlSpinner("".concat(this.action, "_groups"));
791
792 _.each(['tags', 'groups'], function (control) {
793 if (!_this.additionalData.hasOwnProperty("".concat(control))) {
794 return;
795 }
796
797 var controlView = _this.getControlView("".concat(_this.action, "_").concat(control));
798
799 controlView.model.set('options', _this.additionalData["".concat(control)]);
800 controlView.render();
801 });
802 }
803 });
804
805 new ConvertKit({
806 $element: view.$el
807 });
808 }
809
810 },{"./crm-base":6,"@babel/runtime/helpers/interopRequireDefault":16}],11:[function(require,module,exports){
811 "use strict";
812
813 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
814
815 Object.defineProperty(exports, "__esModule", {
816 value: true
817 });
818 exports["default"] = _default;
819
820 var _crmBase = _interopRequireDefault(require("./crm-base"));
821
822 function _default(panel, model, view) {
823 var MailerLite = _crmBase["default"].extend({
824 panel: panel,
825 model: model,
826 action: 'mailerlite'
827 });
828
829 new MailerLite({
830 $element: view.$el
831 });
832 }
833
834 },{"./crm-base":6,"@babel/runtime/helpers/interopRequireDefault":16}],12:[function(require,module,exports){
835 "use strict";
836
837 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
838
839 Object.defineProperty(exports, "__esModule", {
840 value: true
841 });
842 exports["default"] = _default;
843
844 var _util = _interopRequireDefault(require("../../util"));
845
846 function _default(panel, model, view) {
847 var itiTel = _util["default"].extend({
848 panel: panel,
849 model: model,
850 view: view,
851 sectionName: 'section_form_fields',
852 countries: {},
853 onInit: function onInit() {
854 this.getCountries();
855 this.refresh();
856 elementor.channels.editor.on('section:activated', this.onSectionActivated);
857 },
858 onSectionActivated: function onSectionActivated(activeSection, section) {
859 if (activeSection !== this.sectionName || section.model.id !== model.get('id')) {
860 return;
861 }
862
863 this.refresh();
864 },
865 refresh: function refresh() {
866 var _this = this;
867
868 var fieldsRepeater = this.getControlView('fields');
869 this.select2s = [];
870 fieldsRepeater.children.each(function (row) {
871 var typeControl = row.children.find(function (option) {
872 return 'type' === option.model.get('name');
873 }).$el.find('select');
874 typeControl.off('change', _this.refresh).change(_this.refresh);
875
876 if ('tel' !== typeControl.val()) {
877 return;
878 }
879
880 var allowDropdownControl = row.children.find(function (option) {
881 return 'iti_tel_allow_dropdown' === option.model.get('name');
882 }).$el.find('input');
883 allowDropdownControl.off('change', _this.refresh).change(_this.refresh);
884 var allowDropdown = allowDropdownControl[0].checked;
885 var countrySelect2 = row.children.find(function (option) {
886 return 'iti_tel_country_include' === option.model.get('name');
887 });
888 countrySelect2.model.set('multiple', allowDropdown);
889 countrySelect2.model.set('options', _this.countries);
890 countrySelect2.render();
891 });
892 fieldsRepeater.off('add:child', this.refresh).on('add:child', this.refresh);
893 },
894 getCountries: function getCountries() {
895 var _this2 = this;
896
897 require('intl-tel-input');
898
899 _.each(window.intlTelInputGlobals.getCountryData(), function (country) {
900 _this2.countries[country.iso2] = country.name;
901 });
902 }
903 });
904
905 new itiTel({
906 $element: view.$el
907 });
908 }
909
910 },{"../../util":14,"@babel/runtime/helpers/interopRequireDefault":16,"intl-tel-input":27}],13:[function(require,module,exports){
911 "use strict";
912
913 Object.defineProperty(exports, "__esModule", {
914 value: true
915 });
916 exports["default"] = _default;
917
918 function _default(panel, model, view) {
919 var optinModules = {
920 activecampaign: require('./actions/activecampaign')["default"],
921 drip: require('./actions/drip')["default"],
922 convertkit: require('./actions/convertkit')["default"],
923 getresponse: require('./actions/getresponse')["default"],
924 growmatik: require('./actions/growmatik')["default"],
925 mailchimp: require('./actions/mailchimp')["default"],
926 mailerlite: require('./actions/mailerlite')["default"],
927 iti: require('./misc/intelligent-tel')["default"]
928 };
929
930 for (var module in optinModules) {
931 optinModules[module](panel, model, view);
932 }
933 }
934
935 },{"./actions/activecampaign":4,"./actions/convertkit":5,"./actions/drip":7,"./actions/getresponse":8,"./actions/growmatik":9,"./actions/mailchimp":10,"./actions/mailerlite":11,"./misc/intelligent-tel":12}],14:[function(require,module,exports){
936 "use strict";
937
938 Object.defineProperty(exports, "__esModule", {
939 value: true
940 });
941 exports["default"] = void 0;
942 var Module = elementorModules.editor.utils.Module.extend({
943 panel: null,
944 getControl: function getControl(propertyName) {
945 if (!this.panel) {
946 return;
947 }
948
949 var control = this.panel.getCurrentPageView().collection.findWhere({
950 name: propertyName
951 });
952 return control;
953 },
954 getControlView: function getControlView(propertyName) {
955 if (!this.panel) {
956 return;
957 }
958
959 var control = this.getControl(propertyName);
960 var view = this.panel.getCurrentPageView().children.findByModelCid(control.cid);
961 return view;
962 },
963 getControlValue: function getControlValue(id) {
964 return this.getControlView(id).getControlValue();
965 },
966 addControlSpinner: function addControlSpinner(name) {
967 var $el = this.getControlView(name).$el,
968 $input = $el.find(':input');
969
970 if ($input.attr('disabled') || $el.find('.elementor-control-spinner').length > 0) {
971 return;
972 }
973
974 $input.attr('disabled', true);
975 $el.find('.elementor-control-title').after('<span style="display:inline-flex" class="elementor-control-spinner"><span class="fa fa-spinner fa-spin"></span>&nbsp;</span>');
976 },
977 removeControlSpinner: function removeControlSpinner(name) {
978 var $el = this.getControlView(name).$el;
979 $el.find(':input').attr('disabled', false);
980 $el.find('.elementor-control-spinner').remove();
981 },
982 getElementSettings: function getElementSettings(model, name) {
983 if (!model) {
984 return null;
985 }
986
987 var value = model.get('settings').get(name);
988 return value instanceof window.Backbone.Collection ? value.toJSON() : value;
989 }
990 });
991 var _default = Module;
992 exports["default"] = _default;
993
994 },{}],15:[function(require,module,exports){
995 function _defineProperty(obj, key, value) {
996 if (key in obj) {
997 Object.defineProperty(obj, key, {
998 value: value,
999 enumerable: true,
1000 configurable: true,
1001 writable: true
1002 });
1003 } else {
1004 obj[key] = value;
1005 }
1006
1007 return obj;
1008 }
1009
1010 module.exports = _defineProperty;
1011 },{}],16:[function(require,module,exports){
1012 function _interopRequireDefault(obj) {
1013 return obj && obj.__esModule ? obj : {
1014 "default": obj
1015 };
1016 }
1017
1018 module.exports = _interopRequireDefault;
1019 },{}],17:[function(require,module,exports){
1020 'use strict';
1021
1022 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
1023
1024 var postfix = _interopDefault(require('@tannin/postfix'));
1025 var evaluate = _interopDefault(require('@tannin/evaluate'));
1026
1027 /**
1028 * Given a C expression, returns a function which can be called to evaluate its
1029 * result.
1030 *
1031 * @example
1032 *
1033 * ```js
1034 * import compile from '@tannin/compile';
1035 *
1036 * const evaluate = compile( 'n > 1' );
1037 *
1038 * evaluate( { n: 2 } );
1039 * // ⇒ true
1040 * ```
1041 *
1042 * @param {string} expression C expression.
1043 *
1044 * @return {(variables?:{[variable:string]:*})=>*} Compiled evaluator.
1045 */
1046 function compile( expression ) {
1047 var terms = postfix( expression );
1048
1049 return function( variables ) {
1050 return evaluate( terms, variables );
1051 };
1052 }
1053
1054 module.exports = compile;
1055
1056 },{"@tannin/evaluate":18,"@tannin/postfix":20}],18:[function(require,module,exports){
1057 'use strict';
1058
1059 /**
1060 * Operator callback functions.
1061 *
1062 * @type {Object}
1063 */
1064 var OPERATORS = {
1065 '!': function( a ) {
1066 return ! a;
1067 },
1068 '*': function( a, b ) {
1069 return a * b;
1070 },
1071 '/': function( a, b ) {
1072 return a / b;
1073 },
1074 '%': function( a, b ) {
1075 return a % b;
1076 },
1077 '+': function( a, b ) {
1078 return a + b;
1079 },
1080 '-': function( a, b ) {
1081 return a - b;
1082 },
1083 '<': function( a, b ) {
1084 return a < b;
1085 },
1086 '<=': function( a, b ) {
1087 return a <= b;
1088 },
1089 '>': function( a, b ) {
1090 return a > b;
1091 },
1092 '>=': function( a, b ) {
1093 return a >= b;
1094 },
1095 '==': function( a, b ) {
1096 return a === b;
1097 },
1098 '!=': function( a, b ) {
1099 return a !== b;
1100 },
1101 '&&': function( a, b ) {
1102 return a && b;
1103 },
1104 '||': function( a, b ) {
1105 return a || b;
1106 },
1107 '?:': function( a, b, c ) {
1108 if ( a ) {
1109 throw b;
1110 }
1111
1112 return c;
1113 },
1114 };
1115
1116 /**
1117 * Given an array of postfix terms and operand variables, returns the result of
1118 * the postfix evaluation.
1119 *
1120 * @example
1121 *
1122 * ```js
1123 * import evaluate from '@tannin/evaluate';
1124 *
1125 * // 3 + 4 * 5 / 6 ⇒ '3 4 5 * 6 / +'
1126 * const terms = [ '3', '4', '5', '*', '6', '/', '+' ];
1127 *
1128 * evaluate( terms, {} );
1129 * // ⇒ 6.333333333333334
1130 * ```
1131 *
1132 * @param {string[]} postfix Postfix terms.
1133 * @param {Object} variables Operand variables.
1134 *
1135 * @return {*} Result of evaluation.
1136 */
1137 function evaluate( postfix, variables ) {
1138 var stack = [],
1139 i, j, args, getOperatorResult, term, value;
1140
1141 for ( i = 0; i < postfix.length; i++ ) {
1142 term = postfix[ i ];
1143
1144 getOperatorResult = OPERATORS[ term ];
1145 if ( getOperatorResult ) {
1146 // Pop from stack by number of function arguments.
1147 j = getOperatorResult.length;
1148 args = Array( j );
1149 while ( j-- ) {
1150 args[ j ] = stack.pop();
1151 }
1152
1153 try {
1154 value = getOperatorResult.apply( null, args );
1155 } catch ( earlyReturn ) {
1156 return earlyReturn;
1157 }
1158 } else if ( variables.hasOwnProperty( term ) ) {
1159 value = variables[ term ];
1160 } else {
1161 value = +term;
1162 }
1163
1164 stack.push( value );
1165 }
1166
1167 return stack[ 0 ];
1168 }
1169
1170 module.exports = evaluate;
1171
1172 },{}],19:[function(require,module,exports){
1173 'use strict';
1174
1175 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
1176
1177 var compile = _interopDefault(require('@tannin/compile'));
1178
1179 /**
1180 * Given a C expression, returns a function which, when called with a value,
1181 * evaluates the result with the value assumed to be the "n" variable of the
1182 * expression. The result will be coerced to its numeric equivalent.
1183 *
1184 * @param {string} expression C expression.
1185 *
1186 * @return {Function} Evaluator function.
1187 */
1188 function pluralForms( expression ) {
1189 var evaluate = compile( expression );
1190
1191 return function( n ) {
1192 return +evaluate( { n: n } );
1193 };
1194 }
1195
1196 module.exports = pluralForms;
1197
1198 },{"@tannin/compile":17}],20:[function(require,module,exports){
1199 'use strict';
1200
1201 var PRECEDENCE, OPENERS, TERMINATORS, PATTERN;
1202
1203 /**
1204 * Operator precedence mapping.
1205 *
1206 * @type {Object}
1207 */
1208 PRECEDENCE = {
1209 '(': 9,
1210 '!': 8,
1211 '*': 7,
1212 '/': 7,
1213 '%': 7,
1214 '+': 6,
1215 '-': 6,
1216 '<': 5,
1217 '<=': 5,
1218 '>': 5,
1219 '>=': 5,
1220 '==': 4,
1221 '!=': 4,
1222 '&&': 3,
1223 '||': 2,
1224 '?': 1,
1225 '?:': 1,
1226 };
1227
1228 /**
1229 * Characters which signal pair opening, to be terminated by terminators.
1230 *
1231 * @type {string[]}
1232 */
1233 OPENERS = [ '(', '?' ];
1234
1235 /**
1236 * Characters which signal pair termination, the value an array with the
1237 * opener as its first member. The second member is an optional operator
1238 * replacement to push to the stack.
1239 *
1240 * @type {string[]}
1241 */
1242 TERMINATORS = {
1243 ')': [ '(' ],
1244 ':': [ '?', '?:' ],
1245 };
1246
1247 /**
1248 * Pattern matching operators and openers.
1249 *
1250 * @type {RegExp}
1251 */
1252 PATTERN = /<=|>=|==|!=|&&|\|\||\?:|\(|!|\*|\/|%|\+|-|<|>|\?|\)|:/;
1253
1254 /**
1255 * Given a C expression, returns the equivalent postfix (Reverse Polish)
1256 * notation terms as an array.
1257 *
1258 * If a postfix string is desired, simply `.join( ' ' )` the result.
1259 *
1260 * @example
1261 *
1262 * ```js
1263 * import postfix from '@tannin/postfix';
1264 *
1265 * postfix( 'n > 1' );
1266 * // ⇒ [ 'n', '1', '>' ]
1267 * ```
1268 *
1269 * @param {string} expression C expression.
1270 *
1271 * @return {string[]} Postfix terms.
1272 */
1273 function postfix( expression ) {
1274 var terms = [],
1275 stack = [],
1276 match, operator, term, element;
1277
1278 while ( ( match = expression.match( PATTERN ) ) ) {
1279 operator = match[ 0 ];
1280
1281 // Term is the string preceding the operator match. It may contain
1282 // whitespace, and may be empty (if operator is at beginning).
1283 term = expression.substr( 0, match.index ).trim();
1284 if ( term ) {
1285 terms.push( term );
1286 }
1287
1288 while ( ( element = stack.pop() ) ) {
1289 if ( TERMINATORS[ operator ] ) {
1290 if ( TERMINATORS[ operator ][ 0 ] === element ) {
1291 // Substitution works here under assumption that because
1292 // the assigned operator will no longer be a terminator, it
1293 // will be pushed to the stack during the condition below.
1294 operator = TERMINATORS[ operator ][ 1 ] || operator;
1295 break;
1296 }
1297 } else if ( OPENERS.indexOf( element ) >= 0 || PRECEDENCE[ element ] < PRECEDENCE[ operator ] ) {
1298 // Push to stack if either an opener or when pop reveals an
1299 // element of lower precedence.
1300 stack.push( element );
1301 break;
1302 }
1303
1304 // For each popped from stack, push to terms.
1305 terms.push( element );
1306 }
1307
1308 if ( ! TERMINATORS[ operator ] ) {
1309 stack.push( operator );
1310 }
1311
1312 // Slice matched fragment from expression to continue match.
1313 expression = expression.substr( match.index + operator.length );
1314 }
1315
1316 // Push remainder of operand, if exists, to terms.
1317 expression = expression.trim();
1318 if ( expression ) {
1319 terms.push( expression );
1320 }
1321
1322 // Pop remaining items from stack into terms.
1323 return terms.concat( stack.reverse() );
1324 }
1325
1326 module.exports = postfix;
1327
1328 },{}],21:[function(require,module,exports){
1329 "use strict";
1330
1331 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
1332
1333 Object.defineProperty(exports, "__esModule", {
1334 value: true
1335 });
1336 exports.createI18n = void 0;
1337
1338 var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
1339
1340 var _tannin = _interopRequireDefault(require("tannin"));
1341
1342 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; }
1343
1344 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; }
1345
1346 /**
1347 * @typedef {Record<string,any>} LocaleData
1348 */
1349
1350 /**
1351 * Default locale data to use for Tannin domain when not otherwise provided.
1352 * Assumes an English plural forms expression.
1353 *
1354 * @type {LocaleData}
1355 */
1356 var DEFAULT_LOCALE_DATA = {
1357 '': {
1358 /** @param {number} n */
1359 plural_forms: function plural_forms(n) {
1360 return n === 1 ? 0 : 1;
1361 }
1362 }
1363 };
1364 /**
1365 * An i18n instance
1366 *
1367 * @typedef {Object} I18n
1368 * @property {Function} setLocaleData Merges locale data into the Tannin instance by domain. Accepts data in a
1369 * Jed-formatted JSON object shape.
1370 * @property {Function} __ Retrieve the translation of text.
1371 * @property {Function} _x Retrieve translated string with gettext context.
1372 * @property {Function} _n Translates and retrieves the singular or plural form based on the supplied
1373 * number.
1374 * @property {Function} _nx Translates and retrieves the singular or plural form based on the supplied
1375 * number, with gettext context.
1376 * @property {Function} isRTL Check if current locale is RTL.
1377 */
1378
1379 /**
1380 * Create an i18n instance
1381 *
1382 * @param {LocaleData} [initialData] Locale data configuration.
1383 * @param {string} [initialDomain] Domain for which configuration applies.
1384 * @return {I18n} I18n instance
1385 */
1386
1387 var createI18n = function createI18n(initialData, initialDomain) {
1388 /**
1389 * The underlying instance of Tannin to which exported functions interface.
1390 *
1391 * @type {Tannin}
1392 */
1393 var tannin = new _tannin.default({});
1394 /**
1395 * Merges locale data into the Tannin instance by domain. Accepts data in a
1396 * Jed-formatted JSON object shape.
1397 *
1398 * @see http://messageformat.github.io/Jed/
1399 *
1400 * @param {LocaleData} [data] Locale data configuration.
1401 * @param {string} [domain] Domain for which configuration applies.
1402 */
1403
1404 var setLocaleData = function setLocaleData(data) {
1405 var domain = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
1406 tannin.data[domain] = _objectSpread({}, DEFAULT_LOCALE_DATA, {}, tannin.data[domain], {}, data); // Populate default domain configuration (supported locale date which omits
1407 // a plural forms expression).
1408
1409 tannin.data[domain][''] = _objectSpread({}, DEFAULT_LOCALE_DATA[''], {}, tannin.data[domain]['']);
1410 };
1411 /**
1412 * Wrapper for Tannin's `dcnpgettext`. Populates default locale data if not
1413 * otherwise previously assigned.
1414 *
1415 * @param {string|undefined} domain Domain to retrieve the translated text.
1416 * @param {string|undefined} context Context information for the translators.
1417 * @param {string} single Text to translate if non-plural. Used as
1418 * fallback return value on a caught error.
1419 * @param {string} [plural] The text to be used if the number is
1420 * plural.
1421 * @param {number} [number] The number to compare against to use
1422 * either the singular or plural form.
1423 *
1424 * @return {string} The translated string.
1425 */
1426
1427
1428 var dcnpgettext = function dcnpgettext() {
1429 var domain = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';
1430 var context = arguments.length > 1 ? arguments[1] : undefined;
1431 var single = arguments.length > 2 ? arguments[2] : undefined;
1432 var plural = arguments.length > 3 ? arguments[3] : undefined;
1433 var number = arguments.length > 4 ? arguments[4] : undefined;
1434
1435 if (!tannin.data[domain]) {
1436 setLocaleData(undefined, domain);
1437 }
1438
1439 return tannin.dcnpgettext(domain, context, single, plural, number);
1440 };
1441 /**
1442 * Retrieve the translation of text.
1443 *
1444 * @see https://developer.wordpress.org/reference/functions/__/
1445 *
1446 * @param {string} text Text to translate.
1447 * @param {string} [domain] Domain to retrieve the translated text.
1448 *
1449 * @return {string} Translated text.
1450 */
1451
1452
1453 var __ = function __(text, domain) {
1454 return dcnpgettext(domain, undefined, text);
1455 };
1456 /**
1457 * Retrieve translated string with gettext context.
1458 *
1459 * @see https://developer.wordpress.org/reference/functions/_x/
1460 *
1461 * @param {string} text Text to translate.
1462 * @param {string} context Context information for the translators.
1463 * @param {string} [domain] Domain to retrieve the translated text.
1464 *
1465 * @return {string} Translated context string without pipe.
1466 */
1467
1468
1469 var _x = function _x(text, context, domain) {
1470 return dcnpgettext(domain, context, text);
1471 };
1472 /**
1473 * Translates and retrieves the singular or plural form based on the supplied
1474 * number.
1475 *
1476 * @see https://developer.wordpress.org/reference/functions/_n/
1477 *
1478 * @param {string} single The text to be used if the number is singular.
1479 * @param {string} plural The text to be used if the number is plural.
1480 * @param {number} number The number to compare against to use either the
1481 * singular or plural form.
1482 * @param {string} [domain] Domain to retrieve the translated text.
1483 *
1484 * @return {string} The translated singular or plural form.
1485 */
1486
1487
1488 var _n = function _n(single, plural, number, domain) {
1489 return dcnpgettext(domain, undefined, single, plural, number);
1490 };
1491 /**
1492 * Translates and retrieves the singular or plural form based on the supplied
1493 * number, with gettext context.
1494 *
1495 * @see https://developer.wordpress.org/reference/functions/_nx/
1496 *
1497 * @param {string} single The text to be used if the number is singular.
1498 * @param {string} plural The text to be used if the number is plural.
1499 * @param {number} number The number to compare against to use either the
1500 * singular or plural form.
1501 * @param {string} context Context information for the translators.
1502 * @param {string} [domain] Domain to retrieve the translated text.
1503 *
1504 * @return {string} The translated singular or plural form.
1505 */
1506
1507
1508 var _nx = function _nx(single, plural, number, context, domain) {
1509 return dcnpgettext(domain, context, single, plural, number);
1510 };
1511 /**
1512 * Check if current locale is RTL.
1513 *
1514 * **RTL (Right To Left)** is a locale property indicating that text is written from right to left.
1515 * For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common
1516 * language written RTL. The opposite of RTL, LTR (Left To Right) is used in other languages,
1517 * including English (`en`, `en-US`, `en-GB`, etc.), Spanish (`es`), and French (`fr`).
1518 *
1519 * @return {boolean} Whether locale is RTL.
1520 */
1521
1522
1523 var isRTL = function isRTL() {
1524 return 'rtl' === _x('ltr', 'text direction');
1525 };
1526
1527 if (initialData) {
1528 setLocaleData(initialData, initialDomain);
1529 }
1530
1531 return {
1532 setLocaleData: setLocaleData,
1533 __: __,
1534 _x: _x,
1535 _n: _n,
1536 _nx: _nx,
1537 isRTL: isRTL
1538 };
1539 };
1540
1541 exports.createI18n = createI18n;
1542
1543 },{"@babel/runtime/helpers/defineProperty":15,"@babel/runtime/helpers/interopRequireDefault":16,"tannin":30}],22:[function(require,module,exports){
1544 "use strict";
1545
1546 Object.defineProperty(exports, "__esModule", {
1547 value: true
1548 });
1549 exports.isRTL = exports._nx = exports._n = exports._x = exports.__ = exports.setLocaleData = void 0;
1550
1551 var _createI18n = require("./create-i18n");
1552
1553 /**
1554 * Internal dependencies
1555 */
1556 var i18n = (0, _createI18n.createI18n)();
1557 /*
1558 * Comments in this file are duplicated from ./i18n due to
1559 * https://github.com/WordPress/gutenberg/pull/20318#issuecomment-590837722
1560 */
1561
1562 /**
1563 * @typedef {import('./create-i18n').LocaleData} LocaleData
1564 */
1565
1566 /**
1567 * Merges locale data into the Tannin instance by domain. Accepts data in a
1568 * Jed-formatted JSON object shape.
1569 *
1570 * @see http://messageformat.github.io/Jed/
1571 *
1572 * @param {LocaleData} [data] Locale data configuration.
1573 * @param {string} [domain] Domain for which configuration applies.
1574 */
1575
1576 var setLocaleData = i18n.setLocaleData.bind(i18n);
1577 /**
1578 * Retrieve the translation of text.
1579 *
1580 * @see https://developer.wordpress.org/reference/functions/__/
1581 *
1582 * @param {string} text Text to translate.
1583 * @param {string} [domain] Domain to retrieve the translated text.
1584 *
1585 * @return {string} Translated text.
1586 */
1587
1588 exports.setLocaleData = setLocaleData;
1589
1590 var __ = i18n.__.bind(i18n);
1591 /**
1592 * Retrieve translated string with gettext context.
1593 *
1594 * @see https://developer.wordpress.org/reference/functions/_x/
1595 *
1596 * @param {string} text Text to translate.
1597 * @param {string} context Context information for the translators.
1598 * @param {string} [domain] Domain to retrieve the translated text.
1599 *
1600 * @return {string} Translated context string without pipe.
1601 */
1602
1603
1604 exports.__ = __;
1605
1606 var _x = i18n._x.bind(i18n);
1607 /**
1608 * Translates and retrieves the singular or plural form based on the supplied
1609 * number.
1610 *
1611 * @see https://developer.wordpress.org/reference/functions/_n/
1612 *
1613 * @param {string} single The text to be used if the number is singular.
1614 * @param {string} plural The text to be used if the number is plural.
1615 * @param {number} number The number to compare against to use either the
1616 * singular or plural form.
1617 * @param {string} [domain] Domain to retrieve the translated text.
1618 *
1619 * @return {string} The translated singular or plural form.
1620 */
1621
1622
1623 exports._x = _x;
1624
1625 var _n = i18n._n.bind(i18n);
1626 /**
1627 * Translates and retrieves the singular or plural form based on the supplied
1628 * number, with gettext context.
1629 *
1630 * @see https://developer.wordpress.org/reference/functions/_nx/
1631 *
1632 * @param {string} single The text to be used if the number is singular.
1633 * @param {string} plural The text to be used if the number is plural.
1634 * @param {number} number The number to compare against to use either the
1635 * singular or plural form.
1636 * @param {string} context Context information for the translators.
1637 * @param {string} [domain] Domain to retrieve the translated text.
1638 *
1639 * @return {string} The translated singular or plural form.
1640 */
1641
1642
1643 exports._n = _n;
1644
1645 var _nx = i18n._nx.bind(i18n);
1646 /**
1647 * Check if current locale is RTL.
1648 *
1649 * **RTL (Right To Left)** is a locale property indicating that text is written from right to left.
1650 * For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common
1651 * language written RTL. The opposite of RTL, LTR (Left To Right) is used in other languages,
1652 * including English (`en`, `en-US`, `en-GB`, etc.), Spanish (`es`), and French (`fr`).
1653 *
1654 * @return {boolean} Whether locale is RTL.
1655 */
1656
1657
1658 exports._nx = _nx;
1659 var isRTL = i18n.isRTL.bind(i18n);
1660 exports.isRTL = isRTL;
1661
1662 },{"./create-i18n":21}],23:[function(require,module,exports){
1663 "use strict";
1664
1665 Object.defineProperty(exports, "__esModule", {
1666 value: true
1667 });
1668 var _exportNames = {
1669 sprintf: true,
1670 setLocaleData: true,
1671 __: true,
1672 _x: true,
1673 _n: true,
1674 _nx: true,
1675 isRTL: true
1676 };
1677 Object.defineProperty(exports, "sprintf", {
1678 enumerable: true,
1679 get: function get() {
1680 return _sprintf.sprintf;
1681 }
1682 });
1683 Object.defineProperty(exports, "setLocaleData", {
1684 enumerable: true,
1685 get: function get() {
1686 return _defaultI18n.setLocaleData;
1687 }
1688 });
1689 Object.defineProperty(exports, "__", {
1690 enumerable: true,
1691 get: function get() {
1692 return _defaultI18n.__;
1693 }
1694 });
1695 Object.defineProperty(exports, "_x", {
1696 enumerable: true,
1697 get: function get() {
1698 return _defaultI18n._x;
1699 }
1700 });
1701 Object.defineProperty(exports, "_n", {
1702 enumerable: true,
1703 get: function get() {
1704 return _defaultI18n._n;
1705 }
1706 });
1707 Object.defineProperty(exports, "_nx", {
1708 enumerable: true,
1709 get: function get() {
1710 return _defaultI18n._nx;
1711 }
1712 });
1713 Object.defineProperty(exports, "isRTL", {
1714 enumerable: true,
1715 get: function get() {
1716 return _defaultI18n.isRTL;
1717 }
1718 });
1719
1720 var _sprintf = require("./sprintf");
1721
1722 var _createI18n = require("./create-i18n");
1723
1724 Object.keys(_createI18n).forEach(function (key) {
1725 if (key === "default" || key === "__esModule") return;
1726 if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
1727 Object.defineProperty(exports, key, {
1728 enumerable: true,
1729 get: function get() {
1730 return _createI18n[key];
1731 }
1732 });
1733 });
1734
1735 var _defaultI18n = require("./default-i18n");
1736
1737 },{"./create-i18n":21,"./default-i18n":22,"./sprintf":24}],24:[function(require,module,exports){
1738 "use strict";
1739
1740 var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
1741
1742 Object.defineProperty(exports, "__esModule", {
1743 value: true
1744 });
1745 exports.sprintf = sprintf;
1746
1747 var _memize = _interopRequireDefault(require("memize"));
1748
1749 var _sprintfJs = _interopRequireDefault(require("sprintf-js"));
1750
1751 /**
1752 * External dependencies
1753 */
1754
1755 /**
1756 * Log to console, once per message; or more precisely, per referentially equal
1757 * argument set. Because Jed throws errors, we log these to the console instead
1758 * to avoid crashing the application.
1759 *
1760 * @param {...*} args Arguments to pass to `console.error`
1761 */
1762 var logErrorOnce = (0, _memize.default)(console.error); // eslint-disable-line no-console
1763
1764 /**
1765 * Returns a formatted string. If an error occurs in applying the format, the
1766 * original format string is returned.
1767 *
1768 * @param {string} format The format of the string to generate.
1769 * @param {...*} args Arguments to apply to the format.
1770 *
1771 * @see http://www.diveintojavascript.com/projects/javascript-sprintf
1772 *
1773 * @return {string} The formatted string.
1774 */
1775
1776 function sprintf(format) {
1777 try {
1778 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1779 args[_key - 1] = arguments[_key];
1780 }
1781
1782 return _sprintfJs.default.sprintf.apply(_sprintfJs.default, [format].concat(args));
1783 } catch (error) {
1784 logErrorOnce('sprintf error: \n\n' + error.toString());
1785 return format;
1786 }
1787 }
1788
1789 },{"@babel/runtime/helpers/interopRequireDefault":16,"memize":28,"sprintf-js":25}],25:[function(require,module,exports){
1790 /* global window, exports, define */
1791
1792 !function() {
1793 'use strict'
1794
1795 var re = {
1796 not_string: /[^s]/,
1797 not_bool: /[^t]/,
1798 not_type: /[^T]/,
1799 not_primitive: /[^v]/,
1800 number: /[diefg]/,
1801 numeric_arg: /[bcdiefguxX]/,
1802 json: /[j]/,
1803 not_json: /[^j]/,
1804 text: /^[^\x25]+/,
1805 modulo: /^\x25{2}/,
1806 placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
1807 key: /^([a-z_][a-z_\d]*)/i,
1808 key_access: /^\.([a-z_][a-z_\d]*)/i,
1809 index_access: /^\[(\d+)\]/,
1810 sign: /^[+-]/
1811 }
1812
1813 function sprintf(key) {
1814 // `arguments` is not an array, but should be fine for this call
1815 return sprintf_format(sprintf_parse(key), arguments)
1816 }
1817
1818 function vsprintf(fmt, argv) {
1819 return sprintf.apply(null, [fmt].concat(argv || []))
1820 }
1821
1822 function sprintf_format(parse_tree, argv) {
1823 var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
1824 for (i = 0; i < tree_length; i++) {
1825 if (typeof parse_tree[i] === 'string') {
1826 output += parse_tree[i]
1827 }
1828 else if (typeof parse_tree[i] === 'object') {
1829 ph = parse_tree[i] // convenience purposes only
1830 if (ph.keys) { // keyword argument
1831 arg = argv[cursor]
1832 for (k = 0; k < ph.keys.length; k++) {
1833 if (arg == undefined) {
1834 throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
1835 }
1836 arg = arg[ph.keys[k]]
1837 }
1838 }
1839 else if (ph.param_no) { // positional argument (explicit)
1840 arg = argv[ph.param_no]
1841 }
1842 else { // positional argument (implicit)
1843 arg = argv[cursor++]
1844 }
1845
1846 if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
1847 arg = arg()
1848 }
1849
1850 if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
1851 throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
1852 }
1853
1854 if (re.number.test(ph.type)) {
1855 is_positive = arg >= 0
1856 }
1857
1858 switch (ph.type) {
1859 case 'b':
1860 arg = parseInt(arg, 10).toString(2)
1861 break
1862 case 'c':
1863 arg = String.fromCharCode(parseInt(arg, 10))
1864 break
1865 case 'd':
1866 case 'i':
1867 arg = parseInt(arg, 10)
1868 break
1869 case 'j':
1870 arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
1871 break
1872 case 'e':
1873 arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
1874 break
1875 case 'f':
1876 arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
1877 break
1878 case 'g':
1879 arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
1880 break
1881 case 'o':
1882 arg = (parseInt(arg, 10) >>> 0).toString(8)
1883 break
1884 case 's':
1885 arg = String(arg)
1886 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
1887 break
1888 case 't':
1889 arg = String(!!arg)
1890 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
1891 break
1892 case 'T':
1893 arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
1894 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
1895 break
1896 case 'u':
1897 arg = parseInt(arg, 10) >>> 0
1898 break
1899 case 'v':
1900 arg = arg.valueOf()
1901 arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
1902 break
1903 case 'x':
1904 arg = (parseInt(arg, 10) >>> 0).toString(16)
1905 break
1906 case 'X':
1907 arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
1908 break
1909 }
1910 if (re.json.test(ph.type)) {
1911 output += arg
1912 }
1913 else {
1914 if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
1915 sign = is_positive ? '+' : '-'
1916 arg = arg.toString().replace(re.sign, '')
1917 }
1918 else {
1919 sign = ''
1920 }
1921 pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
1922 pad_length = ph.width - (sign + arg).length
1923 pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
1924 output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
1925 }
1926 }
1927 }
1928 return output
1929 }
1930
1931 var sprintf_cache = Object.create(null)
1932
1933 function sprintf_parse(fmt) {
1934 if (sprintf_cache[fmt]) {
1935 return sprintf_cache[fmt]
1936 }
1937
1938 var _fmt = fmt, match, parse_tree = [], arg_names = 0
1939 while (_fmt) {
1940 if ((match = re.text.exec(_fmt)) !== null) {
1941 parse_tree.push(match[0])
1942 }
1943 else if ((match = re.modulo.exec(_fmt)) !== null) {
1944 parse_tree.push('%')
1945 }
1946 else if ((match = re.placeholder.exec(_fmt)) !== null) {
1947 if (match[2]) {
1948 arg_names |= 1
1949 var field_list = [], replacement_field = match[2], field_match = []
1950 if ((field_match = re.key.exec(replacement_field)) !== null) {
1951 field_list.push(field_match[1])
1952 while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
1953 if ((field_match = re.key_access.exec(replacement_field)) !== null) {
1954 field_list.push(field_match[1])
1955 }
1956 else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
1957 field_list.push(field_match[1])
1958 }
1959 else {
1960 throw new SyntaxError('[sprintf] failed to parse named argument key')
1961 }
1962 }
1963 }
1964 else {
1965 throw new SyntaxError('[sprintf] failed to parse named argument key')
1966 }
1967 match[2] = field_list
1968 }
1969 else {
1970 arg_names |= 2
1971 }
1972 if (arg_names === 3) {
1973 throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
1974 }
1975
1976 parse_tree.push(
1977 {
1978 placeholder: match[0],
1979 param_no: match[1],
1980 keys: match[2],
1981 sign: match[3],
1982 pad_char: match[4],
1983 align: match[5],
1984 width: match[6],
1985 precision: match[7],
1986 type: match[8]
1987 }
1988 )
1989 }
1990 else {
1991 throw new SyntaxError('[sprintf] unexpected placeholder')
1992 }
1993 _fmt = _fmt.substring(match[0].length)
1994 }
1995 return sprintf_cache[fmt] = parse_tree
1996 }
1997
1998 /**
1999 * export to either browser or node.js
2000 */
2001 /* eslint-disable quote-props */
2002 if (typeof exports !== 'undefined') {
2003 exports['sprintf'] = sprintf
2004 exports['vsprintf'] = vsprintf
2005 }
2006 if (typeof window !== 'undefined') {
2007 window['sprintf'] = sprintf
2008 window['vsprintf'] = vsprintf
2009
2010 if (typeof define === 'function' && define['amd']) {
2011 define(function() {
2012 return {
2013 'sprintf': sprintf,
2014 'vsprintf': vsprintf
2015 }
2016 })
2017 }
2018 }
2019 /* eslint-enable quote-props */
2020 }(); // eslint-disable-line
2021
2022 },{}],26:[function(require,module,exports){
2023 /*
2024 * International Telephone Input v17.0.16
2025 * https://github.com/jackocnr/intl-tel-input.git
2026 * Licensed under the MIT license
2027 */
2028
2029 // wrap in UMD
2030 (function(factory) {
2031 if (typeof module === "object" && module.exports) module.exports = factory(); else window.intlTelInput = factory();
2032 })(function(undefined) {
2033 "use strict";
2034 return function() {
2035 // Array of country objects for the flag dropdown.
2036 // Here is the criteria for the plugin to support a given country/territory
2037 // - It has an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
2038 // - 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
2039 // - It has a flag in the region-flags project: https://github.com/behdad/region-flags/tree/gh-pages/png
2040 // - It is supported by libphonenumber (it must be listed on this page): https://github.com/googlei18n/libphonenumber/blob/master/resources/ShortNumberMetadata.xml
2041 // Each country array has the following information:
2042 // [
2043 // Country name,
2044 // iso2 code,
2045 // International dial code,
2046 // Order (if >1 country with same dial code),
2047 // Area codes
2048 // ]
2049 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 (‫جزر الق�
2050 ر‬‎)", "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 (‫�
2051 صر‬‎)", "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 (Каза�
2052 стан)", "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 (‫�
2053 وريتانيا‬‎)", "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 (‫ال�
2054 غرب‬‎)", "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 (‫عُ�
2055 ان‬‎)", "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 (‫ال�
2056
2057 لكة العربية السعودية‬‎)", "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 (‫الإ�
2058 ارات العربية ال�
2059 تحدة‬‎)", "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 (‫الي�
2060 ن‬‎)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ], [ "�
2061 land Islands", "ax", "358", 1, [ "18" ] ] ];
2062 // loop over all of the countries above, restructuring the data to be objects with named keys
2063 for (var i = 0; i < allCountries.length; i++) {
2064 var c = allCountries[i];
2065 allCountries[i] = {
2066 name: c[0],
2067 iso2: c[1],
2068 dialCode: c[2],
2069 priority: c[3] || 0,
2070 areaCodes: c[4] || null
2071 };
2072 }
2073 "use strict";
2074 function _classCallCheck(instance, Constructor) {
2075 if (!(instance instanceof Constructor)) {
2076 throw new TypeError("Cannot call a class as a function");
2077 }
2078 }
2079 function _defineProperties(target, props) {
2080 for (var i = 0; i < props.length; i++) {
2081 var descriptor = props[i];
2082 descriptor.enumerable = descriptor.enumerable || false;
2083 descriptor.configurable = true;
2084 if ("value" in descriptor) descriptor.writable = true;
2085 Object.defineProperty(target, descriptor.key, descriptor);
2086 }
2087 }
2088 function _createClass(Constructor, protoProps, staticProps) {
2089 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
2090 if (staticProps) _defineProperties(Constructor, staticProps);
2091 return Constructor;
2092 }
2093 var intlTelInputGlobals = {
2094 getInstance: function getInstance(input) {
2095 var id = input.getAttribute("data-intl-tel-input-id");
2096 return window.intlTelInputGlobals.instances[id];
2097 },
2098 instances: {},
2099 // using a global like this allows us to mock it in the tests
2100 documentReady: function documentReady() {
2101 return document.readyState === "complete";
2102 }
2103 };
2104 if (typeof window === "object") window.intlTelInputGlobals = intlTelInputGlobals;
2105 // these vars persist through all instances of the plugin
2106 var id = 0;
2107 var defaults = {
2108 // whether or not to allow the dropdown
2109 allowDropdown: true,
2110 // if there is just a dial code in the input: remove it on blur
2111 autoHideDialCode: true,
2112 // add a placeholder in the input with an example number for the selected country
2113 autoPlaceholder: "polite",
2114 // modify the parentClass
2115 customContainer: "",
2116 // modify the auto placeholder
2117 customPlaceholder: null,
2118 // append menu to specified element
2119 dropdownContainer: null,
2120 // don't display these countries
2121 excludeCountries: [],
2122 // format the input value during initialisation and on setNumber
2123 formatOnDisplay: true,
2124 // geoIp lookup function
2125 geoIpLookup: null,
2126 // inject a hidden input with this name, and on submit, populate it with the result of getNumber
2127 hiddenInput: "",
2128 // initial country
2129 initialCountry: "",
2130 // localized country names e.g. { 'de': 'Deutschland' }
2131 localizedCountries: null,
2132 // don't insert international dial codes
2133 nationalMode: true,
2134 // display only these countries
2135 onlyCountries: [],
2136 // number type to use for placeholders
2137 placeholderNumberType: "MOBILE",
2138 // the countries at the top of the list. defaults to united states and united kingdom
2139 preferredCountries: [ "us", "gb" ],
2140 // display the country dial code next to the selected flag so it's not part of the typed number
2141 separateDialCode: false,
2142 // specify the path to the libphonenumber script to enable validation/formatting
2143 utilsScript: ""
2144 };
2145 // https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes#Non-geographic_area_codes
2146 var regionlessNanpNumbers = [ "800", "822", "833", "844", "855", "866", "877", "880", "881", "882", "883", "884", "885", "886", "887", "888", "889" ];
2147 // utility function to iterate over an object. can't use Object.entries or native forEach because
2148 // of IE11
2149 var forEachProp = function forEachProp(obj, callback) {
2150 var keys = Object.keys(obj);
2151 for (var i = 0; i < keys.length; i++) {
2152 callback(keys[i], obj[keys[i]]);
2153 }
2154 };
2155 // run a method on each instance of the plugin
2156 var forEachInstance = function forEachInstance(method) {
2157 forEachProp(window.intlTelInputGlobals.instances, function(key) {
2158 window.intlTelInputGlobals.instances[key][method]();
2159 });
2160 };
2161 // this is our plugin class that we will create an instance of
2162 // eslint-disable-next-line no-unused-vars
2163 var Iti = /*#__PURE__*/
2164 function() {
2165 function Iti(input, options) {
2166 var _this = this;
2167 _classCallCheck(this, Iti);
2168 this.id = id++;
2169 this.telInput = input;
2170 this.activeItem = null;
2171 this.highlightedItem = null;
2172 // process specified options / defaults
2173 // alternative to Object.assign, which isn't supported by IE11
2174 var customOptions = options || {};
2175 this.options = {};
2176 forEachProp(defaults, function(key, value) {
2177 _this.options[key] = customOptions.hasOwnProperty(key) ? customOptions[key] : value;
2178 });
2179 this.hadInitialPlaceholder = Boolean(input.getAttribute("placeholder"));
2180 }
2181 _createClass(Iti, [ {
2182 key: "_init",
2183 value: function _init() {
2184 var _this2 = this;
2185 // if in nationalMode, disable options relating to dial codes
2186 if (this.options.nationalMode) this.options.autoHideDialCode = false;
2187 // if separateDialCode then doesn't make sense to A) insert dial code into input
2188 // (autoHideDialCode), and B) display national numbers (because we're displaying the country
2189 // dial code next to them)
2190 if (this.options.separateDialCode) {
2191 this.options.autoHideDialCode = this.options.nationalMode = false;
2192 }
2193 // we cannot just test screen size as some smartphones/website meta tags will report desktop
2194 // resolutions
2195 // Note: for some reason jasmine breaks if you put this in the main Plugin function with the
2196 // rest of these declarations
2197 // Note: to target Android Mobiles (and not Tablets), we must find 'Android' and 'Mobile'
2198 this.isMobile = /Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
2199 if (this.isMobile) {
2200 // trigger the mobile dropdown css
2201 document.body.classList.add("iti-mobile");
2202 // on mobile, we want a full screen dropdown, so we must append it to the body
2203 if (!this.options.dropdownContainer) this.options.dropdownContainer = document.body;
2204 }
2205 // these promises get resolved when their individual requests complete
2206 // this way the dev can do something like iti.promise.then(...) to know when all requests are
2207 // complete
2208 if (typeof Promise !== "undefined") {
2209 var autoCountryPromise = new Promise(function(resolve, reject) {
2210 _this2.resolveAutoCountryPromise = resolve;
2211 _this2.rejectAutoCountryPromise = reject;
2212 });
2213 var utilsScriptPromise = new Promise(function(resolve, reject) {
2214 _this2.resolveUtilsScriptPromise = resolve;
2215 _this2.rejectUtilsScriptPromise = reject;
2216 });
2217 this.promise = Promise.all([ autoCountryPromise, utilsScriptPromise ]);
2218 } else {
2219 // prevent errors when Promise doesn't exist
2220 this.resolveAutoCountryPromise = this.rejectAutoCountryPromise = function() {};
2221 this.resolveUtilsScriptPromise = this.rejectUtilsScriptPromise = function() {};
2222 }
2223 // in various situations there could be no country selected initially, but we need to be able
2224 // to assume this variable exists
2225 this.selectedCountryData = {};
2226 // process all the data: onlyCountries, excludeCountries, preferredCountries etc
2227 this._processCountryData();
2228 // generate the markup
2229 this._generateMarkup();
2230 // set the initial state of the input value and the selected flag
2231 this._setInitialState();
2232 // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click
2233 this._initListeners();
2234 // utils script, and auto country
2235 this._initRequests();
2236 }
2237 }, {
2238 key: "_processCountryData",
2239 value: function _processCountryData() {
2240 // process onlyCountries or excludeCountries array if present
2241 this._processAllCountries();
2242 // process the countryCodes map
2243 this._processCountryCodes();
2244 // process the preferredCountries
2245 this._processPreferredCountries();
2246 // translate countries according to localizedCountries option
2247 if (this.options.localizedCountries) this._translateCountriesByLocale();
2248 // sort countries by name
2249 if (this.options.onlyCountries.length || this.options.localizedCountries) {
2250 this.countries.sort(this._countryNameSort);
2251 }
2252 }
2253 }, {
2254 key: "_addCountryCode",
2255 value: function _addCountryCode(iso2, countryCode, priority) {
2256 if (countryCode.length > this.countryCodeMaxLen) {
2257 this.countryCodeMaxLen = countryCode.length;
2258 }
2259 if (!this.countryCodes.hasOwnProperty(countryCode)) {
2260 this.countryCodes[countryCode] = [];
2261 }
2262 // bail if we already have this country for this countryCode
2263 for (var i = 0; i < this.countryCodes[countryCode].length; i++) {
2264 if (this.countryCodes[countryCode][i] === iso2) return;
2265 }
2266 // check for undefined as 0 is falsy
2267 var index = priority !== undefined ? priority : this.countryCodes[countryCode].length;
2268 this.countryCodes[countryCode][index] = iso2;
2269 }
2270 }, {
2271 key: "_processAllCountries",
2272 value: function _processAllCountries() {
2273 if (this.options.onlyCountries.length) {
2274 var lowerCaseOnlyCountries = this.options.onlyCountries.map(function(country) {
2275 return country.toLowerCase();
2276 });
2277 this.countries = allCountries.filter(function(country) {
2278 return lowerCaseOnlyCountries.indexOf(country.iso2) > -1;
2279 });
2280 } else if (this.options.excludeCountries.length) {
2281 var lowerCaseExcludeCountries = this.options.excludeCountries.map(function(country) {
2282 return country.toLowerCase();
2283 });
2284 this.countries = allCountries.filter(function(country) {
2285 return lowerCaseExcludeCountries.indexOf(country.iso2) === -1;
2286 });
2287 } else {
2288 this.countries = allCountries;
2289 }
2290 }
2291 }, {
2292 key: "_translateCountriesByLocale",
2293 value: function _translateCountriesByLocale() {
2294 for (var i = 0; i < this.countries.length; i++) {
2295 var iso = this.countries[i].iso2.toLowerCase();
2296 if (this.options.localizedCountries.hasOwnProperty(iso)) {
2297 this.countries[i].name = this.options.localizedCountries[iso];
2298 }
2299 }
2300 }
2301 }, {
2302 key: "_countryNameSort",
2303 value: function _countryNameSort(a, b) {
2304 return a.name.localeCompare(b.name);
2305 }
2306 }, {
2307 key: "_processCountryCodes",
2308 value: function _processCountryCodes() {
2309 this.countryCodeMaxLen = 0;
2310 // here we store just dial codes
2311 this.dialCodes = {};
2312 // here we store "country codes" (both dial codes and their area codes)
2313 this.countryCodes = {};
2314 // first: add dial codes
2315 for (var i = 0; i < this.countries.length; i++) {
2316 var c = this.countries[i];
2317 if (!this.dialCodes[c.dialCode]) this.dialCodes[c.dialCode] = true;
2318 this._addCountryCode(c.iso2, c.dialCode, c.priority);
2319 }
2320 // next: add area codes
2321 // this is a second loop over countries, to make sure we have all of the "root" countries
2322 // already in the map, so that we can access them, as each time we add an area code substring
2323 // to the map, we also need to include the "root" country's code, as that also matches
2324 for (var _i = 0; _i < this.countries.length; _i++) {
2325 var _c = this.countries[_i];
2326 // area codes
2327 if (_c.areaCodes) {
2328 var rootCountryCode = this.countryCodes[_c.dialCode][0];
2329 // for each area code
2330 for (var j = 0; j < _c.areaCodes.length; j++) {
2331 var areaCode = _c.areaCodes[j];
2332 // for each digit in the area code to add all partial matches as well
2333 for (var k = 1; k < areaCode.length; k++) {
2334 var partialDialCode = _c.dialCode + areaCode.substr(0, k);
2335 // start with the root country, as that also matches this dial code
2336 this._addCountryCode(rootCountryCode, partialDialCode);
2337 this._addCountryCode(_c.iso2, partialDialCode);
2338 }
2339 // add the full area code
2340 this._addCountryCode(_c.iso2, _c.dialCode + areaCode);
2341 }
2342 }
2343 }
2344 }
2345 }, {
2346 key: "_processPreferredCountries",
2347 value: function _processPreferredCountries() {
2348 this.preferredCountries = [];
2349 for (var i = 0; i < this.options.preferredCountries.length; i++) {
2350 var countryCode = this.options.preferredCountries[i].toLowerCase();
2351 var countryData = this._getCountryData(countryCode, false, true);
2352 if (countryData) this.preferredCountries.push(countryData);
2353 }
2354 }
2355 }, {
2356 key: "_createEl",
2357 value: function _createEl(name, attrs, container) {
2358 var el = document.createElement(name);
2359 if (attrs) forEachProp(attrs, function(key, value) {
2360 return el.setAttribute(key, value);
2361 });
2362 if (container) container.appendChild(el);
2363 return el;
2364 }
2365 }, {
2366 key: "_generateMarkup",
2367 value: function _generateMarkup() {
2368 // if autocomplete does not exist on the element and its form, then
2369 // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can
2370 // easily put the plugin in an inconsistent state e.g. the wrong flag selected for the
2371 // autocompleted number, which on submit could mean wrong number is saved (esp in nationalMode)
2372 if (!this.telInput.hasAttribute("autocomplete") && !(this.telInput.form && this.telInput.form.hasAttribute("autocomplete"))) {
2373 this.telInput.setAttribute("autocomplete", "off");
2374 }
2375 // containers (mostly for positioning)
2376 var parentClass = "iti";
2377 if (this.options.allowDropdown) parentClass += " iti--allow-dropdown";
2378 if (this.options.separateDialCode) parentClass += " iti--separate-dial-code";
2379 if (this.options.customContainer) {
2380 parentClass += " ";
2381 parentClass += this.options.customContainer;
2382 }
2383 var wrapper = this._createEl("div", {
2384 "class": parentClass
2385 });
2386 this.telInput.parentNode.insertBefore(wrapper, this.telInput);
2387 this.flagsContainer = this._createEl("div", {
2388 "class": "iti__flag-container"
2389 }, wrapper);
2390 wrapper.appendChild(this.telInput);
2391 // selected flag (displayed to left of input)
2392 this.selectedFlag = this._createEl("div", {
2393 "class": "iti__selected-flag",
2394 role: "combobox",
2395 "aria-controls": "iti-".concat(this.id, "__country-listbox"),
2396 "aria-owns": "iti-".concat(this.id, "__country-listbox"),
2397 "aria-expanded": "false"
2398 }, this.flagsContainer);
2399 this.selectedFlagInner = this._createEl("div", {
2400 "class": "iti__flag"
2401 }, this.selectedFlag);
2402 if (this.options.separateDialCode) {
2403 this.selectedDialCode = this._createEl("div", {
2404 "class": "iti__selected-dial-code"
2405 }, this.selectedFlag);
2406 }
2407 if (this.options.allowDropdown) {
2408 // make element focusable and tab navigable
2409 this.selectedFlag.setAttribute("tabindex", "0");
2410 this.dropdownArrow = this._createEl("div", {
2411 "class": "iti__arrow"
2412 }, this.selectedFlag);
2413 // country dropdown: preferred countries, then divider, then all countries
2414 this.countryList = this._createEl("ul", {
2415 "class": "iti__country-list iti__hide",
2416 id: "iti-".concat(this.id, "__country-listbox"),
2417 role: "listbox",
2418 "aria-label": "List of countries"
2419 });
2420 if (this.preferredCountries.length) {
2421 this._appendListItems(this.preferredCountries, "iti__preferred", true);
2422 this._createEl("li", {
2423 "class": "iti__divider",
2424 role: "separator",
2425 "aria-disabled": "true"
2426 }, this.countryList);
2427 }
2428 this._appendListItems(this.countries, "iti__standard");
2429 // create dropdownContainer markup
2430 if (this.options.dropdownContainer) {
2431 this.dropdown = this._createEl("div", {
2432 "class": "iti iti--container"
2433 });
2434 this.dropdown.appendChild(this.countryList);
2435 } else {
2436 this.flagsContainer.appendChild(this.countryList);
2437 }
2438 }
2439 if (this.options.hiddenInput) {
2440 var hiddenInputName = this.options.hiddenInput;
2441 var name = this.telInput.getAttribute("name");
2442 if (name) {
2443 var i = name.lastIndexOf("[");
2444 // if input name contains square brackets, then give the hidden input the same name,
2445 // replacing the contents of the last set of brackets with the given hiddenInput name
2446 if (i !== -1) hiddenInputName = "".concat(name.substr(0, i), "[").concat(hiddenInputName, "]");
2447 }
2448 this.hiddenInput = this._createEl("input", {
2449 type: "hidden",
2450 name: hiddenInputName
2451 });
2452 wrapper.appendChild(this.hiddenInput);
2453 }
2454 }
2455 }, {
2456 key: "_appendListItems",
2457 value: function _appendListItems(countries, className, preferred) {
2458 // we create so many DOM elements, it is faster to build a temp string
2459 // and then add everything to the DOM in one go at the end
2460 var tmp = "";
2461 // for each country
2462 for (var i = 0; i < countries.length; i++) {
2463 var c = countries[i];
2464 var idSuffix = preferred ? "-preferred" : "";
2465 // open the list item
2466 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'>");
2467 // add the flag
2468 tmp += "<div class='iti__flag-box'><div class='iti__flag iti__".concat(c.iso2, "'></div></div>");
2469 // and the country name and dial code
2470 tmp += "<span class='iti__country-name'>".concat(c.name, "</span>");
2471 tmp += "<span class='iti__dial-code'>+".concat(c.dialCode, "</span>");
2472 // close the list item
2473 tmp += "</li>";
2474 }
2475 this.countryList.insertAdjacentHTML("beforeend", tmp);
2476 }
2477 }, {
2478 key: "_setInitialState",
2479 value: function _setInitialState() {
2480 // fix firefox bug: when first load page (with input with value set to number with intl dial
2481 // code) and initialising plugin removes the dial code from the input, then refresh page,
2482 // and we try to init plugin again but this time on number without dial code so get grey flag
2483 var attributeValue = this.telInput.getAttribute("value");
2484 var inputValue = this.telInput.value;
2485 var useAttribute = attributeValue && attributeValue.charAt(0) === "+" && (!inputValue || inputValue.charAt(0) !== "+");
2486 var val = useAttribute ? attributeValue : inputValue;
2487 var dialCode = this._getDialCode(val);
2488 var isRegionlessNanp = this._isRegionlessNanp(val);
2489 var _this$options = this.options, initialCountry = _this$options.initialCountry, nationalMode = _this$options.nationalMode, autoHideDialCode = _this$options.autoHideDialCode, separateDialCode = _this$options.separateDialCode;
2490 // if we already have a dial code, and it's not a regionlessNanp, we can go ahead and set the
2491 // flag, else fall back to the default country
2492 if (dialCode && !isRegionlessNanp) {
2493 this._updateFlagFromNumber(val);
2494 } else if (initialCountry !== "auto") {
2495 // see if we should select a flag
2496 if (initialCountry) {
2497 this._setFlag(initialCountry.toLowerCase());
2498 } else {
2499 if (dialCode && isRegionlessNanp) {
2500 // has intl dial code, is regionless nanp, and no initialCountry, so default to US
2501 this._setFlag("us");
2502 } else {
2503 // no dial code and no initialCountry, so default to first in list
2504 this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2;
2505 if (!val) {
2506 this._setFlag(this.defaultCountry);
2507 }
2508 }
2509 }
2510 // if empty and no nationalMode and no autoHideDialCode then insert the default dial code
2511 if (!val && !nationalMode && !autoHideDialCode && !separateDialCode) {
2512 this.telInput.value = "+".concat(this.selectedCountryData.dialCode);
2513 }
2514 }
2515 // NOTE: if initialCountry is set to auto, that will be handled separately
2516 // format - note this wont be run after _updateDialCode as that's only called if no val
2517 if (val) this._updateValFromNumber(val);
2518 }
2519 }, {
2520 key: "_initListeners",
2521 value: function _initListeners() {
2522 this._initKeyListeners();
2523 if (this.options.autoHideDialCode) this._initBlurListeners();
2524 if (this.options.allowDropdown) this._initDropdownListeners();
2525 if (this.hiddenInput) this._initHiddenInputListener();
2526 }
2527 }, {
2528 key: "_initHiddenInputListener",
2529 value: function _initHiddenInputListener() {
2530 var _this3 = this;
2531 this._handleHiddenInputSubmit = function() {
2532 _this3.hiddenInput.value = _this3.getNumber();
2533 };
2534 if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleHiddenInputSubmit);
2535 }
2536 }, {
2537 key: "_getClosestLabel",
2538 value: function _getClosestLabel() {
2539 var el = this.telInput;
2540 while (el && el.tagName !== "LABEL") {
2541 el = el.parentNode;
2542 }
2543 return el;
2544 }
2545 }, {
2546 key: "_initDropdownListeners",
2547 value: function _initDropdownListeners() {
2548 var _this4 = this;
2549 // hack for input nested inside label (which is valid markup): clicking the selected-flag to
2550 // open the dropdown would then automatically trigger a 2nd click on the input which would
2551 // close it again
2552 this._handleLabelClick = function(e) {
2553 // if the dropdown is closed, then focus the input, else ignore the click
2554 if (_this4.countryList.classList.contains("iti__hide")) _this4.telInput.focus(); else e.preventDefault();
2555 };
2556 var label = this._getClosestLabel();
2557 if (label) label.addEventListener("click", this._handleLabelClick);
2558 // toggle country dropdown on click
2559 this._handleClickSelectedFlag = function() {
2560 // only intercept this event if we're opening the dropdown
2561 // else let it bubble up to the top ("click-off-to-close" listener)
2562 // we cannot just stopPropagation as it may be needed to close another instance
2563 if (_this4.countryList.classList.contains("iti__hide") && !_this4.telInput.disabled && !_this4.telInput.readOnly) {
2564 _this4._showDropdown();
2565 }
2566 };
2567 this.selectedFlag.addEventListener("click", this._handleClickSelectedFlag);
2568 // open dropdown list if currently focused
2569 this._handleFlagsContainerKeydown = function(e) {
2570 var isDropdownHidden = _this4.countryList.classList.contains("iti__hide");
2571 if (isDropdownHidden && [ "ArrowUp", "Up", "ArrowDown", "Down", " ", "Enter" ].indexOf(e.key) !== -1) {
2572 // prevent form from being submitted if "ENTER" was pressed
2573 e.preventDefault();
2574 // prevent event from being handled again by document
2575 e.stopPropagation();
2576 _this4._showDropdown();
2577 }
2578 // allow navigation from dropdown to input on TAB
2579 if (e.key === "Tab") _this4._closeDropdown();
2580 };
2581 this.flagsContainer.addEventListener("keydown", this._handleFlagsContainerKeydown);
2582 }
2583 }, {
2584 key: "_initRequests",
2585 value: function _initRequests() {
2586 var _this5 = this;
2587 // if the user has specified the path to the utils script, fetch it on window.load, else resolve
2588 if (this.options.utilsScript && !window.intlTelInputUtils) {
2589 // if the plugin is being initialised after the window.load event has already been fired
2590 if (window.intlTelInputGlobals.documentReady()) {
2591 window.intlTelInputGlobals.loadUtils(this.options.utilsScript);
2592 } else {
2593 // wait until the load event so we don't block any other requests e.g. the flags image
2594 window.addEventListener("load", function() {
2595 window.intlTelInputGlobals.loadUtils(_this5.options.utilsScript);
2596 });
2597 }
2598 } else this.resolveUtilsScriptPromise();
2599 if (this.options.initialCountry === "auto") this._loadAutoCountry(); else this.resolveAutoCountryPromise();
2600 }
2601 }, {
2602 key: "_loadAutoCountry",
2603 value: function _loadAutoCountry() {
2604 // 3 options:
2605 // 1) already loaded (we're done)
2606 // 2) not already started loading (start)
2607 // 3) already started loading (do nothing - just wait for loading callback to fire)
2608 if (window.intlTelInputGlobals.autoCountry) {
2609 this.handleAutoCountry();
2610 } else if (!window.intlTelInputGlobals.startedLoadingAutoCountry) {
2611 // don't do this twice!
2612 window.intlTelInputGlobals.startedLoadingAutoCountry = true;
2613 if (typeof this.options.geoIpLookup === "function") {
2614 this.options.geoIpLookup(function(countryCode) {
2615 window.intlTelInputGlobals.autoCountry = countryCode.toLowerCase();
2616 // tell all instances the auto country is ready
2617 // TODO: this should just be the current instances
2618 // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight
2619 // away (e.g. if they have already done the geo ip lookup somewhere else). Using
2620 // setTimeout means that the current thread of execution will finish before executing
2621 // this, which allows the plugin to finish initialising.
2622 setTimeout(function() {
2623 return forEachInstance("handleAutoCountry");
2624 });
2625 }, function() {
2626 return forEachInstance("rejectAutoCountryPromise");
2627 });
2628 }
2629 }
2630 }
2631 }, {
2632 key: "_initKeyListeners",
2633 value: function _initKeyListeners() {
2634 var _this6 = this;
2635 // update flag on keyup
2636 this._handleKeyupEvent = function() {
2637 if (_this6._updateFlagFromNumber(_this6.telInput.value)) {
2638 _this6._triggerCountryChange();
2639 }
2640 };
2641 this.telInput.addEventListener("keyup", this._handleKeyupEvent);
2642 // update flag on cut/paste events (now supported in all major browsers)
2643 this._handleClipboardEvent = function() {
2644 // hack because "paste" event is fired before input is updated
2645 setTimeout(_this6._handleKeyupEvent);
2646 };
2647 this.telInput.addEventListener("cut", this._handleClipboardEvent);
2648 this.telInput.addEventListener("paste", this._handleClipboardEvent);
2649 }
2650 }, {
2651 key: "_cap",
2652 value: function _cap(number) {
2653 var max = this.telInput.getAttribute("maxlength");
2654 return max && number.length > max ? number.substr(0, max) : number;
2655 }
2656 }, {
2657 key: "_initBlurListeners",
2658 value: function _initBlurListeners() {
2659 var _this7 = this;
2660 // on blur or form submit: if just a dial code then remove it
2661 this._handleSubmitOrBlurEvent = function() {
2662 _this7._removeEmptyDialCode();
2663 };
2664 if (this.telInput.form) this.telInput.form.addEventListener("submit", this._handleSubmitOrBlurEvent);
2665 this.telInput.addEventListener("blur", this._handleSubmitOrBlurEvent);
2666 }
2667 }, {
2668 key: "_removeEmptyDialCode",
2669 value: function _removeEmptyDialCode() {
2670 if (this.telInput.value.charAt(0) === "+") {
2671 var numeric = this._getNumeric(this.telInput.value);
2672 // if just a plus, or if just a dial code
2673 if (!numeric || this.selectedCountryData.dialCode === numeric) {
2674 this.telInput.value = "";
2675 }
2676 }
2677 }
2678 }, {
2679 key: "_getNumeric",
2680 value: function _getNumeric(s) {
2681 return s.replace(/\D/g, "");
2682 }
2683 }, {
2684 key: "_trigger",
2685 value: function _trigger(name) {
2686 // have to use old school document.createEvent as IE11 doesn't support `new Event()` syntax
2687 var e = document.createEvent("Event");
2688 e.initEvent(name, true, true);
2689 // can bubble, and is cancellable
2690 this.telInput.dispatchEvent(e);
2691 }
2692 }, {
2693 key: "_showDropdown",
2694 value: function _showDropdown() {
2695 this.countryList.classList.remove("iti__hide");
2696 this.selectedFlag.setAttribute("aria-expanded", "true");
2697 this._setDropdownPosition();
2698 // update highlighting and scroll to active list item
2699 if (this.activeItem) {
2700 this._highlightListItem(this.activeItem, false);
2701 this._scrollTo(this.activeItem, true);
2702 }
2703 // bind all the dropdown-related listeners: mouseover, click, click-off, keydown
2704 this._bindDropdownListeners();
2705 // update the arrow
2706 this.dropdownArrow.classList.add("iti__arrow--up");
2707 this._trigger("open:countrydropdown");
2708 }
2709 }, {
2710 key: "_toggleClass",
2711 value: function _toggleClass(el, className, shouldHaveClass) {
2712 if (shouldHaveClass && !el.classList.contains(className)) el.classList.add(className); else if (!shouldHaveClass && el.classList.contains(className)) el.classList.remove(className);
2713 }
2714 }, {
2715 key: "_setDropdownPosition",
2716 value: function _setDropdownPosition() {
2717 var _this8 = this;
2718 if (this.options.dropdownContainer) {
2719 this.options.dropdownContainer.appendChild(this.dropdown);
2720 }
2721 if (!this.isMobile) {
2722 var pos = this.telInput.getBoundingClientRect();
2723 // windowTop from https://stackoverflow.com/a/14384091/217866
2724 var windowTop = window.pageYOffset || document.documentElement.scrollTop;
2725 var inputTop = pos.top + windowTop;
2726 var dropdownHeight = this.countryList.offsetHeight;
2727 // dropdownFitsBelow = (dropdownBottom < windowBottom)
2728 var dropdownFitsBelow = inputTop + this.telInput.offsetHeight + dropdownHeight < windowTop + window.innerHeight;
2729 var dropdownFitsAbove = inputTop - dropdownHeight > windowTop;
2730 // by default, the dropdown will be below the input. If we want to position it above the
2731 // input, we add the dropup class.
2732 this._toggleClass(this.countryList, "iti__country-list--dropup", !dropdownFitsBelow && dropdownFitsAbove);
2733 // if dropdownContainer is enabled, calculate postion
2734 if (this.options.dropdownContainer) {
2735 // by default the dropdown will be directly over the input because it's not in the flow.
2736 // If we want to position it below, we need to add some extra top value.
2737 var extraTop = !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.offsetHeight;
2738 // calculate placement
2739 this.dropdown.style.top = "".concat(inputTop + extraTop, "px");
2740 this.dropdown.style.left = "".concat(pos.left + document.body.scrollLeft, "px");
2741 // close menu on window scroll
2742 this._handleWindowScroll = function() {
2743 return _this8._closeDropdown();
2744 };
2745 window.addEventListener("scroll", this._handleWindowScroll);
2746 }
2747 }
2748 }
2749 }, {
2750 key: "_getClosestListItem",
2751 value: function _getClosestListItem(target) {
2752 var el = target;
2753 while (el && el !== this.countryList && !el.classList.contains("iti__country")) {
2754 el = el.parentNode;
2755 }
2756 // if we reached the countryList element, then return null
2757 return el === this.countryList ? null : el;
2758 }
2759 }, {
2760 key: "_bindDropdownListeners",
2761 value: function _bindDropdownListeners() {
2762 var _this9 = this;
2763 // when mouse over a list item, just highlight that one
2764 // we add the class "highlight", so if they hit "enter" we know which one to select
2765 this._handleMouseoverCountryList = function(e) {
2766 // handle event delegation, as we're listening for this event on the countryList
2767 var listItem = _this9._getClosestListItem(e.target);
2768 if (listItem) _this9._highlightListItem(listItem, false);
2769 };
2770 this.countryList.addEventListener("mouseover", this._handleMouseoverCountryList);
2771 // listen for country selection
2772 this._handleClickCountryList = function(e) {
2773 var listItem = _this9._getClosestListItem(e.target);
2774 if (listItem) _this9._selectListItem(listItem);
2775 };
2776 this.countryList.addEventListener("click", this._handleClickCountryList);
2777 // click off to close
2778 // (except when this initial opening click is bubbling up)
2779 // we cannot just stopPropagation as it may be needed to close another instance
2780 var isOpening = true;
2781 this._handleClickOffToClose = function() {
2782 if (!isOpening) _this9._closeDropdown();
2783 isOpening = false;
2784 };
2785 document.documentElement.addEventListener("click", this._handleClickOffToClose);
2786 // listen for up/down scrolling, enter to select, or letters to jump to country name.
2787 // use keydown as keypress doesn't fire for non-char keys and we want to catch if they
2788 // just hit down and hold it to scroll down (no keyup event).
2789 // listen on the document because that's where key events are triggered if no input has focus
2790 var query = "";
2791 var queryTimer = null;
2792 this._handleKeydownOnDropdown = function(e) {
2793 // prevent down key from scrolling the whole page,
2794 // and enter key from submitting a form etc
2795 e.preventDefault();
2796 // up and down to navigate
2797 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)) {
2798 // jump to countries that start with the query string
2799 if (queryTimer) clearTimeout(queryTimer);
2800 query += e.key.toLowerCase();
2801 _this9._searchForCountry(query);
2802 // if the timer hits 1 second, reset the query
2803 queryTimer = setTimeout(function() {
2804 query = "";
2805 }, 1e3);
2806 }
2807 };
2808 document.addEventListener("keydown", this._handleKeydownOnDropdown);
2809 }
2810 }, {
2811 key: "_handleUpDownKey",
2812 value: function _handleUpDownKey(key) {
2813 var next = key === "ArrowUp" || key === "Up" ? this.highlightedItem.previousElementSibling : this.highlightedItem.nextElementSibling;
2814 if (next) {
2815 // skip the divider
2816 if (next.classList.contains("iti__divider")) {
2817 next = key === "ArrowUp" || key === "Up" ? next.previousElementSibling : next.nextElementSibling;
2818 }
2819 this._highlightListItem(next, true);
2820 }
2821 }
2822 }, {
2823 key: "_handleEnterKey",
2824 value: function _handleEnterKey() {
2825 if (this.highlightedItem) this._selectListItem(this.highlightedItem);
2826 }
2827 }, {
2828 key: "_searchForCountry",
2829 value: function _searchForCountry(query) {
2830 for (var i = 0; i < this.countries.length; i++) {
2831 if (this._startsWith(this.countries[i].name, query)) {
2832 var listItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(this.countries[i].iso2));
2833 // update highlighting and scroll
2834 this._highlightListItem(listItem, false);
2835 this._scrollTo(listItem, true);
2836 break;
2837 }
2838 }
2839 }
2840 }, {
2841 key: "_startsWith",
2842 value: function _startsWith(a, b) {
2843 return a.substr(0, b.length).toLowerCase() === b;
2844 }
2845 }, {
2846 key: "_updateValFromNumber",
2847 value: function _updateValFromNumber(originalNumber) {
2848 var number = originalNumber;
2849 if (this.options.formatOnDisplay && window.intlTelInputUtils && this.selectedCountryData) {
2850 var useNational = !this.options.separateDialCode && (this.options.nationalMode || number.charAt(0) !== "+");
2851 var _intlTelInputUtils$nu = intlTelInputUtils.numberFormat, NATIONAL = _intlTelInputUtils$nu.NATIONAL, INTERNATIONAL = _intlTelInputUtils$nu.INTERNATIONAL;
2852 var format = useNational ? NATIONAL : INTERNATIONAL;
2853 number = intlTelInputUtils.formatNumber(number, this.selectedCountryData.iso2, format);
2854 }
2855 number = this._beforeSetNumber(number);
2856 this.telInput.value = number;
2857 }
2858 }, {
2859 key: "_updateFlagFromNumber",
2860 value: function _updateFlagFromNumber(originalNumber) {
2861 // if we're in nationalMode and we already have US/Canada selected, make sure the number starts
2862 // with a +1 so _getDialCode will be able to extract the area code
2863 // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag
2864 // from the number), that means we're initialising the plugin with a number that already has a
2865 // dial code, so fine to ignore this bit
2866 var number = originalNumber;
2867 var selectedDialCode = this.selectedCountryData.dialCode;
2868 var isNanp = selectedDialCode === "1";
2869 if (number && this.options.nationalMode && isNanp && number.charAt(0) !== "+") {
2870 if (number.charAt(0) !== "1") number = "1".concat(number);
2871 number = "+".concat(number);
2872 }
2873 // update flag if user types area code for another country
2874 if (this.options.separateDialCode && selectedDialCode && number.charAt(0) !== "+") {
2875 number = "+".concat(selectedDialCode).concat(number);
2876 }
2877 // try and extract valid dial code from input
2878 var dialCode = this._getDialCode(number, true);
2879 var numeric = this._getNumeric(number);
2880 var countryCode = null;
2881 if (dialCode) {
2882 var countryCodes = this.countryCodes[this._getNumeric(dialCode)];
2883 // check if the right country is already selected. this should be false if the number is
2884 // longer than the matched dial code because in this case we need to make sure that if
2885 // there are multiple country matches, that the first one is selected (note: we could
2886 // just check that here, but it requires the same loop that we already have later)
2887 var alreadySelected = countryCodes.indexOf(this.selectedCountryData.iso2) !== -1 && numeric.length <= dialCode.length - 1;
2888 var isRegionlessNanpNumber = selectedDialCode === "1" && this._isRegionlessNanp(numeric);
2889 // only update the flag if:
2890 // A) NOT (we currently have a NANP flag selected, and the number is a regionlessNanp)
2891 // AND
2892 // B) the right country is not already selected
2893 if (!isRegionlessNanpNumber && !alreadySelected) {
2894 // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first
2895 // non-empty index
2896 for (var j = 0; j < countryCodes.length; j++) {
2897 if (countryCodes[j]) {
2898 countryCode = countryCodes[j];
2899 break;
2900 }
2901 }
2902 }
2903 } else if (number.charAt(0) === "+" && numeric.length) {
2904 // invalid dial code, so empty
2905 // Note: use getNumeric here because the number has not been formatted yet, so could contain
2906 // bad chars
2907 countryCode = "";
2908 } else if (!number || number === "+") {
2909 // empty, or just a plus, so default
2910 countryCode = this.defaultCountry;
2911 }
2912 if (countryCode !== null) {
2913 return this._setFlag(countryCode);
2914 }
2915 return false;
2916 }
2917 }, {
2918 key: "_isRegionlessNanp",
2919 value: function _isRegionlessNanp(number) {
2920 var numeric = this._getNumeric(number);
2921 if (numeric.charAt(0) === "1") {
2922 var areaCode = numeric.substr(1, 3);
2923 return regionlessNanpNumbers.indexOf(areaCode) !== -1;
2924 }
2925 return false;
2926 }
2927 }, {
2928 key: "_highlightListItem",
2929 value: function _highlightListItem(listItem, shouldFocus) {
2930 var prevItem = this.highlightedItem;
2931 if (prevItem) prevItem.classList.remove("iti__highlight");
2932 this.highlightedItem = listItem;
2933 this.highlightedItem.classList.add("iti__highlight");
2934 if (shouldFocus) this.highlightedItem.focus();
2935 }
2936 }, {
2937 key: "_getCountryData",
2938 value: function _getCountryData(countryCode, ignoreOnlyCountriesOption, allowFail) {
2939 var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
2940 for (var i = 0; i < countryList.length; i++) {
2941 if (countryList[i].iso2 === countryCode) {
2942 return countryList[i];
2943 }
2944 }
2945 if (allowFail) {
2946 return null;
2947 }
2948 throw new Error("No country data for '".concat(countryCode, "'"));
2949 }
2950 }, {
2951 key: "_setFlag",
2952 value: function _setFlag(countryCode) {
2953 var prevCountry = this.selectedCountryData.iso2 ? this.selectedCountryData : {};
2954 // do this first as it will throw an error and stop if countryCode is invalid
2955 this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {};
2956 // update the defaultCountry - we only need the iso2 from now on, so just store that
2957 if (this.selectedCountryData.iso2) {
2958 this.defaultCountry = this.selectedCountryData.iso2;
2959 }
2960 this.selectedFlagInner.setAttribute("class", "iti__flag iti__".concat(countryCode));
2961 // update the selected country's title attribute
2962 var title = countryCode ? "".concat(this.selectedCountryData.name, ": +").concat(this.selectedCountryData.dialCode) : "Unknown";
2963 this.selectedFlag.setAttribute("title", title);
2964 if (this.options.separateDialCode) {
2965 var dialCode = this.selectedCountryData.dialCode ? "+".concat(this.selectedCountryData.dialCode) : "";
2966 this.selectedDialCode.innerHTML = dialCode;
2967 // offsetWidth is zero if input is in a hidden container during initialisation
2968 var selectedFlagWidth = this.selectedFlag.offsetWidth || this._getHiddenSelectedFlagWidth();
2969 // add 6px of padding after the grey selected-dial-code box, as this is what we use in the css
2970 this.telInput.style.paddingLeft = "".concat(selectedFlagWidth + 6, "px");
2971 }
2972 // and the input's placeholder
2973 this._updatePlaceholder();
2974 // update the active list item
2975 if (this.options.allowDropdown) {
2976 var prevItem = this.activeItem;
2977 if (prevItem) {
2978 prevItem.classList.remove("iti__active");
2979 prevItem.setAttribute("aria-selected", "false");
2980 }
2981 if (countryCode) {
2982 // check if there is a preferred item first, else fall back to standard
2983 var nextItem = this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode, "-preferred")) || this.countryList.querySelector("#iti-".concat(this.id, "__item-").concat(countryCode));
2984 nextItem.setAttribute("aria-selected", "true");
2985 nextItem.classList.add("iti__active");
2986 this.activeItem = nextItem;
2987 this.selectedFlag.setAttribute("aria-activedescendant", nextItem.getAttribute("id"));
2988 }
2989 }
2990 // return if the flag has changed or not
2991 return prevCountry.iso2 !== countryCode;
2992 }
2993 }, {
2994 key: "_getHiddenSelectedFlagWidth",
2995 value: function _getHiddenSelectedFlagWidth() {
2996 // to get the right styling to apply, all we need is a shallow clone of the container,
2997 // and then to inject a deep clone of the selectedFlag element
2998 var containerClone = this.telInput.parentNode.cloneNode();
2999 containerClone.style.visibility = "hidden";
3000 document.body.appendChild(containerClone);
3001 var flagsContainerClone = this.flagsContainer.cloneNode();
3002 containerClone.appendChild(flagsContainerClone);
3003 var selectedFlagClone = this.selectedFlag.cloneNode(true);
3004 flagsContainerClone.appendChild(selectedFlagClone);
3005 var width = selectedFlagClone.offsetWidth;
3006 containerClone.parentNode.removeChild(containerClone);
3007 return width;
3008 }
3009 }, {
3010 key: "_updatePlaceholder",
3011 value: function _updatePlaceholder() {
3012 var shouldSetPlaceholder = this.options.autoPlaceholder === "aggressive" || !this.hadInitialPlaceholder && this.options.autoPlaceholder === "polite";
3013 if (window.intlTelInputUtils && shouldSetPlaceholder) {
3014 var numberType = intlTelInputUtils.numberType[this.options.placeholderNumberType];
3015 var placeholder = this.selectedCountryData.iso2 ? intlTelInputUtils.getExampleNumber(this.selectedCountryData.iso2, this.options.nationalMode, numberType) : "";
3016 placeholder = this._beforeSetNumber(placeholder);
3017 if (typeof this.options.customPlaceholder === "function") {
3018 placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData);
3019 }
3020 this.telInput.setAttribute("placeholder", placeholder);
3021 }
3022 }
3023 }, {
3024 key: "_selectListItem",
3025 value: function _selectListItem(listItem) {
3026 // update selected flag and active list item
3027 var flagChanged = this._setFlag(listItem.getAttribute("data-country-code"));
3028 this._closeDropdown();
3029 this._updateDialCode(listItem.getAttribute("data-dial-code"), true);
3030 // focus the input
3031 this.telInput.focus();
3032 // put cursor at end - this fix is required for FF and IE11 (with nationalMode=false i.e. auto
3033 // inserting dial code), who try to put the cursor at the beginning the first time
3034 var len = this.telInput.value.length;
3035 this.telInput.setSelectionRange(len, len);
3036 if (flagChanged) {
3037 this._triggerCountryChange();
3038 }
3039 }
3040 }, {
3041 key: "_closeDropdown",
3042 value: function _closeDropdown() {
3043 this.countryList.classList.add("iti__hide");
3044 this.selectedFlag.setAttribute("aria-expanded", "false");
3045 // update the arrow
3046 this.dropdownArrow.classList.remove("iti__arrow--up");
3047 // unbind key events
3048 document.removeEventListener("keydown", this._handleKeydownOnDropdown);
3049 document.documentElement.removeEventListener("click", this._handleClickOffToClose);
3050 this.countryList.removeEventListener("mouseover", this._handleMouseoverCountryList);
3051 this.countryList.removeEventListener("click", this._handleClickCountryList);
3052 // remove menu from container
3053 if (this.options.dropdownContainer) {
3054 if (!this.isMobile) window.removeEventListener("scroll", this._handleWindowScroll);
3055 if (this.dropdown.parentNode) this.dropdown.parentNode.removeChild(this.dropdown);
3056 }
3057 this._trigger("close:countrydropdown");
3058 }
3059 }, {
3060 key: "_scrollTo",
3061 value: function _scrollTo(element, middle) {
3062 var container = this.countryList;
3063 // windowTop from https://stackoverflow.com/a/14384091/217866
3064 var windowTop = window.pageYOffset || document.documentElement.scrollTop;
3065 var containerHeight = container.offsetHeight;
3066 var containerTop = container.getBoundingClientRect().top + windowTop;
3067 var containerBottom = containerTop + containerHeight;
3068 var elementHeight = element.offsetHeight;
3069 var elementTop = element.getBoundingClientRect().top + windowTop;
3070 var elementBottom = elementTop + elementHeight;
3071 var newScrollTop = elementTop - containerTop + container.scrollTop;
3072 var middleOffset = containerHeight / 2 - elementHeight / 2;
3073 if (elementTop < containerTop) {
3074 // scroll up
3075 if (middle) newScrollTop -= middleOffset;
3076 container.scrollTop = newScrollTop;
3077 } else if (elementBottom > containerBottom) {
3078 // scroll down
3079 if (middle) newScrollTop += middleOffset;
3080 var heightDifference = containerHeight - elementHeight;
3081 container.scrollTop = newScrollTop - heightDifference;
3082 }
3083 }
3084 }, {
3085 key: "_updateDialCode",
3086 value: function _updateDialCode(newDialCodeBare, hasSelectedListItem) {
3087 var inputVal = this.telInput.value;
3088 // save having to pass this every time
3089 var newDialCode = "+".concat(newDialCodeBare);
3090 var newNumber;
3091 if (inputVal.charAt(0) === "+") {
3092 // there's a plus so we're dealing with a replacement (doesn't matter if nationalMode or not)
3093 var prevDialCode = this._getDialCode(inputVal);
3094 if (prevDialCode) {
3095 // current number contains a valid dial code, so replace it
3096 newNumber = inputVal.replace(prevDialCode, newDialCode);
3097 } else {
3098 // current number contains an invalid dial code, so ditch it
3099 // (no way to determine where the invalid dial code ends and the rest of the number begins)
3100 newNumber = newDialCode;
3101 }
3102 } else if (this.options.nationalMode || this.options.separateDialCode) {
3103 // don't do anything
3104 return;
3105 } else {
3106 // nationalMode is disabled
3107 if (inputVal) {
3108 // there is an existing value with no dial code: prefix the new dial code
3109 newNumber = newDialCode + inputVal;
3110 } else if (hasSelectedListItem || !this.options.autoHideDialCode) {
3111 // no existing value and either they've just selected a list item, or autoHideDialCode is
3112 // disabled: insert new dial code
3113 newNumber = newDialCode;
3114 } else {
3115 return;
3116 }
3117 }
3118 this.telInput.value = newNumber;
3119 }
3120 }, {
3121 key: "_getDialCode",
3122 value: function _getDialCode(number, includeAreaCode) {
3123 var dialCode = "";
3124 // only interested in international numbers (starting with a plus)
3125 if (number.charAt(0) === "+") {
3126 var numericChars = "";
3127 // iterate over chars
3128 for (var i = 0; i < number.length; i++) {
3129 var c = number.charAt(i);
3130 // if char is number (https://stackoverflow.com/a/8935649/217866)
3131 if (!isNaN(parseInt(c, 10))) {
3132 numericChars += c;
3133 // if current numericChars make a valid dial code
3134 if (includeAreaCode) {
3135 if (this.countryCodes[numericChars]) {
3136 // store the actual raw string (useful for matching later)
3137 dialCode = number.substr(0, i + 1);
3138 }
3139 } else {
3140 if (this.dialCodes[numericChars]) {
3141 dialCode = number.substr(0, i + 1);
3142 // if we're just looking for a dial code, we can break as soon as we find one
3143 break;
3144 }
3145 }
3146 // stop searching as soon as we can - in this case when we hit max len
3147 if (numericChars.length === this.countryCodeMaxLen) {
3148 break;
3149 }
3150 }
3151 }
3152 }
3153 return dialCode;
3154 }
3155 }, {
3156 key: "_getFullNumber",
3157 value: function _getFullNumber() {
3158 var val = this.telInput.value.trim();
3159 var dialCode = this.selectedCountryData.dialCode;
3160 var prefix;
3161 var numericVal = this._getNumeric(val);
3162 if (this.options.separateDialCode && val.charAt(0) !== "+" && dialCode && numericVal) {
3163 // when using separateDialCode, it is visible so is effectively part of the typed number
3164 prefix = "+".concat(dialCode);
3165 } else {
3166 prefix = "";
3167 }
3168 return prefix + val;
3169 }
3170 }, {
3171 key: "_beforeSetNumber",
3172 value: function _beforeSetNumber(originalNumber) {
3173 var number = originalNumber;
3174 if (this.options.separateDialCode) {
3175 var dialCode = this._getDialCode(number);
3176 // if there is a valid dial code
3177 if (dialCode) {
3178 // in case _getDialCode returned an area code as well
3179 dialCode = "+".concat(this.selectedCountryData.dialCode);
3180 // a lot of numbers will have a space separating the dial code and the main number, and
3181 // some NANP numbers will have a hyphen e.g. +1 684-733-1234 - in both cases we want to get
3182 // rid of it
3183 // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc
3184 var start = number[dialCode.length] === " " || number[dialCode.length] === "-" ? dialCode.length + 1 : dialCode.length;
3185 number = number.substr(start);
3186 }
3187 }
3188 return this._cap(number);
3189 }
3190 }, {
3191 key: "_triggerCountryChange",
3192 value: function _triggerCountryChange() {
3193 this._trigger("countrychange");
3194 }
3195 }, {
3196 key: "handleAutoCountry",
3197 value: function handleAutoCountry() {
3198 if (this.options.initialCountry === "auto") {
3199 // we must set this even if there is an initial val in the input: in case the initial val is
3200 // invalid and they delete it - they should see their auto country
3201 this.defaultCountry = window.intlTelInputGlobals.autoCountry;
3202 // if there's no initial value in the input, then update the flag
3203 if (!this.telInput.value) {
3204 this.setCountry(this.defaultCountry);
3205 }
3206 this.resolveAutoCountryPromise();
3207 }
3208 }
3209 }, {
3210 key: "handleUtils",
3211 value: function handleUtils() {
3212 // if the request was successful
3213 if (window.intlTelInputUtils) {
3214 // if there's an initial value in the input, then format it
3215 if (this.telInput.value) {
3216 this._updateValFromNumber(this.telInput.value);
3217 }
3218 this._updatePlaceholder();
3219 }
3220 this.resolveUtilsScriptPromise();
3221 }
3222 }, {
3223 key: "destroy",
3224 value: function destroy() {
3225 var form = this.telInput.form;
3226 if (this.options.allowDropdown) {
3227 // make sure the dropdown is closed (and unbind listeners)
3228 this._closeDropdown();
3229 this.selectedFlag.removeEventListener("click", this._handleClickSelectedFlag);
3230 this.flagsContainer.removeEventListener("keydown", this._handleFlagsContainerKeydown);
3231 // label click hack
3232 var label = this._getClosestLabel();
3233 if (label) label.removeEventListener("click", this._handleLabelClick);
3234 }
3235 // unbind hiddenInput listeners
3236 if (this.hiddenInput && form) form.removeEventListener("submit", this._handleHiddenInputSubmit);
3237 // unbind autoHideDialCode listeners
3238 if (this.options.autoHideDialCode) {
3239 if (form) form.removeEventListener("submit", this._handleSubmitOrBlurEvent);
3240 this.telInput.removeEventListener("blur", this._handleSubmitOrBlurEvent);
3241 }
3242 // unbind key events, and cut/paste events
3243 this.telInput.removeEventListener("keyup", this._handleKeyupEvent);
3244 this.telInput.removeEventListener("cut", this._handleClipboardEvent);
3245 this.telInput.removeEventListener("paste", this._handleClipboardEvent);
3246 // remove attribute of id instance: data-intl-tel-input-id
3247 this.telInput.removeAttribute("data-intl-tel-input-id");
3248 // remove markup (but leave the original input)
3249 var wrapper = this.telInput.parentNode;
3250 wrapper.parentNode.insertBefore(this.telInput, wrapper);
3251 wrapper.parentNode.removeChild(wrapper);
3252 delete window.intlTelInputGlobals.instances[this.id];
3253 }
3254 }, {
3255 key: "getExtension",
3256 value: function getExtension() {
3257 if (window.intlTelInputUtils) {
3258 return intlTelInputUtils.getExtension(this._getFullNumber(), this.selectedCountryData.iso2);
3259 }
3260 return "";
3261 }
3262 }, {
3263 key: "getNumber",
3264 value: function getNumber(format) {
3265 if (window.intlTelInputUtils) {
3266 var iso2 = this.selectedCountryData.iso2;
3267 return intlTelInputUtils.formatNumber(this._getFullNumber(), iso2, format);
3268 }
3269 return "";
3270 }
3271 }, {
3272 key: "getNumberType",
3273 value: function getNumberType() {
3274 if (window.intlTelInputUtils) {
3275 return intlTelInputUtils.getNumberType(this._getFullNumber(), this.selectedCountryData.iso2);
3276 }
3277 return -99;
3278 }
3279 }, {
3280 key: "getSelectedCountryData",
3281 value: function getSelectedCountryData() {
3282 return this.selectedCountryData;
3283 }
3284 }, {
3285 key: "getValidationError",
3286 value: function getValidationError() {
3287 if (window.intlTelInputUtils) {
3288 var iso2 = this.selectedCountryData.iso2;
3289 return intlTelInputUtils.getValidationError(this._getFullNumber(), iso2);
3290 }
3291 return -99;
3292 }
3293 }, {
3294 key: "isValidNumber",
3295 value: function isValidNumber() {
3296 var val = this._getFullNumber().trim();
3297 var countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "";
3298 return window.intlTelInputUtils ? intlTelInputUtils.isValidNumber(val, countryCode) : null;
3299 }
3300 }, {
3301 key: "setCountry",
3302 value: function setCountry(originalCountryCode) {
3303 var countryCode = originalCountryCode.toLowerCase();
3304 // check if already selected
3305 if (!this.selectedFlagInner.classList.contains("iti__".concat(countryCode))) {
3306 this._setFlag(countryCode);
3307 this._updateDialCode(this.selectedCountryData.dialCode, false);
3308 this._triggerCountryChange();
3309 }
3310 }
3311 }, {
3312 key: "setNumber",
3313 value: function setNumber(number) {
3314 // we must update the flag first, which updates this.selectedCountryData, which is used for
3315 // formatting the number before displaying it
3316 var flagChanged = this._updateFlagFromNumber(number);
3317 this._updateValFromNumber(number);
3318 if (flagChanged) {
3319 this._triggerCountryChange();
3320 }
3321 }
3322 }, {
3323 key: "setPlaceholderNumberType",
3324 value: function setPlaceholderNumberType(type) {
3325 this.options.placeholderNumberType = type;
3326 this._updatePlaceholder();
3327 }
3328 } ]);
3329 return Iti;
3330 }();
3331 /********************
3332 * STATIC METHODS
3333 ********************/
3334 // get the country data object
3335 intlTelInputGlobals.getCountryData = function() {
3336 return allCountries;
3337 };
3338 // inject a <script> element to load utils.js
3339 var injectScript = function injectScript(path, handleSuccess, handleFailure) {
3340 // inject a new script element into the page
3341 var script = document.createElement("script");
3342 script.onload = function() {
3343 forEachInstance("handleUtils");
3344 if (handleSuccess) handleSuccess();
3345 };
3346 script.onerror = function() {
3347 forEachInstance("rejectUtilsScriptPromise");
3348 if (handleFailure) handleFailure();
3349 };
3350 script.className = "iti-load-utils";
3351 script.async = true;
3352 script.src = path;
3353 document.body.appendChild(script);
3354 };
3355 // load the utils script
3356 intlTelInputGlobals.loadUtils = function(path) {
3357 // 2 options:
3358 // 1) not already started loading (start)
3359 // 2) already started loading (do nothing - just wait for the onload callback to fire, which will
3360 // trigger handleUtils on all instances, invoking their resolveUtilsScriptPromise functions)
3361 if (!window.intlTelInputUtils && !window.intlTelInputGlobals.startedLoadingUtilsScript) {
3362 // only do this once
3363 window.intlTelInputGlobals.startedLoadingUtilsScript = true;
3364 // if we have promises, then return a promise
3365 if (typeof Promise !== "undefined") {
3366 return new Promise(function(resolve, reject) {
3367 return injectScript(path, resolve, reject);
3368 });
3369 }
3370 injectScript(path);
3371 }
3372 return null;
3373 };
3374 // default options
3375 intlTelInputGlobals.defaults = defaults;
3376 // version
3377 intlTelInputGlobals.version = "17.0.16";
3378 // convenience wrapper
3379 return function(input, options) {
3380 var iti = new Iti(input, options);
3381 iti._init();
3382 input.setAttribute("data-intl-tel-input-id", iti.id);
3383 window.intlTelInputGlobals.instances[iti.id] = iti;
3384 return iti;
3385 };
3386 }();
3387 });
3388 },{}],27:[function(require,module,exports){
3389 /**
3390 * Exposing intl-tel-input as a component
3391 */
3392 module.exports = require("./build/js/intlTelInput");
3393
3394 },{"./build/js/intlTelInput":26}],28:[function(require,module,exports){
3395 (function (process){
3396 /**
3397 * Memize options object.
3398 *
3399 * @typedef MemizeOptions
3400 *
3401 * @property {number} [maxSize] Maximum size of the cache.
3402 */
3403
3404 /**
3405 * Internal cache entry.
3406 *
3407 * @typedef MemizeCacheNode
3408 *
3409 * @property {?MemizeCacheNode|undefined} [prev] Previous node.
3410 * @property {?MemizeCacheNode|undefined} [next] Next node.
3411 * @property {Array<*>} args Function arguments for cache
3412 * entry.
3413 * @property {*} val Function result.
3414 */
3415
3416 /**
3417 * Properties of the enhanced function for controlling cache.
3418 *
3419 * @typedef MemizeMemoizedFunction
3420 *
3421 * @property {()=>void} clear Clear the cache.
3422 */
3423
3424 /**
3425 * Accepts a function to be memoized, and returns a new memoized function, with
3426 * optional options.
3427 *
3428 * @template {Function} F
3429 *
3430 * @param {F} fn Function to memoize.
3431 * @param {MemizeOptions} [options] Options object.
3432 *
3433 * @return {F & MemizeMemoizedFunction} Memoized function.
3434 */
3435 function memize( fn, options ) {
3436 var size = 0;
3437
3438 /** @type {?MemizeCacheNode|undefined} */
3439 var head;
3440
3441 /** @type {?MemizeCacheNode|undefined} */
3442 var tail;
3443
3444 options = options || {};
3445
3446 function memoized( /* ...args */ ) {
3447 var node = head,
3448 len = arguments.length,
3449 args, i;
3450
3451 searchCache: while ( node ) {
3452 // Perform a shallow equality test to confirm that whether the node
3453 // under test is a candidate for the arguments passed. Two arrays
3454 // are shallowly equal if their length matches and each entry is
3455 // strictly equal between the two sets. Avoid abstracting to a
3456 // function which could incur an arguments leaking deoptimization.
3457
3458 // Check whether node arguments match arguments length
3459 if ( node.args.length !== arguments.length ) {
3460 node = node.next;
3461 continue;
3462 }
3463
3464 // Check whether node arguments match arguments values
3465 for ( i = 0; i < len; i++ ) {
3466 if ( node.args[ i ] !== arguments[ i ] ) {
3467 node = node.next;
3468 continue searchCache;
3469 }
3470 }
3471
3472 // At this point we can assume we've found a match
3473
3474 // Surface matched node to head if not already
3475 if ( node !== head ) {
3476 // As tail, shift to previous. Must only shift if not also
3477 // head, since if both head and tail, there is no previous.
3478 if ( node === tail ) {
3479 tail = node.prev;
3480 }
3481
3482 // Adjust siblings to point to each other. If node was tail,
3483 // this also handles new tail's empty `next` assignment.
3484 /** @type {MemizeCacheNode} */ ( node.prev ).next = node.next;
3485 if ( node.next ) {
3486 node.next.prev = node.prev;
3487 }
3488
3489 node.next = head;
3490 node.prev = null;
3491 /** @type {MemizeCacheNode} */ ( head ).prev = node;
3492 head = node;
3493 }
3494
3495 // Return immediately
3496 return node.val;
3497 }
3498
3499 // No cached value found. Continue to insertion phase:
3500
3501 // Create a copy of arguments (avoid leaking deoptimization)
3502 args = new Array( len );
3503 for ( i = 0; i < len; i++ ) {
3504 args[ i ] = arguments[ i ];
3505 }
3506
3507 node = {
3508 args: args,
3509
3510 // Generate the result from original function
3511 val: fn.apply( null, args ),
3512 };
3513
3514 // Don't need to check whether node is already head, since it would
3515 // have been returned above already if it was
3516
3517 // Shift existing head down list
3518 if ( head ) {
3519 head.prev = node;
3520 node.next = head;
3521 } else {
3522 // If no head, follows that there's no tail (at initial or reset)
3523 tail = node;
3524 }
3525
3526 // Trim tail if we're reached max size and are pending cache insertion
3527 if ( size === /** @type {MemizeOptions} */ ( options ).maxSize ) {
3528 tail = /** @type {MemizeCacheNode} */ ( tail ).prev;
3529 /** @type {MemizeCacheNode} */ ( tail ).next = null;
3530 } else {
3531 size++;
3532 }
3533
3534 head = node;
3535
3536 return node.val;
3537 }
3538
3539 memoized.clear = function() {
3540 head = null;
3541 tail = null;
3542 size = 0;
3543 };
3544
3545 if ( process.env.NODE_ENV === 'test' ) {
3546 // Cache is not exposed in the public API, but used in tests to ensure
3547 // expected list progression
3548 memoized.getCache = function() {
3549 return [ head, tail, size ];
3550 };
3551 }
3552
3553 // Ignore reason: There's not a clear solution to create an intersection of
3554 // the function with additional properties, where the goal is to retain the
3555 // function signature of the incoming argument and add control properties
3556 // on the return value.
3557
3558 // @ts-ignore
3559 return memoized;
3560 }
3561
3562 module.exports = memize;
3563
3564 }).call(this,require('_process'))
3565 },{"_process":29}],29:[function(require,module,exports){
3566 // shim for using process in browser
3567 var process = module.exports = {};
3568
3569 // cached from whatever global is present so that test runners that stub it
3570 // don't break things. But we need to wrap it in a try catch in case it is
3571 // wrapped in strict mode code which doesn't define any globals. It's inside a
3572 // function because try/catches deoptimize in certain engines.
3573
3574 var cachedSetTimeout;
3575 var cachedClearTimeout;
3576
3577 function defaultSetTimout() {
3578 throw new Error('setTimeout has not been defined');
3579 }
3580 function defaultClearTimeout () {
3581 throw new Error('clearTimeout has not been defined');
3582 }
3583 (function () {
3584 try {
3585 if (typeof setTimeout === 'function') {
3586 cachedSetTimeout = setTimeout;
3587 } else {
3588 cachedSetTimeout = defaultSetTimout;
3589 }
3590 } catch (e) {
3591 cachedSetTimeout = defaultSetTimout;
3592 }
3593 try {
3594 if (typeof clearTimeout === 'function') {
3595 cachedClearTimeout = clearTimeout;
3596 } else {
3597 cachedClearTimeout = defaultClearTimeout;
3598 }
3599 } catch (e) {
3600 cachedClearTimeout = defaultClearTimeout;
3601 }
3602 } ())
3603 function runTimeout(fun) {
3604 if (cachedSetTimeout === setTimeout) {
3605 //normal enviroments in sane situations
3606 return setTimeout(fun, 0);
3607 }
3608 // if setTimeout wasn't available but was latter defined
3609 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
3610 cachedSetTimeout = setTimeout;
3611 return setTimeout(fun, 0);
3612 }
3613 try {
3614 // when when somebody has screwed with setTimeout but no I.E. maddness
3615 return cachedSetTimeout(fun, 0);
3616 } catch(e){
3617 try {
3618 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3619 return cachedSetTimeout.call(null, fun, 0);
3620 } catch(e){
3621 // 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
3622 return cachedSetTimeout.call(this, fun, 0);
3623 }
3624 }
3625
3626
3627 }
3628 function runClearTimeout(marker) {
3629 if (cachedClearTimeout === clearTimeout) {
3630 //normal enviroments in sane situations
3631 return clearTimeout(marker);
3632 }
3633 // if clearTimeout wasn't available but was latter defined
3634 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
3635 cachedClearTimeout = clearTimeout;
3636 return clearTimeout(marker);
3637 }
3638 try {
3639 // when when somebody has screwed with setTimeout but no I.E. maddness
3640 return cachedClearTimeout(marker);
3641 } catch (e){
3642 try {
3643 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3644 return cachedClearTimeout.call(null, marker);
3645 } catch (e){
3646 // 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.
3647 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
3648 return cachedClearTimeout.call(this, marker);
3649 }
3650 }
3651
3652
3653
3654 }
3655 var queue = [];
3656 var draining = false;
3657 var currentQueue;
3658 var queueIndex = -1;
3659
3660 function cleanUpNextTick() {
3661 if (!draining || !currentQueue) {
3662 return;
3663 }
3664 draining = false;
3665 if (currentQueue.length) {
3666 queue = currentQueue.concat(queue);
3667 } else {
3668 queueIndex = -1;
3669 }
3670 if (queue.length) {
3671 drainQueue();
3672 }
3673 }
3674
3675 function drainQueue() {
3676 if (draining) {
3677 return;
3678 }
3679 var timeout = runTimeout(cleanUpNextTick);
3680 draining = true;
3681
3682 var len = queue.length;
3683 while(len) {
3684 currentQueue = queue;
3685 queue = [];
3686 while (++queueIndex < len) {
3687 if (currentQueue) {
3688 currentQueue[queueIndex].run();
3689 }
3690 }
3691 queueIndex = -1;
3692 len = queue.length;
3693 }
3694 currentQueue = null;
3695 draining = false;
3696 runClearTimeout(timeout);
3697 }
3698
3699 process.nextTick = function (fun) {
3700 var args = new Array(arguments.length - 1);
3701 if (arguments.length > 1) {
3702 for (var i = 1; i < arguments.length; i++) {
3703 args[i - 1] = arguments[i];
3704 }
3705 }
3706 queue.push(new Item(fun, args));
3707 if (queue.length === 1 && !draining) {
3708 runTimeout(drainQueue);
3709 }
3710 };
3711
3712 // v8 likes predictible objects
3713 function Item(fun, array) {
3714 this.fun = fun;
3715 this.array = array;
3716 }
3717 Item.prototype.run = function () {
3718 this.fun.apply(null, this.array);
3719 };
3720 process.title = 'browser';
3721 process.browser = true;
3722 process.env = {};
3723 process.argv = [];
3724 process.version = ''; // empty string to avoid regexp issues
3725 process.versions = {};
3726
3727 function noop() {}
3728
3729 process.on = noop;
3730 process.addListener = noop;
3731 process.once = noop;
3732 process.off = noop;
3733 process.removeListener = noop;
3734 process.removeAllListeners = noop;
3735 process.emit = noop;
3736 process.prependListener = noop;
3737 process.prependOnceListener = noop;
3738
3739 process.listeners = function (name) { return [] }
3740
3741 process.binding = function (name) {
3742 throw new Error('process.binding is not supported');
3743 };
3744
3745 process.cwd = function () { return '/' };
3746 process.chdir = function (dir) {
3747 throw new Error('process.chdir is not supported');
3748 };
3749 process.umask = function() { return 0; };
3750
3751 },{}],30:[function(require,module,exports){
3752 'use strict';
3753
3754 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
3755
3756 var pluralForms = _interopDefault(require('@tannin/plural-forms'));
3757
3758 /**
3759 * Tannin constructor options.
3760 *
3761 * @typedef {Object} TanninOptions
3762 *
3763 * @property {string} [contextDelimiter] Joiner in string lookup with context.
3764 * @property {Function} [onMissingKey] Callback to invoke when key missing.
3765 */
3766
3767 /**
3768 * Domain metadata.
3769 *
3770 * @typedef {Object} TanninDomainMetadata
3771 *
3772 * @property {string} [domain] Domain name.
3773 * @property {string} [lang] Language code.
3774 * @property {(string|Function)} [plural_forms] Plural forms expression or
3775 * function evaluator.
3776 */
3777
3778 /**
3779 * Domain translation pair respectively representing the singular and plural
3780 * translation.
3781 *
3782 * @typedef {[string,string]} TanninTranslation
3783 */
3784
3785 /**
3786 * Locale data domain. The key is used as reference for lookup, the value an
3787 * array of two string entries respectively representing the singular and plural
3788 * translation.
3789 *
3790 * @typedef {{[key:string]:TanninDomainMetadata|TanninTranslation,'':TanninDomainMetadata|TanninTranslation}} TanninLocaleDomain
3791 */
3792
3793 /**
3794 * Jed-formatted locale data.
3795 *
3796 * @see http://messageformat.github.io/Jed/
3797 *
3798 * @typedef {{[domain:string]:TanninLocaleDomain}} TanninLocaleData
3799 */
3800
3801 /**
3802 * Default Tannin constructor options.
3803 *
3804 * @type {TanninOptions}
3805 */
3806 var DEFAULT_OPTIONS = {
3807 contextDelimiter: '\u0004',
3808 onMissingKey: null,
3809 };
3810
3811 /**
3812 * Given a specific locale data's config `plural_forms` value, returns the
3813 * expression.
3814 *
3815 * @example
3816 *
3817 * ```
3818 * getPluralExpression( 'nplurals=2; plural=(n != 1);' ) === '(n != 1)'
3819 * ```
3820 *
3821 * @param {string} pf Locale data plural forms.
3822 *
3823 * @return {string} Plural forms expression.
3824 */
3825 function getPluralExpression( pf ) {
3826 var parts, i, part;
3827
3828 parts = pf.split( ';' );
3829
3830 for ( i = 0; i < parts.length; i++ ) {
3831 part = parts[ i ].trim();
3832 if ( part.indexOf( 'plural=' ) === 0 ) {
3833 return part.substr( 7 );
3834 }
3835 }
3836 }
3837
3838 /**
3839 * Tannin constructor.
3840 *
3841 * @class
3842 *
3843 * @param {TanninLocaleData} data Jed-formatted locale data.
3844 * @param {TanninOptions} [options] Tannin options.
3845 */
3846 function Tannin( data, options ) {
3847 var key;
3848
3849 /**
3850 * Jed-formatted locale data.
3851 *
3852 * @name Tannin#data
3853 * @type {TanninLocaleData}
3854 */
3855 this.data = data;
3856
3857 /**
3858 * Plural forms function cache, keyed by plural forms string.
3859 *
3860 * @name Tannin#pluralForms
3861 * @type {Object<string,Function>}
3862 */
3863 this.pluralForms = {};
3864
3865 /**
3866 * Effective options for instance, including defaults.
3867 *
3868 * @name Tannin#options
3869 * @type {TanninOptions}
3870 */
3871 this.options = {};
3872
3873 for ( key in DEFAULT_OPTIONS ) {
3874 this.options[ key ] = options !== undefined && key in options
3875 ? options[ key ]
3876 : DEFAULT_OPTIONS[ key ];
3877 }
3878 }
3879
3880 /**
3881 * Returns the plural form index for the given domain and value.
3882 *
3883 * @param {string} domain Domain on which to calculate plural form.
3884 * @param {number} n Value for which plural form is to be calculated.
3885 *
3886 * @return {number} Plural form index.
3887 */
3888 Tannin.prototype.getPluralForm = function( domain, n ) {
3889 var getPluralForm = this.pluralForms[ domain ],
3890 config, plural, pf;
3891
3892 if ( ! getPluralForm ) {
3893 config = this.data[ domain ][ '' ];
3894
3895 pf = (
3896 config[ 'Plural-Forms' ] ||
3897 config[ 'plural-forms' ] ||
3898 // Ignore reason: As known, there's no way to document the empty
3899 // string property on a key to guarantee this as metadata.
3900 // @ts-ignore
3901 config.plural_forms
3902 );
3903
3904 if ( typeof pf !== 'function' ) {
3905 plural = getPluralExpression(
3906 config[ 'Plural-Forms' ] ||
3907 config[ 'plural-forms' ] ||
3908 // Ignore reason: As known, there's no way to document the empty
3909 // string property on a key to guarantee this as metadata.
3910 // @ts-ignore
3911 config.plural_forms
3912 );
3913
3914 pf = pluralForms( plural );
3915 }
3916
3917 getPluralForm = this.pluralForms[ domain ] = pf;
3918 }
3919
3920 return getPluralForm( n );
3921 };
3922
3923 /**
3924 * Translate a string.
3925 *
3926 * @param {string} domain Translation domain.
3927 * @param {string|void} context Context distinguishing terms of the same name.
3928 * @param {string} singular Primary key for translation lookup.
3929 * @param {string=} plural Fallback value used for non-zero plural
3930 * form index.
3931 * @param {number=} n Value to use in calculating plural form.
3932 *
3933 * @return {string} Translated string.
3934 */
3935 Tannin.prototype.dcnpgettext = function( domain, context, singular, plural, n ) {
3936 var index, key, entry;
3937
3938 if ( n === undefined ) {
3939 // Default to singular.
3940 index = 0;
3941 } else {
3942 // Find index by evaluating plural form for value.
3943 index = this.getPluralForm( domain, n );
3944 }
3945
3946 key = singular;
3947
3948 // If provided, context is prepended to key with delimiter.
3949 if ( context ) {
3950 key = context + this.options.contextDelimiter + singular;
3951 }
3952
3953 entry = this.data[ domain ][ key ];
3954
3955 // Verify not only that entry exists, but that the intended index is within
3956 // range and non-empty.
3957 if ( entry && entry[ index ] ) {
3958 return entry[ index ];
3959 }
3960
3961 if ( this.options.onMissingKey ) {
3962 this.options.onMissingKey( singular, domain );
3963 }
3964
3965 // If entry not found, fall back to singular vs. plural with zero index
3966 // representing the singular value.
3967 return index === 0 ? singular : plural;
3968 };
3969
3970 module.exports = Tannin;
3971
3972 },{"@tannin/plural-forms":19}]},{},[2]);
3973