feat: images upload
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
"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<string | null>(null);
|
||||
const [clientError, setClientError] = useState<string | null>(null);
|
||||
|
||||
const MAX_SIZE = 5 * 1024 * 1024;
|
||||
const ACCEPTED_TYPES = ["image/jpeg", "image/png", "image/webp"];
|
||||
|
||||
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
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 (
|
||||
<Field data-invalid={!!displayedError}>
|
||||
<FieldLabel htmlFor={id}>{label}</FieldLabel>
|
||||
<div className="flex items-center gap-4">
|
||||
{previewUrl && (
|
||||
<img
|
||||
src={previewUrl}
|
||||
alt=""
|
||||
className={cn(
|
||||
"w-16 h-16 rounded-md object-cover ring-1 ring-foreground/10 shrink-0"
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<Input
|
||||
id={id}
|
||||
name={name}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
aria-invalid={!!displayedError}
|
||||
onChange={handleChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<FieldDescription>{description}</FieldDescription>
|
||||
{displayedError && <FieldError>{displayedError}</FieldError>}
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user