"use client"; import { useState } from "react"; import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; import { cn } from "@/lib/utils"; type Props = { id: string; name: string; label: string; description: string; error?: string; }; export function ImageUploadField({ id, name, label, description, error }: Props) { const [previewUrl, setPreviewUrl] = useState(null); const [clientError, setClientError] = useState(null); const MAX_SIZE = 5 * 1024 * 1024; const ACCEPTED_TYPES = ["image/jpeg", "image/png", "image/webp"]; function handleChange(e: React.ChangeEvent) { const file = e.target.files?.[0]; if (previewUrl) URL.revokeObjectURL(previewUrl); if (!file) { setPreviewUrl(null); setClientError(null); return; } if (!ACCEPTED_TYPES.includes(file.type)) { setClientError("Only JPEG, PNG, or WEBP images are allowed."); setPreviewUrl(null); e.target.value = ""; return; } if (file.size > MAX_SIZE) { setClientError("Image must be smaller than 5MB."); setPreviewUrl(null); e.target.value = ""; return; } setClientError(null); setPreviewUrl(URL.createObjectURL(file)); } const displayedError = clientError ?? error; return ( {label}
{previewUrl && ( )}
{description} {displayedError && {displayedError}}
); }