UNPKG

16.9 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports["default"] = void 0;
7
8var _metadata = _interopRequireDefault(require("./metadata"));
9
10var _PhoneNumber = _interopRequireDefault(require("./PhoneNumber"));
11
12var _AsYouTypeState = _interopRequireDefault(require("./AsYouTypeState"));
13
14var _AsYouTypeFormatter = _interopRequireWildcard(require("./AsYouTypeFormatter"));
15
16var _AsYouTypeParser = _interopRequireWildcard(require("./AsYouTypeParser"));
17
18var _getCountryByCallingCode = _interopRequireDefault(require("./helpers/getCountryByCallingCode"));
19
20function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
21
22function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
23
24function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
25
26function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
27
28function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
29
30function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
31
32function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
33
34function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
35
36function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
37
38function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
39
40var USE_NON_GEOGRAPHIC_COUNTRY_CODE = false;
41
42var AsYouType =
43/*#__PURE__*/
44function () {
45 /**
46 * @param {(string|object)?} [optionsOrDefaultCountry] - The default country used for parsing non-international phone numbers. Can also be an `options` object.
47 * @param {Object} metadata
48 */
49 function AsYouType(optionsOrDefaultCountry, metadata) {
50 _classCallCheck(this, AsYouType);
51
52 this.metadata = new _metadata["default"](metadata);
53
54 var _this$getCountryAndCa = this.getCountryAndCallingCode(optionsOrDefaultCountry),
55 _this$getCountryAndCa2 = _slicedToArray(_this$getCountryAndCa, 2),
56 defaultCountry = _this$getCountryAndCa2[0],
57 defaultCallingCode = _this$getCountryAndCa2[1];
58
59 this.defaultCountry = defaultCountry;
60 this.defaultCallingCode = defaultCallingCode;
61 this.reset();
62 }
63
64 _createClass(AsYouType, [{
65 key: "getCountryAndCallingCode",
66 value: function getCountryAndCallingCode(optionsOrDefaultCountry) {
67 // Set `defaultCountry` and `defaultCallingCode` options.
68 var defaultCountry;
69 var defaultCallingCode; // Turns out `null` also has type "object". Weird.
70
71 if (optionsOrDefaultCountry) {
72 if (_typeof(optionsOrDefaultCountry) === 'object') {
73 defaultCountry = optionsOrDefaultCountry.defaultCountry;
74 defaultCallingCode = optionsOrDefaultCountry.defaultCallingCode;
75 } else {
76 defaultCountry = optionsOrDefaultCountry;
77 }
78 }
79
80 if (defaultCountry && !this.metadata.hasCountry(defaultCountry)) {
81 defaultCountry = undefined;
82 }
83
84 if (defaultCallingCode) {
85 /* istanbul ignore if */
86 if (USE_NON_GEOGRAPHIC_COUNTRY_CODE) {
87 if (this.metadata.isNonGeographicCallingCode(defaultCallingCode)) {
88 defaultCountry = '001';
89 }
90 }
91 }
92
93 return [defaultCountry, defaultCallingCode];
94 }
95 /**
96 * Inputs "next" phone number characters.
97 * @param {string} text
98 * @return {string} Formatted phone number characters that have been input so far.
99 */
100
101 }, {
102 key: "input",
103 value: function input(text) {
104 var _this$parser$input = this.parser.input(text, this.state),
105 digits = _this$parser$input.digits,
106 justLeadingPlus = _this$parser$input.justLeadingPlus;
107
108 if (justLeadingPlus) {
109 this.formattedOutput = '+';
110 } else if (digits) {
111 this.determineTheCountryIfNeeded(); // Match the available formats by the currently available leading digits.
112
113 if (this.state.nationalSignificantNumber) {
114 this.formatter.narrowDownMatchingFormats(this.state);
115 }
116
117 var formattedNationalNumber;
118
119 if (this.metadata.hasSelectedNumberingPlan()) {
120 formattedNationalNumber = this.formatter.format(digits, this.state);
121 }
122
123 if (formattedNationalNumber === undefined) {
124 // See if another national (significant) number could be re-extracted.
125 if (this.parser.reExtractNationalSignificantNumber(this.state)) {
126 this.determineTheCountryIfNeeded(); // If it could, then re-try formatting the new national (significant) number.
127
128 var nationalDigits = this.state.getNationalDigits();
129
130 if (nationalDigits) {
131 formattedNationalNumber = this.formatter.format(nationalDigits, this.state);
132 }
133 }
134 }
135
136 this.formattedOutput = formattedNationalNumber ? this.getFullNumber(formattedNationalNumber) : this.getNonFormattedNumber();
137 }
138
139 return this.formattedOutput;
140 }
141 }, {
142 key: "reset",
143 value: function reset() {
144 var _this = this;
145
146 this.state = new _AsYouTypeState["default"]({
147 onCountryChange: function onCountryChange(country) {
148 // Before version `1.6.0`, the official `AsYouType` formatter API
149 // included the `.country` property of an `AsYouType` instance.
150 // Since that property (along with the others) have been moved to
151 // `this.state`, `this.country` property is emulated for compatibility
152 // with the old versions.
153 _this.country = country;
154 },
155 onCallingCodeChange: function onCallingCodeChange(country, callingCode) {
156 _this.metadata.selectNumberingPlan(country, callingCode);
157
158 _this.formatter.reset(_this.metadata.numberingPlan, _this.state);
159
160 _this.parser.reset(_this.metadata.numberingPlan);
161 }
162 });
163 this.formatter = new _AsYouTypeFormatter["default"]({
164 state: this.state,
165 metadata: this.metadata
166 });
167 this.parser = new _AsYouTypeParser["default"]({
168 defaultCountry: this.defaultCountry,
169 defaultCallingCode: this.defaultCallingCode,
170 metadata: this.metadata,
171 state: this.state,
172 onNationalSignificantNumberChange: function onNationalSignificantNumberChange() {
173 _this.determineTheCountryIfNeeded();
174
175 _this.formatter.reset(_this.metadata.numberingPlan, _this.state);
176 }
177 });
178 this.state.reset(this.defaultCountry, this.defaultCallingCode);
179 this.formattedOutput = '';
180 return this;
181 }
182 /**
183 * Returns `true` if the phone number is being input in international format.
184 * In other words, returns `true` if and only if the parsed phone number starts with a `"+"`.
185 * @return {boolean}
186 */
187
188 }, {
189 key: "isInternational",
190 value: function isInternational() {
191 return this.state.international;
192 }
193 /**
194 * Returns the "country calling code" part of the phone number.
195 * Returns `undefined` if the number is not being input in international format.
196 * Returns "country calling code" for "non-geographic" phone numbering plans too.
197 * @return {string} [callingCode]
198 */
199
200 }, {
201 key: "getCallingCode",
202 value: function getCallingCode() {
203 return this.state.callingCode;
204 } // A legacy alias.
205
206 }, {
207 key: "getCountryCallingCode",
208 value: function getCountryCallingCode() {
209 return this.getCallingCode();
210 }
211 /**
212 * Returns a two-letter country code of the phone number.
213 * Returns `undefined` for "non-geographic" phone numbering plans.
214 * Returns `undefined` if no phone number has been input yet.
215 * @return {string} [country]
216 */
217
218 }, {
219 key: "getCountry",
220 value: function getCountry() {
221 var _this$state = this.state,
222 digits = _this$state.digits,
223 country = _this$state.country; // If no digits have been input yet,
224 // then `this.country` is the `defaultCountry`.
225 // Won't return the `defaultCountry` in such case.
226
227 if (!digits) {
228 return;
229 }
230
231 var countryCode = country;
232 /* istanbul ignore if */
233
234 if (USE_NON_GEOGRAPHIC_COUNTRY_CODE) {
235 // `AsYouType.getCountry()` returns `undefined`
236 // for "non-geographic" phone numbering plans.
237 if (countryCode === '001') {
238 countryCode = undefined;
239 }
240 }
241
242 return countryCode;
243 }
244 }, {
245 key: "determineTheCountryIfNeeded",
246 value: function determineTheCountryIfNeeded() {
247 // Suppose a user enters a phone number in international format,
248 // and there're several countries corresponding to that country calling code,
249 // and a country has been derived from the number, and then
250 // a user enters one more digit and the number is no longer
251 // valid for the derived country, so the country should be re-derived
252 // on every new digit in those cases.
253 //
254 // If the phone number is being input in national format,
255 // then it could be a case when `defaultCountry` wasn't specified
256 // when creating `AsYouType` instance, and just `defaultCallingCode` was specified,
257 // and that "calling code" could correspond to a "non-geographic entity",
258 // or there could be several countries corresponding to that country calling code.
259 // In those cases, `this.country` is `undefined` and should be derived
260 // from the number. Again, if country calling code is ambiguous, then
261 // `this.country` should be re-derived with each new digit.
262 //
263 if (!this.state.country || this.isCountryCallingCodeAmbiguous()) {
264 this.determineTheCountry();
265 }
266 } // Prepends `+CountryCode ` in case of an international phone number
267
268 }, {
269 key: "getFullNumber",
270 value: function getFullNumber(formattedNationalNumber) {
271 var _this2 = this;
272
273 if (this.isInternational()) {
274 var prefix = function prefix(text) {
275 return _this2.formatter.getInternationalPrefixBeforeCountryCallingCode(_this2.state, {
276 spacing: text ? true : false
277 }) + text;
278 };
279
280 var callingCode = this.state.callingCode;
281
282 if (!callingCode) {
283 return prefix("".concat(this.state.getDigitsWithoutInternationalPrefix()));
284 }
285
286 if (!formattedNationalNumber) {
287 return prefix(callingCode);
288 }
289
290 return prefix("".concat(callingCode, " ").concat(formattedNationalNumber));
291 }
292
293 return formattedNationalNumber;
294 }
295 }, {
296 key: "getNonFormattedNationalNumberWithPrefix",
297 value: function getNonFormattedNationalNumberWithPrefix() {
298 var _this$state2 = this.state,
299 nationalSignificantNumber = _this$state2.nationalSignificantNumber,
300 complexPrefixBeforeNationalSignificantNumber = _this$state2.complexPrefixBeforeNationalSignificantNumber,
301 nationalPrefix = _this$state2.nationalPrefix;
302 var number = nationalSignificantNumber;
303 var prefix = complexPrefixBeforeNationalSignificantNumber || nationalPrefix;
304
305 if (prefix) {
306 number = prefix + number;
307 }
308
309 return number;
310 }
311 }, {
312 key: "getNonFormattedNumber",
313 value: function getNonFormattedNumber() {
314 var nationalSignificantNumberMatchesInput = this.state.nationalSignificantNumberMatchesInput;
315 return this.getFullNumber(nationalSignificantNumberMatchesInput ? this.getNonFormattedNationalNumberWithPrefix() : this.state.getNationalDigits());
316 }
317 }, {
318 key: "getNonFormattedTemplate",
319 value: function getNonFormattedTemplate() {
320 var number = this.getNonFormattedNumber();
321
322 if (number) {
323 return number.replace(/[\+\d]/g, _AsYouTypeFormatter.DIGIT_PLACEHOLDER);
324 }
325 }
326 }, {
327 key: "isCountryCallingCodeAmbiguous",
328 value: function isCountryCallingCodeAmbiguous() {
329 var callingCode = this.state.callingCode;
330 var countryCodes = this.metadata.getCountryCodesForCallingCode(callingCode);
331 return countryCodes && countryCodes.length > 1;
332 } // Determines the country of the phone number
333 // entered so far based on the country phone code
334 // and the national phone number.
335
336 }, {
337 key: "determineTheCountry",
338 value: function determineTheCountry() {
339 this.state.setCountry((0, _getCountryByCallingCode["default"])(this.isInternational() ? this.state.callingCode : this.defaultCallingCode, this.state.nationalSignificantNumber, this.metadata));
340 }
341 /**
342 * Returns an instance of `PhoneNumber` class.
343 * Will return `undefined` if no national (significant) number
344 * digits have been entered so far, or if no `defaultCountry` has been
345 * set and the user enters a phone number not in international format.
346 */
347
348 }, {
349 key: "getNumber",
350 value: function getNumber() {
351 var _this$state3 = this.state,
352 nationalSignificantNumber = _this$state3.nationalSignificantNumber,
353 carrierCode = _this$state3.carrierCode;
354
355 if (this.isInternational()) {
356 if (!this.state.callingCode) {
357 return;
358 }
359 } else {
360 if (!this.state.country && !this.defaultCallingCode) {
361 return;
362 }
363 }
364
365 if (!nationalSignificantNumber) {
366 return;
367 }
368
369 var countryCode = this.getCountry();
370 var callingCode = this.getCountryCallingCode() || this.defaultCallingCode;
371 var phoneNumber = new _PhoneNumber["default"](countryCode || callingCode, nationalSignificantNumber, this.metadata.metadata);
372
373 if (carrierCode) {
374 phoneNumber.carrierCode = carrierCode;
375 } // Phone number extensions are not supported by "As You Type" formatter.
376
377
378 return phoneNumber;
379 }
380 /**
381 * Returns `true` if the phone number is "possible".
382 * Is just a shortcut for `PhoneNumber.isPossible()`.
383 * @return {boolean}
384 */
385
386 }, {
387 key: "isPossible",
388 value: function isPossible() {
389 var phoneNumber = this.getNumber();
390
391 if (!phoneNumber) {
392 return false;
393 }
394
395 return phoneNumber.isPossible();
396 }
397 /**
398 * Returns `true` if the phone number is "valid".
399 * Is just a shortcut for `PhoneNumber.isValid()`.
400 * @return {boolean}
401 */
402
403 }, {
404 key: "isValid",
405 value: function isValid() {
406 var phoneNumber = this.getNumber();
407
408 if (!phoneNumber) {
409 return false;
410 }
411
412 return phoneNumber.isValid();
413 }
414 /**
415 * @deprecated
416 * This method is used in `react-phone-number-input/source/input-control.js`
417 * in versions before `3.0.16`.
418 */
419
420 }, {
421 key: "getNationalNumber",
422 value: function getNationalNumber() {
423 return this.state.nationalSignificantNumber;
424 }
425 /**
426 * Returns the phone number characters entered by the user.
427 * @return {string}
428 */
429
430 }, {
431 key: "getChars",
432 value: function getChars() {
433 return (this.state.international ? '+' : '') + this.state.digits;
434 }
435 /**
436 * Returns the template for the formatted phone number.
437 * @return {string}
438 */
439
440 }, {
441 key: "getTemplate",
442 value: function getTemplate() {
443 return this.formatter.getTemplate(this.state) || this.getNonFormattedTemplate() || '';
444 }
445 }]);
446
447 return AsYouType;
448}();
449
450exports["default"] = AsYouType;
451//# sourceMappingURL=AsYouType.js.map
\No newline at end of file