Skip to content
Shaken UI
Sign in

File Upload

Save

A drop zone and file list whose outline closes from dashed to solid as a dragged file approaches, with type, size, and count checks, per-file progress you control, retry, and image thumbnails.

Category
Forms
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

File Upload preview
  • PDFq3-usage-report.pdf2.4 MB
  • onboarding-step-2.png439 KB of 1.1 MB38%
  • CSVcustomer-export.csvConnection lost at 61%. Retry to resume.

Installation

npx @shakenui/cli add file-upload

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add file-upload --dry-run

Usage

file-upload-example.tsx
"use client";

import { useEffect, useState } from "react";
import { createUploadItem, FileUpload, type FileUploadItem } from "@/components/shaken/ui/file-upload";

const screenshot =
  "data:image/svg+xml," +
  encodeURIComponent(
    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80"><rect width="80" height="80" fill="#0c4a6e"/><rect x="8" y="10" width="40" height="6" rx="3" fill="#e0f2fe"/><rect x="8" y="22" width="64" height="4" rx="2" fill="#7dd3fc" opacity=".6"/><rect x="8" y="30" width="52" height="4" rx="2" fill="#7dd3fc" opacity=".6"/><rect x="8" y="46" width="30" height="24" rx="4" fill="#34d399"/><rect x="42" y="46" width="30" height="24" rx="4" fill="#fbbf24"/></svg>`,
  );

const seeded: FileUploadItem[] = [
  { id: "seed-report", name: "q3-usage-report.pdf", size: 2_516_582, type: "application/pdf", status: "done" },
  { id: "seed-shot", name: "onboarding-step-2.png", size: 1_183_744, type: "image/png", previewUrl: screenshot, status: "uploading", progress: 38 },
  { id: "seed-export", name: "customer-export.csv", size: 8_912_000, type: "text/csv", status: "error", error: "Connection lost at 61%. Retry to resume." },
];

export default function FileUploadExample() {
  const [files, setFiles] = useState<FileUploadItem[]>(seeded);
  const uploading = files.some((file) => file.status === "uploading");

  // Stands in for a real upload: nudges every running row forward until it lands.
  useEffect(() => {
    if (!uploading) return;
    const timer = setInterval(() => {
      setFiles((list) =>
        list.map((file) => {
          if (file.status !== "uploading") return file;
          const progress = Math.min(100, (file.progress ?? 0) + 4 + Math.random() * 10);
          return progress >= 100 ? { ...file, progress: 100, status: "done" } : { ...file, progress };
        }),
      );
    }, 220);
    return () => clearInterval(timer);
  }, [uploading]);

  return (
    <FileUpload
      className="w-full max-w-md"
      label="Attachments"
      files={files}
      accept="image/*,.pdf,.csv"
      maxSize={10 * 1024 * 1024}
      maxFiles={6}
      onFilesAdded={(added) => setFiles((list) => [...list, ...added.map(createUploadItem)])}
      onRemove={(id) => setFiles((list) => list.filter((file) => file.id !== id))}
      onRetry={(id) => setFiles((list) => list.map((file) => (file.id === id ? { ...file, status: "uploading", progress: 0, error: undefined } : file)))}
    />
  );
}

API

