"use client"; import { useRef, useState, useEffect } from "react"; import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { XIcon, ImageIcon, RefreshCwIcon } from "lucide-react"; import { cn } from "@/lib/utils"; import { Spinner } from "@/components/ui/spinner"; type Props = { id: string; name?: string; label: string; description?: string; error?: string; variant?: "default" | "editor"; previewClassName?: string; previewStyle?: React.CSSProperties; accept?: string; required?: boolean; value?: string; onFileSelect?: (file: File, previewUrl: string) => void; onRemove?: () => void; isUploading?: boolean; children?: React.ReactNode; caption?: string; onCaptionChange?: (caption: string) => void; imgRef?: React.Ref; resizeHandle?: React.ReactNode; }; const MAX_SIZE = 5 * 1024 * 1024; const DEFAULT_ACCEPT = "image/jpeg,image/png,image/webp"; const EDITOR_WRAPPER_CLASS = "flex flex-col gap-2 items-stretch md:items-start"; function formatFileSize(bytes: number): string { return bytes < 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / (1024 * 1024)).toFixed(1)} MB`; } function validateFile(file: File, accept: string): string | null { const allowed = accept.split(",").map((t) => t.trim()); if (!allowed.includes(file.type)) { return "Only JPEG, PNG, or WEBP images are allowed."; } if (file.size > MAX_SIZE) { return "Image must be smaller than 5MB."; } return null; } function fileToFileList(file: File): FileList { const dt = new DataTransfer(); dt.items.add(file); return dt.files; } export function ImageUploader({ id, name, label, description, error, variant = "default", previewClassName, previewStyle, accept = DEFAULT_ACCEPT, required, value, onFileSelect, onRemove, isUploading, children, caption, onCaptionChange, imgRef, resizeHandle }: Props) { const inputRef = useRef(null); const [previewUrl, setPreviewUrl] = useState(null); const [fileInfo, setFileInfo] = useState<{ name: string; size: number } | null>(null); const [clientError, setClientError] = useState(null); const [isDragOver, setIsDragOver] = useState(false); useEffect(() => { return () => { if (previewUrl) URL.revokeObjectURL(previewUrl); }; }, [previewUrl]); function clearFileState() { if (previewUrl) URL.revokeObjectURL(previewUrl); setPreviewUrl(null); setFileInfo(null); if (inputRef.current) inputRef.current.value = ""; } function reset() { clearFileState(); setClientError(null); onRemove?.(); } function applyFile(file: File) { const validationError = validateFile(file, accept); if (validationError) { setClientError(validationError); clearFileState(); return; } setClientError(null); const url = URL.createObjectURL(file); setPreviewUrl(url); setFileInfo({ name: file.name, size: file.size }); onFileSelect?.(file, url); } function handleChange(e: React.ChangeEvent) { const file = e.target.files?.[0]; if (!file) return; applyFile(file); } function handleDrop(e: React.DragEvent) { e.preventDefault(); setIsDragOver(false); const file = e.dataTransfer.files?.[0]; if (!file) return; if (inputRef.current) { inputRef.current.files = fileToFileList(file); } applyFile(file); } const displayedError = clientError ?? error; const displayUrl = previewUrl ?? value; if (variant === "editor") { return ( {displayUrl ? (
{resizeHandle} {isUploading && (
)}
{onCaptionChange && ( onCaptionChange(e.target.value)} /> )}
) : (
inputRef.current?.click()} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") inputRef.current?.click(); }} onDragOver={(e) => { e.preventDefault(); setIsDragOver(true); }} onDragLeave={() => setIsDragOver(false)} onDrop={handleDrop} className={cn( "flex flex-row rounded-md bg-card px-2.5 py-1 text-sm text-muted-foreground ring-1 ring-foreground/10 transition-colors items-center gap-2", "hover:bg-muted/60", isDragOver && "bg-muted" )} > Add image
)} {displayedError && {displayedError}}
); } return ( {label}
{ e.preventDefault(); setIsDragOver(true); }} onDragLeave={() => setIsDragOver(false)} onDrop={handleDrop} className="flex flex-col md:flex-row items-start gap-4" >
{isUploading ? ( ) : displayUrl ? ( ) : ( )}
{fileInfo && (
{fileInfo.name} ({formatFileSize(fileInfo.size)})
)} {description && {description}} {children}
{displayedError && {displayedError}}
); }