import { useInputResize } from '@/internal/hooks/useInputResize'; import { cn, text } from '@/styles/theme'; import { useCallback, useEffect, useRef } from 'react'; import { useAmountInput } from '@/internal/hooks/useAmountInput'; import { isValidAmount } from '@/internal/utils/isValidAmount'; import { TextInput } from '../TextInput'; type AmountInputProps = { asset: string; currency: string; fiatAmount: string; cryptoAmount: string; selectedInputType: 'fiat' | 'crypto'; setFiatAmount: (value: string) => void; setCryptoAmount: (value: string) => void; exchangeRate: string; delayMs?: number; className?: string; textClassName?: string; }; export function AmountInput({ fiatAmount, cryptoAmount, asset, selectedInputType, currency, setFiatAmount, setCryptoAmount, exchangeRate, delayMs, className, textClassName, }: AmountInputProps) { const containerRef = useRef(null); const wrapperRef = useRef(null); const inputRef = useRef(null); const measureRef = useRef(null); const labelRef = useRef(null); const currencyOrAsset = selectedInputType === 'fiat' ? currency : asset; const value = selectedInputType === 'fiat' ? fiatAmount : cryptoAmount; const updateScale = useInputResize( containerRef, wrapperRef, inputRef, measureRef, labelRef, ); const { handleChange } = useAmountInput({ setFiatAmount, setCryptoAmount, selectedInputType, exchangeRate, }); const handleAmountChange = useCallback( (value: string) => { handleChange(value, () => { if (inputRef.current) { inputRef.current.focus(); } }); }, [handleChange], ); useEffect(() => { updateScale(); }, [value, updateScale]); const selectedInputTypeRef = useRef(selectedInputType); useEffect(() => { /** * We need to focus the input when the input type changes * but not on the initial render. */ if (selectedInputTypeRef.current !== selectedInputType) { selectedInputTypeRef.current = selectedInputType; handleFocusInput(); } }, [selectedInputType]); const handleFocusInput = () => { if (inputRef.current) { inputRef.current.focus(); } }; return (
{currencyOrAsset}
{/* Hidden span for measuring text width Without this span the input field would not adjust its width based on the text width and would look like this: [0.12--------Empty Space-------][ETH] - As you can see the currency symbol is far away from the inputted value With this span we can measure the width of the text in the input field and set the width of the input field to match the text width [0.12][ETH] - Now the currency symbol is displayed next to the input field */} {value ? `${value}.` : '0.'}
); }