137 lines
4.6 KiB
TypeScript
137 lines
4.6 KiB
TypeScript
"use client";
|
|
|
|
import { useRef, useState } 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 } from "lucide-react";
|
|
import { cn } from "@/lib/utils";
|
|
import { removeBackground } from "@imgly/background-removal";
|
|
import { Spinner } from "@/components/ui/spinner";
|
|
|
|
type Props = {
|
|
id: string;
|
|
name: string;
|
|
label: string;
|
|
description: string;
|
|
error?: string;
|
|
previewClassName?: string;
|
|
removeBg?: boolean;
|
|
};
|
|
|
|
const MAX_SIZE = 5 * 1024 * 1024;
|
|
const ACCEPTED_TYPES = ["image/jpeg", "image/png", "image/webp"];
|
|
|
|
function formatFileSize(bytes: number): string {
|
|
return bytes < 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
}
|
|
|
|
export function ImageUploadField({ id, name, label, description, error, previewClassName, removeBg }: 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 [isProcessing, setIsProcessing] = useState(false);
|
|
|
|
function reset() {
|
|
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
|
setPreviewUrl(null);
|
|
setFileInfo(null);
|
|
if (inputRef.current) inputRef.current.value = "";
|
|
}
|
|
|
|
async function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
|
|
const file = e.target.files?.[0];
|
|
if (!file) { reset(); setClientError(null); return; }
|
|
|
|
if (!ACCEPTED_TYPES.includes(file.type)) {
|
|
setClientError("Only JPEG, PNG, or WEBP images are allowed.");
|
|
reset();
|
|
return;
|
|
}
|
|
if (file.size > MAX_SIZE) {
|
|
setClientError("Image must be smaller than 5MB.");
|
|
reset();
|
|
return;
|
|
}
|
|
|
|
setClientError(null);
|
|
|
|
if (!removeBg) {
|
|
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
|
setPreviewUrl(URL.createObjectURL(file));
|
|
setFileInfo({ name: file.name, size: file.size });
|
|
return;
|
|
}
|
|
|
|
setIsProcessing(true);
|
|
try {
|
|
const resultBlob = await removeBackground(file);
|
|
const processedFile = new File([resultBlob], file.name, { type: "image/png" });
|
|
|
|
const dt = new DataTransfer();
|
|
dt.items.add(processedFile);
|
|
if (inputRef.current) inputRef.current.files = dt.files;
|
|
|
|
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
|
setPreviewUrl(URL.createObjectURL(processedFile));
|
|
setFileInfo({ name: processedFile.name, size: processedFile.size });
|
|
} catch {
|
|
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
|
setPreviewUrl(URL.createObjectURL(file));
|
|
setFileInfo({ name: file.name, size: file.size });
|
|
} finally {
|
|
setIsProcessing(false);
|
|
}
|
|
}
|
|
|
|
const displayedError = clientError ?? error;
|
|
|
|
return (
|
|
<Field data-invalid={!!displayedError}>
|
|
<FieldLabel htmlFor={id}>{label}</FieldLabel>
|
|
<div 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",
|
|
previewClassName ?? "aspect-4/5"
|
|
)}
|
|
>
|
|
{isProcessing ? (
|
|
<Spinner className="text-muted-foreground" />
|
|
) : previewUrl ? (
|
|
<img src={previewUrl} 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="image/jpeg,image/png,image/webp"
|
|
aria-invalid={!!displayedError}
|
|
onChange={handleChange}
|
|
disabled={isProcessing}
|
|
required={!fileInfo}
|
|
/>
|
|
{fileInfo && (
|
|
<div className="flex items-center gap-2 text-sm text-muted-foreground w-full min-w-0">
|
|
<span className="flex-1 min-w-0 truncate">
|
|
{fileInfo.name} ({formatFileSize(fileInfo.size)})
|
|
</span>
|
|
<Button type="button" variant="ghost" size="icon" className="h-6 w-6" onClick={reset} disabled={isProcessing}>
|
|
<XIcon size={14} />
|
|
</Button>
|
|
</div>
|
|
)}
|
|
<FieldDescription className="mt-1">{description}</FieldDescription>
|
|
</div>
|
|
</div>
|
|
{displayedError && <FieldError>{displayedError}</FieldError>}
|
|
</Field>
|
|
);
|
|
} |