Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(NumberInput): bound the separator alphabet and read the machine decimal point (#5459)

Cindy Zhang86c10d7a6ebd
diff --git a/.changeset/number-input-bounded-separators.md b/.changeset/number-input-bounded-separators.md
new file mode 100644
index 0000000000..c554602e10
--- /dev/null
+++ b/.changeset/number-input-bounded-separators.md
@@ -0,0 +1,30 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] NumberInput: `1.5` reads as 1.5 everywhere again, and `123-456-789` is not a number
+
+Two defects in the locale-aware parsing added last release, both from one
+decision: which characters may separate digits was decided per input rather
+than from a bounded set.
+
+**The machine decimal point stopped parsing in comma-decimal locales.** In
+de-DE, typing `1.5` committed 1 with no error shown, and pasting `1.5` or
+`1234.56` was refused outright — all three committed the right number before.
+A full stop the locale cannot read as grouping has exactly one reading left,
+so it is now read, the way Chromium's own `<input type="number">` reads it. A
+full stop that _is_ well-formed grouping still belongs to the locale: `1.234`
+in de-DE is 1234, not 1.234.
+
+**Any repeated character read as a thousands separator.** `123-456-789`
+committed 123456789, and so did `1_234_567`, `1/234/567` and `1:234:567` — a
+hyphenated ID pasted into a quantity field became a number. Only the
+characters some locale actually writes between digits are separators now.
+
+Also: `(-1,234)` and `(+1,234)` each flipped their own sign and now refuse — an
+accounting paren already says negative, so a sign inside it reads two ways.
+
+Everything the previous release got right is unchanged, `formatValue` is
+untouched, and there is no API change.
+
+@cixzhang
diff --git a/packages/core/src/NumberInput/numberParser.test.ts b/packages/core/src/NumberInput/numberParser.test.ts
index 95c8fd685d..5ae93046c6 100644
--- a/packages/core/src/NumberInput/numberParser.test.ts
+++ b/packages/core/src/NumberInput/numberParser.test.ts
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect} from 'vitest';
-import {parseLocaleNumber} from './numberParser';
+import {formatEditableNumber, parseLocaleNumber} from './numberParser';
const NBSP = '\u00A0';
const NARROW_NBSP = '\u202F';
@@ -41,7 +41,18 @@ const CORPUS: [string, string, number | null][] = [
['1,5', 'de-DE', 1.5],
['1,5', 'en-US', null],
['1.5', 'en-US', 1.5],
- ['1.5', 'de-DE', null],
+
+ // The machine decimal point reads everywhere: a full stop the locale cannot
+ // read as grouping has one meaning left, and refusing it lost a number the
+ // person had typed. Where grouping IS well formed the locale still wins.
+ ['1.5', 'de-DE', 1.5],
+ ['1.5', 'fr-FR', 1.5],
+ ['1234.56', 'de-DE', 1234.56],
+ ['-3.25', 'fr-FR', -3.25],
+ ['0.5', 'de-DE', 0.5],
+ ['1.5e3', 'de-DE', 1500],
+ ['1.234', 'de-DE', 1234],
+ ['1.2345', 'de-DE', 1.2345],
// Decimals and signs.
['1,234.56', 'en-US', 1234.56],
@@ -89,6 +100,9 @@ const CORPUS: [string, string, number | null][] = [
['(1,234)', 'en-US', -1234],
['($1,234.50)', 'en-US', -1234.5],
['(1,234', 'en-US', null],
+ // The parens already carry the sign; a second one reads two ways.
+ ['(-1,234)', 'en-US', null],
+ ['(+1,234)', 'en-US', null],
// Typographic minus signs.
['\u22121234', 'en-US', -1234],
@@ -114,6 +128,25 @@ const CORPUS: [string, string, number | null][] = [
['1 234 (approx)', 'en-US', null],
['--5', 'en-US', null],
['1..234', 'en-US', null],
+
+ // Only a character some locale writes between digits is a separator. None of
+ // these are numbers, and the last two were refused before only because their
+ // final group is the wrong length — luck, not a rule.
+ ['123-456-789', 'en-US', null],
+ ['1-800-555', 'en-US', null],
+ ['555-123-456', 'en-US', null],
+ ['1_234_567', 'en-US', null],
+ ['1/234/567', 'en-US', null],
+ ['1:234:567', 'en-US', null],
+ ['1*234*567', 'en-US', null],
+ ['800-555-1212', 'en-US', null],
+ ['2024-01-15', 'en-US', null],
+
+ // The field has no percent semantics, so a percent sign is not dropped:
+ // committing 45 for `45%` is off by a factor of a hundred.
+ ['45%', 'en-US', null],
+ ['0.5%', 'en-US', null],
+ ['45 %', 'fr-FR', null],
];
describe('parseLocaleNumber', () => {
@@ -135,3 +168,43 @@ describe('parseLocaleNumber', () => {
}
});
});
+
+describe('formatEditableNumber', () => {
+ it.each([
+ [1.5, 'en-US', '1.5'],
+ [1.5, 'de-DE', '1,5'],
+ [-1234.56, 'fr-FR', '-1234,56'],
+ [3.5, 'ar-SA', '3٫5'],
+ // No grouping: the text has to be editable, and a separator the person did
+ // not type is one they have to delete.
+ [1234234234, 'de-DE', '1234234234'],
+ [42, 'de-DE', '42'],
+ // What `String` writes for the extremes stays untouched but for the point.
+ [1e21, 'de-DE', '1e+21'],
+ [1.5e-7, 'de-DE', '1,5e-7'],
+ ])('shows %j in %s as %j', (value, locale, expected) => {
+ expect(formatEditableNumber(value, locale)).toBe(expected);
+ });
+
+ it('round trips through the parser in every locale', () => {
+ for (const locale of [
+ 'en-US',
+ 'de-DE',
+ 'fr-FR',
+ 'de-CH',
+ 'en-IN',
+ 'ar-SA',
+ 'ja-JP',
+ 'hi-IN',
+ ]) {
+ for (const value of [
+ 0, 1, -1, 0.1, 1.5, -0.5, 1234.56, -1234567.125, 123456789,
+ 3.141592653589793, 1e21, 1.5e-7, -9007199254740991,
+ ]) {
+ expect(
+ parseLocaleNumber(formatEditableNumber(value, locale), locale),
+ ).toBe(value);
+ }
+ }
+ });
+});
diff --git a/packages/core/src/NumberInput/numberParser.ts b/packages/core/src/NumberInput/numberParser.ts
index 34a65830a6..2d87fa4cf8 100644
--- a/packages/core/src/NumberInput/numberParser.ts
+++ b/packages/core/src/NumberInput/numberParser.ts
@@ -13,6 +13,10 @@
* that could mean two different numbers returns null so the field stays
* visibly invalid instead of committing a guess.
*
+ * Which characters may separate digits at all is the one thing that is NOT
+ * read off the input: SEPARATOR_CHARS below is a bounded alphabet, the same
+ * shape utils/dateParser.ts uses for its `[-/.]` date separators.
+ *
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/NumberInput/NumberInput.tsx
* - /packages/core/src/NumberInput/numberParser.test.ts
@@ -69,7 +73,6 @@ function getLocaleNumberSymbols(locale: Locale | undefined) {
// 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;
@@ -77,6 +80,20 @@ const INVISIBLES = /[\u200B-\u200D\u200E\u200F\u061C\u2066-\u2069\uFEFF]/g;
// open a range.
const MINUS_SIGNS = '\u2212\u2012\u2013-';
+/**
+ * Every character a locale writes between digits: comma, full stop, space
+ * (the whole space family folds to it under NFKC), the Swiss apostrophes, the
+ * Catalan middle dot, and the Arabic decimal and thousands separators.
+ *
+ * The alphabet is bounded on purpose. Read the candidates off the input
+ * instead and any repeated character is grouping, so a hyphenated ID commits
+ * as a number.
+ */
+const SEPARATOR_CHARS = ",.' \u2019\u00B7\u066B\u066C";
+const NUMBER_BODY = new RegExp(`^[0-9${SEPARATOR_CHARS}]+$`);
+/** No grouping and at most one full stop: the format `Number()` reads. */
+const MACHINE_NUMBER = /^(?:\d+\.?\d*|\.\d+)$/;
+
/**
* 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
@@ -188,7 +205,7 @@ function toPlainNumber(
core: string,
locale: Locale | undefined,
): string | null {
- if (LETTER.test(core)) {
+ if (!NUMBER_BODY.test(core)) {
return null;
}
@@ -206,10 +223,20 @@ function toPlainNumber(
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.
+ // The machine format, which is what the field read before this parser
+ // existed. It comes after the locale rather than before it — dateParser.ts
+ // can put ISO first because `2026-01-25` has no second reading, while
+ // `1.234` in de-DE has one and grouping is the reading a German means. What
+ // reaches here is a full stop the locale could NOT read, so it is not
+ // well-formed grouping either, and exactly one reading is left.
+ if (MACHINE_NUMBER.test(core)) {
+ return core;
+ }
+
+ // 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;
@@ -240,13 +267,17 @@ function toPlainNumber(
* 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.
+ * Only the characters some locale writes between digits count as separators,
+ * so `123-456-789` is not a number at all.
*
* @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', 'de-DE') // 1.5
* parseLocaleNumber('1,5', 'en-US') // null
+ * parseLocaleNumber('123-456-789', 'en-US') // null
* ```
*/
export function parseLocaleNumber(
@@ -274,18 +305,27 @@ export function parseLocaleNumber(
// The sign lands on either end — RTL locales trail it, and Intl writes
// U+2212 where a keyboard writes a hyphen.
+ let hasWrittenSign = false;
const leadingSign = new RegExp(`^([+${MINUS_SIGNS}])\\s*`).exec(rest);
if (leadingSign) {
+ hasWrittenSign = true;
sign = leadingSign[1] === '+' ? sign : -sign;
rest = rest.slice(leadingSign[0].length);
} else {
const trailingSign = new RegExp(`\\s*([+${MINUS_SIGNS}])$`).exec(rest);
if (trailingSign) {
+ hasWrittenSign = true;
sign = trailingSign[1] === '+' ? sign : -sign;
rest = rest.slice(0, rest.length - trailingSign[0].length);
}
}
+ // The parens already say negative, so a sign inside them contradicts or
+ // doubles it: `(-1,234)` is -1234 to one reader and +1234 to another.
+ if (accounting && hasWrittenSign) {
+ return null;
+ }
+
rest = stripCurrency(rest);
let exponent = 0;