Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Accept the separator the keyboard actually emits (#141) (#147)
Carter0450ce2ed339
diff --git a/mobile/app/(tabs)/settings/index.tsx b/mobile/app/(tabs)/settings/index.tsxindex f1d8079..80414e4 100644--- a/mobile/app/(tabs)/settings/index.tsx+++ b/mobile/app/(tabs)/settings/index.tsx@@ -24,6 +24,7 @@ import {testServerConnection,isInsecureServerUrl,INSECURE_SERVER_WARNING,+ sanitizeNumericInput,} from '@lyftr/shared'import {AppText,@@ -109,7 +110,7 @@ export default function SettingsScreen() {const restCustomActive = restIsCustom || showCustomRestconst onDigits = (key: keyof typeof targets) => (t: string) =>- setTargets((p) => ({ ...p, [key]: t.replace(/[^0-9]/g, '') }))+ setTargets((p) => ({ ...p, [key]: sanitizeNumericInput(t, 'numeric') }))const handleSaveTargets = async () => {setSaving(true)diff --git a/mobile/src/components/numericFields.test.ts b/mobile/src/components/numericFields.test.tsnew file mode 100644index 0000000..3c8c3f1--- /dev/null+++ b/mobile/src/components/numericFields.test.ts@@ -0,0 +1,35 @@+import { readFileSync, readdirSync } from 'fs'+import { join } from 'path'++// #141 was reported as "the weight field won't take a decimal", and the first fix+// corrected NumberField — while ActiveExerciseCard and ExerciseFormCard carried their+// own copies of the same strip and stayed broken. ActiveExerciseCard is the List view,+// which is the *default*, so the reporter's own screen was still broken after the fix.+//+// Three copies is how that happened, so sanitizeNumericInput now lives in+// @lyftr/shared and this asserts nobody grows a fourth. It reads the sources rather+// than rendering anything: the bug was never in what a component does with the value,+// it was in one component not asking the shared helper in the first place.+const SRC = join(__dirname, '..', '..')+const CODE = /\.tsx?$/+const SKIP = new Set(['node_modules', '.expo', 'android', 'ios', 'dist'])++// A character class that filters input down to digits — with or without a decimal+// point. This is the shape of the logic that must not be re-implemented.+const STRIP = /\[\^0-9\.?\]/++function sources(dir: string): string[] {+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {+ if (e.name.startsWith('.') || SKIP.has(e.name)) return []+ const p = join(dir, e.name)+ if (e.isDirectory()) return sources(p)+ return CODE.test(e.name) && !e.name.includes('.test.') ? [p] : []+ })+}++it('has exactly one implementation of numeric input sanitizing', () => {+ const offenders = [...sources(join(SRC, 'src')), ...sources(join(SRC, 'app'))].filter((p) =>+ STRIP.test(readFileSync(p, 'utf8')),+ )+ expect(offenders.map((p) => p.slice(SRC.length + 1).replace(/\\/g, '/'))).toEqual([])+})diff --git a/mobile/src/components/ui/NumberField.tsx b/mobile/src/components/ui/NumberField.tsxindex 43f15e0..c7560f4 100644--- a/mobile/src/components/ui/NumberField.tsx+++ b/mobile/src/components/ui/NumberField.tsx@@ -1,6 +1,6 @@import { TextInput } from 'react-native'import { useTheme } from '../../theme/useTheme'-import { useNumericText } from '@lyftr/shared'+import { sanitizeNumericInput, useNumericText } from '@lyftr/shared'interface Props {value: string@@ -14,18 +14,6 @@ interface Props {inputAccessoryViewID?: string}-// Web blocks bad keys in onKeyDown; RN keyboards have no such hook, so we sanitize-// the changed text instead. Non-negative always; integer mode also strips the-// decimal point so reps can't be typed fractional.-function sanitize(raw: string, decimal: boolean): string {- let v = raw.replace(decimal ? /[^0-9.]/g : /[^0-9]/g, '')- if (decimal) {- const i = v.indexOf('.')- if (i !== -1) v = v.slice(0, i + 1) + v.slice(i + 1).replace(/\./g, '')- }- return v-}-// Mirrors web ui/NumberField: borderless big-number field for the inside of a// StepperTile (the tile is the visual container). Robust partial-entry typing via// useNumericText; the parent owns conversion/validation in onChange.@@ -52,7 +40,7 @@ export function NumberField({accessibilityLabel={accessibilityLabel}inputAccessoryViewID={inputAccessoryViewID}onChangeText={(raw) => {- const v = sanitize(raw, inputMode === 'decimal')+ const v = sanitizeNumericInput(raw, inputMode)setText(v)onChange(v)}}diff --git a/mobile/src/components/workouts/ActiveExerciseCard.test.tsx b/mobile/src/components/workouts/ActiveExerciseCard.test.tsxnew file mode 100644index 0000000..6c58205--- /dev/null+++ b/mobile/src/components/workouts/ActiveExerciseCard.test.tsx@@ -0,0 +1,43 @@+import { renderHook, act } from '@testing-library/react-native'+import { useNumericText } from '@lyftr/shared'++// Regression guard for the defect review found in #146: sanitizeNumericInput was wired+// into ActiveExerciseCard, but the weight field had no useNumericText buffer. Its `value`+// is re-derived from a *number* in the session store on every keystroke, so typing "12."+// stored Number("12.") === 12, re-rendered as "12", and RN pushed that back into the+// native field — deleting the separator before the fractional digit could be typed.+//+// Net effect: #141 was declared fixed while the List view, which is the *default* workout+// layout (`workout_layout ?? 'list'`), still could not accept 12,5 or 12.5 at all.+//+// The helper's own rules live in packages/shared number.test.ts. What is worth pinning+// here is the part that was actually missing: the buffer has to survive a parent that+// round-trips the value through Number(). Rendering the whole card would need the theme,+// router and session store mocked to assert the same one thing.+describe('ActiveExerciseCard weight entry', () => {+ it('keeps a trailing separator when the parent re-derives value through Number()', () => {+ const { result, rerender } = renderHook((v: string) => useNumericText(v), {+ initialProps: '',+ })++ act(() => result.current[1]('12.'))+ expect(result.current[0]).toBe('12.')++ // Exactly what the card does: Number('12.') is 12, stored, handed back as '12'.+ rerender(String(Number('12.')))++ // Without the buffer this reads '12' and the fraction is unreachable.+ expect(result.current[0]).toBe('12.')++ act(() => result.current[1]('12.5'))+ expect(result.current[0]).toBe('12.5')+ })++ it('still follows the parent when the weight genuinely changes elsewhere', () => {+ const { result, rerender } = renderHook((v: string) => useNumericText(v), {+ initialProps: '100',+ })+ rerender('102.5')+ expect(result.current[0]).toBe('102.5')+ })+})diff --git a/mobile/src/components/workouts/ActiveExerciseCard.tsx b/mobile/src/components/workouts/ActiveExerciseCard.tsxindex a056c84..54f6b5c 100644--- a/mobile/src/components/workouts/ActiveExerciseCard.tsx+++ b/mobile/src/components/workouts/ActiveExerciseCard.tsx@@ -2,7 +2,7 @@ import { memo } from 'react'import { Pressable, Text, TextInput, View, type LayoutChangeEvent } from 'react-native'import { router, type Href } from 'expo-router'import { CheckCircle2, ChevronLeft, ChevronRight, Flag, Plus, X } from 'lucide-react-native'-import { displayToLbs, displayWeight, type ActiveSessionExercise } from '@lyftr/shared'+import { displayToLbs, displayWeight, sanitizeNumericInput, useNumericText, type ActiveSessionExercise } from '@lyftr/shared'import { AppText, NUMERIC_ACCESSORY_ID } from '../ui'import { ExerciseImage } from './ExerciseImage'import { useTheme } from '../../theme/useTheme'@@ -12,6 +12,53 @@ const exerciseHref = (id: number) => `/workouts/exercise/${id}` as unknown as Hrconst CELL = 'h-11 flex-1 rounded-lg border border-surface-border/60 bg-surface-overlay px-2 text-center font-sans text-base text-tx-primary'++// Both cells of a set row. A component rather than two inline TextInputs because each+// row needs its own text buffer, and these render inside a .map over the sets - a hook+// cannot be called in a loop.+//+// The buffer is half of #141. The parent re-derives `value` from a *number* every+// keystroke, so typing "12." stores Number("12.") === 12, re-renders as "12", and RN+// pushes that back into the native field - deleting the separator before the fractional+// digit can be typed. ExerciseFormCard's WeightCell already had a buffer and says why;+// this one, which backs the *default* List layout, never got the same treatment, so a+// decimal weight could not be entered here by any route.+//+// No selectTextOnFocus, unlike the log/edit form: these are live sets being corrected+// mid-workout, so a tap should land where it was aimed rather than replacing the value.+// That is the case sanitizeNumericInput's first-separator-wins rule exists for - the+// cursor can sit inside a prefilled "82,5".+function SetCell({ value, editable, mode, placeholder, placeholderColor, accessibilityLabel, onChange }: {+ value: string+ editable: boolean+ /** Reps are whole; weight takes one decimal separator. */+ mode: 'numeric' | 'decimal'+ placeholder: string+ placeholderColor: string+ accessibilityLabel: string+ onChange: (next: string) => void+}) {+ const [text, setText] = useNumericText(value)+ return (+ <TextInput+ value={text}+ editable={editable}+ onChangeText={(t) => {+ const v = sanitizeNumericInput(t, mode)+ setText(v)+ onChange(v)+ }}+ keyboardType={mode === 'numeric' ? 'number-pad' : 'decimal-pad'}+ inputAccessoryViewID={NUMERIC_ACCESSORY_ID}+ placeholder={placeholder}+ placeholderTextColor={placeholderColor}+ className={`${CELL} ${editable ? '' : 'opacity-40'}`}+ style={{ fontVariant: ['tabular-nums'] }}+ accessibilityLabel={accessibilityLabel}+ />+ )+}+interface Props {/** Position in the session — rendered as-is in callbacks so the owning screendoesn't bind a fresh closure per card (that would defeat the memo below and@@ -108,35 +155,24 @@ function ActiveExerciseCardBase({<Text className="font-sans-bold text-sm" style={{ color: set.completed ? accent : colors.txMuted, fontVariant: ['tabular-nums'] }}>{set.set_number}</Text></View><View className="flex-1">- <TextInput+ <SetCell+ mode="numeric"editable={!set.completed}value={set.actual_reps ? String(set.actual_reps) : ''}- onChangeText={(t) => onUpdateSet(index, setIdx, 'actual_reps', Number(t.replace(/[^0-9]/g, '')) || 0)}- keyboardType="number-pad"- inputAccessoryViewID={NUMERIC_ACCESSORY_ID}+ onChange={(v) => onUpdateSet(index, setIdx, 'actual_reps', Number(v) || 0)}placeholder={set.target_reps > 0 ? String(set.target_reps) : '—'}- placeholderTextColor={colors.txMuted}- className={`${CELL} ${set.completed ? 'opacity-40' : ''}`}- style={{ fontVariant: ['tabular-nums'] }}+ placeholderColor={colors.txMuted}accessibilityLabel={`Reps, set ${set.set_number}, ${ex.exercise.name}`}/></View><View className="flex-1">- <TextInput+ <SetCell+ mode="decimal"editable={!set.completed}value={set.actual_weight ? String(displayWeight(set.actual_weight, wUnit)) : ''}- onChangeText={(t) => {- let v = t.replace(/[^0-9.]/g, '')- const i = v.indexOf('.')- if (i !== -1) v = v.slice(0, i + 1) + v.slice(i + 1).replace(/\./g, '')- onUpdateSet(index, setIdx, 'actual_weight', displayToLbs(Number(v) || 0, weightUnit))- }}- keyboardType="decimal-pad"- inputAccessoryViewID={NUMERIC_ACCESSORY_ID}+ onChange={(v) => onUpdateSet(index, setIdx, 'actual_weight', displayToLbs(Number(v) || 0, weightUnit))}placeholder={set.target_weight > 0 ? String(displayWeight(set.target_weight, wUnit)) : '—'}- placeholderTextColor={colors.txMuted}- className={`${CELL} ${set.completed ? 'opacity-40' : ''}`}- style={{ fontVariant: ['tabular-nums'] }}+ placeholderColor={colors.txMuted}accessibilityLabel={`Weight, set ${set.set_number}, ${ex.exercise.name}`}/></View>diff --git a/mobile/src/components/workouts/DurationField.tsx b/mobile/src/components/workouts/DurationField.tsxindex 4079a2c..24ae08b 100644--- a/mobile/src/components/workouts/DurationField.tsx+++ b/mobile/src/components/workouts/DurationField.tsx@@ -1,5 +1,6 @@import { Pressable, Text, TextInput, View } from 'react-native'import { Minus, Plus } from 'lucide-react-native'+import { sanitizeNumericInput } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'// A thumb-friendly duration input: one unified stepper — −/+ as integrated end@@ -42,7 +43,7 @@ export function DurationField({ value, onChange, inputAccessoryViewID }: {<View className="flex-row items-baseline"><TextInputvalue={value ? String(value) : ''}- onChangeText={(t) => onChange(Number(t.replace(/[^0-9]/g, '')) || 0)}+ onChangeText={(t) => onChange(Number(sanitizeNumericInput(t, 'numeric')) || 0)}keyboardType="number-pad"returnKeyType="done"selectTextOnFocusdiff --git a/mobile/src/components/workouts/ExerciseFormCard.tsx b/mobile/src/components/workouts/ExerciseFormCard.tsxindex 0a5488e..94dde50 100644--- a/mobile/src/components/workouts/ExerciseFormCard.tsx+++ b/mobile/src/components/workouts/ExerciseFormCard.tsx@@ -5,7 +5,7 @@ import type { Exercise } from '@lyftr/shared'import { AppText, IconButton, Label } from '../ui'import { ExerciseImage } from './ExerciseImage'import { RestPicker } from './RestPicker'-import { useNumericText } from '@lyftr/shared'+import { sanitizeNumericInput, useNumericText } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'interface SetData {@@ -61,9 +61,7 @@ function WeightCell({ value, onChange, placeholderColor, inputRef, onNext, input}) {const [text, setText] = useNumericText(value)const emit = (raw: string) => {- let v = raw.replace(/[^0-9.]/g, '')- const i = v.indexOf('.')- if (i !== -1) v = v.slice(0, i + 1) + v.slice(i + 1).replace(/\./g, '')+ const v = sanitizeNumericInput(raw, 'decimal')setText(v)onChange(v)}@@ -160,7 +158,7 @@ function ExerciseFormCardBase({<TextInputref={(r) => { repsRefs.current[setIdx] = r }}value={set.reps ? String(set.reps) : ''}- onChangeText={(t) => onUpdateSet(index, setIdx, 'reps', t.replace(/[^0-9]/g, ''))}+ onChangeText={(t) => onUpdateSet(index, setIdx, 'reps', sanitizeNumericInput(t, 'numeric'))}keyboardType="number-pad"returnKeyType="next"submitBehavior="submit"diff --git a/mobile/src/components/workouts/RestPicker.tsx b/mobile/src/components/workouts/RestPicker.tsxindex f5223a3..2da7916 100644--- a/mobile/src/components/workouts/RestPicker.tsx+++ b/mobile/src/components/workouts/RestPicker.tsx@@ -3,6 +3,7 @@ import { Pressable, Text, TextInput, View } from 'react-native'import * as Haptics from 'expo-haptics'import { Clock, Minus, Pencil, Plus, TimerOff } from 'lucide-react-native'import type { LucideIcon } from 'lucide-react-native'+import { sanitizeNumericInput } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'interface Props {@@ -97,7 +98,7 @@ export function RestPicker({ value, onChange }: Props) {<View className="h-11 w-28 flex-row items-center rounded-lg border border-surface-border bg-surface-overlay px-3"><TextInputvalue={String(value)}- onChangeText={(raw) => onChange(clamp(Number(raw.replace(/[^0-9]/g, '')) || 0))}+ onChangeText={(raw) => onChange(clamp(Number(sanitizeNumericInput(raw, 'numeric')) || 0))}keyboardType="number-pad"returnKeyType="done"selectTextOnFocusdiff --git a/packages/shared/src/utils/number.test.ts b/packages/shared/src/utils/number.test.tsindex 7c123f2..cd647ca 100644--- a/packages/shared/src/utils/number.test.ts+++ b/packages/shared/src/utils/number.test.ts@@ -1,4 +1,4 @@-import { BODYWEIGHT_STEP, PLATE_STEP, REP_STEP, clampStep, clampValue } from './number'+import { BODYWEIGHT_STEP, PLATE_STEP, REP_STEP, clampStep, clampValue, sanitizeNumericInput } from './number'// The stepping math behind every +/- button in the app. It used to be covered only// through WeightInput's buttons; those moved to StepperTile (#91), so it's tested@@ -68,3 +68,88 @@ describe('clampValue', () => {expect(clampValue('abc', 5)).toBe(5)})})++// #141: a German user could not enter a decimal weight at all. Android's decimal-pad+// draws the locale's separator and the field deleted it as "not a digit", so these are+// the cases that bug is made of - plus the ones wger hit when they fixed the same report+// against their Flutter app (wger-project/flutter#1147).+describe('sanitizeNumericInput', () => {+ const dec = (s: string) => sanitizeNumericInput(s, 'decimal')++ it('accepts a comma as the decimal separator - the reported bug', () => {+ expect(dec('12,5')).toBe('12.5')+ })++ it('accepts a dot too, whatever the locale', () => {+ // The keypad may emit either: a numeric keyboard cannot be pinned to a locale.+ expect(dec('12.5')).toBe('12.5')+ })++ it('keeps a half-typed separator, so the fraction digit can still be typed', () => {+ expect(dec('12,')).toBe('12.')+ expect(dec('12.')).toBe('12.')+ })++ it('takes the FIRST separator, whichever kinds appear', () => {+ // A TextInput re-sends the whole field per keystroke and the cursor can sit inside a+ // prefilled value, so preferring the last would turn one keypress in "82,5" into 825+ // - a silent 10x that backspace cannot undo.+ expect(dec('82,5,')).toBe('82.5')+ expect(dec('12.5.')).toBe('12.5')+ })++ it('does not guess which character was grouping - same rule as wger', () => {+ // Telling grouping from a decimal needs the locale's own separator, and then the+ // other character is grouping by definition (react-aria and Expensify both do that).+ // No locale is injected here, so a pasted grouped number keeps the first separator+ // rather than being second-guessed. Typing is unaffected, which is the reported path.+ expect(dec('1.234,5')).toBe('1.2345')+ expect(dec('1,234.5')).toBe('1.2345')+ })++ it('never reads whitespace as a separator', () => {+ // fr, ru, sv, pl, cs, fi, nb and uk group with a space.+ expect(dec('12,50 kg')).toBe('12.50')+ expect(dec('12,5 ')).toBe('12.5')+ })++ it('drops everything that is not a digit or a separator', () => {+ expect(dec('abc12,5kg')).toBe('12.5')+ expect(dec('-12,5')).toBe('12.5')+ })++ it('does not detect grouping - it cannot be, mid-type', () => {+ // "1," arrives with nothing after it, so a grouping-aware rule works on paste and+ // lies while typing. 1,200 is 1.2 by both routes, deliberately. wger agrees.+ expect(dec('1,200')).toBe('1.200')+ })++ it('refuses a separator in numeric mode, so reps stay whole', () => {+ expect(sanitizeNumericInput('8,5', 'numeric')).toBe('85')+ expect(sanitizeNumericInput('8.5', 'numeric')).toBe('85')+ })++ // Ported from Dart's intl (number_parser_base.dart), which is what wger's own+ // NumberFormat.parse runs on. Their widget's filter is ASCII-only and strips these+ // before the parser ever sees them, so this is a case their app still gets wrong.+ it('folds localised digits instead of deleting them', () => {+ expect(dec('١٢٫٥')).toBe('12.5') // ar_EG: Arabic-Indic+ expect(dec('۱۲٫۵')).toBe('12.5') // fa: Extended Arabic-Indic+ expect(sanitizeNumericInput('٨٥', 'numeric')).toBe('85')+ })++ it('reads U+066B, the decimal separator those keypads emit', () => {+ // Folding the digits alone would leave this as 125 - a silent 10x, worse than the+ // zero it fixes. Dart lists U+066B as DECIMAL_SEP for both fa and ar_EG.+ expect(dec('12٫5')).toBe('12.5')+ })++ it('drops U+066C, their group separator, like any other thousands mark', () => {+ expect(dec('1٬234٫5')).toBe('1234.5')+ })++ it('leaves an empty field empty', () => {+ expect(dec('')).toBe('')+ expect(dec(',')).toBe('.')+ })+})diff --git a/packages/shared/src/utils/number.ts b/packages/shared/src/utils/number.tsindex 5aab5d8..f5eb5ba 100644--- a/packages/shared/src/utils/number.ts+++ b/packages/shared/src/utils/number.ts@@ -40,3 +40,122 @@ export function clampValue(raw: string | number, min = 0): number {const n = typeof raw === 'number' ? raw : Number(raw)return Number.isFinite(n) ? Math.max(min, n) : min}++// Typed text -> the canonical form the app stores. Every numeric field on mobile calls+// this; web needs none of it, because <input type="number"> lets the browser parse the+// locale's own separator. React Native has no equivalent hook: ReactEditText replaces+// Android's KeyListener specifically to "permit all keyboard input through", so+// `keyboardType` constrains what is *drawn* and never what arrives.+//+// The separator is the whole bug (#141). Android's decimal-pad draws the *locale's*+// decimal character - a comma across most of Europe, and on those keypads often with no+// full stop at all - so stripping it as "not a digit" left those users unable to enter a+// decimal weight by any route.+//+// The rule is wger's, who fixed the same report against their Flutter app+// (wger-project/flutter#1147, lib/core/number_input.dart):+//+// digits, plus ONE separator - the FIRST one. A "." and a "," both count, whatever+// the locale, because "a numeric keyboard cannot be pinned to a locale": the keypad+// may emit either. Everything else is dropped.+//+// First rather than last is load-bearing, not a tie-break. A TextInput re-sends the WHOLE+// field on every keystroke and the cursor can sit mid-string, so preferring the last would+// turn one keypress inside a prefilled "82,5" into "825" - a silent 10x that backspace+// cannot undo, because the fraction digit has become an integer digit.+//+// What this deliberately does NOT do is work out which character was meant as grouping.+// Doing that properly needs the locale's own decimal character, and then the other one is+// grouping by definition - which is what ICU-based parsers (react-aria's NumberParser,+// Expensify's LocaleDigitUtils) do. No locale is injected here, so guessing would be a+// heuristic no other app ships. The cost is that a *pasted* "1.234,5" reads 1.2345; typing+// is unaffected, and wger accepts the same trade. If the locale ever is injected, replace+// this with the ICU rule rather than a smarter guess.+//+// It also cannot be done mid-type in any case: "1," arrives with nothing after it, so a+// grouping-aware rule works on paste and lies while typing, which is the path people use.+// "1,200" is therefore 1.2 in every locale and by both routes.+//+// Why this is hand-written rather than a dependency, so nobody has to re-derive it:+// JavaScript has a number FORMATTER and no number PARSER. Intl.NumberFormat.prototype+// exposes format, formatToParts, formatRange, formatRangeToParts and resolvedOptions -+// nothing that reads a string back. (wger's version is shorter because Dart's intl ships+// NumberFormat.tryParse, so their widget formats and parses from one object.)+//+// The one maintained library that does this properly is react-aria's+// @internationalized/number, and its NumberParser calls formatToParts in four places -+// which Hermes does not implement on iOS (facebook/hermes#1188, open). Adopting it means+// also shipping @formatjs/intl-numberformat and CLDR locale data as a polyfill, to replace+// the ~20 lines below. The two React Native-specific packages are stale (2022 and 2023) and+// one depends on the deprecated `intl` polyfill. Web needs none of this at all:+// <input type="number"> lets the browser parse the locale's separator.+//+// REVISIT if @formatjs/intl-numberformat ever lands here for another reason. At that point+// react-aria's parser works on both platforms and this function should be deleted for it.+//+// Localised digits, folded the way Dart's intl does it - the library wger's own+// NumberFormat.parse runs on, so this is the reference implementation rather than our+// invention:+//+// number_parser_base.dart:118 var digitValue = charCode - _localeZero;+// number_parser_base.dart:224 writeCharCode(asciiZeroCodeUnit + digit);+//+// Subtracting a zero code point is the whole trick: digit sets are contiguous, so+// `code - zero` is the value and `0x30 + value` is the ASCII form. Deliberately NOT+// String.normalize('NFKC') - NFKC folds fullwidth digits and leaves Arabic-Indic alone, so+// a test written with fullwidth characters passes while the real case still logs a 0.+//+// One deviation, and it is the only one: Dart reads a single zero digit from the ACTIVE+// locale's symbols (`fa` -> U+06F0, `ar_EG` -> U+0660, most locales -> U+0030). No locale+// is injected here, so we carry both ranges CLDR actually assigns and fold whichever+// arrives. That is strictly broader than Dart - it accepts Persian digits from a device+// claiming en-US, which Dart would reject - and it needs no locale to be correct. If a+// locale is ever injected (see #146), narrow this to that locale's zero digit and the+// port becomes exact.+const ASCII_ZERO = 0x30+const LOCALE_ZEROS = [0x0660, 0x06f0] // Arabic-Indic, Extended Arabic-Indic++function foldDigits(raw: string): string {+ let out = ''+ for (const ch of raw) {+ const code = ch.codePointAt(0)!+ let folded = ch+ for (const localeZero of LOCALE_ZEROS) {+ const digitValue = code - localeZero+ if (digitValue >= 0 && digitValue <= 9) {+ folded = String.fromCharCode(ASCII_ZERO + digitValue)+ break+ }+ }+ out += folded+ }+ return out+}++// U+066B ARABIC DECIMAL SEPARATOR is a separator wherever those digits are. It is what+// Dart lists as DECIMAL_SEP for both `fa` and `ar_EG`, and folding the digits without it+// would leave "12٫5" as 125 - a silent 10x, worse than the zero this fixes. U+066C,+// their GROUP_SEP, needs no case: it falls through and is dropped like any other+// character, which is the same thing we do to a Latin thousands separator.+const isSeparator = (ch: string): boolean => ch === '.' || ch === ',' || ch === '٫'++// 'numeric' keeps digits only, so a separator cannot sneak a fractional rep in sideways.+export function sanitizeNumericInput(raw: string, mode: 'numeric' | 'decimal'): string {+ const folded = foldDigits(raw)+ if (mode !== 'decimal') return folded.replace(/[^0-9]/g, '')++ // Whitespace never counts as a separator. fr, ru, sv, pl, cs, fi, nb and uk group with+ // a space, so a trailing space or a pasted "12,50 kg" would otherwise read as 1250.+ const bare = folded.replace(/\s/g, '')++ let out = ''+ let seen = false+ for (const ch of bare) {+ if (ch >= '0' && ch <= '9') out += ch+ else if (isSeparator(ch) && !seen) {+ out += '.'+ seen = true+ }+ }+ return out+}