PropTypeDefaultDescription
filesFileUploadItem[]—The rows: { id, name, size, type?, file?, previewUrl?, status, progress?, error? }. You own this list.
onFilesAdded(files: File[]) => void—Files that passed the checks. createUploadItem(file) turns one into a row.
onRemove / onRetry(id) => void—Show remove (cancel while uploading) and retry buttons.
onReject(rejections) => void—Files turned away, each with a reason (type, size, count) and a message.
acceptstring—Accepted types, as for <input accept>: image/*, application/pdf, .csv.
maxSizenumber—Largest file in bytes.
maxFilesnumber—Most files in the list at once. The zone disables when full.
multiplebooleantrueAllows picking several files at once.
label / hintReactNode—A label above the zone and a replacement for the generated hint line.
disabledbooleanfalseTurns the zone off.

Accessibility

  • The drop zone is a button: Enter or Space opens the file picker, and the accepted types and limits are linked with aria-describedby.
  • Rejected files are listed in a role="alert" box that names each file and the reason, with a Dismiss button.
  • Each uploading row has a progressbar with a value and a label; remove and retry buttons name the file.
  • Finished and failed uploads are announced once through a polite live region.
  • The proximity response only changes opacity and color; with reduced motion preferred the arrow does not lift, rows appear in place, and the thumbnail and check change without transitions.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/file-upload.tsxfile-upload
  • npm packages: motion@^14.14.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/file-upload/0.1.0.json.

ui/file-upload.tsxShow
ui/file-upload.tsx
"use client";

import { AnimatePresence, MotionConfig, motion } from "motion/react";
import {
  type ChangeEvent,
  type DragEvent as ReactDragEvent,
  type ReactNode,
  useEffect,
  useId,
  useReducer,
  useRef,
  useState,
} from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";

export type FileUploadStatus = "uploading" | "done" | "error";

export interface FileUploadItem {
  /** Stable id for the row. `createUploadItem` makes one. */
  id: string;
  /** File name with its extension. */
  name: string;
  /** Size in bytes. */
  size: number;
  /** MIME type. */
  type?: string;
  /** The picked file. Image files get a thumbnail made from it automatically. */
  file?: File;
  /** Thumbnail URL, when you already have one (for example a file uploaded earlier). */
  previewUrl?: string;
  status: FileUploadStatus;
  /** 0 to 100 while uploading. Leave unset for an upload of unknown length. */
  progress?: number;
  /** Why the upload failed. */
  error?: string;
}

export interface FileUploadRejection {
  file: File;
  reason: "type" | "size" | "count";
  message: string;
}

export interface FileUploadProps {
  /** The rows to show. You own this list: add items in `onFilesAdded`, then update `progress` and `status` as the upload runs. */
  files: FileUploadItem[];
  /** Called with the files that passed `accept`, `maxSize`, and `maxFiles`. */
  onFilesAdded: (files: File[]) => void;
  /** Shows a remove button on each row (a cancel button while uploading). */
  onRemove?: (id: string) => void;
  /** Shows a retry button on failed rows. */
  onRetry?: (id: string) => void;
  /** Called with the files that were turned away. They are also listed under the drop zone. */
  onReject?: (rejections: FileUploadRejection[]) => void;
  /** Accepted types, as for `<input accept>`: `image/*`, `application/pdf`, `.csv`. */
  accept?: string;
  /** Largest file in bytes. */
  maxSize?: number;
  /** Most files in the list at once. */
  maxFiles?: number;
  /** Lets the user pick several files at once. */
  multiple?: boolean;
  disabled?: boolean;
  /** Visible label above the drop zone. */
  label?: ReactNode;
  /** Replaces the generated line under the prompt, such as "PNG or PDF, up to 10 MB each". */
  hint?: ReactNode;
  /** Name for the hidden file input, for plain form posts. */
  name?: string;
  id?: string;
  /** Classes for the wrapping element. */
  className?: string;
}

function extensionOf(name: string): string {
  const dot = name.lastIndexOf(".");
  return dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
}

