Files
eu/components/image-uploader.tsx
T

227 lines
7.7 KiB
TypeScript

"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;
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;
};
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";
const EDITOR_IMG_CLASS = "block max-w-full md:max-w-200 h-auto rounded-md border object-contain";
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, accept = DEFAULT_ACCEPT, required, value, onFileSelect, onRemove, isUploading, children, caption, onCaptionChange }: Props) {
const inputRef = useRef<HTMLInputElement>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const [fileInfo, setFileInfo] = useState<{ name: string; size: number } | null>(null);
const [clientError, setClientError] = useState<string | null>(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<HTMLInputElement>) {
const file = e.target.files?.[0];
if (!file) return;
applyFile(file);
}
function handleDrop(e: React.DragEvent<HTMLDivElement>) {
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 (
<Field data-invalid={!!displayedError}>
<Input ref={inputRef} id={id} name={name} type="file" accept={accept} className="hidden" onChange={handleChange} disabled={isUploading} />
{displayUrl ? (
<div className={EDITOR_WRAPPER_CLASS}>
<div className="group relative rounded-md">
<img src={displayUrl} alt="" className={previewClassName ?? EDITOR_IMG_CLASS} />
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
<Button type="button" variant="secondary" size="sm" onClick={() => inputRef.current?.click()} disabled={isUploading}>
<RefreshCwIcon />
Replace
</Button>
</div>
{isUploading && (
<div className="absolute inset-0 flex items-center justify-center bg-background/90 rounded-md">
<Spinner />
</div>
)}
</div>
{onCaptionChange && (
<input
className="w-full bg-transparent outline-none text-xs md:text-sm text-muted-foreground placeholder:text-muted-foreground/50"
placeholder="Add a caption..."
value={caption ?? ""}
onChange={(e) => onCaptionChange(e.target.value)}
/>
)}
</div>
) : (
<div
role="button"
tabIndex={0}
onClick={() => 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"
)}
>
<ImageIcon size={16} />
<span>Add image</span>
</div>
)}
{displayedError && <FieldError>{displayedError}</FieldError>}
</Field>
);
}
return (
<Field data-invalid={!!displayedError}>
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<div
onDragOver={(e) => { e.preventDefault(); setIsDragOver(true); }}
onDragLeave={() => setIsDragOver(false)}
onDrop={handleDrop}
className="flex flex-col md:flex-row items-start gap-4"
>
<div
className={cn(
"w-28 rounded-md border border-dashed border-foreground/15 bg-muted flex items-center justify-center overflow-hidden shrink-0 transition-colors",
previewClassName ?? "aspect-square",
isDragOver && "bg-muted/60 border-foreground/30"
)}
>
{isUploading ? (
<Spinner className="text-muted-foreground" />
) : displayUrl ? (
<img src={displayUrl} alt="" className="w-full h-full object-cover" />
) : (
<ImageIcon className="text-muted-foreground" size={24} />
)}
</div>
<div className="flex flex-col gap-1 flex-1 min-w-0">
<Input ref={inputRef} id={id} name={name} type="file" accept={accept} aria-invalid={!!displayedError} onChange={handleChange} disabled={isUploading} required={required && !fileInfo && !value} />
{fileInfo && (
<div className="flex items-center gap-2 text-sm text-muted-foreground min-w-0">
<span className="flex-1 truncate">
{fileInfo.name} ({formatFileSize(fileInfo.size)})
</span>
<Button type="button" variant="ghost" size="icon" className="h-6 w-6" onClick={reset} disabled={isUploading}>
<XIcon size={14} />
</Button>
</div>
)}
{description && <FieldDescription className="mt-1">{description}</FieldDescription>}
{children}
</div>
</div>
{displayedError && <FieldError>{displayedError}</FieldError>}
</Field>
);
}