import React, { useEffect, useRef, useState } from 'react' import type { FieldProps } from './field-types' const NumberField: React.FC> = ({ value, config, onSave, readOnly, }) => { const numberConfig = config?.number const [isEditing, setIsEditing] = useState(false) // Store as string to allow intermediate states like "1." or empty const [localValue, setLocalValue] = useState('') const inputRef = useRef(null) useEffect(() => { setLocalValue(value !== undefined && value !== null ? value.toString() : '') }, [value]) useEffect(() => { if (isEditing && inputRef.current) { inputRef.current.focus() } }, [isEditing]) const handleStartEdit = () => { if (!readOnly) { setIsEditing(true) } } const handleBlur = () => { setIsEditing(false) if (localValue === '') { onSave(undefined) // Handle empty } else { const num = parseFloat(localValue) onSave(isNaN(num) ? undefined : num) } } const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { e.stopPropagation() inputRef.current?.blur() } } const formatNumber = (val: number | undefined) => { if (val === undefined || val === null || isNaN(val)) return '' return val.toFixed(numberConfig?.scale) } if (isEditing) { return ( setLocalValue(e.target.value)} onBlur={handleBlur} onKeyDown={handleKeyDown} onDoubleClick={(e) => e.stopPropagation()} className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm text-left font-mono" /> ) } return (
e.stopPropagation()} className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded border border-transparent transition-colors text-left font-mono ${ !readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : '' }`} > {value !== undefined && value !== null ? ( formatNumber(value) ) : ( Empty )}
) } export default NumberField