node_modules ignore

This commit is contained in:
2025-05-08 23:43:47 +02:00
parent e19d52f172
commit 4574544c9f
65041 changed files with 10593536 additions and 0 deletions

201
server/node_modules/@internationalized/number/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2019 Adobe
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,49 @@
# @internationalized/number
This package is part of [react-spectrum](https://github.com/adobe/react-spectrum). See the repo for more details.
## NumberParser
The `NumberParser` class can be used perform locale-aware parsing of numbers from Unicode strings,
as well as validation of partial user input. It automatically detects the numbering system
used in the input, and supports parsing decimals, percentages, currency values, and units
according to the locale.
### Parsing
```js
import {NumberParser} from '@internationalized/number';
let parser = new NumberParser('en-US', {style: 'percent'});
parser.parse('10%'); // -> 0.1
```
### Validation
```js
import {NumberParser} from '@internationalized/number';
let parser = new NumberParser('en-US', {style: 'unit', unit: 'inch'});
parser.isValidPartialNumber('10 '); // -> true
parser.isValidPartialNumber('10 in'); // -> true
parser.isValidPartialNumber('10 i'); // -> false
parser.isValidPartialNumber('10 x'); // -> false
```
### Detecting the numbering system
```js
import {NumberParser} from '@internationalized/number';
let parser = new NumberParser('en-US', {style: 'decimal'});
parser.getNumberingSystem('١٢') // -> 'arabic'
```
## NumberFormatter
The `NumberFormatter` class is a wrapper around [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) providing additional options, polyfills, and caching for performance. It provides the exact same interface as Intl.NumberFormat, so it is a drop-in replacement. Please see the MDN docs linked above for more details.
We currently polyfill the following features:
* The `signDisplay` option
* The `unit` style, currently only for the `degree` unit in the `narrow` style

View File

@@ -0,0 +1,164 @@
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
$parcel$export(module.exports, "NumberFormatter", () => $0c1d5654b62fc485$export$cc77c4ff7e8673c5);
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/ let $0c1d5654b62fc485$var$formatterCache = new Map();
let $0c1d5654b62fc485$var$supportsSignDisplay = false;
try {
// @ts-ignore
$0c1d5654b62fc485$var$supportsSignDisplay = new Intl.NumberFormat('de-DE', {
signDisplay: 'exceptZero'
}).resolvedOptions().signDisplay === 'exceptZero';
// eslint-disable-next-line no-empty
} catch (e) {}
let $0c1d5654b62fc485$var$supportsUnit = false;
try {
// @ts-ignore
$0c1d5654b62fc485$var$supportsUnit = new Intl.NumberFormat('de-DE', {
style: 'unit',
unit: 'degree'
}).resolvedOptions().style === 'unit';
// eslint-disable-next-line no-empty
} catch (e) {}
// Polyfill for units since Safari doesn't support them yet. See https://bugs.webkit.org/show_bug.cgi?id=215438.
// Currently only polyfilling the unit degree in narrow format for ColorSlider in our supported locales.
// Values were determined by switching to each locale manually in Chrome.
const $0c1d5654b62fc485$var$UNITS = {
degree: {
narrow: {
default: "\xb0",
'ja-JP': " \u5EA6",
'zh-TW': "\u5EA6",
'sl-SI': " \xb0"
}
}
};
class $0c1d5654b62fc485$export$cc77c4ff7e8673c5 {
/** Formats a number value as a string, according to the locale and options provided to the constructor. */ format(value) {
let res = '';
if (!$0c1d5654b62fc485$var$supportsSignDisplay && this.options.signDisplay != null) res = $0c1d5654b62fc485$export$711b50b3c525e0f2(this.numberFormatter, this.options.signDisplay, value);
else res = this.numberFormatter.format(value);
if (this.options.style === 'unit' && !$0c1d5654b62fc485$var$supportsUnit) {
var _UNITS_unit;
let { unit: unit, unitDisplay: unitDisplay = 'short', locale: locale } = this.resolvedOptions();
if (!unit) return res;
let values = (_UNITS_unit = $0c1d5654b62fc485$var$UNITS[unit]) === null || _UNITS_unit === void 0 ? void 0 : _UNITS_unit[unitDisplay];
res += values[locale] || values.default;
}
return res;
}
/** Formats a number to an array of parts such as separators, digits, punctuation, and more. */ formatToParts(value) {
// TODO: implement signDisplay for formatToParts
// @ts-ignore
return this.numberFormatter.formatToParts(value);
}
/** Formats a number range as a string. */ formatRange(start, end) {
// @ts-ignore
if (typeof this.numberFormatter.formatRange === 'function') // @ts-ignore
return this.numberFormatter.formatRange(start, end);
if (end < start) throw new RangeError('End date must be >= start date');
// Very basic fallback for old browsers.
return `${this.format(start)} \u{2013} ${this.format(end)}`;
}
/** Formats a number range as an array of parts. */ formatRangeToParts(start, end) {
// @ts-ignore
if (typeof this.numberFormatter.formatRangeToParts === 'function') // @ts-ignore
return this.numberFormatter.formatRangeToParts(start, end);
if (end < start) throw new RangeError('End date must be >= start date');
let startParts = this.numberFormatter.formatToParts(start);
let endParts = this.numberFormatter.formatToParts(end);
return [
...startParts.map((p)=>({
...p,
source: 'startRange'
})),
{
type: 'literal',
value: " \u2013 ",
source: 'shared'
},
...endParts.map((p)=>({
...p,
source: 'endRange'
}))
];
}
/** Returns the resolved formatting options based on the values passed to the constructor. */ resolvedOptions() {
let options = this.numberFormatter.resolvedOptions();
if (!$0c1d5654b62fc485$var$supportsSignDisplay && this.options.signDisplay != null) options = {
...options,
signDisplay: this.options.signDisplay
};
if (!$0c1d5654b62fc485$var$supportsUnit && this.options.style === 'unit') options = {
...options,
style: 'unit',
unit: this.options.unit,
unitDisplay: this.options.unitDisplay
};
return options;
}
constructor(locale, options = {}){
this.numberFormatter = $0c1d5654b62fc485$var$getCachedNumberFormatter(locale, options);
this.options = options;
}
}
function $0c1d5654b62fc485$var$getCachedNumberFormatter(locale, options = {}) {
let { numberingSystem: numberingSystem } = options;
if (numberingSystem && locale.includes('-nu-')) {
if (!locale.includes('-u-')) locale += '-u-';
locale += `-nu-${numberingSystem}`;
}
if (options.style === 'unit' && !$0c1d5654b62fc485$var$supportsUnit) {
var _UNITS_unit;
let { unit: unit, unitDisplay: unitDisplay = 'short' } = options;
if (!unit) throw new Error('unit option must be provided with style: "unit"');
if (!((_UNITS_unit = $0c1d5654b62fc485$var$UNITS[unit]) === null || _UNITS_unit === void 0 ? void 0 : _UNITS_unit[unitDisplay])) throw new Error(`Unsupported unit ${unit} with unitDisplay = ${unitDisplay}`);
options = {
...options,
style: 'decimal'
};
}
let cacheKey = locale + (options ? Object.entries(options).sort((a, b)=>a[0] < b[0] ? -1 : 1).join() : '');
if ($0c1d5654b62fc485$var$formatterCache.has(cacheKey)) return $0c1d5654b62fc485$var$formatterCache.get(cacheKey);
let numberFormatter = new Intl.NumberFormat(locale, options);
$0c1d5654b62fc485$var$formatterCache.set(cacheKey, numberFormatter);
return numberFormatter;
}
function $0c1d5654b62fc485$export$711b50b3c525e0f2(numberFormat, signDisplay, num) {
if (signDisplay === 'auto') return numberFormat.format(num);
else if (signDisplay === 'never') return numberFormat.format(Math.abs(num));
else {
let needsPositiveSign = false;
if (signDisplay === 'always') needsPositiveSign = num > 0 || Object.is(num, 0);
else if (signDisplay === 'exceptZero') {
if (Object.is(num, -0) || Object.is(num, 0)) num = Math.abs(num);
else needsPositiveSign = num > 0;
}
if (needsPositiveSign) {
let negative = numberFormat.format(-num);
let noSign = numberFormat.format(num);
// ignore RTL/LTR marker character
let minus = negative.replace(noSign, '').replace(/\u200e|\u061C/, '');
if ([
...minus
].length !== 1) console.warn('@react-aria/i18n polyfill for NumberFormat signDisplay: Unsupported case');
let positive = negative.replace(noSign, '!!!').replace(minus, '+').replace('!!!', noSign);
return positive;
} else return numberFormat.format(num);
}
}
//# sourceMappingURL=NumberFormatter.main.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,159 @@
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/ let $488c6ddbf4ef74c2$var$formatterCache = new Map();
let $488c6ddbf4ef74c2$var$supportsSignDisplay = false;
try {
// @ts-ignore
$488c6ddbf4ef74c2$var$supportsSignDisplay = new Intl.NumberFormat('de-DE', {
signDisplay: 'exceptZero'
}).resolvedOptions().signDisplay === 'exceptZero';
// eslint-disable-next-line no-empty
} catch (e) {}
let $488c6ddbf4ef74c2$var$supportsUnit = false;
try {
// @ts-ignore
$488c6ddbf4ef74c2$var$supportsUnit = new Intl.NumberFormat('de-DE', {
style: 'unit',
unit: 'degree'
}).resolvedOptions().style === 'unit';
// eslint-disable-next-line no-empty
} catch (e) {}
// Polyfill for units since Safari doesn't support them yet. See https://bugs.webkit.org/show_bug.cgi?id=215438.
// Currently only polyfilling the unit degree in narrow format for ColorSlider in our supported locales.
// Values were determined by switching to each locale manually in Chrome.
const $488c6ddbf4ef74c2$var$UNITS = {
degree: {
narrow: {
default: "\xb0",
'ja-JP': " \u5EA6",
'zh-TW': "\u5EA6",
'sl-SI': " \xb0"
}
}
};
class $488c6ddbf4ef74c2$export$cc77c4ff7e8673c5 {
/** Formats a number value as a string, according to the locale and options provided to the constructor. */ format(value) {
let res = '';
if (!$488c6ddbf4ef74c2$var$supportsSignDisplay && this.options.signDisplay != null) res = $488c6ddbf4ef74c2$export$711b50b3c525e0f2(this.numberFormatter, this.options.signDisplay, value);
else res = this.numberFormatter.format(value);
if (this.options.style === 'unit' && !$488c6ddbf4ef74c2$var$supportsUnit) {
var _UNITS_unit;
let { unit: unit, unitDisplay: unitDisplay = 'short', locale: locale } = this.resolvedOptions();
if (!unit) return res;
let values = (_UNITS_unit = $488c6ddbf4ef74c2$var$UNITS[unit]) === null || _UNITS_unit === void 0 ? void 0 : _UNITS_unit[unitDisplay];
res += values[locale] || values.default;
}
return res;
}
/** Formats a number to an array of parts such as separators, digits, punctuation, and more. */ formatToParts(value) {
// TODO: implement signDisplay for formatToParts
// @ts-ignore
return this.numberFormatter.formatToParts(value);
}
/** Formats a number range as a string. */ formatRange(start, end) {
// @ts-ignore
if (typeof this.numberFormatter.formatRange === 'function') // @ts-ignore
return this.numberFormatter.formatRange(start, end);
if (end < start) throw new RangeError('End date must be >= start date');
// Very basic fallback for old browsers.
return `${this.format(start)} \u{2013} ${this.format(end)}`;
}
/** Formats a number range as an array of parts. */ formatRangeToParts(start, end) {
// @ts-ignore
if (typeof this.numberFormatter.formatRangeToParts === 'function') // @ts-ignore
return this.numberFormatter.formatRangeToParts(start, end);
if (end < start) throw new RangeError('End date must be >= start date');
let startParts = this.numberFormatter.formatToParts(start);
let endParts = this.numberFormatter.formatToParts(end);
return [
...startParts.map((p)=>({
...p,
source: 'startRange'
})),
{
type: 'literal',
value: " \u2013 ",
source: 'shared'
},
...endParts.map((p)=>({
...p,
source: 'endRange'
}))
];
}
/** Returns the resolved formatting options based on the values passed to the constructor. */ resolvedOptions() {
let options = this.numberFormatter.resolvedOptions();
if (!$488c6ddbf4ef74c2$var$supportsSignDisplay && this.options.signDisplay != null) options = {
...options,
signDisplay: this.options.signDisplay
};
if (!$488c6ddbf4ef74c2$var$supportsUnit && this.options.style === 'unit') options = {
...options,
style: 'unit',
unit: this.options.unit,
unitDisplay: this.options.unitDisplay
};
return options;
}
constructor(locale, options = {}){
this.numberFormatter = $488c6ddbf4ef74c2$var$getCachedNumberFormatter(locale, options);
this.options = options;
}
}
function $488c6ddbf4ef74c2$var$getCachedNumberFormatter(locale, options = {}) {
let { numberingSystem: numberingSystem } = options;
if (numberingSystem && locale.includes('-nu-')) {
if (!locale.includes('-u-')) locale += '-u-';
locale += `-nu-${numberingSystem}`;
}
if (options.style === 'unit' && !$488c6ddbf4ef74c2$var$supportsUnit) {
var _UNITS_unit;
let { unit: unit, unitDisplay: unitDisplay = 'short' } = options;
if (!unit) throw new Error('unit option must be provided with style: "unit"');
if (!((_UNITS_unit = $488c6ddbf4ef74c2$var$UNITS[unit]) === null || _UNITS_unit === void 0 ? void 0 : _UNITS_unit[unitDisplay])) throw new Error(`Unsupported unit ${unit} with unitDisplay = ${unitDisplay}`);
options = {
...options,
style: 'decimal'
};
}
let cacheKey = locale + (options ? Object.entries(options).sort((a, b)=>a[0] < b[0] ? -1 : 1).join() : '');
if ($488c6ddbf4ef74c2$var$formatterCache.has(cacheKey)) return $488c6ddbf4ef74c2$var$formatterCache.get(cacheKey);
let numberFormatter = new Intl.NumberFormat(locale, options);
$488c6ddbf4ef74c2$var$formatterCache.set(cacheKey, numberFormatter);
return numberFormatter;
}
function $488c6ddbf4ef74c2$export$711b50b3c525e0f2(numberFormat, signDisplay, num) {
if (signDisplay === 'auto') return numberFormat.format(num);
else if (signDisplay === 'never') return numberFormat.format(Math.abs(num));
else {
let needsPositiveSign = false;
if (signDisplay === 'always') needsPositiveSign = num > 0 || Object.is(num, 0);
else if (signDisplay === 'exceptZero') {
if (Object.is(num, -0) || Object.is(num, 0)) num = Math.abs(num);
else needsPositiveSign = num > 0;
}
if (needsPositiveSign) {
let negative = numberFormat.format(-num);
let noSign = numberFormat.format(num);
// ignore RTL/LTR marker character
let minus = negative.replace(noSign, '').replace(/\u200e|\u061C/, '');
if ([
...minus
].length !== 1) console.warn('@react-aria/i18n polyfill for NumberFormat signDisplay: Unsupported case');
let positive = negative.replace(noSign, '!!!').replace(minus, '+').replace('!!!', noSign);
return positive;
} else return numberFormat.format(num);
}
}
export {$488c6ddbf4ef74c2$export$cc77c4ff7e8673c5 as NumberFormatter, $488c6ddbf4ef74c2$export$711b50b3c525e0f2 as numberFormatSignDisplayPolyfill};
//# sourceMappingURL=NumberFormatter.module.js.map

View File

@@ -0,0 +1,159 @@
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/ let $488c6ddbf4ef74c2$var$formatterCache = new Map();
let $488c6ddbf4ef74c2$var$supportsSignDisplay = false;
try {
// @ts-ignore
$488c6ddbf4ef74c2$var$supportsSignDisplay = new Intl.NumberFormat('de-DE', {
signDisplay: 'exceptZero'
}).resolvedOptions().signDisplay === 'exceptZero';
// eslint-disable-next-line no-empty
} catch (e) {}
let $488c6ddbf4ef74c2$var$supportsUnit = false;
try {
// @ts-ignore
$488c6ddbf4ef74c2$var$supportsUnit = new Intl.NumberFormat('de-DE', {
style: 'unit',
unit: 'degree'
}).resolvedOptions().style === 'unit';
// eslint-disable-next-line no-empty
} catch (e) {}
// Polyfill for units since Safari doesn't support them yet. See https://bugs.webkit.org/show_bug.cgi?id=215438.
// Currently only polyfilling the unit degree in narrow format for ColorSlider in our supported locales.
// Values were determined by switching to each locale manually in Chrome.
const $488c6ddbf4ef74c2$var$UNITS = {
degree: {
narrow: {
default: "\xb0",
'ja-JP': " \u5EA6",
'zh-TW': "\u5EA6",
'sl-SI': " \xb0"
}
}
};
class $488c6ddbf4ef74c2$export$cc77c4ff7e8673c5 {
/** Formats a number value as a string, according to the locale and options provided to the constructor. */ format(value) {
let res = '';
if (!$488c6ddbf4ef74c2$var$supportsSignDisplay && this.options.signDisplay != null) res = $488c6ddbf4ef74c2$export$711b50b3c525e0f2(this.numberFormatter, this.options.signDisplay, value);
else res = this.numberFormatter.format(value);
if (this.options.style === 'unit' && !$488c6ddbf4ef74c2$var$supportsUnit) {
var _UNITS_unit;
let { unit: unit, unitDisplay: unitDisplay = 'short', locale: locale } = this.resolvedOptions();
if (!unit) return res;
let values = (_UNITS_unit = $488c6ddbf4ef74c2$var$UNITS[unit]) === null || _UNITS_unit === void 0 ? void 0 : _UNITS_unit[unitDisplay];
res += values[locale] || values.default;
}
return res;
}
/** Formats a number to an array of parts such as separators, digits, punctuation, and more. */ formatToParts(value) {
// TODO: implement signDisplay for formatToParts
// @ts-ignore
return this.numberFormatter.formatToParts(value);
}
/** Formats a number range as a string. */ formatRange(start, end) {
// @ts-ignore
if (typeof this.numberFormatter.formatRange === 'function') // @ts-ignore
return this.numberFormatter.formatRange(start, end);
if (end < start) throw new RangeError('End date must be >= start date');
// Very basic fallback for old browsers.
return `${this.format(start)} \u{2013} ${this.format(end)}`;
}
/** Formats a number range as an array of parts. */ formatRangeToParts(start, end) {
// @ts-ignore
if (typeof this.numberFormatter.formatRangeToParts === 'function') // @ts-ignore
return this.numberFormatter.formatRangeToParts(start, end);
if (end < start) throw new RangeError('End date must be >= start date');
let startParts = this.numberFormatter.formatToParts(start);
let endParts = this.numberFormatter.formatToParts(end);
return [
...startParts.map((p)=>({
...p,
source: 'startRange'
})),
{
type: 'literal',
value: " \u2013 ",
source: 'shared'
},
...endParts.map((p)=>({
...p,
source: 'endRange'
}))
];
}
/** Returns the resolved formatting options based on the values passed to the constructor. */ resolvedOptions() {
let options = this.numberFormatter.resolvedOptions();
if (!$488c6ddbf4ef74c2$var$supportsSignDisplay && this.options.signDisplay != null) options = {
...options,
signDisplay: this.options.signDisplay
};
if (!$488c6ddbf4ef74c2$var$supportsUnit && this.options.style === 'unit') options = {
...options,
style: 'unit',
unit: this.options.unit,
unitDisplay: this.options.unitDisplay
};
return options;
}
constructor(locale, options = {}){
this.numberFormatter = $488c6ddbf4ef74c2$var$getCachedNumberFormatter(locale, options);
this.options = options;
}
}
function $488c6ddbf4ef74c2$var$getCachedNumberFormatter(locale, options = {}) {
let { numberingSystem: numberingSystem } = options;
if (numberingSystem && locale.includes('-nu-')) {
if (!locale.includes('-u-')) locale += '-u-';
locale += `-nu-${numberingSystem}`;
}
if (options.style === 'unit' && !$488c6ddbf4ef74c2$var$supportsUnit) {
var _UNITS_unit;
let { unit: unit, unitDisplay: unitDisplay = 'short' } = options;
if (!unit) throw new Error('unit option must be provided with style: "unit"');
if (!((_UNITS_unit = $488c6ddbf4ef74c2$var$UNITS[unit]) === null || _UNITS_unit === void 0 ? void 0 : _UNITS_unit[unitDisplay])) throw new Error(`Unsupported unit ${unit} with unitDisplay = ${unitDisplay}`);
options = {
...options,
style: 'decimal'
};
}
let cacheKey = locale + (options ? Object.entries(options).sort((a, b)=>a[0] < b[0] ? -1 : 1).join() : '');
if ($488c6ddbf4ef74c2$var$formatterCache.has(cacheKey)) return $488c6ddbf4ef74c2$var$formatterCache.get(cacheKey);
let numberFormatter = new Intl.NumberFormat(locale, options);
$488c6ddbf4ef74c2$var$formatterCache.set(cacheKey, numberFormatter);
return numberFormatter;
}
function $488c6ddbf4ef74c2$export$711b50b3c525e0f2(numberFormat, signDisplay, num) {
if (signDisplay === 'auto') return numberFormat.format(num);
else if (signDisplay === 'never') return numberFormat.format(Math.abs(num));
else {
let needsPositiveSign = false;
if (signDisplay === 'always') needsPositiveSign = num > 0 || Object.is(num, 0);
else if (signDisplay === 'exceptZero') {
if (Object.is(num, -0) || Object.is(num, 0)) num = Math.abs(num);
else needsPositiveSign = num > 0;
}
if (needsPositiveSign) {
let negative = numberFormat.format(-num);
let noSign = numberFormat.format(num);
// ignore RTL/LTR marker character
let minus = negative.replace(noSign, '').replace(/\u200e|\u061C/, '');
if ([
...minus
].length !== 1) console.warn('@react-aria/i18n polyfill for NumberFormat signDisplay: Unsupported case');
let positive = negative.replace(noSign, '!!!').replace(minus, '+').replace('!!!', noSign);
return positive;
} else return numberFormat.format(num);
}
}
export {$488c6ddbf4ef74c2$export$cc77c4ff7e8673c5 as NumberFormatter, $488c6ddbf4ef74c2$export$711b50b3c525e0f2 as numberFormatSignDisplayPolyfill};
//# sourceMappingURL=NumberFormatter.module.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,257 @@
var $0c1d5654b62fc485$exports = require("./NumberFormatter.main.js");
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
$parcel$export(module.exports, "NumberParser", () => $d68f3f4c684426c6$export$cd11ab140839f11d);
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
const $d68f3f4c684426c6$var$CURRENCY_SIGN_REGEX = new RegExp('^.*\\(.*\\).*$');
const $d68f3f4c684426c6$var$NUMBERING_SYSTEMS = [
'latn',
'arab',
'hanidec'
];
class $d68f3f4c684426c6$export$cd11ab140839f11d {
/**
* Parses the given string to a number. Returns NaN if a valid number could not be parsed.
*/ parse(value) {
return $d68f3f4c684426c6$var$getNumberParserImpl(this.locale, this.options, value).parse(value);
}
/**
* Returns whether the given string could potentially be a valid number. This should be used to
* validate user input as the user types. If a `minValue` or `maxValue` is provided, the validity
* of the minus/plus sign characters can be checked.
*/ isValidPartialNumber(value, minValue, maxValue) {
return $d68f3f4c684426c6$var$getNumberParserImpl(this.locale, this.options, value).isValidPartialNumber(value, minValue, maxValue);
}
/**
* Returns a numbering system for which the given string is valid in the current locale.
* If no numbering system could be detected, the default numbering system for the current
* locale is returned.
*/ getNumberingSystem(value) {
return $d68f3f4c684426c6$var$getNumberParserImpl(this.locale, this.options, value).options.numberingSystem;
}
constructor(locale, options = {}){
this.locale = locale;
this.options = options;
}
}
const $d68f3f4c684426c6$var$numberParserCache = new Map();
function $d68f3f4c684426c6$var$getNumberParserImpl(locale, options, value) {
// First try the default numbering system for the provided locale
let defaultParser = $d68f3f4c684426c6$var$getCachedNumberParser(locale, options);
// If that doesn't match, and the locale doesn't include a hard coded numbering system,
// try each of the other supported numbering systems until we find one that matches.
if (!locale.includes('-nu-') && !defaultParser.isValidPartialNumber(value)) {
for (let numberingSystem of $d68f3f4c684426c6$var$NUMBERING_SYSTEMS)if (numberingSystem !== defaultParser.options.numberingSystem) {
let parser = $d68f3f4c684426c6$var$getCachedNumberParser(locale + (locale.includes('-u-') ? '-nu-' : '-u-nu-') + numberingSystem, options);
if (parser.isValidPartialNumber(value)) return parser;
}
}
return defaultParser;
}
function $d68f3f4c684426c6$var$getCachedNumberParser(locale, options) {
let cacheKey = locale + (options ? Object.entries(options).sort((a, b)=>a[0] < b[0] ? -1 : 1).join() : '');
let parser = $d68f3f4c684426c6$var$numberParserCache.get(cacheKey);
if (!parser) {
parser = new $d68f3f4c684426c6$var$NumberParserImpl(locale, options);
$d68f3f4c684426c6$var$numberParserCache.set(cacheKey, parser);
}
return parser;
}
// The actual number parser implementation. Instances of this class are cached
// based on the locale, options, and detected numbering system.
class $d68f3f4c684426c6$var$NumberParserImpl {
parse(value) {
// to parse the number, we need to remove anything that isn't actually part of the number, for example we want '-10.40' not '-10.40 USD'
let fullySanitizedValue = this.sanitize(value);
if (this.symbols.group) // Remove group characters, and replace decimal points and numerals with ASCII values.
fullySanitizedValue = $d68f3f4c684426c6$var$replaceAll(fullySanitizedValue, this.symbols.group, '');
if (this.symbols.decimal) fullySanitizedValue = fullySanitizedValue.replace(this.symbols.decimal, '.');
if (this.symbols.minusSign) fullySanitizedValue = fullySanitizedValue.replace(this.symbols.minusSign, '-');
fullySanitizedValue = fullySanitizedValue.replace(this.symbols.numeral, this.symbols.index);
if (this.options.style === 'percent') {
// javascript is bad at dividing by 100 and maintaining the same significant figures, so perform it on the string before parsing
let isNegative = fullySanitizedValue.indexOf('-');
fullySanitizedValue = fullySanitizedValue.replace('-', '');
let index = fullySanitizedValue.indexOf('.');
if (index === -1) index = fullySanitizedValue.length;
fullySanitizedValue = fullySanitizedValue.replace('.', '');
if (index - 2 === 0) fullySanitizedValue = `0.${fullySanitizedValue}`;
else if (index - 2 === -1) fullySanitizedValue = `0.0${fullySanitizedValue}`;
else if (index - 2 === -2) fullySanitizedValue = '0.00';
else fullySanitizedValue = `${fullySanitizedValue.slice(0, index - 2)}.${fullySanitizedValue.slice(index - 2)}`;
if (isNegative > -1) fullySanitizedValue = `-${fullySanitizedValue}`;
}
let newValue = fullySanitizedValue ? +fullySanitizedValue : NaN;
if (isNaN(newValue)) return NaN;
if (this.options.style === 'percent') {
var _this_options_minimumFractionDigits, _this_options_maximumFractionDigits;
// extra step for rounding percents to what our formatter would output
let options = {
...this.options,
style: 'decimal',
minimumFractionDigits: Math.min(((_this_options_minimumFractionDigits = this.options.minimumFractionDigits) !== null && _this_options_minimumFractionDigits !== void 0 ? _this_options_minimumFractionDigits : 0) + 2, 20),
maximumFractionDigits: Math.min(((_this_options_maximumFractionDigits = this.options.maximumFractionDigits) !== null && _this_options_maximumFractionDigits !== void 0 ? _this_options_maximumFractionDigits : 0) + 2, 20)
};
return new $d68f3f4c684426c6$export$cd11ab140839f11d(this.locale, options).parse(new (0, $0c1d5654b62fc485$exports.NumberFormatter)(this.locale, options).format(newValue));
}
// accounting will always be stripped to a positive number, so if it's accounting and has a () around everything, then we need to make it negative again
if (this.options.currencySign === 'accounting' && $d68f3f4c684426c6$var$CURRENCY_SIGN_REGEX.test(value)) newValue = -1 * newValue;
return newValue;
}
sanitize(value) {
// Remove literals and whitespace, which are allowed anywhere in the string
value = value.replace(this.symbols.literals, '');
// Replace the ASCII minus sign with the minus sign used in the current locale
// so that both are allowed in case the user's keyboard doesn't have the locale's minus sign.
if (this.symbols.minusSign) value = value.replace('-', this.symbols.minusSign);
// In arab numeral system, their decimal character is 1643, but most keyboards don't type that
// instead they use the , (44) character or apparently the (1548) character.
if (this.options.numberingSystem === 'arab') {
if (this.symbols.decimal) {
value = value.replace(',', this.symbols.decimal);
value = value.replace(String.fromCharCode(1548), this.symbols.decimal);
}
if (this.symbols.group) value = $d68f3f4c684426c6$var$replaceAll(value, '.', this.symbols.group);
}
// fr-FR group character is char code 8239, but that's not a key on the french keyboard,
// so allow 'period' as a group char and replace it with a space
if (this.options.locale === 'fr-FR') value = $d68f3f4c684426c6$var$replaceAll(value, '.', String.fromCharCode(8239));
return value;
}
isValidPartialNumber(value, minValue = -Infinity, maxValue = Infinity) {
value = this.sanitize(value);
// Remove minus or plus sign, which must be at the start of the string.
if (this.symbols.minusSign && value.startsWith(this.symbols.minusSign) && minValue < 0) value = value.slice(this.symbols.minusSign.length);
else if (this.symbols.plusSign && value.startsWith(this.symbols.plusSign) && maxValue > 0) value = value.slice(this.symbols.plusSign.length);
// Numbers cannot start with a group separator
if (this.symbols.group && value.startsWith(this.symbols.group)) return false;
// Numbers that can't have any decimal values fail if a decimal character is typed
if (this.symbols.decimal && value.indexOf(this.symbols.decimal) > -1 && this.options.maximumFractionDigits === 0) return false;
// Remove numerals, groups, and decimals
if (this.symbols.group) value = $d68f3f4c684426c6$var$replaceAll(value, this.symbols.group, '');
value = value.replace(this.symbols.numeral, '');
if (this.symbols.decimal) value = value.replace(this.symbols.decimal, '');
// The number is valid if there are no remaining characters
return value.length === 0;
}
constructor(locale, options = {}){
this.locale = locale;
this.formatter = new Intl.NumberFormat(locale, options);
this.options = this.formatter.resolvedOptions();
this.symbols = $d68f3f4c684426c6$var$getSymbols(locale, this.formatter, this.options, options);
var _this_options_minimumFractionDigits, _this_options_maximumFractionDigits;
if (this.options.style === 'percent' && (((_this_options_minimumFractionDigits = this.options.minimumFractionDigits) !== null && _this_options_minimumFractionDigits !== void 0 ? _this_options_minimumFractionDigits : 0) > 18 || ((_this_options_maximumFractionDigits = this.options.maximumFractionDigits) !== null && _this_options_maximumFractionDigits !== void 0 ? _this_options_maximumFractionDigits : 0) > 18)) console.warn('NumberParser cannot handle percentages with greater than 18 decimal places, please reduce the number in your options.');
}
}
const $d68f3f4c684426c6$var$nonLiteralParts = new Set([
'decimal',
'fraction',
'integer',
'minusSign',
'plusSign',
'group'
]);
// This list is derived from https://www.unicode.org/cldr/charts/43/supplemental/language_plural_rules.html#comparison and includes
// all unique numbers which we need to check in order to determine all the plural forms for a given locale.
// See: https://github.com/adobe/react-spectrum/pull/5134/files#r1337037855 for used script
const $d68f3f4c684426c6$var$pluralNumbers = [
0,
4,
2,
1,
11,
20,
3,
7,
100,
21,
0.1,
1.1
];
function $d68f3f4c684426c6$var$getSymbols(locale, formatter, intlOptions, originalOptions) {
var _allParts_find, _posAllParts_find, _decimalParts_find, _allParts_find1;
// formatter needs access to all decimal places in order to generate the correct literal strings for the plural set
let symbolFormatter = new Intl.NumberFormat(locale, {
...intlOptions,
minimumSignificantDigits: 1,
maximumSignificantDigits: 21
});
// Note: some locale's don't add a group symbol until there is a ten thousands place
let allParts = symbolFormatter.formatToParts(-10000.111);
let posAllParts = symbolFormatter.formatToParts(10000.111);
let pluralParts = $d68f3f4c684426c6$var$pluralNumbers.map((n)=>symbolFormatter.formatToParts(n));
var _allParts_find_value;
let minusSign = (_allParts_find_value = (_allParts_find = allParts.find((p)=>p.type === 'minusSign')) === null || _allParts_find === void 0 ? void 0 : _allParts_find.value) !== null && _allParts_find_value !== void 0 ? _allParts_find_value : '-';
let plusSign = (_posAllParts_find = posAllParts.find((p)=>p.type === 'plusSign')) === null || _posAllParts_find === void 0 ? void 0 : _posAllParts_find.value;
// Safari does not support the signDisplay option, but our number parser polyfills it.
// If no plus sign was returned, but the original options contained signDisplay, default to the '+' character.
// @ts-ignore
if (!plusSign && ((originalOptions === null || originalOptions === void 0 ? void 0 : originalOptions.signDisplay) === 'exceptZero' || (originalOptions === null || originalOptions === void 0 ? void 0 : originalOptions.signDisplay) === 'always')) plusSign = '+';
// If maximumSignificantDigits is 1 (the minimum) then we won't get decimal characters out of the above formatters
// Percent also defaults to 0 fractionDigits, so we need to make a new one that isn't percent to get an accurate decimal
let decimalParts = new Intl.NumberFormat(locale, {
...intlOptions,
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).formatToParts(0.001);
let decimal = (_decimalParts_find = decimalParts.find((p)=>p.type === 'decimal')) === null || _decimalParts_find === void 0 ? void 0 : _decimalParts_find.value;
let group = (_allParts_find1 = allParts.find((p)=>p.type === 'group')) === null || _allParts_find1 === void 0 ? void 0 : _allParts_find1.value;
// this set is also for a regex, it's all literals that might be in the string we want to eventually parse that
// don't contribute to the numerical value
let allPartsLiterals = allParts.filter((p)=>!$d68f3f4c684426c6$var$nonLiteralParts.has(p.type)).map((p)=>$d68f3f4c684426c6$var$escapeRegex(p.value));
let pluralPartsLiterals = pluralParts.flatMap((p)=>p.filter((p)=>!$d68f3f4c684426c6$var$nonLiteralParts.has(p.type)).map((p)=>$d68f3f4c684426c6$var$escapeRegex(p.value)));
let sortedLiterals = [
...new Set([
...allPartsLiterals,
...pluralPartsLiterals
])
].sort((a, b)=>b.length - a.length);
let literals = sortedLiterals.length === 0 ? new RegExp('[\\p{White_Space}]', 'gu') : new RegExp(`${sortedLiterals.join('|')}|[\\p{White_Space}]`, 'gu');
// These are for replacing non-latn characters with the latn equivalent
let numerals = [
...new Intl.NumberFormat(intlOptions.locale, {
useGrouping: false
}).format(9876543210)
].reverse();
let indexes = new Map(numerals.map((d, i)=>[
d,
i
]));
let numeral = new RegExp(`[${numerals.join('')}]`, 'g');
let index = (d)=>String(indexes.get(d));
return {
minusSign: minusSign,
plusSign: plusSign,
decimal: decimal,
group: group,
literals: literals,
numeral: numeral,
index: index
};
}
function $d68f3f4c684426c6$var$replaceAll(str, find, replace) {
// @ts-ignore
if (str.replaceAll) // @ts-ignore
return str.replaceAll(find, replace);
return str.split(find).join(replace);
}
function $d68f3f4c684426c6$var$escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
//# sourceMappingURL=NumberParser.main.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,252 @@
import {NumberFormatter as $488c6ddbf4ef74c2$export$cc77c4ff7e8673c5} from "./NumberFormatter.mjs";
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
const $6c7bd7858deea686$var$CURRENCY_SIGN_REGEX = new RegExp('^.*\\(.*\\).*$');
const $6c7bd7858deea686$var$NUMBERING_SYSTEMS = [
'latn',
'arab',
'hanidec'
];
class $6c7bd7858deea686$export$cd11ab140839f11d {
/**
* Parses the given string to a number. Returns NaN if a valid number could not be parsed.
*/ parse(value) {
return $6c7bd7858deea686$var$getNumberParserImpl(this.locale, this.options, value).parse(value);
}
/**
* Returns whether the given string could potentially be a valid number. This should be used to
* validate user input as the user types. If a `minValue` or `maxValue` is provided, the validity
* of the minus/plus sign characters can be checked.
*/ isValidPartialNumber(value, minValue, maxValue) {
return $6c7bd7858deea686$var$getNumberParserImpl(this.locale, this.options, value).isValidPartialNumber(value, minValue, maxValue);
}
/**
* Returns a numbering system for which the given string is valid in the current locale.
* If no numbering system could be detected, the default numbering system for the current
* locale is returned.
*/ getNumberingSystem(value) {
return $6c7bd7858deea686$var$getNumberParserImpl(this.locale, this.options, value).options.numberingSystem;
}
constructor(locale, options = {}){
this.locale = locale;
this.options = options;
}
}
const $6c7bd7858deea686$var$numberParserCache = new Map();
function $6c7bd7858deea686$var$getNumberParserImpl(locale, options, value) {
// First try the default numbering system for the provided locale
let defaultParser = $6c7bd7858deea686$var$getCachedNumberParser(locale, options);
// If that doesn't match, and the locale doesn't include a hard coded numbering system,
// try each of the other supported numbering systems until we find one that matches.
if (!locale.includes('-nu-') && !defaultParser.isValidPartialNumber(value)) {
for (let numberingSystem of $6c7bd7858deea686$var$NUMBERING_SYSTEMS)if (numberingSystem !== defaultParser.options.numberingSystem) {
let parser = $6c7bd7858deea686$var$getCachedNumberParser(locale + (locale.includes('-u-') ? '-nu-' : '-u-nu-') + numberingSystem, options);
if (parser.isValidPartialNumber(value)) return parser;
}
}
return defaultParser;
}
function $6c7bd7858deea686$var$getCachedNumberParser(locale, options) {
let cacheKey = locale + (options ? Object.entries(options).sort((a, b)=>a[0] < b[0] ? -1 : 1).join() : '');
let parser = $6c7bd7858deea686$var$numberParserCache.get(cacheKey);
if (!parser) {
parser = new $6c7bd7858deea686$var$NumberParserImpl(locale, options);
$6c7bd7858deea686$var$numberParserCache.set(cacheKey, parser);
}
return parser;
}
// The actual number parser implementation. Instances of this class are cached
// based on the locale, options, and detected numbering system.
class $6c7bd7858deea686$var$NumberParserImpl {
parse(value) {
// to parse the number, we need to remove anything that isn't actually part of the number, for example we want '-10.40' not '-10.40 USD'
let fullySanitizedValue = this.sanitize(value);
if (this.symbols.group) // Remove group characters, and replace decimal points and numerals with ASCII values.
fullySanitizedValue = $6c7bd7858deea686$var$replaceAll(fullySanitizedValue, this.symbols.group, '');
if (this.symbols.decimal) fullySanitizedValue = fullySanitizedValue.replace(this.symbols.decimal, '.');
if (this.symbols.minusSign) fullySanitizedValue = fullySanitizedValue.replace(this.symbols.minusSign, '-');
fullySanitizedValue = fullySanitizedValue.replace(this.symbols.numeral, this.symbols.index);
if (this.options.style === 'percent') {
// javascript is bad at dividing by 100 and maintaining the same significant figures, so perform it on the string before parsing
let isNegative = fullySanitizedValue.indexOf('-');
fullySanitizedValue = fullySanitizedValue.replace('-', '');
let index = fullySanitizedValue.indexOf('.');
if (index === -1) index = fullySanitizedValue.length;
fullySanitizedValue = fullySanitizedValue.replace('.', '');
if (index - 2 === 0) fullySanitizedValue = `0.${fullySanitizedValue}`;
else if (index - 2 === -1) fullySanitizedValue = `0.0${fullySanitizedValue}`;
else if (index - 2 === -2) fullySanitizedValue = '0.00';
else fullySanitizedValue = `${fullySanitizedValue.slice(0, index - 2)}.${fullySanitizedValue.slice(index - 2)}`;
if (isNegative > -1) fullySanitizedValue = `-${fullySanitizedValue}`;
}
let newValue = fullySanitizedValue ? +fullySanitizedValue : NaN;
if (isNaN(newValue)) return NaN;
if (this.options.style === 'percent') {
var _this_options_minimumFractionDigits, _this_options_maximumFractionDigits;
// extra step for rounding percents to what our formatter would output
let options = {
...this.options,
style: 'decimal',
minimumFractionDigits: Math.min(((_this_options_minimumFractionDigits = this.options.minimumFractionDigits) !== null && _this_options_minimumFractionDigits !== void 0 ? _this_options_minimumFractionDigits : 0) + 2, 20),
maximumFractionDigits: Math.min(((_this_options_maximumFractionDigits = this.options.maximumFractionDigits) !== null && _this_options_maximumFractionDigits !== void 0 ? _this_options_maximumFractionDigits : 0) + 2, 20)
};
return new $6c7bd7858deea686$export$cd11ab140839f11d(this.locale, options).parse(new (0, $488c6ddbf4ef74c2$export$cc77c4ff7e8673c5)(this.locale, options).format(newValue));
}
// accounting will always be stripped to a positive number, so if it's accounting and has a () around everything, then we need to make it negative again
if (this.options.currencySign === 'accounting' && $6c7bd7858deea686$var$CURRENCY_SIGN_REGEX.test(value)) newValue = -1 * newValue;
return newValue;
}
sanitize(value) {
// Remove literals and whitespace, which are allowed anywhere in the string
value = value.replace(this.symbols.literals, '');
// Replace the ASCII minus sign with the minus sign used in the current locale
// so that both are allowed in case the user's keyboard doesn't have the locale's minus sign.
if (this.symbols.minusSign) value = value.replace('-', this.symbols.minusSign);
// In arab numeral system, their decimal character is 1643, but most keyboards don't type that
// instead they use the , (44) character or apparently the (1548) character.
if (this.options.numberingSystem === 'arab') {
if (this.symbols.decimal) {
value = value.replace(',', this.symbols.decimal);
value = value.replace(String.fromCharCode(1548), this.symbols.decimal);
}
if (this.symbols.group) value = $6c7bd7858deea686$var$replaceAll(value, '.', this.symbols.group);
}
// fr-FR group character is char code 8239, but that's not a key on the french keyboard,
// so allow 'period' as a group char and replace it with a space
if (this.options.locale === 'fr-FR') value = $6c7bd7858deea686$var$replaceAll(value, '.', String.fromCharCode(8239));
return value;
}
isValidPartialNumber(value, minValue = -Infinity, maxValue = Infinity) {
value = this.sanitize(value);
// Remove minus or plus sign, which must be at the start of the string.
if (this.symbols.minusSign && value.startsWith(this.symbols.minusSign) && minValue < 0) value = value.slice(this.symbols.minusSign.length);
else if (this.symbols.plusSign && value.startsWith(this.symbols.plusSign) && maxValue > 0) value = value.slice(this.symbols.plusSign.length);
// Numbers cannot start with a group separator
if (this.symbols.group && value.startsWith(this.symbols.group)) return false;
// Numbers that can't have any decimal values fail if a decimal character is typed
if (this.symbols.decimal && value.indexOf(this.symbols.decimal) > -1 && this.options.maximumFractionDigits === 0) return false;
// Remove numerals, groups, and decimals
if (this.symbols.group) value = $6c7bd7858deea686$var$replaceAll(value, this.symbols.group, '');
value = value.replace(this.symbols.numeral, '');
if (this.symbols.decimal) value = value.replace(this.symbols.decimal, '');
// The number is valid if there are no remaining characters
return value.length === 0;
}
constructor(locale, options = {}){
this.locale = locale;
this.formatter = new Intl.NumberFormat(locale, options);
this.options = this.formatter.resolvedOptions();
this.symbols = $6c7bd7858deea686$var$getSymbols(locale, this.formatter, this.options, options);
var _this_options_minimumFractionDigits, _this_options_maximumFractionDigits;
if (this.options.style === 'percent' && (((_this_options_minimumFractionDigits = this.options.minimumFractionDigits) !== null && _this_options_minimumFractionDigits !== void 0 ? _this_options_minimumFractionDigits : 0) > 18 || ((_this_options_maximumFractionDigits = this.options.maximumFractionDigits) !== null && _this_options_maximumFractionDigits !== void 0 ? _this_options_maximumFractionDigits : 0) > 18)) console.warn('NumberParser cannot handle percentages with greater than 18 decimal places, please reduce the number in your options.');
}
}
const $6c7bd7858deea686$var$nonLiteralParts = new Set([
'decimal',
'fraction',
'integer',
'minusSign',
'plusSign',
'group'
]);
// This list is derived from https://www.unicode.org/cldr/charts/43/supplemental/language_plural_rules.html#comparison and includes
// all unique numbers which we need to check in order to determine all the plural forms for a given locale.
// See: https://github.com/adobe/react-spectrum/pull/5134/files#r1337037855 for used script
const $6c7bd7858deea686$var$pluralNumbers = [
0,
4,
2,
1,
11,
20,
3,
7,
100,
21,
0.1,
1.1
];
function $6c7bd7858deea686$var$getSymbols(locale, formatter, intlOptions, originalOptions) {
var _allParts_find, _posAllParts_find, _decimalParts_find, _allParts_find1;
// formatter needs access to all decimal places in order to generate the correct literal strings for the plural set
let symbolFormatter = new Intl.NumberFormat(locale, {
...intlOptions,
minimumSignificantDigits: 1,
maximumSignificantDigits: 21
});
// Note: some locale's don't add a group symbol until there is a ten thousands place
let allParts = symbolFormatter.formatToParts(-10000.111);
let posAllParts = symbolFormatter.formatToParts(10000.111);
let pluralParts = $6c7bd7858deea686$var$pluralNumbers.map((n)=>symbolFormatter.formatToParts(n));
var _allParts_find_value;
let minusSign = (_allParts_find_value = (_allParts_find = allParts.find((p)=>p.type === 'minusSign')) === null || _allParts_find === void 0 ? void 0 : _allParts_find.value) !== null && _allParts_find_value !== void 0 ? _allParts_find_value : '-';
let plusSign = (_posAllParts_find = posAllParts.find((p)=>p.type === 'plusSign')) === null || _posAllParts_find === void 0 ? void 0 : _posAllParts_find.value;
// Safari does not support the signDisplay option, but our number parser polyfills it.
// If no plus sign was returned, but the original options contained signDisplay, default to the '+' character.
// @ts-ignore
if (!plusSign && ((originalOptions === null || originalOptions === void 0 ? void 0 : originalOptions.signDisplay) === 'exceptZero' || (originalOptions === null || originalOptions === void 0 ? void 0 : originalOptions.signDisplay) === 'always')) plusSign = '+';
// If maximumSignificantDigits is 1 (the minimum) then we won't get decimal characters out of the above formatters
// Percent also defaults to 0 fractionDigits, so we need to make a new one that isn't percent to get an accurate decimal
let decimalParts = new Intl.NumberFormat(locale, {
...intlOptions,
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).formatToParts(0.001);
let decimal = (_decimalParts_find = decimalParts.find((p)=>p.type === 'decimal')) === null || _decimalParts_find === void 0 ? void 0 : _decimalParts_find.value;
let group = (_allParts_find1 = allParts.find((p)=>p.type === 'group')) === null || _allParts_find1 === void 0 ? void 0 : _allParts_find1.value;
// this set is also for a regex, it's all literals that might be in the string we want to eventually parse that
// don't contribute to the numerical value
let allPartsLiterals = allParts.filter((p)=>!$6c7bd7858deea686$var$nonLiteralParts.has(p.type)).map((p)=>$6c7bd7858deea686$var$escapeRegex(p.value));
let pluralPartsLiterals = pluralParts.flatMap((p)=>p.filter((p)=>!$6c7bd7858deea686$var$nonLiteralParts.has(p.type)).map((p)=>$6c7bd7858deea686$var$escapeRegex(p.value)));
let sortedLiterals = [
...new Set([
...allPartsLiterals,
...pluralPartsLiterals
])
].sort((a, b)=>b.length - a.length);
let literals = sortedLiterals.length === 0 ? new RegExp('[\\p{White_Space}]', 'gu') : new RegExp(`${sortedLiterals.join('|')}|[\\p{White_Space}]`, 'gu');
// These are for replacing non-latn characters with the latn equivalent
let numerals = [
...new Intl.NumberFormat(intlOptions.locale, {
useGrouping: false
}).format(9876543210)
].reverse();
let indexes = new Map(numerals.map((d, i)=>[
d,
i
]));
let numeral = new RegExp(`[${numerals.join('')}]`, 'g');
let index = (d)=>String(indexes.get(d));
return {
minusSign: minusSign,
plusSign: plusSign,
decimal: decimal,
group: group,
literals: literals,
numeral: numeral,
index: index
};
}
function $6c7bd7858deea686$var$replaceAll(str, find, replace) {
// @ts-ignore
if (str.replaceAll) // @ts-ignore
return str.replaceAll(find, replace);
return str.split(find).join(replace);
}
function $6c7bd7858deea686$var$escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export {$6c7bd7858deea686$export$cd11ab140839f11d as NumberParser};
//# sourceMappingURL=NumberParser.module.js.map

View File

@@ -0,0 +1,252 @@
import {NumberFormatter as $488c6ddbf4ef74c2$export$cc77c4ff7e8673c5} from "./NumberFormatter.module.js";
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
const $6c7bd7858deea686$var$CURRENCY_SIGN_REGEX = new RegExp('^.*\\(.*\\).*$');
const $6c7bd7858deea686$var$NUMBERING_SYSTEMS = [
'latn',
'arab',
'hanidec'
];
class $6c7bd7858deea686$export$cd11ab140839f11d {
/**
* Parses the given string to a number. Returns NaN if a valid number could not be parsed.
*/ parse(value) {
return $6c7bd7858deea686$var$getNumberParserImpl(this.locale, this.options, value).parse(value);
}
/**
* Returns whether the given string could potentially be a valid number. This should be used to
* validate user input as the user types. If a `minValue` or `maxValue` is provided, the validity
* of the minus/plus sign characters can be checked.
*/ isValidPartialNumber(value, minValue, maxValue) {
return $6c7bd7858deea686$var$getNumberParserImpl(this.locale, this.options, value).isValidPartialNumber(value, minValue, maxValue);
}
/**
* Returns a numbering system for which the given string is valid in the current locale.
* If no numbering system could be detected, the default numbering system for the current
* locale is returned.
*/ getNumberingSystem(value) {
return $6c7bd7858deea686$var$getNumberParserImpl(this.locale, this.options, value).options.numberingSystem;
}
constructor(locale, options = {}){
this.locale = locale;
this.options = options;
}
}
const $6c7bd7858deea686$var$numberParserCache = new Map();
function $6c7bd7858deea686$var$getNumberParserImpl(locale, options, value) {
// First try the default numbering system for the provided locale
let defaultParser = $6c7bd7858deea686$var$getCachedNumberParser(locale, options);
// If that doesn't match, and the locale doesn't include a hard coded numbering system,
// try each of the other supported numbering systems until we find one that matches.
if (!locale.includes('-nu-') && !defaultParser.isValidPartialNumber(value)) {
for (let numberingSystem of $6c7bd7858deea686$var$NUMBERING_SYSTEMS)if (numberingSystem !== defaultParser.options.numberingSystem) {
let parser = $6c7bd7858deea686$var$getCachedNumberParser(locale + (locale.includes('-u-') ? '-nu-' : '-u-nu-') + numberingSystem, options);
if (parser.isValidPartialNumber(value)) return parser;
}
}
return defaultParser;
}
function $6c7bd7858deea686$var$getCachedNumberParser(locale, options) {
let cacheKey = locale + (options ? Object.entries(options).sort((a, b)=>a[0] < b[0] ? -1 : 1).join() : '');
let parser = $6c7bd7858deea686$var$numberParserCache.get(cacheKey);
if (!parser) {
parser = new $6c7bd7858deea686$var$NumberParserImpl(locale, options);
$6c7bd7858deea686$var$numberParserCache.set(cacheKey, parser);
}
return parser;
}
// The actual number parser implementation. Instances of this class are cached
// based on the locale, options, and detected numbering system.
class $6c7bd7858deea686$var$NumberParserImpl {
parse(value) {
// to parse the number, we need to remove anything that isn't actually part of the number, for example we want '-10.40' not '-10.40 USD'
let fullySanitizedValue = this.sanitize(value);
if (this.symbols.group) // Remove group characters, and replace decimal points and numerals with ASCII values.
fullySanitizedValue = $6c7bd7858deea686$var$replaceAll(fullySanitizedValue, this.symbols.group, '');
if (this.symbols.decimal) fullySanitizedValue = fullySanitizedValue.replace(this.symbols.decimal, '.');
if (this.symbols.minusSign) fullySanitizedValue = fullySanitizedValue.replace(this.symbols.minusSign, '-');
fullySanitizedValue = fullySanitizedValue.replace(this.symbols.numeral, this.symbols.index);
if (this.options.style === 'percent') {
// javascript is bad at dividing by 100 and maintaining the same significant figures, so perform it on the string before parsing
let isNegative = fullySanitizedValue.indexOf('-');
fullySanitizedValue = fullySanitizedValue.replace('-', '');
let index = fullySanitizedValue.indexOf('.');
if (index === -1) index = fullySanitizedValue.length;
fullySanitizedValue = fullySanitizedValue.replace('.', '');
if (index - 2 === 0) fullySanitizedValue = `0.${fullySanitizedValue}`;
else if (index - 2 === -1) fullySanitizedValue = `0.0${fullySanitizedValue}`;
else if (index - 2 === -2) fullySanitizedValue = '0.00';
else fullySanitizedValue = `${fullySanitizedValue.slice(0, index - 2)}.${fullySanitizedValue.slice(index - 2)}`;
if (isNegative > -1) fullySanitizedValue = `-${fullySanitizedValue}`;
}
let newValue = fullySanitizedValue ? +fullySanitizedValue : NaN;
if (isNaN(newValue)) return NaN;
if (this.options.style === 'percent') {
var _this_options_minimumFractionDigits, _this_options_maximumFractionDigits;
// extra step for rounding percents to what our formatter would output
let options = {
...this.options,
style: 'decimal',
minimumFractionDigits: Math.min(((_this_options_minimumFractionDigits = this.options.minimumFractionDigits) !== null && _this_options_minimumFractionDigits !== void 0 ? _this_options_minimumFractionDigits : 0) + 2, 20),
maximumFractionDigits: Math.min(((_this_options_maximumFractionDigits = this.options.maximumFractionDigits) !== null && _this_options_maximumFractionDigits !== void 0 ? _this_options_maximumFractionDigits : 0) + 2, 20)
};
return new $6c7bd7858deea686$export$cd11ab140839f11d(this.locale, options).parse(new (0, $488c6ddbf4ef74c2$export$cc77c4ff7e8673c5)(this.locale, options).format(newValue));
}
// accounting will always be stripped to a positive number, so if it's accounting and has a () around everything, then we need to make it negative again
if (this.options.currencySign === 'accounting' && $6c7bd7858deea686$var$CURRENCY_SIGN_REGEX.test(value)) newValue = -1 * newValue;
return newValue;
}
sanitize(value) {
// Remove literals and whitespace, which are allowed anywhere in the string
value = value.replace(this.symbols.literals, '');
// Replace the ASCII minus sign with the minus sign used in the current locale
// so that both are allowed in case the user's keyboard doesn't have the locale's minus sign.
if (this.symbols.minusSign) value = value.replace('-', this.symbols.minusSign);
// In arab numeral system, their decimal character is 1643, but most keyboards don't type that
// instead they use the , (44) character or apparently the (1548) character.
if (this.options.numberingSystem === 'arab') {
if (this.symbols.decimal) {
value = value.replace(',', this.symbols.decimal);
value = value.replace(String.fromCharCode(1548), this.symbols.decimal);
}
if (this.symbols.group) value = $6c7bd7858deea686$var$replaceAll(value, '.', this.symbols.group);
}
// fr-FR group character is char code 8239, but that's not a key on the french keyboard,
// so allow 'period' as a group char and replace it with a space
if (this.options.locale === 'fr-FR') value = $6c7bd7858deea686$var$replaceAll(value, '.', String.fromCharCode(8239));
return value;
}
isValidPartialNumber(value, minValue = -Infinity, maxValue = Infinity) {
value = this.sanitize(value);
// Remove minus or plus sign, which must be at the start of the string.
if (this.symbols.minusSign && value.startsWith(this.symbols.minusSign) && minValue < 0) value = value.slice(this.symbols.minusSign.length);
else if (this.symbols.plusSign && value.startsWith(this.symbols.plusSign) && maxValue > 0) value = value.slice(this.symbols.plusSign.length);
// Numbers cannot start with a group separator
if (this.symbols.group && value.startsWith(this.symbols.group)) return false;
// Numbers that can't have any decimal values fail if a decimal character is typed
if (this.symbols.decimal && value.indexOf(this.symbols.decimal) > -1 && this.options.maximumFractionDigits === 0) return false;
// Remove numerals, groups, and decimals
if (this.symbols.group) value = $6c7bd7858deea686$var$replaceAll(value, this.symbols.group, '');
value = value.replace(this.symbols.numeral, '');
if (this.symbols.decimal) value = value.replace(this.symbols.decimal, '');
// The number is valid if there are no remaining characters
return value.length === 0;
}
constructor(locale, options = {}){
this.locale = locale;
this.formatter = new Intl.NumberFormat(locale, options);
this.options = this.formatter.resolvedOptions();
this.symbols = $6c7bd7858deea686$var$getSymbols(locale, this.formatter, this.options, options);
var _this_options_minimumFractionDigits, _this_options_maximumFractionDigits;
if (this.options.style === 'percent' && (((_this_options_minimumFractionDigits = this.options.minimumFractionDigits) !== null && _this_options_minimumFractionDigits !== void 0 ? _this_options_minimumFractionDigits : 0) > 18 || ((_this_options_maximumFractionDigits = this.options.maximumFractionDigits) !== null && _this_options_maximumFractionDigits !== void 0 ? _this_options_maximumFractionDigits : 0) > 18)) console.warn('NumberParser cannot handle percentages with greater than 18 decimal places, please reduce the number in your options.');
}
}
const $6c7bd7858deea686$var$nonLiteralParts = new Set([
'decimal',
'fraction',
'integer',
'minusSign',
'plusSign',
'group'
]);
// This list is derived from https://www.unicode.org/cldr/charts/43/supplemental/language_plural_rules.html#comparison and includes
// all unique numbers which we need to check in order to determine all the plural forms for a given locale.
// See: https://github.com/adobe/react-spectrum/pull/5134/files#r1337037855 for used script
const $6c7bd7858deea686$var$pluralNumbers = [
0,
4,
2,
1,
11,
20,
3,
7,
100,
21,
0.1,
1.1
];
function $6c7bd7858deea686$var$getSymbols(locale, formatter, intlOptions, originalOptions) {
var _allParts_find, _posAllParts_find, _decimalParts_find, _allParts_find1;
// formatter needs access to all decimal places in order to generate the correct literal strings for the plural set
let symbolFormatter = new Intl.NumberFormat(locale, {
...intlOptions,
minimumSignificantDigits: 1,
maximumSignificantDigits: 21
});
// Note: some locale's don't add a group symbol until there is a ten thousands place
let allParts = symbolFormatter.formatToParts(-10000.111);
let posAllParts = symbolFormatter.formatToParts(10000.111);
let pluralParts = $6c7bd7858deea686$var$pluralNumbers.map((n)=>symbolFormatter.formatToParts(n));
var _allParts_find_value;
let minusSign = (_allParts_find_value = (_allParts_find = allParts.find((p)=>p.type === 'minusSign')) === null || _allParts_find === void 0 ? void 0 : _allParts_find.value) !== null && _allParts_find_value !== void 0 ? _allParts_find_value : '-';
let plusSign = (_posAllParts_find = posAllParts.find((p)=>p.type === 'plusSign')) === null || _posAllParts_find === void 0 ? void 0 : _posAllParts_find.value;
// Safari does not support the signDisplay option, but our number parser polyfills it.
// If no plus sign was returned, but the original options contained signDisplay, default to the '+' character.
// @ts-ignore
if (!plusSign && ((originalOptions === null || originalOptions === void 0 ? void 0 : originalOptions.signDisplay) === 'exceptZero' || (originalOptions === null || originalOptions === void 0 ? void 0 : originalOptions.signDisplay) === 'always')) plusSign = '+';
// If maximumSignificantDigits is 1 (the minimum) then we won't get decimal characters out of the above formatters
// Percent also defaults to 0 fractionDigits, so we need to make a new one that isn't percent to get an accurate decimal
let decimalParts = new Intl.NumberFormat(locale, {
...intlOptions,
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).formatToParts(0.001);
let decimal = (_decimalParts_find = decimalParts.find((p)=>p.type === 'decimal')) === null || _decimalParts_find === void 0 ? void 0 : _decimalParts_find.value;
let group = (_allParts_find1 = allParts.find((p)=>p.type === 'group')) === null || _allParts_find1 === void 0 ? void 0 : _allParts_find1.value;
// this set is also for a regex, it's all literals that might be in the string we want to eventually parse that
// don't contribute to the numerical value
let allPartsLiterals = allParts.filter((p)=>!$6c7bd7858deea686$var$nonLiteralParts.has(p.type)).map((p)=>$6c7bd7858deea686$var$escapeRegex(p.value));
let pluralPartsLiterals = pluralParts.flatMap((p)=>p.filter((p)=>!$6c7bd7858deea686$var$nonLiteralParts.has(p.type)).map((p)=>$6c7bd7858deea686$var$escapeRegex(p.value)));
let sortedLiterals = [
...new Set([
...allPartsLiterals,
...pluralPartsLiterals
])
].sort((a, b)=>b.length - a.length);
let literals = sortedLiterals.length === 0 ? new RegExp('[\\p{White_Space}]', 'gu') : new RegExp(`${sortedLiterals.join('|')}|[\\p{White_Space}]`, 'gu');
// These are for replacing non-latn characters with the latn equivalent
let numerals = [
...new Intl.NumberFormat(intlOptions.locale, {
useGrouping: false
}).format(9876543210)
].reverse();
let indexes = new Map(numerals.map((d, i)=>[
d,
i
]));
let numeral = new RegExp(`[${numerals.join('')}]`, 'g');
let index = (d)=>String(indexes.get(d));
return {
minusSign: minusSign,
plusSign: plusSign,
decimal: decimal,
group: group,
literals: literals,
numeral: numeral,
index: index
};
}
function $6c7bd7858deea686$var$replaceAll(str, find, replace) {
// @ts-ignore
if (str.replaceAll) // @ts-ignore
return str.replaceAll(find, replace);
return str.split(find).join(replace);
}
function $6c7bd7858deea686$var$escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export {$6c7bd7858deea686$export$cd11ab140839f11d as NumberParser};
//# sourceMappingURL=NumberParser.module.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,19 @@
import {NumberFormatter as $488c6ddbf4ef74c2$export$cc77c4ff7e8673c5} from "./NumberFormatter.mjs";
import {NumberParser as $6c7bd7858deea686$export$cd11ab140839f11d} from "./NumberParser.mjs";
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
export {$488c6ddbf4ef74c2$export$cc77c4ff7e8673c5 as NumberFormatter, $6c7bd7858deea686$export$cd11ab140839f11d as NumberParser};
//# sourceMappingURL=module.js.map

View File

@@ -0,0 +1,25 @@
var $0c1d5654b62fc485$exports = require("./NumberFormatter.main.js");
var $d68f3f4c684426c6$exports = require("./NumberParser.main.js");
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
$parcel$export(module.exports, "NumberFormatter", () => $0c1d5654b62fc485$exports.NumberFormatter);
$parcel$export(module.exports, "NumberParser", () => $d68f3f4c684426c6$exports.NumberParser);
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
//# sourceMappingURL=main.js.map

View File

@@ -0,0 +1 @@
{"mappings":";;;;;;;;;;AAAA;;;;;;;;;;CAUC","sources":["packages/@internationalized/number/src/index.ts"],"sourcesContent":["/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nexport type {NumberFormatOptions} from './NumberFormatter';\n\nexport {NumberFormatter} from './NumberFormatter';\nexport {NumberParser} from './NumberParser';\n"],"names":[],"version":3,"file":"main.js.map"}

View File

@@ -0,0 +1,19 @@
import {NumberFormatter as $488c6ddbf4ef74c2$export$cc77c4ff7e8673c5} from "./NumberFormatter.module.js";
import {NumberParser as $6c7bd7858deea686$export$cd11ab140839f11d} from "./NumberParser.module.js";
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
export {$488c6ddbf4ef74c2$export$cc77c4ff7e8673c5 as NumberFormatter, $6c7bd7858deea686$export$cd11ab140839f11d as NumberParser};
//# sourceMappingURL=module.js.map

View File

@@ -0,0 +1 @@
{"mappings":";;;AAAA;;;;;;;;;;CAUC","sources":["packages/@internationalized/number/src/index.ts"],"sourcesContent":["/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nexport type {NumberFormatOptions} from './NumberFormatter';\n\nexport {NumberFormatter} from './NumberFormatter';\nexport {NumberParser} from './NumberParser';\n"],"names":[],"version":3,"file":"module.js.map"}

View File

@@ -0,0 +1,50 @@
export interface NumberFormatOptions extends Intl.NumberFormatOptions {
/** Overrides default numbering system for the current locale. */
numberingSystem?: string;
}
interface NumberRangeFormatPart extends Intl.NumberFormatPart {
source: 'startRange' | 'endRange' | 'shared';
}
/**
* A wrapper around Intl.NumberFormat providing additional options, polyfills, and caching for performance.
*/
export class NumberFormatter implements Intl.NumberFormat {
constructor(locale: string, options?: NumberFormatOptions);
/** Formats a number value as a string, according to the locale and options provided to the constructor. */
format(value: number): string;
/** Formats a number to an array of parts such as separators, digits, punctuation, and more. */
formatToParts(value: number): Intl.NumberFormatPart[];
/** Formats a number range as a string. */
formatRange(start: number, end: number): string;
/** Formats a number range as an array of parts. */
formatRangeToParts(start: number, end: number): NumberRangeFormatPart[];
/** Returns the resolved formatting options based on the values passed to the constructor. */
resolvedOptions(): Intl.ResolvedNumberFormatOptions;
}
/**
* A NumberParser can be used to perform locale-aware parsing of numbers from Unicode strings,
* as well as validation of partial user input. It automatically detects the numbering system
* used in the input, and supports parsing decimals, percentages, currency values, and units
* according to the locale.
*/
export class NumberParser {
constructor(locale: string, options?: Intl.NumberFormatOptions);
/**
* Parses the given string to a number. Returns NaN if a valid number could not be parsed.
*/
parse(value: string): number;
/**
* Returns whether the given string could potentially be a valid number. This should be used to
* validate user input as the user types. If a `minValue` or `maxValue` is provided, the validity
* of the minus/plus sign characters can be checked.
*/
isValidPartialNumber(value: string, minValue?: number, maxValue?: number): boolean;
/**
* Returns a numbering system for which the given string is valid in the current locale.
* If no numbering system could be detected, the default numbering system for the current
* locale is returned.
*/
getNumberingSystem(value: string): string;
}
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1 @@
{"mappings":"AA4CA,oCAAqC,SAAQ,IAAI,oBAAoB;IACnE,iEAAiE;IACjE,eAAe,CAAC,EAAE,MAAM,CAAA;CACzB;AAED,+BAAgC,SAAQ,IAAI,CAAC,gBAAgB;IAC3D,MAAM,EAAE,YAAY,GAAG,UAAU,GAAG,QAAQ,CAAA;CAC7C;AAED;;GAEG;AACH,4BAA6B,YAAW,IAAI,CAAC,YAAY;gBAI3C,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB;IAK7D,2GAA2G;IAC3G,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAoB7B,+FAA+F;IAC/F,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,gBAAgB,EAAE;IAMrD,0CAA0C;IAC1C,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM;IAe/C,mDAAmD;IACnD,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,qBAAqB,EAAE;IAoBvE,6FAA6F;IAC7F,eAAe,IAAI,KAAK,2BAA2B;CAYpD;ACpHD;;;;;GAKG;AACH;gBAIc,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,KAAK,mBAAwB;IAKlE;;OAEG;IACH,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAI5B;;;;OAIG;IACH,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO;IAIlF;;;;OAIG;IACH,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;CAG1C","sources":["packages/@internationalized/number/src/packages/@internationalized/number/src/NumberFormatter.ts","packages/@internationalized/number/src/packages/@internationalized/number/src/NumberParser.ts","packages/@internationalized/number/src/packages/@internationalized/number/src/index.ts","packages/@internationalized/number/src/index.ts"],"sourcesContent":[null,null,null,"/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nexport type {NumberFormatOptions} from './NumberFormatter';\n\nexport {NumberFormatter} from './NumberFormatter';\nexport {NumberParser} from './NumberParser';\n"],"names":[],"version":3,"file":"types.d.ts.map"}

View File

@@ -0,0 +1,31 @@
{
"name": "@internationalized/number",
"version": "3.5.3",
"description": "Internationalized number formatting and parsing utilities",
"license": "Apache-2.0",
"main": "dist/main.js",
"module": "dist/module.js",
"exports": {
"types": "./dist/types.d.ts",
"import": "./dist/import.mjs",
"require": "./dist/main.js"
},
"types": "dist/types.d.ts",
"source": "src/index.ts",
"files": [
"dist",
"src"
],
"sideEffects": false,
"repository": {
"type": "git",
"url": "https://github.com/adobe/react-spectrum"
},
"dependencies": {
"@swc/helpers": "^0.5.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "b77d7d594dff4dcfb5359bffbcfd18142b146433"
}

View File

@@ -0,0 +1,208 @@
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
let formatterCache = new Map<string, Intl.NumberFormat>();
let supportsSignDisplay = false;
try {
// @ts-ignore
supportsSignDisplay = (new Intl.NumberFormat('de-DE', {signDisplay: 'exceptZero'})).resolvedOptions().signDisplay === 'exceptZero';
// eslint-disable-next-line no-empty
} catch (e) {}
let supportsUnit = false;
try {
// @ts-ignore
supportsUnit = (new Intl.NumberFormat('de-DE', {style: 'unit', unit: 'degree'})).resolvedOptions().style === 'unit';
// eslint-disable-next-line no-empty
} catch (e) {}
// Polyfill for units since Safari doesn't support them yet. See https://bugs.webkit.org/show_bug.cgi?id=215438.
// Currently only polyfilling the unit degree in narrow format for ColorSlider in our supported locales.
// Values were determined by switching to each locale manually in Chrome.
const UNITS = {
degree: {
narrow: {
default: '°',
'ja-JP': ' 度',
'zh-TW': '度',
'sl-SI': ' °'
// Arabic?? But Safari already doesn't use Arabic digits so might be ok...
// https://bugs.webkit.org/show_bug.cgi?id=218139
}
}
};
export interface NumberFormatOptions extends Intl.NumberFormatOptions {
/** Overrides default numbering system for the current locale. */
numberingSystem?: string
}
interface NumberRangeFormatPart extends Intl.NumberFormatPart {
source: 'startRange' | 'endRange' | 'shared'
}
/**
* A wrapper around Intl.NumberFormat providing additional options, polyfills, and caching for performance.
*/
export class NumberFormatter implements Intl.NumberFormat {
private numberFormatter: Intl.NumberFormat;
private options: NumberFormatOptions;
constructor(locale: string, options: NumberFormatOptions = {}) {
this.numberFormatter = getCachedNumberFormatter(locale, options);
this.options = options;
}
/** Formats a number value as a string, according to the locale and options provided to the constructor. */
format(value: number): string {
let res = '';
if (!supportsSignDisplay && this.options.signDisplay != null) {
res = numberFormatSignDisplayPolyfill(this.numberFormatter, this.options.signDisplay, value);
} else {
res = this.numberFormatter.format(value);
}
if (this.options.style === 'unit' && !supportsUnit) {
let {unit, unitDisplay = 'short', locale} = this.resolvedOptions();
if (!unit) {
return res;
}
let values = UNITS[unit]?.[unitDisplay];
res += values[locale] || values.default;
}
return res;
}
/** Formats a number to an array of parts such as separators, digits, punctuation, and more. */
formatToParts(value: number): Intl.NumberFormatPart[] {
// TODO: implement signDisplay for formatToParts
// @ts-ignore
return this.numberFormatter.formatToParts(value);
}
/** Formats a number range as a string. */
formatRange(start: number, end: number): string {
// @ts-ignore
if (typeof this.numberFormatter.formatRange === 'function') {
// @ts-ignore
return this.numberFormatter.formatRange(start, end);
}
if (end < start) {
throw new RangeError('End date must be >= start date');
}
// Very basic fallback for old browsers.
return `${this.format(start)} ${this.format(end)}`;
}
/** Formats a number range as an array of parts. */
formatRangeToParts(start: number, end: number): NumberRangeFormatPart[] {
// @ts-ignore
if (typeof this.numberFormatter.formatRangeToParts === 'function') {
// @ts-ignore
return this.numberFormatter.formatRangeToParts(start, end);
}
if (end < start) {
throw new RangeError('End date must be >= start date');
}
let startParts = this.numberFormatter.formatToParts(start);
let endParts = this.numberFormatter.formatToParts(end);
return [
...startParts.map(p => ({...p, source: 'startRange'} as NumberRangeFormatPart)),
{type: 'literal', value: ' ', source: 'shared'},
...endParts.map(p => ({...p, source: 'endRange'} as NumberRangeFormatPart))
];
}
/** Returns the resolved formatting options based on the values passed to the constructor. */
resolvedOptions(): Intl.ResolvedNumberFormatOptions {
let options = this.numberFormatter.resolvedOptions();
if (!supportsSignDisplay && this.options.signDisplay != null) {
options = {...options, signDisplay: this.options.signDisplay};
}
if (!supportsUnit && this.options.style === 'unit') {
options = {...options, style: 'unit', unit: this.options.unit, unitDisplay: this.options.unitDisplay};
}
return options;
}
}
function getCachedNumberFormatter(locale: string, options: NumberFormatOptions = {}): Intl.NumberFormat {
let {numberingSystem} = options;
if (numberingSystem && locale.includes('-nu-')) {
if (!locale.includes('-u-')) {
locale += '-u-';
}
locale += `-nu-${numberingSystem}`;
}
if (options.style === 'unit' && !supportsUnit) {
let {unit, unitDisplay = 'short'} = options;
if (!unit) {
throw new Error('unit option must be provided with style: "unit"');
}
if (!UNITS[unit]?.[unitDisplay]) {
throw new Error(`Unsupported unit ${unit} with unitDisplay = ${unitDisplay}`);
}
options = {...options, style: 'decimal'};
}
let cacheKey = locale + (options ? Object.entries(options).sort((a, b) => a[0] < b[0] ? -1 : 1).join() : '');
if (formatterCache.has(cacheKey)) {
return formatterCache.get(cacheKey)!;
}
let numberFormatter = new Intl.NumberFormat(locale, options);
formatterCache.set(cacheKey, numberFormatter);
return numberFormatter;
}
/** @private - exported for tests */
export function numberFormatSignDisplayPolyfill(numberFormat: Intl.NumberFormat, signDisplay: string, num: number) {
if (signDisplay === 'auto') {
return numberFormat.format(num);
} else if (signDisplay === 'never') {
return numberFormat.format(Math.abs(num));
} else {
let needsPositiveSign = false;
if (signDisplay === 'always') {
needsPositiveSign = num > 0 || Object.is(num, 0);
} else if (signDisplay === 'exceptZero') {
if (Object.is(num, -0) || Object.is(num, 0)) {
num = Math.abs(num);
} else {
needsPositiveSign = num > 0;
}
}
if (needsPositiveSign) {
let negative = numberFormat.format(-num);
let noSign = numberFormat.format(num);
// ignore RTL/LTR marker character
let minus = negative.replace(noSign, '').replace(/\u200e|\u061C/, '');
if ([...minus].length !== 1) {
console.warn('@react-aria/i18n polyfill for NumberFormat signDisplay: Unsupported case');
}
let positive = negative.replace(noSign, '!!!').replace(minus, '+').replace('!!!', noSign);
return positive;
} else {
return numberFormat.format(num);
}
}
}

View File

@@ -0,0 +1,312 @@
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {NumberFormatter} from './NumberFormatter';
interface Symbols {
minusSign?: string,
plusSign?: string,
decimal?: string,
group?: string,
literals: RegExp,
numeral: RegExp,
index: (v: string) => string
}
const CURRENCY_SIGN_REGEX = new RegExp('^.*\\(.*\\).*$');
const NUMBERING_SYSTEMS = ['latn', 'arab', 'hanidec'];
/**
* A NumberParser can be used to perform locale-aware parsing of numbers from Unicode strings,
* as well as validation of partial user input. It automatically detects the numbering system
* used in the input, and supports parsing decimals, percentages, currency values, and units
* according to the locale.
*/
export class NumberParser {
private locale: string;
private options: Intl.NumberFormatOptions;
constructor(locale: string, options: Intl.NumberFormatOptions = {}) {
this.locale = locale;
this.options = options;
}
/**
* Parses the given string to a number. Returns NaN if a valid number could not be parsed.
*/
parse(value: string): number {
return getNumberParserImpl(this.locale, this.options, value).parse(value);
}
/**
* Returns whether the given string could potentially be a valid number. This should be used to
* validate user input as the user types. If a `minValue` or `maxValue` is provided, the validity
* of the minus/plus sign characters can be checked.
*/
isValidPartialNumber(value: string, minValue?: number, maxValue?: number): boolean {
return getNumberParserImpl(this.locale, this.options, value).isValidPartialNumber(value, minValue, maxValue);
}
/**
* Returns a numbering system for which the given string is valid in the current locale.
* If no numbering system could be detected, the default numbering system for the current
* locale is returned.
*/
getNumberingSystem(value: string): string {
return getNumberParserImpl(this.locale, this.options, value).options.numberingSystem;
}
}
const numberParserCache = new Map<string, NumberParserImpl>();
function getNumberParserImpl(locale: string, options: Intl.NumberFormatOptions, value: string) {
// First try the default numbering system for the provided locale
let defaultParser = getCachedNumberParser(locale, options);
// If that doesn't match, and the locale doesn't include a hard coded numbering system,
// try each of the other supported numbering systems until we find one that matches.
if (!locale.includes('-nu-') && !defaultParser.isValidPartialNumber(value)) {
for (let numberingSystem of NUMBERING_SYSTEMS) {
if (numberingSystem !== defaultParser.options.numberingSystem) {
let parser = getCachedNumberParser(locale + (locale.includes('-u-') ? '-nu-' : '-u-nu-') + numberingSystem, options);
if (parser.isValidPartialNumber(value)) {
return parser;
}
}
}
}
return defaultParser;
}
function getCachedNumberParser(locale: string, options: Intl.NumberFormatOptions) {
let cacheKey = locale + (options ? Object.entries(options).sort((a, b) => a[0] < b[0] ? -1 : 1).join() : '');
let parser = numberParserCache.get(cacheKey);
if (!parser) {
parser = new NumberParserImpl(locale, options);
numberParserCache.set(cacheKey, parser);
}
return parser;
}
// The actual number parser implementation. Instances of this class are cached
// based on the locale, options, and detected numbering system.
class NumberParserImpl {
formatter: Intl.NumberFormat;
options: Intl.ResolvedNumberFormatOptions;
symbols: Symbols;
locale: string;
constructor(locale: string, options: Intl.NumberFormatOptions = {}) {
this.locale = locale;
this.formatter = new Intl.NumberFormat(locale, options);
this.options = this.formatter.resolvedOptions();
this.symbols = getSymbols(locale, this.formatter, this.options, options);
if (this.options.style === 'percent' && ((this.options.minimumFractionDigits ?? 0) > 18 || (this.options.maximumFractionDigits ?? 0) > 18)) {
console.warn('NumberParser cannot handle percentages with greater than 18 decimal places, please reduce the number in your options.');
}
}
parse(value: string) {
// to parse the number, we need to remove anything that isn't actually part of the number, for example we want '-10.40' not '-10.40 USD'
let fullySanitizedValue = this.sanitize(value);
if (this.symbols.group) {
// Remove group characters, and replace decimal points and numerals with ASCII values.
fullySanitizedValue = replaceAll(fullySanitizedValue, this.symbols.group, '');
}
if (this.symbols.decimal) {
fullySanitizedValue = fullySanitizedValue.replace(this.symbols.decimal!, '.');
}
if (this.symbols.minusSign) {
fullySanitizedValue = fullySanitizedValue.replace(this.symbols.minusSign!, '-');
}
fullySanitizedValue = fullySanitizedValue.replace(this.symbols.numeral, this.symbols.index);
if (this.options.style === 'percent') {
// javascript is bad at dividing by 100 and maintaining the same significant figures, so perform it on the string before parsing
let isNegative = fullySanitizedValue.indexOf('-');
fullySanitizedValue = fullySanitizedValue.replace('-', '');
let index = fullySanitizedValue.indexOf('.');
if (index === -1) {
index = fullySanitizedValue.length;
}
fullySanitizedValue = fullySanitizedValue.replace('.', '');
if (index - 2 === 0) {
fullySanitizedValue = `0.${fullySanitizedValue}`;
} else if (index - 2 === -1) {
fullySanitizedValue = `0.0${fullySanitizedValue}`;
} else if (index - 2 === -2) {
fullySanitizedValue = '0.00';
} else {
fullySanitizedValue = `${fullySanitizedValue.slice(0, index - 2)}.${fullySanitizedValue.slice(index - 2)}`;
}
if (isNegative > -1) {
fullySanitizedValue = `-${fullySanitizedValue}`;
}
}
let newValue = fullySanitizedValue ? +fullySanitizedValue : NaN;
if (isNaN(newValue)) {
return NaN;
}
if (this.options.style === 'percent') {
// extra step for rounding percents to what our formatter would output
let options = {
...this.options,
style: 'decimal' as const,
minimumFractionDigits: Math.min((this.options.minimumFractionDigits ?? 0) + 2, 20),
maximumFractionDigits: Math.min((this.options.maximumFractionDigits ?? 0) + 2, 20)
};
return (new NumberParser(this.locale, options)).parse(new NumberFormatter(this.locale, options).format(newValue));
}
// accounting will always be stripped to a positive number, so if it's accounting and has a () around everything, then we need to make it negative again
if (this.options.currencySign === 'accounting' && CURRENCY_SIGN_REGEX.test(value)) {
newValue = -1 * newValue;
}
return newValue;
}
sanitize(value: string) {
// Remove literals and whitespace, which are allowed anywhere in the string
value = value.replace(this.symbols.literals, '');
// Replace the ASCII minus sign with the minus sign used in the current locale
// so that both are allowed in case the user's keyboard doesn't have the locale's minus sign.
if (this.symbols.minusSign) {
value = value.replace('-', this.symbols.minusSign);
}
// In arab numeral system, their decimal character is 1643, but most keyboards don't type that
// instead they use the , (44) character or apparently the (1548) character.
if (this.options.numberingSystem === 'arab') {
if (this.symbols.decimal) {
value = value.replace(',', this.symbols.decimal);
value = value.replace(String.fromCharCode(1548), this.symbols.decimal);
}
if (this.symbols.group) {
value = replaceAll(value, '.', this.symbols.group);
}
}
// fr-FR group character is char code 8239, but that's not a key on the french keyboard,
// so allow 'period' as a group char and replace it with a space
if (this.options.locale === 'fr-FR') {
value = replaceAll(value, '.', String.fromCharCode(8239));
}
return value;
}
isValidPartialNumber(value: string, minValue: number = -Infinity, maxValue: number = Infinity): boolean {
value = this.sanitize(value);
// Remove minus or plus sign, which must be at the start of the string.
if (this.symbols.minusSign && value.startsWith(this.symbols.minusSign) && minValue < 0) {
value = value.slice(this.symbols.minusSign.length);
} else if (this.symbols.plusSign && value.startsWith(this.symbols.plusSign) && maxValue > 0) {
value = value.slice(this.symbols.plusSign.length);
}
// Numbers cannot start with a group separator
if (this.symbols.group && value.startsWith(this.symbols.group)) {
return false;
}
// Numbers that can't have any decimal values fail if a decimal character is typed
if (this.symbols.decimal && value.indexOf(this.symbols.decimal) > -1 && this.options.maximumFractionDigits === 0) {
return false;
}
// Remove numerals, groups, and decimals
if (this.symbols.group) {
value = replaceAll(value, this.symbols.group, '');
}
value = value.replace(this.symbols.numeral, '');
if (this.symbols.decimal) {
value = value.replace(this.symbols.decimal, '');
}
// The number is valid if there are no remaining characters
return value.length === 0;
}
}
const nonLiteralParts = new Set(['decimal', 'fraction', 'integer', 'minusSign', 'plusSign', 'group']);
// This list is derived from https://www.unicode.org/cldr/charts/43/supplemental/language_plural_rules.html#comparison and includes
// all unique numbers which we need to check in order to determine all the plural forms for a given locale.
// See: https://github.com/adobe/react-spectrum/pull/5134/files#r1337037855 for used script
const pluralNumbers = [
0, 4, 2, 1, 11, 20, 3, 7, 100, 21, 0.1, 1.1
];
function getSymbols(locale: string, formatter: Intl.NumberFormat, intlOptions: Intl.ResolvedNumberFormatOptions, originalOptions: Intl.NumberFormatOptions): Symbols {
// formatter needs access to all decimal places in order to generate the correct literal strings for the plural set
let symbolFormatter = new Intl.NumberFormat(locale, {...intlOptions, minimumSignificantDigits: 1, maximumSignificantDigits: 21});
// Note: some locale's don't add a group symbol until there is a ten thousands place
let allParts = symbolFormatter.formatToParts(-10000.111);
let posAllParts = symbolFormatter.formatToParts(10000.111);
let pluralParts = pluralNumbers.map(n => symbolFormatter.formatToParts(n));
let minusSign = allParts.find(p => p.type === 'minusSign')?.value ?? '-';
let plusSign = posAllParts.find(p => p.type === 'plusSign')?.value;
// Safari does not support the signDisplay option, but our number parser polyfills it.
// If no plus sign was returned, but the original options contained signDisplay, default to the '+' character.
// @ts-ignore
if (!plusSign && (originalOptions?.signDisplay === 'exceptZero' || originalOptions?.signDisplay === 'always')) {
plusSign = '+';
}
// If maximumSignificantDigits is 1 (the minimum) then we won't get decimal characters out of the above formatters
// Percent also defaults to 0 fractionDigits, so we need to make a new one that isn't percent to get an accurate decimal
let decimalParts = new Intl.NumberFormat(locale, {...intlOptions, minimumFractionDigits: 2, maximumFractionDigits: 2}).formatToParts(0.001);
let decimal = decimalParts.find(p => p.type === 'decimal')?.value;
let group = allParts.find(p => p.type === 'group')?.value;
// this set is also for a regex, it's all literals that might be in the string we want to eventually parse that
// don't contribute to the numerical value
let allPartsLiterals = allParts.filter(p => !nonLiteralParts.has(p.type)).map(p => escapeRegex(p.value));
let pluralPartsLiterals = pluralParts.flatMap(p => p.filter(p => !nonLiteralParts.has(p.type)).map(p => escapeRegex(p.value)));
let sortedLiterals = [...new Set([...allPartsLiterals, ...pluralPartsLiterals])].sort((a, b) => b.length - a.length);
let literals = sortedLiterals.length === 0 ?
new RegExp('[\\p{White_Space}]', 'gu') :
new RegExp(`${sortedLiterals.join('|')}|[\\p{White_Space}]`, 'gu');
// These are for replacing non-latn characters with the latn equivalent
let numerals = [...new Intl.NumberFormat(intlOptions.locale, {useGrouping: false}).format(9876543210)].reverse();
let indexes = new Map(numerals.map((d, i) => [d, i]));
let numeral = new RegExp(`[${numerals.join('')}]`, 'g');
let index = d => String(indexes.get(d));
return {minusSign, plusSign, decimal, group, literals, numeral, index};
}
function replaceAll(str: string, find: string, replace: string) {
// @ts-ignore
if (str.replaceAll) {
// @ts-ignore
return str.replaceAll(find, replace);
}
return str.split(find).join(replace);
}
function escapeRegex(string: string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

View File

@@ -0,0 +1,16 @@
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
export type {NumberFormatOptions} from './NumberFormatter';
export {NumberFormatter} from './NumberFormatter';
export {NumberParser} from './NumberParser';