import type { ChangeEvent } from 'react'; import React from 'react'; import type { ControllerRenderProps, FieldValues, Path } from 'react-hook-form'; import { Input } from '@luxfi/ui/input'; interface InjectedProps { onChange: (files: Array) => void; } interface Props> { children: React.ReactNode | ((props: InjectedProps) => React.ReactNode); field: ControllerRenderProps; accept?: string; multiple?: boolean; } const FileInputContent = >({ children, accept, multiple, field }: Props) => { const ref = React.useRef(null); React.useEffect(() => { if (!multiple && field.value?.length === 0 && ref.current?.value) { ref.current.value = ''; } }, [ field.value?.length, multiple ]); const onChange = React.useCallback((files: Array) => { field.onChange([ ...(field.value || []), ...files ]); }, [ field ]); const handleInputChange = React.useCallback((event: ChangeEvent) => { const fileList = event.target.files; if (!fileList) { return; } const files = Array.from(fileList); onChange(files); field.onBlur(); }, [ onChange, field ]); const handleClick = React.useCallback(() => { ref.current?.click(); }, []); const handleInputBlur = React.useCallback(() => { field.onBlur(); }, [ field ]); const injectedProps = React.useMemo(() => ({ onChange, }), [ onChange ]); const content = typeof children === 'function' ? children(injectedProps) : children; return (
{ content }
); }; export const FileInput = React.memo(FileInputContent) as typeof FileInputContent;