import type {
DetailedHTMLProps,
ForwardRefExoticComponent,
InputHTMLAttributes,
} from "react"
import {
forwardRef,
useImperativeHandle,
useLayoutEffect,
useRef,
useState,
} from "react"
export type ElasticInputProps = DetailedHTMLProps<
InputHTMLAttributes,
HTMLInputElement
> & {
widthPadding?: number
}
export const ElasticInput: ForwardRefExoticComponent<
DetailedHTMLProps, HTMLInputElement> & {
widthPadding?: number
}
> = forwardRef(function ElasticInputFC(props, ref) {
const inputRef = useRef(null)
const spanRef = useRef(null)
const [inputWidth, setInputWidth] = useState(`auto`)
useImperativeHandle, Partial>(
ref,
() => ({
focus: () => {
inputRef.current?.focus()
},
}),
)
const extraWidth = props.type === `number` ? 15 : 0
useLayoutEffect(() => {
if (spanRef.current) {
setInputWidth(`${spanRef.current.offsetWidth + extraWidth}px`)
const interval = setInterval(() => {
if (spanRef.current) {
setInputWidth(`${spanRef.current.offsetWidth + extraWidth}px`)
}
}, 1000)
return () => {
clearInterval(interval)
}
}
}, [inputRef.current?.value, props.value])
return (
{props.value}
)
})