import React, { useCallback, useRef, useImperativeHandle, useEffect } from 'react' import { createUseStyles } from 'react-jss' type AutoSizeInputProps = { value: string } & React.DetailedHTMLProps, HTMLInputElement> export const AutoSizeInput = React.forwardRef(({ className, value, placeholder, onChange, ...inputProps }, ref) => { // hooks const styles = useStyles() // refs const inputRef = useRef(null) const sizerRef = useRef(null) useEffect(() => { if (!inputRef.current || !sizerRef.current) return const targetValue = value || placeholder || '' sizerRef.current.innerHTML = targetValue.replaceAll(' ', ' ') requestAnimationFrame(() => { if (!sizerRef.current || !inputRef.current) return const bounds = sizerRef.current.getBoundingClientRect() inputRef.current.style.width = `${bounds.width}px` }) }, [placeholder, value]) // imperative logic useImperativeHandle(ref, () => inputRef.current as HTMLInputElement) // event handlers const handleInputChange = useCallback((event: React.ChangeEvent) => { if (sizerRef.current) { sizerRef.current.innerHTML = event.target.value.replaceAll(' ', ' ') requestAnimationFrame(() => { if (sizerRef.current && inputRef.current) { const bounds = sizerRef.current.getBoundingClientRect() inputRef.current.style.width = `${bounds.width}px` } }) } onChange && onChange(event) }, [onChange]) return ( <>
) }) const useStyles = createUseStyles({ autoSizeInput: { fontSize: 15, border: 'none', backgroundColor: 'transparent', outline: 'none', width: 1, fontFamily: 'Poppins, Roboto, "Helvetica Neue", Arial, sans-serif', boxSizing: 'content-box', '&::placeholder': { fontStyle: 'italic', }, }, inputSizer: { fontSize: 15, position: 'fixed', left: -100, top: -100, zIndex: -100, opacity: 0, minWidth: 1, pointerEvents: 'none', fontFamily: 'Poppins, Roboto, "Helvetica Neue", Arial, sans-serif', }, })