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); const reinterpreted = 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 ? 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); }} /> {reinterpreted && ( Lido como {presentDecimal(reinterpreted)} )} ); }