Skip to content
File

Blob: src/components/Dropzone.tsx

typescript86 lines
1import { useRef, useState, type DragEvent } from "react";
2import { cn } from "../lib/cn";
3import { ImagePlusIcon, SpinnerIcon } from "./icons";
4 
5interface DropzoneProps {
6 onFile: (file: File) => void;
7 loading?: boolean;
8 error?: string | null;
9}
10 
11export function Dropzone({ onFile, loading = false, error }: DropzoneProps) {
12 const inputRef = useRef<HTMLInputElement>(null);
13 const [dragging, setDragging] = useState(false);
14 
15 function handleFiles(files: FileList | null) {
16 const file = files?.[0];
17 if (file) onFile(file);
18 }
19 
20 function onDrop(e: DragEvent<HTMLDivElement>) {
21 e.preventDefault();
22 setDragging(false);
23 handleFiles(e.dataTransfer.files);
24 }
25 
26 return (
27 <div className="flex h-full w-full items-center justify-center p-6">
28 <div
29 role="button"
30 tabIndex={0}
31 onClick={() => inputRef.current?.click()}
32 onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && inputRef.current?.click()}
33 onDragOver={(e) => {
34 e.preventDefault();
35 setDragging(true);
36 }}
37 onDragLeave={() => setDragging(false)}
38 onDrop={onDrop}
39 className={cn(
40 "group relative flex w-full max-w-xl cursor-pointer flex-col items-center justify-center gap-4",
41 "rounded-2xl border-2 border-dashed px-8 py-16 text-center transition-transform",
42 dragging
43 ? "border-accent-500 bg-accent-500/10"
44 : "border-zinc-700 bg-zinc-900/60 hover:border-zinc-600 hover:bg-zinc-900",
45 )}
46 >
47 <div
48 className={cn(
49 "flex size-16 items-center justify-center rounded-2xl bg-zinc-800 text-zinc-400 transition-transform",
50 "group-hover:text-accent-400",
51 dragging && "text-accent-400",
52 )}
53 >
54 {loading ? <SpinnerIcon className="size-7 animate-spin" /> : <ImagePlusIcon className="size-7" />}
55 </div>
56
57 <div className="space-y-1">
58 <p className="text-base font-semibold text-zinc-100">
59 {loading ? "Loading image…" : dragging ? "Drop to load" : "Drop an image here"}
60 </p>
61 <p className="text-sm text-zinc-400">or click to browse · paste from your clipboard</p>
62 </div>
63
64 <p className="text-xs text-zinc-500">JPEG · PNG · WebP · AVIF · GIF · BMP · SVG</p>
65
66 {error && (
67 <p className="max-w-sm rounded-lg border border-red-500/20 bg-red-500/10 px-3 py-2 text-sm text-red-400">
68 {error}
69 </p>
70 )}
71
72 <input
73 ref={inputRef}
74 type="file"
75 accept="image/*"
76 className="hidden"
77 onChange={(e) => {
78 handleFiles(e.target.files);
79 e.target.value = "";
80 }}
81 />
82 </div>
83 </div>
84 );
85}