/** Bytes as a short size, e.g. 2.4 MB. */
export function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${Math.round(bytes)} B`;
  const units = ["KB", "MB", "GB"];
  let value = bytes / 1024;
  let unit = 0;
  while (value >= 1024 && unit < units.length - 1) {
    value /= 1024;
    unit++;
  }
  return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
}

let counter = 0;

/** Wraps a picked file as an uploading row with a fresh id. */
export function createUploadItem(file: File): FileUploadItem {
  counter += 1;
  const id = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : `upload-${Date.now()}-${counter}`;
  return { id, name: file.name, size: file.size, type: file.type, file, status: "uploading", progress: 0 };
}

/** True when the file matches an `accept` string (MIME types, `type/*` wildcards, and extensions). */
export function fileMatchesAccept(file: Pick<File, "name" | "type">, accept?: string): boolean {
  if (!accept) return true;
  const tokens = accept.split(",").map((token) => token.trim().toLowerCase()).filter(Boolean);
  const type = (file.type || "").toLowerCase();
  const extension = `.${extensionOf(file.name)}`;
  return tokens.some((token) => {
    if (token.startsWith(".")) return token === extension;
    if (token.endsWith("/*")) return type.startsWith(token.slice(0, -1));
    return token === type;
  });
}

function describeAccept(accept: string): string {
  const names = accept
    .split(",")
    .map((token) => token.trim().toLowerCase())
    .filter(Boolean)
    .map((token) => {
      if (token === "image/*") return "Images";
      if (token === "video/*") return "Videos";
      if (token === "audio/*") return "Audio";
      if (token.startsWith(".")) return token.slice(1).toUpperCase();
      const subtype = token.split("/")[1] ?? token;
      return subtype.replace(/^x-/, "").replace(/\+.*$/, "").toUpperCase();
    });
  const unique = [...new Set(names)];
  if (unique.length <= 1) return unique[0] ?? "";
  return `${unique.slice(0, -1).join(", ")} or ${unique[unique.length - 1]}`;
}

function UploadGlyph() {
  return (
    <svg aria-hidden="true" viewBox="0 0 20 20" fill="none" className="size-5">
      {/* The tray stays put; the arrow lifts as a file comes near (see the translate on its group). */}
      <path d="M3.75 12.5v1.75c0 1.1.9 2 2 2h8.5c1.1 0 2-.9 2-2V12.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
      <g className={`[translate:0_calc(var(--p,0)_*_-2.5px)] transition-[translate] duration-200 ${ease} motion-reduce:[translate:none] motion-reduce:transition-none`}>
        <path d="M10 12.25V3.75M6.75 7L10 3.75 13.25 7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      </g>
    </svg>
  );
}

function FileGlyph() {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4">
      <path d="M4 1.75h5L12.25 5v8.25a1 1 0 0 1-1 1h-7.25a1 1 0 0 1-1-1V2.75a1 1 0 0 1 1-1z" stroke="currentColor" strokeWidth="1.25" strokeLinejoin="round" />
      <path d="M8.75 1.75V5.25h3.5" stroke="currentColor" strokeWidth="1.25" strokeLinejoin="round" />
    </svg>
  );
}

function StatusGlyph({ status, indeterminate }: { status: FileUploadStatus; indeterminate: boolean }) {
  if (status === "uploading" && indeterminate) {
    return (
      <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-3.5 shrink-0 text-sky-600 motion-safe:animate-spin dark:text-sky-400">
        <path d="M8 1.75a6.25 6.25 0 1 1-6.25 6.25" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
      </svg>
    );
  }
  if (status === "error") {
    return (
      <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="mt-px size-3.5 shrink-0 text-red-600 dark:text-red-400">
        <circle cx="8" cy="8" r="6.25" stroke="currentColor" strokeWidth="1.5" />
        <path d="M6 6l4 4M10 6l-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
      </svg>
    );
  }
  const done = status === "done";
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className={cx("size-3.5 shrink-0 text-emerald-600 dark:text-emerald-400", !done && "hidden")}>
      <circle cx="8" cy="8" r="6.25" stroke="currentColor" strokeWidth="1.5" />
      <path
        d="M5.25 8.25l1.9 1.9 3.6-4.15"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
        pathLength={1}
        strokeDasharray="1"
        className={`[stroke-dashoffset:0] transition-[stroke-dashoffset] delay-100 duration-300 ${ease} starting:[stroke-dashoffset:1] motion-reduce:transition-none`}
      />
    </svg>
  );
}

