import { useEffect, useId, useRef, useState, type InputHTMLAttributes, } from 'react'; import { normalizeDecimalInput, presentDecimal } from '@/lib/decimal-input'; type Props = Omit< InputHTMLAttributes, 'type' | 'value' | 'onChange' | 'min' | 'max' | 'step' > & { value: string | number | null | undefined; /** Receives the stored format ("1500.50"), or the raw text when it is not a number, so validation can explain it. */ onValueChange: (value: string) => void; min?: string | number; max?: string | number; step?: string | number; }; /** * Number field that reads «25.000», «1 500» and «1500,50» as written in * Mozambique, instead of the browser's number input, which follows the * browser locale (25.000 → 25; a comma may be refused). */ export function DecimalInput({ value: rawValue, onValueChange, min: _min, max: _max, step: _step, onBlur, ...rest }: Props) { const value = rawValue === null || rawValue === undefined ? '' : String(rawValue); const hintId = useId(); const [text, setText] = useState(value); const emitted = useRef(value); useEffect(() => { // A value set elsewhere (draft recovery, another field) replaces the text. if (normalizeDecimalInput(text) !== value) setText(value); emitted.current = value; // eslint-disable-next-line react-hooks/exhaustive-deps }, [value]); const read = normalizeDecimalInput(text); // A value saved before this field existed (for example «25.000» from the // browser's number input) is kept as it is until the investor says what it // meant: as written in Mozambique, or with the point as decimal separator. const storedRead = normalizeDecimalInput(value); const pointRead = Number(value.trim()); const legacyChoices = value !== '' && text === value && storedRead !== value ? [ ...(storedRead ? [storedRead] : []), ...(Number.isFinite(pointRead) && String(pointRead) !== storedRead ? [String(pointRead)] : []), ] : []; const choose = (choice: string) => { setText(choice); emitted.current = choice; onValueChange(choice); }; const reinterpreted = !legacyChoices.length && read !== null && read !== '' && read !== text.trim() ? read : null; return ( <> { // A field the plan did not accept (an emptied horizon, a // fraction of a month) shows again the value still in force. if (emitted.current !== value) { setText(value); emitted.current = value; } onBlur?.(event); }} aria-describedby={ [ rest['aria-describedby'], reinterpreted || legacyChoices.length ? hintId : null, ] .filter(Boolean) .join(' ') || undefined } onChange={(event) => { setText(event.target.value); const normalized = normalizeDecimalInput( event.target.value, ); emitted.current = normalized === null ? event.target.value : normalized; onValueChange(emitted.current); }} /> {legacyChoices.length > 0 && ( Valor guardado «{value}». Confirme o que pretendia:{' '} {legacyChoices.map((choice) => ( ))} )} {reinterpreted && ( Lido como {presentDecimal(reinterpreted)} )} ); }