From d2a0815cb7f663f60b591753f6f5636ce4cabeb5 Mon Sep 17 00:00:00 2001 From: Aivan Monceller Date: Mon, 25 Aug 2025 13:27:58 +0800 Subject: [PATCH] enhance Input component to manage numeric values and improve onChange handling --- ui/src/components/ui/input.tsx | 61 ++++++++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/ui/src/components/ui/input.tsx b/ui/src/components/ui/input.tsx index 68551b9..2185509 100644 --- a/ui/src/components/ui/input.tsx +++ b/ui/src/components/ui/input.tsx @@ -4,15 +4,72 @@ import { cn } from "@/lib/utils" const Input = React.forwardRef>( ({ className, type, ...props }, ref) => { + const isNumeric = type === "number"; + const [tempValue, setTempValue] = React.useState(props.value?.toString() || ''); + + React.useEffect(() => { + if (props.value !== undefined) { + setTempValue(props.value.toString()); + } + }, [props.value]); + + const handleChange = (e: React.ChangeEvent) => { + const newValue = e.target.value; + + if (isNumeric) { + // Only allow empty string or numbers for numeric input + if (newValue === '' || /^\d+$/.test(newValue)) { + setTempValue(newValue); + // Only call onChange if the value is not empty + if (props.onChange && newValue !== '') { + props.onChange(e); + } + } + } else { + setTempValue(newValue); + if (props.onChange) { + props.onChange(e); + } + } + }; + + const handleBlur = (e: React.FocusEvent) => { + if (isNumeric && tempValue === '') { + const defaultValue = props.placeholder || "1"; + setTempValue(defaultValue); + + // Create a synthetic event for the corrected value + if (props.onChange) { + const syntheticEvent = { + ...e, + target: { ...e.target, value: defaultValue } + } as React.ChangeEvent; + + props.onChange(syntheticEvent); + } + } + + if (props.onBlur) { + props.onBlur(e); + } + }; + + // For numeric inputs, use text type and manage value internally + const inputType = isNumeric ? "text" : type; + const inputValue = isNumeric ? tempValue : props.value; + return ( ) }