'use client'; import type { FormEvent, MouseEventHandler } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react'; import Image from 'next/image'; import { UploadCloud, X } from 'lucide-react'; import { cn } from '../lib/utils'; import { Button } from '../shadcn/button'; import { Label } from '../shadcn/label'; import { If } from './if'; type Props = Omit, 'value'> & { image?: string | null; onClear?: () => void; onValueChange?: (props: { image: string; file: File }) => void; visible?: boolean; } & React.ComponentPropsWithRef<'input'>; const IMAGE_SIZE = 22; export const ImageUploadInput: React.FC = function ImageUploadInputComponent({ children, image, onClear, onInput, onValueChange, ref: forwardedRef, visible = true, ...props }) { const localRef = useRef(null); const [state, setState] = useState({ image, fileName: '', }); const onInputChange = useCallback( (e: FormEvent) => { e.preventDefault(); const files = e.currentTarget.files; if (files?.length) { const file = files[0]; if (!file) { return; } const data = URL.createObjectURL(file); setState({ image: data, fileName: file.name, }); if (onValueChange) { onValueChange({ image: data, file, }); } } if (onInput) { onInput(e); } }, [onInput, onValueChange], ); const onRemove = useCallback(() => { setState({ image: '', fileName: '', }); if (localRef.current) { localRef.current.value = ''; } if (onClear) { onClear(); } }, [onClear]); const imageRemoved: MouseEventHandler = useCallback( (e) => { e.preventDefault(); onRemove(); }, [onRemove], ); const setRef = useCallback( (input: HTMLInputElement) => { localRef.current = input; if (typeof forwardedRef === 'function') { forwardedRef(localRef.current); } }, [forwardedRef], ); useEffect(() => { setState((state) => ({ ...state, image })); }, [image]); useEffect(() => { if (!image) { onRemove(); } }, [image, onRemove]); const Input = () => ( ); if (!visible) { return ; } return ( ); };