const iconButton = cx(
  "flex size-7 shrink-0 cursor-default items-center justify-center rounded-md text-zinc-500 dark:text-zinc-400",
  "hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white",
  "transition-colors duration-150 ease-out motion-reduce:transition-none",
  "focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500 [&_svg]:size-4",
);

function UploadRow({
  item,
  thumbnail,
  onRemove,
  onRetry,
}: {
  item: FileUploadItem;
  thumbnail?: string;
  onRemove?: (id: string) => void;
  onRetry?: (id: string) => void;
}) {
  const uploading = item.status === "uploading";
  const failed = item.status === "error";
  const done = item.status === "done";
  const progress = item.progress == null ? null : Math.max(0, Math.min(100, item.progress));
  const extension = extensionOf(item.name).toUpperCase();

  return (
    <motion.li
      layout="position"
      initial={{ opacity: 0, y: 6 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, scale: 0.98, transition: { duration: 0.15, ease: "easeOut" } }}
      transition={{ type: "spring", duration: 0.35, bounce: 0 }}
      data-status={item.status}
      className={cx(
        "relative flex items-center gap-3 overflow-hidden rounded-lg border bg-white py-2 pr-2 pl-2 dark:bg-black",
        "transition-[border-color] duration-200 ease-out motion-reduce:transition-none",
        failed ? "border-red-500/35" : "border-zinc-950/10 dark:border-white/10",
      )}
    >
      {/* The thumbnail develops from a dim grayscale proof into full color when the upload lands. */}
      <span
        className={cx(
          "relative flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-md text-zinc-500 dark:text-zinc-400",
          "shadow-[inset_0_0_0_1px_rgb(9_9_11/0.08)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.1)]",
        )}
      >
        {thumbnail ? (
          <img
            src={thumbnail}
            alt=""
            className={cx(
              `size-full object-cover transition-[filter,opacity] duration-500 ${ease} motion-reduce:transition-none`,
              done ? "opacity-100 grayscale-0" : "opacity-60 grayscale",
            )}
          />
        ) : (
          <span className="flex flex-col items-center gap-0.5">
            <FileGlyph />
            <span className="font-mono text-[9px] leading-none font-medium">{extension.slice(0, 4) || "FILE"}</span>
          </span>
        )}
      </span>

      <span className="grid min-w-0 flex-1 gap-1">
        <span className="truncate text-[13px] leading-4 font-medium text-zinc-950 dark:text-white" title={item.name}>
          {item.name}
        </span>
        <span className={cx("flex min-w-0 gap-1.5 text-xs leading-4 tabular-nums", failed ? "items-start text-red-600 dark:text-red-400" : "items-center text-zinc-500")}>
          <StatusGlyph status={item.status} indeterminate={progress == null} />
          <span className={failed ? "min-w-0 break-words" : "truncate"} role={failed ? "alert" : undefined}>
            {failed
              ? (item.error ?? "Upload failed")
              : uploading
                ? progress != null
                  ? `${formatBytes((item.size * progress) / 100)} of ${formatBytes(item.size)}`
                  : `Uploading, ${formatBytes(item.size)}`
                : formatBytes(item.size)}
          </span>
          {uploading && progress != null ? <span className="ms-auto shrink-0 font-mono text-[11px] text-zinc-500">{Math.round(progress)}%</span> : null}
        </span>
        {/* Thin progress line. It fades out as the row settles. */}
        <span
          role={uploading ? "progressbar" : undefined}
          aria-label={uploading ? `Uploading ${item.name}` : undefined}
          aria-valuemin={uploading ? 0 : undefined}
          aria-valuemax={uploading ? 100 : undefined}
          aria-valuenow={uploading && progress != null ? Math.round(progress) : undefined}
          aria-hidden={uploading ? undefined : true}
          className={cx(
            "relative h-0.5 overflow-hidden rounded-full bg-zinc-950/[0.07] dark:bg-white/10",
            `transition-opacity duration-300 ${ease} motion-reduce:transition-none`,
            uploading ? "opacity-100" : "opacity-0",
            (failed || (uploading && progress == null)) && "hidden",
          )}
        >
          <span
            className={cx(
              "absolute inset-y-0 left-0 w-full origin-left rounded-full",
              done ? "bg-emerald-500" : "bg-zinc-950 dark:bg-white",
              `transition-[scale,background-color] duration-300 ${ease} motion-reduce:transition-none`,
            )}
            style={{ scale: `${done ? 1 : (progress ?? 0) / 100} 1` }}
          />
        </span>
      </span>

      {(failed && onRetry) || onRemove ? (
        <span className="flex shrink-0 items-center self-center">
          {failed && onRetry ? (
            <button type="button" aria-label={`Retry uploading ${item.name}`} onClick={() => onRetry(item.id)} className={iconButton}>
              <svg aria-hidden="true" viewBox="0 0 16 16" fill="none">
                <path d="M13 8a5 5 0 1 1-1.46-3.54M13 3v2.5h-2.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          ) : null}
          {onRemove ? (
            <button
              type="button"
              aria-label={uploading ? `Cancel uploading ${item.name}` : `Remove ${item.name}`}
              onClick={() => onRemove(item.id)}
              className={iconButton}
            >
              <svg aria-hidden="true" viewBox="0 0 16 16" fill="none">
                <path d="M5 5l6 6M11 5l-6 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
              </svg>
            </button>
          ) : null}
        </span>
      ) : null}
    </motion.li>
  );
}

/**
 * A drop zone and file list. Click, press Enter or Space, or drag files in. The zone notices a
 * file being dragged anywhere on the page: its dashed outline closes into a solid line as the
 * file gets near, and lights up under the pointer once it is over. Files are checked against
 * `accept`, `maxSize`, and `maxFiles` with inline reasons. You drive each row's progress through
 * `files`; finished rows settle as their thumbnail develops into color.
 */
export function FileUpload({
  files,
  onFilesAdded,
  onRemove,
  onRetry,
  onReject,
  accept,
  maxSize,
  maxFiles,
  multiple = true,
  disabled = false,
  label,
  hint,
  name,
  id,
  className,
}: FileUploadProps) {
  const generatedId = useId();
  const zoneId = id ?? generatedId;
  const hintId = `${zoneId}-hint`;
  const errorsId = `${zoneId}-errors`;
  const inputRef = useRef<HTMLInputElement>(null);
  const zoneRef = useRef<HTMLButtonElement>(null);
  const [over, setOver] = useState(false);
  const [incoming, setIncoming] = useState(0);
  const [rejections, setRejections] = useState<FileUploadRejection[]>([]);
  const overDepth = useRef(0);

  const full = maxFiles != null && files.length >= maxFiles;
  const inactive = disabled || full;

  // Object URLs for image thumbnails, made once per row and revoked when the row goes away.
  const urls = useRef(new Map<string, string>());
  const [, refresh] = useReducer((count: number) => count + 1, 0);
  useEffect(() => {
    let changed = false;
    for (const item of files) {
      if (!item.previewUrl && item.file && item.file.type.startsWith("image/") && !urls.current.has(item.id)) {
        urls.current.set(item.id, URL.createObjectURL(item.file));
        changed = true;
      }
    }
    for (const [key, url] of urls.current) {
      if (!files.some((item) => item.id === key)) {
        URL.revokeObjectURL(url);
        urls.current.delete(key);
        changed = true;
      }
    }
    if (changed) refresh();
  }, [files]);
  useEffect(() => {
    const map = urls.current;
    return () => {
      for (const url of map.values()) URL.revokeObjectURL(url);
      map.clear();
    };
  }, []);

  // Announces finished and failed uploads once each.
  const [announcement, setAnnouncement] = useState("");
  const lastStatus = useRef(new Map<string, FileUploadStatus>());
  useEffect(() => {
    const messages: string[] = [];
    for (const item of files) {
      const previous = lastStatus.current.get(item.id);
      if (previous && previous !== item.status) {
        if (item.status === "done") messages.push(`${item.name} uploaded`);
        if (item.status === "error") messages.push(`${item.name} failed${item.error ? `: ${item.error}` : ""}`);
      }
    }
    lastStatus.current = new Map(files.map((item) => [item.id, item.status]));
    if (messages.length) setAnnouncement(messages.join(". "));
  }, [files]);

  // Proximity: while a file is dragged anywhere in the window, --p rises from 0 to 1 as the pointer
  // nears the zone, and --x / --y track it for the highlight. Written straight to the element so
  // dragover does not re-render React.
  useEffect(() => {
    if (inactive) return;
    const zone = zoneRef.current;
    if (!zone) return;
    let depth = 0;
    const hasFiles = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes("Files");
    const reset = () => {
      depth = 0;
      overDepth.current = 0;
      setOver(false);
      zone.style.setProperty("--p", "0");
      zone.removeAttribute("data-armed");
    };
    const onEnter = (event: DragEvent) => {
      if (!hasFiles(event)) return;
      depth += 1;
      zone.setAttribute("data-armed", "");
    };
    const onLeave = (event: DragEvent) => {
      if (!hasFiles(event)) return;
      depth = Math.max(0, depth - 1);
      if (depth === 0) reset();
    };
    const onMove = (event: DragEvent) => {
      if (!hasFiles(event)) return;
      const rect = zone.getBoundingClientRect();
      const dx = Math.max(rect.left - event.clientX, 0, event.clientX - rect.right);
      const dy = Math.max(rect.top - event.clientY, 0, event.clientY - rect.bottom);
      const proximity = Math.max(0, Math.min(1, 1 - Math.hypot(dx, dy) / 220));
      zone.style.setProperty("--p", proximity.toFixed(3));
      zone.style.setProperty("--x", `${Math.round(Math.min(Math.max(event.clientX - rect.left, 0), rect.width))}px`);
      zone.style.setProperty("--y", `${Math.round(Math.min(Math.max(event.clientY - rect.top, 0), rect.height))}px`);
    };
    window.addEventListener("dragenter", onEnter);
    window.addEventListener("dragleave", onLeave);
    window.addEventListener("dragover", onMove);
    window.addEventListener("drop", reset);
    window.addEventListener("dragend", reset);
    return () => {
      window.removeEventListener("dragenter", onEnter);
      window.removeEventListener("dragleave", onLeave);
      window.removeEventListener("dragover", onMove);
      window.removeEventListener("drop", reset);
      window.removeEventListener("dragend", reset);
      reset();
    };
  }, [inactive]);

  function take(list: File[]) {
    if (inactive || list.length === 0) return;
    const accepted: File[] = [];
    const turnedAway: FileUploadRejection[] = [];
    const picked = multiple ? list : list.slice(0, 1);
    let room = maxFiles == null ? Number.POSITIVE_INFINITY : Math.max(0, maxFiles - files.length);
    const overflow: File[] = [];
    for (const file of picked) {
      if (!fileMatchesAccept(file, accept)) {
        turnedAway.push({ file, reason: "type", message: `${file.name} is not a supported type. Use ${describeAccept(accept ?? "")}.` });
      } else if (maxSize != null && file.size > maxSize) {
        turnedAway.push({ file, reason: "size", message: `${file.name} is ${formatBytes(file.size)}. The limit is ${formatBytes(maxSize)}.` });
      } else if (room <= 0) {
        overflow.push(file);
      } else {
        accepted.push(file);
        room -= 1;
      }
    }
    if (overflow.length) {
      const message = `${overflow.length === 1 ? `${overflow[0]!.name} was` : `${overflow.length} files were`} not added. The limit is ${maxFiles} files.`;
      for (const file of overflow) turnedAway.push({ file, reason: "count", message });
    }
    setRejections(turnedAway);
    if (turnedAway.length) onReject?.(turnedAway);
    if (accepted.length) onFilesAdded(accepted);
  }

  function handleInput(event: ChangeEvent<HTMLInputElement>) {
    take(Array.from(event.target.files ?? []));
    event.target.value = "";
  }

  function handleDragEnter(event: ReactDragEvent<HTMLButtonElement>) {
    if (inactive) return;
    event.preventDefault();
    overDepth.current += 1;
    setOver(true);
    setIncoming(event.dataTransfer.items?.length ?? 0);
  }

  function handleDragLeave() {
    overDepth.current = Math.max(0, overDepth.current - 1);
    if (overDepth.current === 0) setOver(false);
  }

  function handleDrop(event: ReactDragEvent<HTMLButtonElement>) {
    event.preventDefault();
    overDepth.current = 0;
    setOver(false);
    take(Array.from(event.dataTransfer.files));
  }

  const generatedHint = [
    accept ? describeAccept(accept) : "Any file",
    maxSize != null ? `up to ${formatBytes(maxSize)}${multiple ? " each" : ""}` : null,
  ]
    .filter(Boolean)
    .join(", ");
  const hintText = hint ?? `${generatedHint}.${maxFiles != null && multiple ? ` ${maxFiles} files at most.` : ""}`;
  // De-duplicate the count message, which every overflowed file shares.
  const messages = [...new Set(rejections.map((rejection) => rejection.message))];
  const uniqueUrls = urls.current;

  return (
    <MotionConfig reducedMotion="user">
      <div className={cx("grid gap-3", className)}>
        {label ? (
          <label htmlFor={zoneId} className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
            {label}
          </label>
        ) : null}
        <button
          ref={zoneRef}
          id={zoneId}
          type="button"
          disabled={inactive}
          onClick={() => inputRef.current?.click()}
          onDragEnter={handleDragEnter}
          onDragOver={(event) => {
            if (inactive) return;
            event.preventDefault();
            event.dataTransfer.dropEffect = "copy";
          }}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
          aria-describedby={[hintId, messages.length ? errorsId : null].filter(Boolean).join(" ")}
          data-over={over ? "" : undefined}
          className={cx(
            "group/zone relative isolate flex w-full cursor-default flex-col items-center justify-center gap-3 rounded-xl px-6 py-8 text-center",
            "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
            "transition-colors duration-200 ease-out motion-reduce:transition-none",
            "data-[over]:bg-sky-500/[0.05] data-[over]:[--p:1]",
            "disabled:cursor-not-allowed",
          )}
        >
          {/* Dashed outline at rest; it hands over to the solid one as --p rises. */}
          <span
            aria-hidden="true"
            className={cx(
              "pointer-events-none absolute inset-0 -z-10 rounded-xl border border-dashed opacity-[calc(1_-_var(--p,0))]",
              "border-zinc-950/20 group-hover/zone:border-zinc-950/35 group-focus-visible/zone:border-zinc-950/35 dark:border-white/20 dark:group-hover/zone:border-white/35",
              "group-disabled/zone:border-zinc-950/10 dark:group-disabled/zone:border-white/10",
              "transition-[opacity,border-color] duration-150 ease-out motion-reduce:transition-none",
            )}
          />
          <span
            aria-hidden="true"
            className={cx(
              "pointer-events-none absolute inset-0 -z-10 rounded-xl border opacity-[var(--p,0)]",
              "border-zinc-950/40 group-data-[over]/zone:border-sky-500 dark:border-white/45 dark:group-data-[over]/zone:border-sky-400",
              "transition-[opacity,border-color] duration-150 ease-out motion-reduce:transition-none",
            )}
          />
          {/* A soft light under the pointer, only while a file is over the zone. */}
          <span
            aria-hidden="true"
            className={cx(
              "pointer-events-none absolute inset-0 -z-10 rounded-xl text-sky-500 opacity-0 group-data-[over]/zone:opacity-[0.14] dark:group-data-[over]/zone:opacity-[0.2]",
              "transition-opacity duration-200 ease-out motion-reduce:transition-none",
            )}
            style={{ background: "radial-gradient(200px circle at var(--x, 50%) var(--y, 50%), currentColor, transparent 70%)" }}
          />
          <span
            aria-hidden="true"
            className={cx(
              "flex size-10 items-center justify-center rounded-lg border bg-white text-zinc-600 dark:bg-black dark:text-zinc-300",
              "border-zinc-950/10 shadow-[0_1px_2px_rgb(0_0_0/0.05)] dark:border-white/15 dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
              "transition-[color,border-color,scale] duration-200 ease-out motion-reduce:transition-none",
              "group-data-[armed]/zone:text-zinc-950 dark:group-data-[armed]/zone:text-white",
              "group-data-[over]/zone:border-sky-500/40 group-data-[over]/zone:text-sky-600 motion-safe:group-data-[over]/zone:scale-105 dark:group-data-[over]/zone:text-sky-400",
              "group-disabled/zone:opacity-50",
            )}
          >
            <UploadGlyph />
          </span>
          <span className="grid gap-1">
            <span className="text-sm font-medium text-zinc-950 group-disabled/zone:text-zinc-500 dark:text-white dark:group-disabled/zone:text-zinc-500">
              {full ? (
                "File limit reached"
              ) : over ? (
                incoming > 1 ? `Drop to add ${incoming} files` : "Drop to add the file"
              ) : (
                <>
                  Drop files here or{" "}
                  <span className="underline decoration-zinc-950/25 underline-offset-[3px] group-hover/zone:decoration-zinc-950 dark:decoration-white/30 dark:group-hover/zone:decoration-white">
                    browse
                  </span>
                </>
              )}
            </span>
            <span id={hintId} className="text-xs text-zinc-500 dark:text-zinc-400">
              {full ? "Remove a file to add another." : hintText}
            </span>
          </span>
        </button>
        <input
          ref={inputRef}
          type="file"
          name={name}
          accept={accept}
          multiple={multiple}
          disabled={inactive}
          onChange={handleInput}
          tabIndex={-1}
          aria-hidden="true"
          className="sr-only"
        />

        {messages.length ? (
          <div
            id={errorsId}
            role="alert"
            className="flex items-start gap-3 rounded-lg border border-red-500/35 bg-red-500/[0.06] px-3 py-2.5 text-[13px] text-red-700 dark:bg-red-500/[0.08] dark:text-red-300"
          >
            <ul className="grid min-w-0 flex-1 gap-1">
              {messages.map((message) => (
                <li key={message} className="break-words">
                  {message}
                </li>
              ))}
            </ul>
            <button
              type="button"
              onClick={() => setRejections([])}
              className="shrink-0 rounded-sm text-xs font-medium text-red-700 underline-offset-2 hover:underline focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500 dark:text-red-300"
            >
              Dismiss
            </button>
          </div>
        ) : null}

        {files.length ? (
          <ul aria-label="Files" className="grid gap-2">
            <AnimatePresence initial={false} mode="popLayout">
              {files.map((item) => (
                <UploadRow key={item.id} item={item} thumbnail={item.previewUrl ?? uniqueUrls.get(item.id)} onRemove={onRemove} onRetry={onRetry} />
              ))}
            </AnimatePresence>
          </ul>
        ) : null}

        <p aria-live="polite" className="sr-only">
          {announcement}
        </p>
      </div>
    </MotionConfig>
  );
}