File Upload
FreeA drop zone that lifts on drag-over, validates type and size, shows image thumbnails, per-file spring progress with cancel, a dropped-connection error with retry, and remove.
Hide codecomponents/blocks/file-upload.tsx
"use client";
import { useEffect, useRef, useState } from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { AlertCircle, Check, FileText, Image as ImageIcon, RotateCcw, UploadCloud, X } from "lucide-react";
import { cn } from "@/lib/utils";
type Status = "uploading" | "done" | "error" | "canceled";
type Item = { id: number; name: string; size: number; type: string; progress: number; status: Status; error?: string; preview?: string; fail?: boolean };
const MAX = 10 * 1024 * 1024;
const ACCEPT = ["image/png", "image/jpeg", "image/webp", "application/pdf", "text/csv"];
const EXT: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", pdf: "application/pdf", csv: "text/csv" };
const kind = (f: File) => {
if (ACCEPT.includes(f.type)) return f.type;
const ext = f.name.split(".").pop()?.toLowerCase() ?? "";
return Object.hasOwn(EXT, ext) ? EXT[ext] : undefined;
};
const ring = "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background";
const bytes = (n: number) => (n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(0)} KB` : `${(n / 1024 ** 2).toFixed(1)} MB`);
export default function FileUploadBlock() {
const reduce = useReducedMotion();
const [items, setItems] = useState<Item[]>([]);
const [over, setOver] = useState(false);
const [rejected, setRejected] = useState<string | null>(null);
const input = useRef<HTMLInputElement>(null);
const nextId = useRef(1);
const depth = useRef(0);
const active = items.some((i) => i.status === "uploading");
useEffect(() => {
if (!active) return;
const t = setInterval(() => {
setItems((list) =>
list.map((it) => {
if (it.status !== "uploading") return it;
const p = Math.min(100, it.progress + 6 + Math.random() * 14);
if (it.fail && p > 62) return { ...it, progress: 62, status: "error", error: "Connection dropped at 62%." };
return p >= 100 ? { ...it, progress: 100, status: "done" } : { ...it, progress: p };
}),
);
}, 220);
return () => clearInterval(t);
}, [active]);
const previews = useRef(new Set<string>());
useEffect(() => {
const urls = previews.current;
return () => urls.forEach((u) => URL.revokeObjectURL(u));
}, []);
function addFiles(files: FileList | File[]) {
const bad: string[] = [];
const fresh: Item[] = [];
for (const f of Array.from(files)) {
const type = kind(f);
if (!type) bad.push(`${f.name} isn't a supported type.`);
else if (f.size > MAX) bad.push(`${f.name} is ${bytes(f.size)}; the limit is 10 MB.`);
else {
const id = nextId.current++;
fresh.push({
id,
name: f.name,
size: f.size,
type,
progress: 0,
status: "uploading",
preview: type.startsWith("image/") ? track(URL.createObjectURL(f)) : undefined,
fail: /fail/i.test(f.name) || (id % 4 === 0),
});
}
}
setRejected(bad.length ? bad.join(" ") : null);
if (!fresh.length) return;
setItems((l) => [...fresh, ...l]);
}
function track(url: string) {
previews.current.add(url);
return url;
}
const update = (id: number, patch: Partial<Item>) => setItems((l) => l.map((i) => (i.id === id ? { ...i, ...patch } : i)));
const cancel = (id: number) => update(id, { status: "canceled" });
const retry = (id: number) => update(id, { status: "uploading", progress: 0, error: undefined, fail: false });
const remove = (id: number) => {
const it = items.find((i) => i.id === id);
if (it?.preview) {
URL.revokeObjectURL(it.preview);
previews.current.delete(it.preview);
}
setItems((l) => l.filter((i) => i.id !== id));
};
const sample = () => {
const mk = (name: string, type: string, kb: number) => new File([new Uint8Array(kb * 1024)], name, { type });
addFiles([mk("q4-board-deck.pdf", "application/pdf", 2400), mk("customers-export.csv", "text/csv", 380), samplePng(), mk("contract-final.pdf", "application/pdf", 1200)]);
};
const uploading = items.filter((i) => i.status === "uploading").length;
const done = items.filter((i) => i.status === "done").length;
return (
<section className="max-w-[100vw] flex min-h-full w-full items-start justify-center bg-muted/40 px-4 py-10">
<div className="w-full max-w-xl">
<h2 className="text-lg font-semibold tracking-tight">Upload files</h2>
<p className="mt-1 text-sm text-muted-foreground">PNG, JPG, WebP, PDF or CSV, up to 10 MB each.</p>
<motion.div
onDragEnter={(e) => {
e.preventDefault();
depth.current++;
setOver(true);
}}
onDragOver={(e) => e.preventDefault()}
onDragLeave={() => {
depth.current = Math.max(0, depth.current - 1);
if (!depth.current) setOver(false);
}}
onDrop={(e) => {
e.preventDefault();
depth.current = 0;
setOver(false);
addFiles(e.dataTransfer.files);
}}
animate={over && !reduce ? { scale: 1.01 } : { scale: 1 }}
transition={{ type: "spring", stiffness: 400, damping: 28 }}
className={cn(
"relative mt-5 overflow-hidden rounded-xl border border-dashed bg-card p-8 text-center transition-[border-color,background-color,box-shadow]",
over ? "border-foreground/40 bg-background shadow-[0_0_0_4px_rgb(0_0_0/0.04),0_20px_40px_-24px_rgb(0_0_0/0.4)]" : "border-border shadow-[inset_0_1px_0_rgb(255_255_255/0.04)]",
)}
>
<div aria-hidden className={cn("pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_50%_0%,rgb(255_255_255/0.06),transparent_60%)] transition-opacity", over ? "opacity-100" : "opacity-0")} />
<motion.div animate={over && !reduce ? { y: -4 } : { y: 0 }} className="mx-auto grid size-11 place-items-center rounded-lg border border-border bg-background shadow-[inset_0_1px_0_rgb(255_255_255/0.06),0_4px_10px_-4px_rgb(0_0_0/0.25)]">
<UploadCloud className="size-5 text-muted-foreground" aria-hidden />
</motion.div>
<p className="mt-4 text-[13px] font-medium">{over ? "Drop to upload" : "Drag files here"}</p>
<p className="mt-1 text-xs text-muted-foreground">
or{" "}
<button type="button" onClick={() => input.current?.click()} className={cn("rounded-sm font-medium text-foreground underline underline-offset-4", ring)}>browse</button>
{" · "}
<button type="button" onClick={sample} className={cn("rounded-sm font-medium text-foreground underline underline-offset-4", ring)}>try sample files</button>
</p>
<input ref={input} type="file" multiple accept={ACCEPT.join(",")} className="sr-only" tabIndex={-1} aria-hidden onChange={(e) => (e.target.files && addFiles(e.target.files), (e.target.value = ""))} />
</motion.div>
<AnimatePresence>
{rejected ? (
<motion.p role="alert" initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: "auto" }} exit={{ opacity: 0, height: 0 }} className="flex gap-1.5 overflow-hidden pt-2.5 text-xs text-red-600 dark:text-red-400">
<AlertCircle className="mt-px size-3.5 shrink-0" aria-hidden />
{rejected}
</motion.p>
) : null}
</AnimatePresence>
{items.length ? (
<p className="mt-5 text-xs text-muted-foreground" aria-live="polite">
{uploading ? `Uploading ${uploading} of ${items.length}…` : `${done} of ${items.length} uploaded`}
</p>
) : null}
<ul className="mt-2 space-y-2">
<AnimatePresence initial={false}>
{items.map((it) => (
<motion.li
key={it.id}
layout={!reduce}
initial={reduce ? { opacity: 0 } : { opacity: 0, y: -8, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, x: 24, transition: { duration: 0.18 } }}
transition={{ type: "spring", stiffness: 420, damping: 34 }}
className={cn(
"relative overflow-hidden rounded-lg border bg-card p-3 shadow-[inset_0_1px_0_rgb(255_255_255/0.04),0_1px_2px_rgb(0_0_0/0.05)]",
it.status === "error" ? "border-red-500/40" : "border-border",
)}
>
<div className="flex items-center gap-3">
<div className="relative grid size-10 shrink-0 place-items-center overflow-hidden rounded-md border border-border bg-muted">
{it.preview ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={it.preview} alt="" className="size-full object-cover" />
) : it.type.startsWith("image/") ? (
<ImageIcon className="size-4 text-muted-foreground" aria-hidden />
) : (
<FileText className="size-4 text-muted-foreground" aria-hidden />
)}
<AnimatePresence>
{it.status === "done" ? (
<motion.span initial={{ scale: 0 }} animate={{ scale: 1 }} transition={{ type: "spring", stiffness: 500, damping: 18 }} className="absolute -bottom-0.5 -right-0.5 grid size-4 place-items-center rounded-full bg-emerald-500 text-white ring-2 ring-card">
<Check className="size-2.5" strokeWidth={4} aria-hidden />
</motion.span>
) : null}
</AnimatePresence>
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-[13px] font-medium">{it.name}</p>
<p className={cn("text-xs tabular-nums", it.status === "error" ? "text-red-600 dark:text-red-400" : "text-muted-foreground")}>
{it.status === "error" ? it.error : it.status === "canceled" ? "Canceled" : it.status === "done" ? bytes(it.size) : `${bytes((it.size * it.progress) / 100)} of ${bytes(it.size)} · ${Math.floor(it.progress)}%`}
</p>
</div>
{it.status === "uploading" ? (
<button type="button" aria-label={`Cancel ${it.name}`} onClick={() => cancel(it.id)} className={cn("grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground", ring)}>
<X className="size-3.5" aria-hidden />
</button>
) : it.status === "error" || it.status === "canceled" ? (
<div className="flex">
<button type="button" aria-label={`Retry ${it.name}`} onClick={() => retry(it.id)} className={cn("grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground", ring)}>
<RotateCcw className="size-3.5" aria-hidden />
</button>
<button type="button" aria-label={`Remove ${it.name}`} onClick={() => remove(it.id)} className={cn("grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground", ring)}>
<X className="size-3.5" aria-hidden />
</button>
</div>
) : (
<button type="button" aria-label={`Remove ${it.name}`} onClick={() => remove(it.id)} className={cn("grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground", ring)}>
<X className="size-3.5" aria-hidden />
</button>
)}
</div>
{it.status === "uploading" || it.status === "error" ? (
<div className="mt-2.5 h-1 overflow-hidden rounded-full bg-muted" role="progressbar" aria-label={`${it.name} progress`} aria-valuenow={Math.round(it.progress)} aria-valuemin={0} aria-valuemax={100}>
<motion.div
className={cn("relative h-full rounded-full", it.status === "error" ? "bg-red-500" : "bg-foreground")}
animate={{ width: `${it.progress}%` }}
transition={{ type: "spring", stiffness: 160, damping: 26 }}
>
{it.status === "uploading" && !reduce ? (
<span className="absolute inset-0 animate-[shimmer_1.2s_linear_infinite] bg-[linear-gradient(90deg,transparent,rgb(255_255_255/0.35),transparent)] bg-[length:200%_100%]" />
) : null}
</motion.div>
</div>
) : null}
</motion.li>
))}
</AnimatePresence>
</ul>
</div>
</section>
);
}
function samplePng() {
const c = document.createElement("canvas");
c.width = c.height = 80;
const g = c.getContext("2d");
if (g) {
const grad = g.createLinearGradient(0, 0, 80, 80);
grad.addColorStop(0, "#6366f1");
grad.addColorStop(1, "#f59e0b");
g.fillStyle = grad;
g.fillRect(0, 0, 80, 80);
}
const bin = atob(c.toDataURL("image/png").split(",")[1]);
return new File([Uint8Array.from(bin, (ch) => ch.charCodeAt(0))], "hero-shot.png", { type: "image/png" });
}