An open source design system that's fully customizable and agent ready
TypeScript
fix(NumberInput): parse pasted grouped and localized numbers (#5450)
Cindy Zhang32a62fd35abd
diff --git a/.changeset/number-input-paste-grouped-numbers.md b/.changeset/number-input-paste-grouped-numbers.mdnew file mode 100644index 0000000000..3835d1031c--- /dev/null+++ b/.changeset/number-input-paste-grouped-numbers.md@@ -0,0 +1,28 @@+---+'@astryxdesign/core': patch+---++[fix] NumberInput: a pasted `1,234,234,234` now commits as 1234234234++Pasting a number out of a spreadsheet used to fail. The field parsed with+`Number()`, so `1,234,234,234` read as `NaN`, the field went invalid, and the+paste was lost — the single most common way anyone puts a large number into a+form.++Typed and pasted text is now read under the field's locale: grouping and+decimal separators and group sizes come from `Intl` (so `1.234.234.234` in+de-DE, narrow-no-break-space grouping in fr-FR, and lakh grouping in en-IN all+work), digits come from `\p{Nd}` (Arabic-Indic, Devanagari, full-width), and+the shapes a spreadsheet attaches — a currency symbol, an accounting `(1,234)`,+a `1.23E+09`, a stray BOM — are handled.++A separator that could mean two different numbers still refuses: `1,5` is 1.5+in de-DE and nothing in en-US, and a `1,234 GB` keeps its unit rather than+guessing which trailing letters are inert. Refusing leaves the field+`aria-invalid` with its existing alert, which is the honest outcome — a wrong+number committed silently is the failure this is designed against.++Typing is never intercepted and nothing is rewritten mid-composition. No API+change: `formatValue` is untouched.++@cixzhangdiff --git a/apps/storybook/stories/NumberInput.stories.tsx b/apps/storybook/stories/NumberInput.stories.tsxindex 9b7c50c2a2..e1b486296f 100644--- a/apps/storybook/stories/NumberInput.stories.tsx+++ b/apps/storybook/stories/NumberInput.stories.tsx@@ -3,6 +3,7 @@import {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {NumberInput} from '@astryxdesign/core/NumberInput';+import {InternationalizationProvider} from '@astryxdesign/core/i18n';import {HashtagIcon, CurrencyDollarIcon} from '@heroicons/react/24/outline';const meta: Meta<typeof NumberInput> = {@@ -125,6 +126,44 @@ export const Default: Story = {},};+export const PasteFormattedNumber: Story = {+ render: () => {+ const [enUS, setEnUS] = useState<number | null>(null);+ const [deDE, setDeDE] = useState<number | null>(null);+ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: 24}}>+ <div>+ <NumberInput+ label="Impressions (en-US)"+ description="Paste 1,234,234,234 or $1,234.56, then blur"+ placeholder="Paste a formatted number"+ value={enUS}+ onChange={setEnUS}+ hasClear+ />+ <p data-testid="en-committed">Committed: {String(enUS)}</p>+ </div>+ <InternationalizationProvider locale="de-DE">+ <div>+ <NumberInput+ label="Impressionen (de-DE)"+ description="Paste 1.234.234.234 or 1,5"+ placeholder="Paste a formatted number"+ value={deDE}+ onChange={setDeDE}+ formatValue={value =>+ new Intl.NumberFormat('de-DE').format(value)+ }+ hasClear+ />+ <p data-testid="de-committed">Committed: {String(deDE)}</p>+ </div>+ </InternationalizationProvider>+ </div>+ );+ },+};+export const WithDescription: Story = {render: args => {const [value, setValue] = useState<number | null>(args.value ?? null);diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.mdindex d2fb52b71c..4130c84d74 100644--- a/internal/eslint-plugin-astryx/README.md+++ b/internal/eslint-plugin-astryx/README.md@@ -67,6 +67,8 @@ Approved implementations:`.../Timestamp/tooltipEntries.ts` — Timestamp formatting and itsnon-display time-zone validity probe- `packages/core/src/PowerSearch/formatFilterValue.ts`+- `packages/core/src/NumberInput/numberParser.ts` — reads typed and pasted+ numbers under the field's locale- `packages/core/src/i18n/useCollator.ts`- `packages/charts/src/formatters.ts`@@ -75,6 +77,7 @@ Named test oracles:- `packages/charts/src/formatters.test.ts`- `packages/core/src/Calendar/Calendar.test.tsx`- `packages/core/src/NumberInput/NumberInput.test.tsx`+- `packages/core/src/NumberInput/numberParser.test.ts`- `packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx`- `packages/core/src/Timestamp/tooltipEntries.test.ts`- `packages/core/src/PowerSearch/formatFilterValue.test.ts`diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.js b/internal/eslint-plugin-astryx/no-raw-intl-locale.jsindex 31e73e80bd..646bacd7bd 100644--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.js+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.js@@ -111,6 +111,9 @@ const APPROVED_IMPLEMENTATION_FILES = ['packages/core/src/Timestamp/formatInstant.ts','packages/core/src/Timestamp/tooltipEntries.ts','packages/core/src/PowerSearch/formatFilterValue.ts',+ // NumberInput's locale-aware read of typed and pasted text: it derives the+ // grouping/decimal separators and group sizes from Intl rather than a table.+ 'packages/core/src/NumberInput/numberParser.ts','packages/core/src/i18n/useCollator.ts','packages/charts/src/formatters.ts',];@@ -119,6 +122,7 @@ const APPROVED_TEST_ORACLE_FILES = ['packages/charts/src/formatters.test.ts','packages/core/src/Calendar/Calendar.test.tsx','packages/core/src/NumberInput/NumberInput.test.tsx',+ 'packages/core/src/NumberInput/numberParser.test.ts','packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx','packages/core/src/Timestamp/tooltipEntries.test.ts','packages/core/src/PowerSearch/formatFilterValue.test.ts',diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjsindex 6df6c339ea..5574e2a5e4 100644--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs@@ -33,6 +33,10 @@ const COMPONENT_FILE = 'packages/core/src/Calendar/Calendar.tsx';const INFRA_FILE = 'packages/core/src/utils/plainDate.ts';const DATE_PARSER_INFRA_FILE = 'packages/core/src/utils/dateParser.ts';const COLLATOR_INFRA_FILE = 'packages/core/src/i18n/useCollator.ts';+const NUMBER_PARSER_INFRA_FILE =+ 'packages/core/src/NumberInput/numberParser.ts';+const NUMBER_PARSER_TEST_ORACLE_FILE =+ 'packages/core/src/NumberInput/numberParser.test.ts';const CHARTS_INFRA_FILE = 'packages/charts/src/formatters.ts';const TIMESTAMP_TEST_ORACLE_FILE = 'packages/core/src/Timestamp/Timestamp.test.tsx';const CALENDAR_TEST_ORACLE_FILE = 'packages/core/src/Calendar/Calendar.test.tsx';@@ -126,6 +130,10 @@ tester.run('no-raw-intl-locale', rule, {code: `new Intl.Collator(locale, options);`,filename: COLLATOR_INFRA_FILE,},+ {+ code: `new Intl.NumberFormat(locale).formatToParts(12345.6);`,+ filename: NUMBER_PARSER_INFRA_FILE,+ },// -- Named test-oracle files retain meaningful explicit-locale fixtures. --{code: `number.toLocaleString('en-US');`,@@ -135,6 +143,10 @@ tester.run('no-raw-intl-locale', rule, {code: `left.localeCompare(right, 'en-US');`,filename: 'packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx',},+ {+ code: `new Intl.NumberFormat('de-DE').format(1234234234);`,+ filename: NUMBER_PARSER_TEST_ORACLE_FILE,+ },// -- A named test-oracle file may also construct raw Intl with a// non-navigator locale argument, exactly like an infra implementation@@ -169,6 +181,11 @@ tester.run('no-raw-intl-locale', rule, {filename: CHARTS_INFRA_FILE,errors: [ambientIntlInImplementation],},+ {+ code: `new Intl.NumberFormat().formatToParts(1);`,+ filename: NUMBER_PARSER_INFRA_FILE,+ errors: [ambientIntlInImplementation],+ },{code: `value.toLocaleString();`,filename: CHARTS_INFRA_FILE,diff --git a/packages/core/src/NumberInput/NumberInput.doc.mjs b/packages/core/src/NumberInput/NumberInput.doc.mjsindex 6f121e5f8e..bcfc134a90 100644--- a/packages/core/src/NumberInput/NumberInput.doc.mjs+++ b/packages/core/src/NumberInput/NumberInput.doc.mjs@@ -242,6 +242,11 @@ export const docs = {description:'A form input for numeric values with built-in validation, min/max constraints, and step controls. Use NumberInput for quantities, measurements, percentages, and similar inputs.',bestPractices: [+ {+ guidance: true,+ description:+ "Let people paste formatted numbers: a pasted 1,234,234,234 is read under the field's locale and commits as 1234234234 on blur. Typing is never intercepted.",+ },{guidance: true,description:@@ -509,6 +514,11 @@ export const docsZh = {description:'A form input for numeric values with built-in validation, min/max constraints, and step controls. Use NumberInput for quantities, measurements, percentages, and similar inputs.',bestPractices: [+ {+ guidance: true,+ description:+ '可以直接粘贴带格式的数字:粘贴 1,234,234,234 会按字段所在区域设置解析,失去焦点时提交为 1234234234。输入过程中不会拦截按键。',+ },{guidance: true,description:@@ -578,6 +588,11 @@ export const docsDense = {description:'A form input for numeric values with built-in validation, min/max constraints, and step controls. Use NumberInput for quantities, measurements, percentages, and similar inputs.',bestPractices: [+ {+ guidance: true,+ description:+ "Pasted formatted numbers parse: 1,234,234,234 commits as 1234234234 under the field's locale. Typing is never intercepted.",+ },{guidance: true,description:diff --git a/packages/core/src/NumberInput/NumberInput.tsx b/packages/core/src/NumberInput/NumberInput.tsxindex 7f6662e039..d10bcc8f0f 100644--- a/packages/core/src/NumberInput/NumberInput.tsx+++ b/packages/core/src/NumberInput/NumberInput.tsx@@ -9,6 +9,7 @@* @position Core implementation; consumed by index.ts, tested by NumberInput.test.tsx** SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/NumberInput/numberParser.ts (locale-aware parsing)* - /packages/core/src/NumberInput/NumberInput.doc.mjs (props table, features, implementation notes)* - /packages/core/src/NumberInput/NumberInput.test.tsx (tests for new/changed behavior)* - /packages/core/src/NumberInput/index.ts (exports if types change)@@ -213,7 +214,9 @@ import {isImeKeyEvent, mergeProps, mergeRefs} from '../utils';import type {BaseProps} from '../BaseProps';import type {SizeValue} from '../utils/types';import {themeProps} from '../utils/themeProps';-import {useTranslator} from '../i18n';+import {useTranslator, useLocale} from '../i18n';+import {formatEditableNumber, parseLocaleNumber} from './numberParser';+import type {Locale} from '../i18n';interface NumberInputPropsBase extends Omit<BaseProps,@@ -426,7 +429,8 @@ export type NumberInputProps =NumberInputPropsNonClearable | NumberInputPropsClearable;/**- * Parse and validate a string input as a number.+ * Read the typed or pasted text as a number, then apply the field's+ * constraints.* Returns null if the input is not a valid number or fails validation.*/function parseNumberInput(@@ -435,15 +439,16 @@ function parseNumberInput(min?: number | null;max?: number | null;isIntegerOnly?: boolean;+ locale?: Locale;},): number | null {const trimmed = input.trim();- if (trimmed === '' || trimmed === '-') {+ if (trimmed === '') {return null;}- const num = Number(trimmed);- if (!Number.isFinite(num)) {+ const num = parseLocaleNumber(trimmed, options.locale);+ if (num == null || !Number.isFinite(num)) {return null;}@@ -599,6 +604,7 @@ export function NumberInput({...rest}: NumberInputProps) {const t = useTranslator();+ const locale = useLocale();const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});const size = useSize(sizeProp, 'md');const id = useId();@@ -653,6 +659,11 @@ export function NumberInput({inputGroup,);+ const parseInput = useCallback(+ (text: string) => parseNumberInput(text, {min, max, isIntegerOnly, locale}),+ [isIntegerOnly, locale, max, min],+ );+const formattedValue = useMemo(() => {if (value == null) {return '';@@ -669,16 +680,16 @@ export function NumberInput({if (value == null) {return '';}- return isFocused ? String(value) : formattedValue;- }, [formattedValue, isFocused, pendingInput, value]);+ return isFocused ? formatEditableNumber(value, locale) : formattedValue;+ }, [formattedValue, isFocused, locale, pendingInput, value]);// Check if current pending input is valid (for styling purposes)const isInputValid = useMemo(() => {if (pendingInput === null || !pendingInput.trim()) {return true;}- return parseNumberInput(pendingInput, {min, max, isIntegerOnly}) !== null;- }, [pendingInput, min, max, isIntegerOnly]);+ return parseInput(pendingInput) !== null;+ }, [pendingInput, parseInput]);// Handle input text change - update immediately if validconst handleInputChange = useCallback(@@ -693,12 +704,12 @@ export function NumberInput({setPendingInput(newValue);// If the input is valid, update immediately- const parsed = parseNumberInput(newValue, {min, max, isIntegerOnly});+ const parsed = parseInput(newValue);if (parsed !== null && parsed !== value) {onChange(parsed);}},- [value, onChange, min, max, isIntegerOnly, isDisabled, isReadOnly],+ [value, onChange, parseInput, isDisabled, isReadOnly],);// Handle focus@@ -721,11 +732,7 @@ export function NumberInput({onChange(null);}} else {- const parsed = parseNumberInput(pendingInput, {- min,- max,- isIntegerOnly,- });+ const parsed = parseInput(pendingInput);if (parsed !== null && parsed !== value) {onChange(parsed);}@@ -737,7 +744,7 @@ export function NumberInput({setIsFocused(false);onBlur?.(e);},- [pendingInput, value, onChange, min, max, isIntegerOnly, onBlur, hasClear],+ [pendingInput, value, onChange, parseInput, onBlur, hasClear],);const valueForStepping = useMemo(() => {@@ -747,10 +754,8 @@ export function NumberInput({if (pendingInput.trim() === '') {return null;}- return (- parseNumberInput(pendingInput, {min, max, isIntegerOnly}) ?? value ?? null- );- }, [isIntegerOnly, max, min, pendingInput, value]);+ return parseInput(pendingInput) ?? value ?? null;+ }, [parseInput, pendingInput, value]);const getNextValue = useCallback((direction: StepDirection) =>@@ -815,11 +820,7 @@ export function NumberInput({onChange(null);}} else {- const parsed = parseNumberInput(pendingInput, {- min,- max,- isIntegerOnly,- });+ const parsed = parseInput(pendingInput);if (parsed !== null && parsed !== value) {onChange(parsed);}@@ -833,9 +834,7 @@ export function NumberInput({pendingInput,value,onChange,- min,- max,- isIntegerOnly,+ parseInput,onEnter,onKeyDown,hasClear,diff --git a/packages/core/src/NumberInput/numberParser.test.ts b/packages/core/src/NumberInput/numberParser.test.tsnew file mode 100644index 0000000000..95c8fd685d--- /dev/null+++ b/packages/core/src/NumberInput/numberParser.test.ts@@ -0,0 +1,137 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect} from 'vitest';+import {parseLocaleNumber} from './numberParser';++const NBSP = '\u00A0';+const NARROW_NBSP = '\u202F';+const APOSTROPHE = '\u2019';++/**+ * The contract, enumerated. A row is `[input, locale, expected]`, and `null`+ * means the field stays visibly invalid rather than committing a guess.+ */+const CORPUS: [string, string, number | null][] = [+ // Grouped — the case this exists for, and it holds in every locale because+ // a repeated separator with three digits after it cannot be a decimal point.+ ['1,234,234,234', 'en-US', 1234234234],+ ['1,234,234,234', 'de-DE', 1234234234],+ ['1,234,234,234', 'fr-FR', 1234234234],+ ['1,234,234,234', 'ar-SA', 1234234234],+ ['1.234.234.234', 'de-DE', 1234234234],+ ['1.234.234.234', 'en-US', 1234234234],+ [`1${NARROW_NBSP}234${NARROW_NBSP}234${NARROW_NBSP}234`, 'fr-FR', 1234234234],+ [`1${NBSP}234${NBSP}234`, 'fr-FR', 1234234],+ [`1${NBSP}234`, 'en-US', 1234],+ [`1${APOSTROPHE}234${APOSTROPHE}234`, 'de-CH', 1234234],+ ["1'234'234", 'de-CH', 1234234],+ ['1,234', 'en-US', 1234],+ ['1,234', 'de-DE', 1.234],++ // Indian lakh grouping, derived from the locale's own group sizes.+ ['12,34,567', 'en-IN', 1234567],+ ['12,34,567', 'en-US', null],++ // Ragged grouping is a typo, not a number: the last group is not three.+ ['1,23,4', 'en-US', null],+ ['1,2345', 'en-US', null],+ ['12 34', 'en-US', null],++ // One separator, one meaning per locale, and no meaning across them.+ ['1,5', 'de-DE', 1.5],+ ['1,5', 'en-US', null],+ ['1.5', 'en-US', 1.5],+ ['1.5', 'de-DE', null],++ // Decimals and signs.+ ['1,234.56', 'en-US', 1234.56],+ ['1.234,56', 'de-DE', 1234.56],+ ['1,234.56', 'de-DE', null],+ ['-1,234.56', 'en-US', -1234.56],+ ['+7', 'en-US', 7],+ ['-7', 'en-US', -7],+ ['7-', 'ar-SA', -7],+ ['.5', 'en-US', 0.5],+ ['5.', 'en-US', 5],+ ['-', 'en-US', null],+ ['', 'en-US', null],+ [' ', 'en-US', null],++ // Spreadsheet cells arrive with their whitespace attached.+ [' 42 ', 'en-US', 42],+ ['\t1,234\n', 'en-US', 1234],+ ['1,234\n5,678', 'en-US', null],++ // Digit scripts, derived from \p{Nd} rather than enumerated.+ ['١٢٣', 'ar-SA', 123],+ ['۱۲۳', 'fa-IR', 123],+ ['१२३', 'hi-IN', 123],+ ['123', 'ja-JP', 123],+ ['١,٢٣٤', 'en-US', 1234],+ ['٣٫٥', 'ar-SA', 3.5],++ // Currency decorates the number without changing its magnitude, so the+ // symbol is dropped and the separators still decide. A number written for+ // another locale still refuses.+ ['$1,234.56', 'en-US', 1234.56],+ ['£1,234', 'en-US', 1234],+ ['1.234,56 €', 'de-DE', 1234.56],+ ['1.234,56 €', 'en-US', null],+ ['-$1,234', 'en-US', -1234],++ // A unit suffix is not dropped: `B` and `k` carry magnitude, so guessing+ // which trailing letters are inert is how a wrong number gets committed.+ ['1,234 GB', 'en-US', null],+ ['72°F', 'en-US', null],+ ['1,234 kg', 'en-US', null],++ // Accounting negatives.+ ['(1,234)', 'en-US', -1234],+ ['($1,234.50)', 'en-US', -1234.5],+ ['(1,234', 'en-US', null],++ // Typographic minus signs.+ ['\u22121234', 'en-US', -1234],+ ['\u20131234', 'en-US', -1234],++ // Exponents, including the shape a spreadsheet exports.+ ['1.23E+09', 'en-US', 1230000000],+ ['1.23e9', 'en-US', 1230000000],+ ['1.5e-3', 'en-US', 0.0015],+ ['1e', 'en-US', null],++ // Invisible characters Excel and Sheets attach.+ ['\uFEFF1,234', 'en-US', 1234],+ ['1,234\u200B', 'en-US', 1234],+ ['\u200E1,234', 'en-US', 1234],++ // Junk.+ ['NaN', 'en-US', null],+ ['Infinity', 'en-US', null],+ ['abc', 'en-US', null],+ ['12abc', 'en-US', null],+ ['1/2', 'en-US', null],+ ['1 234 (approx)', 'en-US', null],+ ['--5', 'en-US', null],+ ['1..234', 'en-US', null],+];++describe('parseLocaleNumber', () => {+ it.each(CORPUS)('parses %j in %s', (input, locale, expected) => {+ expect(parseLocaleNumber(input, locale)).toBe(expected);+ });++ it('reads back the grouping every locale writes', () => {+ for (const locale of [+ 'en-US',+ 'de-DE',+ 'fr-FR',+ 'de-CH',+ 'en-IN',+ 'ar-SA',+ ]) {+ const text = new Intl.NumberFormat(locale).format(1234234234);+ expect(parseLocaleNumber(text, locale)).toBe(1234234234);+ }+ });+});diff --git a/packages/core/src/NumberInput/numberParser.ts b/packages/core/src/NumberInput/numberParser.tsnew file mode 100644index 0000000000..34a65830a6--- /dev/null+++ b/packages/core/src/NumberInput/numberParser.ts@@ -0,0 +1,346 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file numberParser.ts+ * @input Text a person typed or pasted, plus the resolved BCP 47 locale+ * @output Exports parseLocaleNumber and formatEditableNumber+ * @position Internal to NumberInput; not part of the public surface+ *+ * People paste numbers out of spreadsheets, and a spreadsheet writes them+ * grouped, signed, and decorated. This reads those back. Everything locale+ * specific — the grouping and decimal separators, the group sizes, the digit+ * script — is derived from Intl and Unicode rather than a table, and anything+ * that could mean two different numbers returns null so the field stays+ * visibly invalid instead of committing a guess.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/NumberInput/NumberInput.tsx+ * - /packages/core/src/NumberInput/numberParser.test.ts+ */++import type {Locale} from '../i18n';++interface LocaleNumberSymbols {+ group: string;+ decimal: string;+ /** Digits in the rightmost group — 3 nearly everywhere, 3 in en-IN too. */+ primaryGroupSize: number;+ /** Digits in every group left of it — 2 in en-IN's lakh grouping. */+ secondaryGroupSize: number;+}++const symbolsByLocale = new Map<string, LocaleNumberSymbols>();++function getLocaleNumberSymbols(locale: Locale | undefined) {+ const key = locale ?? '';+ let symbols = symbolsByLocale.get(key);+ if (symbols === undefined) {+ let format: Intl.NumberFormat;+ try {+ format = new Intl.NumberFormat(locale);+ } catch {+ format = new Intl.NumberFormat('en');+ }+ const parts = format.formatToParts(12345.6);+ // A probe long enough to expose a second grouping size where one exists.+ const groupSizes = format+ .formatToParts(11111111111)+ .filter(part => part.type === 'integer')+ .map(part => part.value.length);+ const hasGrouping = groupSizes.length > 1;+ symbols = {+ // Normalized so the space-family separators compare equal to the plain+ // space that input text is normalized to.+ group: (parts.find(p => p.type === 'group')?.value ?? ',').normalize(+ 'NFKC',+ ),+ decimal: parts.find(p => p.type === 'decimal')?.value ?? '.',+ primaryGroupSize: hasGrouping ? groupSizes[groupSizes.length - 1] : 3,+ secondaryGroupSize: hasGrouping ? groupSizes[groupSizes.length - 2] : 3,+ };+ symbolsByLocale.set(key, symbols);+ }+ return symbols;+}++// Built at runtime rather than written as literals: Babel's+// transform-unicode-property-regex rewrites a `\p{...}` regex LITERAL into an+// enumerated character class, and the copy bundled with Next rejects the+// General_Category short names, failing the sandbox build. Property escapes are+// ES2018 and need no transform in any browser this package supports.+const DECIMAL_DIGIT = new RegExp('\\p{Nd}', 'u');+const LETTER = new RegExp('\\p{L}', 'u');+const CURRENCY = new RegExp('\\p{Sc}', 'u');+// Zero-width joiners, bidi isolates and the BOM Excel prepends.+const INVISIBLES = /[\u200B-\u200D\u200E\u200F\u061C\u2066-\u2069\uFEFF]/g;+// Hyphen last: inside the character class this builds, a leading one would+// open a range.+const MINUS_SIGNS = '\u2212\u2012\u2013-';++/**+ * Value of any Unicode decimal digit. Each digit script lays its ten digits+ * out consecutively, so walking back to the script's zero derives the value+ * for Arabic-Indic, Devanagari, full-width and the rest without shipping a+ * table of them. Returns null in the one shape the walk cannot resolve: two+ * digit blocks adjacent in code space (the mathematical alphanumerics).+ */+function digitValue(char: string): number | null {+ const codePoint = char.codePointAt(0);+ if (codePoint == null) {+ return null;+ }+ for (let zero = codePoint; codePoint - zero < 10; zero--) {+ if (!DECIMAL_DIGIT.test(String.fromCodePoint(zero - 1))) {+ return codePoint - zero;+ }+ }+ return null;+}++function toAsciiDigits(text: string): string | null {+ let out = '';+ for (const char of text) {+ if (!DECIMAL_DIGIT.test(char)) {+ out += char;+ continue;+ }+ const value = digitValue(char);+ if (value == null) {+ return null;+ }+ out += String(value);+ }+ return out;+}++/**+ * Reduce a digits-and-separators string to a plain machine number under one+ * candidate reading, or null when it is not well formed under that reading.+ * `minGroups` is how many grouping separators the reading has to see before it+ * believes the separator is grouping at all.+ */+function readUnder(+ core: string,+ group: string,+ decimal: string,+ primaryGroupSize: number,+ secondaryGroupSize: number,+ minGroups: number,+): string | null {+ let intText = core;+ let fracText: string | null = null;++ if (decimal !== '' && core.includes(decimal)) {+ const at = core.indexOf(decimal);+ if (core.includes(decimal, at + decimal.length)) {+ return null;+ }+ intText = core.slice(0, at);+ fracText = core.slice(at + decimal.length);+ if (!/^\d*$/.test(fracText)) {+ return null;+ }+ }++ let digits: string;+ if (group !== '' && intText.includes(group)) {+ const chunks = intText.split(group);+ if (+ chunks.length - 1 < minGroups ||+ !chunks.every(chunk => /^\d+$/.test(chunk))+ ) {+ return null;+ }+ const first = chunks[0];+ const last = chunks[chunks.length - 1];+ if (last.length !== primaryGroupSize || first.length > secondaryGroupSize) {+ return null;+ }+ for (let i = 1; i < chunks.length - 1; i++) {+ if (chunks[i].length !== secondaryGroupSize) {+ return null;+ }+ }+ digits = chunks.join('');+ } else {+ if (!/^\d*$/.test(intText)) {+ return null;+ }+ digits = intText;+ }++ if (digits === '' && (fracText == null || fracText === '')) {+ return null;+ }+ return fracText == null ? digits : `${digits}.${fracText}`;+}++/**+ * A separator that no locale uses as a decimal point, so one well-formed group+ * of it is already unambiguous. Everything else needs two before grouping+ * beats the decimal-point reading.+ */+function isGroupOnlySeparator(separator: string): boolean {+ return /^[\s'\u2019\u00B7]$/.test(separator);+}++function toPlainNumber(+ core: string,+ locale: Locale | undefined,+): string | null {+ if (LETTER.test(core)) {+ return null;+ }++ const {group, decimal, primaryGroupSize, secondaryGroupSize} =+ getLocaleNumberSymbols(locale);+ const inLocale = readUnder(+ core,+ group,+ decimal,+ primaryGroupSize,+ secondaryGroupSize,+ 1,+ );+ if (inLocale != null) {+ return inLocale;+ }++ // The locale could not read it. A repeated separator with three digits after+ // each occurrence can only be grouping — a decimal point appears once — so+ // that shape reads the same in every locale, which is what lets a+ // `1,234,234,234` pasted out of a spreadsheet land in a de-DE app.+ const separators = [...new Set(core.replace(/\d/g, ''))];+ if (separators.length === 0 || separators.length > 2) {+ return null;+ }+ for (const candidate of separators) {+ const occurrences = core.split(candidate).length - 1;+ const minGroups = isGroupOnlySeparator(candidate) ? 1 : 2;+ if (occurrences < minGroups) {+ continue;+ }+ const other = separators.find(s => s !== candidate) ?? '';+ if (other !== '' && core.split(other).length - 1 !== 1) {+ continue;+ }+ const read = readUnder(core, candidate, other, 3, 3, minGroups);+ if (read != null) {+ return read;+ }+ }+ return null;+}++/**+ * Read a number out of text the way a person in `locale` writes one: their+ * grouping and decimal separators, their group sizes, their digit script, an+ * optional currency symbol, and the shapes a spreadsheet pastes.+ *+ * Returns null rather than a guess. Grouping is validated, so en-US `1,23` —+ * a comma that is neither a decimal point nor a well-formed group — is not+ * silently read as 123, and neither is a number written for another locale.+ *+ * @example+ * ```+ * parseLocaleNumber('1,234,234,234', 'en-US') // 1234234234+ * parseLocaleNumber('1,234,234,234', 'de-DE') // 1234234234+ * parseLocaleNumber('1,5', 'de-DE') // 1.5+ * parseLocaleNumber('1,5', 'en-US') // null+ * ```+ */+export function parseLocaleNumber(+ text: string,+ locale?: Locale,+): number | null {+ const normalized = toAsciiDigits(+ text.normalize('NFKC').replace(INVISIBLES, ''),+ );+ if (normalized == null) {+ return null;+ }++ let rest = normalized.trim();+ let sign = 1;++ // Accounting negatives: spreadsheets write -1234 as (1,234).+ const accounting = /^\((.*)\)$/s.exec(rest);+ if (accounting) {+ sign = -1;+ rest = accounting[1].trim();+ }++ rest = stripCurrency(rest);++ // The sign lands on either end — RTL locales trail it, and Intl writes+ // U+2212 where a keyboard writes a hyphen.+ const leadingSign = new RegExp(`^([+${MINUS_SIGNS}])\\s*`).exec(rest);+ if (leadingSign) {+ sign = leadingSign[1] === '+' ? sign : -sign;+ rest = rest.slice(leadingSign[0].length);+ } else {+ const trailingSign = new RegExp(`\\s*([+${MINUS_SIGNS}])$`).exec(rest);+ if (trailingSign) {+ sign = trailingSign[1] === '+' ? sign : -sign;+ rest = rest.slice(0, rest.length - trailingSign[0].length);+ }+ }++ rest = stripCurrency(rest);++ let exponent = 0;+ const exponentMatch = /\s*[eE]\s*([+-]?\d+)$/.exec(rest);+ if (exponentMatch) {+ exponent = Number(exponentMatch[1]);+ rest = rest.slice(0, rest.length - exponentMatch[0].length);+ }++ const core = rest.trim();+ if (core === '') {+ return null;+ }++ const plain = toPlainNumber(core, locale);+ if (plain == null) {+ return null;+ }++ const magnitude = Number(plain);+ if (!Number.isFinite(magnitude)) {+ return null;+ }++ const scaled =+ exponent === 0+ ? magnitude+ : // 1.23 * 1e3 is 1229.9999999999998 in binary floating point, and a+ // field that commits that instead of 1230 has not round-tripped.+ Number((magnitude * 10 ** exponent).toPrecision(15));+ if (!Number.isFinite(scaled)) {+ return null;+ }+ const result = sign * scaled;+ return Object.is(result, -0) ? 0 : result;+}++function stripCurrency(text: string): string {+ let out = text.trim();+ if (CURRENCY.test(out.charAt(0))) {+ out = out.slice(1).trim();+ }+ if (CURRENCY.test(out.charAt(out.length - 1))) {+ out = out.slice(0, -1).trim();+ }+ return out;+}++/**+ * The text shown while the field is focused: the plain machine number in the+ * locale's decimal separator, so what a person sees mid-edit is what the+ * parser reads back on blur.+ */+export function formatEditableNumber(value: number, locale?: Locale): string {+ const {decimal} = getLocaleNumberSymbols(locale);+ const raw = String(value);+ return decimal === '.' ? raw : raw.replace('.', decimal);+}