{
  "schemaVersion": 1,
  "target": "react",
  "name": "file-upload",
  "version": "0.1.0",
  "category": "forms",
  "title": "File Upload",
  "description": "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.",
  "tags": [
    "form",
    "upload",
    "dropzone",
    "drag-and-drop",
    "files",
    "progress"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "motion": "^14.14.0"
  },
  "registryDependencies": [],
  "docsPath": "/components/file-upload",
  "props": [
    {
      "name": "files",
      "type": "FileUploadItem[]",
      "description": "The rows: { id, name, size, type?, file?, previewUrl?, status, progress?, error? }. You own this list."
    },
    {
      "name": "onFilesAdded",
      "type": "(files: File[]) => void",
      "description": "Files that passed the checks. createUploadItem(file) turns one into a row."
    },
    {
      "name": "onRemove / onRetry",
      "type": "(id) => void",
      "description": "Show remove (cancel while uploading) and retry buttons."
    },
    {
      "name": "onReject",
      "type": "(rejections) => void",
      "description": "Files turned away, each with a reason (type, size, count) and a message."
    },
    {
      "name": "accept",
      "type": "string",
      "description": "Accepted types, as for <input accept>: image/*, application/pdf, .csv."
    },
    {
      "name": "maxSize",
      "type": "number",
      "description": "Largest file in bytes."
    },
    {
      "name": "maxFiles",
      "type": "number",
      "description": "Most files in the list at once. The zone disables when full."
    },
    {
      "name": "multiple",
      "type": "boolean",
      "default": "true",
      "description": "Allows picking several files at once."
    },
    {
      "name": "label / hint",
      "type": "ReactNode",
      "description": "A label above the zone and a replacement for the generated hint line."
    },
    {
      "name": "disabled",
      "type": "boolean",
      "default": "false",
      "description": "Turns 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."
  ],
  "states": [
    "empty",
    "file approaching",
    "file over",
    "uploading",
    "done",
    "failed",
    "rejected",
    "full",
    "disabled"
  ],
  "files": [
    {
      "path": "ui/file-upload.tsx",
      "content": "\"use client\";\n\nimport { AnimatePresence, MotionConfig, motion } from \"motion/react\";\nimport {\n  type ChangeEvent,\n  type DragEvent as ReactDragEvent,\n  type ReactNode,\n  useEffect,\n  useId,\n  useReducer,\n  useRef,\n  useState,\n} from \"react\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nconst ease = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\n\nexport type FileUploadStatus = \"uploading\" | \"done\" | \"error\";\n\nexport interface FileUploadItem {\n  /** Stable id for the row. `createUploadItem` makes one. */\n  id: string;\n  /** File name with its extension. */\n  name: string;\n  /** Size in bytes. */\n  size: number;\n  /** MIME type. */\n  type?: string;\n  /** The picked file. Image files get a thumbnail made from it automatically. */\n  file?: File;\n  /** Thumbnail URL, when you already have one (for example a file uploaded earlier). */\n  previewUrl?: string;\n  status: FileUploadStatus;\n  /** 0 to 100 while uploading. Leave unset for an upload of unknown length. */\n  progress?: number;\n  /** Why the upload failed. */\n  error?: string;\n}\n\nexport interface FileUploadRejection {\n  file: File;\n  reason: \"type\" | \"size\" | \"count\";\n  message: string;\n}\n\nexport interface FileUploadProps {\n  /** The rows to show. You own this list: add items in `onFilesAdded`, then update `progress` and `status` as the upload runs. */\n  files: FileUploadItem[];\n  /** Called with the files that passed `accept`, `maxSize`, and `maxFiles`. */\n  onFilesAdded: (files: File[]) => void;\n  /** Shows a remove button on each row (a cancel button while uploading). */\n  onRemove?: (id: string) => void;\n  /** Shows a retry button on failed rows. */\n  onRetry?: (id: string) => void;\n  /** Called with the files that were turned away. They are also listed under the drop zone. */\n  onReject?: (rejections: FileUploadRejection[]) => void;\n  /** Accepted types, as for `<input accept>`: `image/*`, `application/pdf`, `.csv`. */\n  accept?: string;\n  /** Largest file in bytes. */\n  maxSize?: number;\n  /** Most files in the list at once. */\n  maxFiles?: number;\n  /** Lets the user pick several files at once. */\n  multiple?: boolean;\n  disabled?: boolean;\n  /** Visible label above the drop zone. */\n  label?: ReactNode;\n  /** Replaces the generated line under the prompt, such as \"PNG or PDF, up to 10 MB each\". */\n  hint?: ReactNode;\n  /** Name for the hidden file input, for plain form posts. */\n  name?: string;\n  id?: string;\n  /** Classes for the wrapping element. */\n  className?: string;\n}\n\nfunction extensionOf(name: string): string {\n  const dot = name.lastIndexOf(\".\");\n  return dot > 0 ? name.slice(dot + 1).toLowerCase() : \"\";\n}\n\n/** Bytes as a short size, e.g. 2.4 MB. */\nexport function formatBytes(bytes: number): string {\n  if (bytes < 1024) return `${Math.round(bytes)} B`;\n  const units = [\"KB\", \"MB\", \"GB\"];\n  let value = bytes / 1024;\n  let unit = 0;\n  while (value >= 1024 && unit < units.length - 1) {\n    value /= 1024;\n    unit++;\n  }\n  return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;\n}\n\nlet counter = 0;\n\n/** Wraps a picked file as an uploading row with a fresh id. */\nexport function createUploadItem(file: File): FileUploadItem {\n  counter += 1;\n  const id = typeof crypto !== \"undefined\" && \"randomUUID\" in crypto ? crypto.randomUUID() : `upload-${Date.now()}-${counter}`;\n  return { id, name: file.name, size: file.size, type: file.type, file, status: \"uploading\", progress: 0 };\n}\n\n/** True when the file matches an `accept` string (MIME types, `type/*` wildcards, and extensions). */\nexport function fileMatchesAccept(file: Pick<File, \"name\" | \"type\">, accept?: string): boolean {\n  if (!accept) return true;\n  const tokens = accept.split(\",\").map((token) => token.trim().toLowerCase()).filter(Boolean);\n  const type = (file.type || \"\").toLowerCase();\n  const extension = `.${extensionOf(file.name)}`;\n  return tokens.some((token) => {\n    if (token.startsWith(\".\")) return token === extension;\n    if (token.endsWith(\"/*\")) return type.startsWith(token.slice(0, -1));\n    return token === type;\n  });\n}\n\nfunction describeAccept(accept: string): string {\n  const names = accept\n    .split(\",\")\n    .map((token) => token.trim().toLowerCase())\n    .filter(Boolean)\n    .map((token) => {\n      if (token === \"image/*\") return \"Images\";\n      if (token === \"video/*\") return \"Videos\";\n      if (token === \"audio/*\") return \"Audio\";\n      if (token.startsWith(\".\")) return token.slice(1).toUpperCase();\n      const subtype = token.split(\"/\")[1] ?? token;\n      return subtype.replace(/^x-/, \"\").replace(/\\+.*$/, \"\").toUpperCase();\n    });\n  const unique = [...new Set(names)];\n  if (unique.length <= 1) return unique[0] ?? \"\";\n  return `${unique.slice(0, -1).join(\", \")} or ${unique[unique.length - 1]}`;\n}\n\nfunction UploadGlyph() {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 20 20\" fill=\"none\" className=\"size-5\">\n      {/* The tray stays put; the arrow lifts as a file comes near (see the translate on its group). */}\n      <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\" />\n      <g className={`[translate:0_calc(var(--p,0)_*_-2.5px)] transition-[translate] duration-200 ${ease} motion-reduce:[translate:none] motion-reduce:transition-none`}>\n        <path d=\"M10 12.25V3.75M6.75 7L10 3.75 13.25 7\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n      </g>\n    </svg>\n  );\n}\n\nfunction FileGlyph() {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-4\">\n      <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\" />\n      <path d=\"M8.75 1.75V5.25h3.5\" stroke=\"currentColor\" strokeWidth=\"1.25\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n\nfunction StatusGlyph({ status, indeterminate }: { status: FileUploadStatus; indeterminate: boolean }) {\n  if (status === \"uploading\" && indeterminate) {\n    return (\n      <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\">\n        <path d=\"M8 1.75a6.25 6.25 0 1 1-6.25 6.25\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n      </svg>\n    );\n  }\n  if (status === \"error\") {\n    return (\n      <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\">\n        <circle cx=\"8\" cy=\"8\" r=\"6.25\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n        <path d=\"M6 6l4 4M10 6l-4 4\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n      </svg>\n    );\n  }\n  const done = status === \"done\";\n  return (\n    <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\")}>\n      <circle cx=\"8\" cy=\"8\" r=\"6.25\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n      <path\n        d=\"M5.25 8.25l1.9 1.9 3.6-4.15\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        pathLength={1}\n        strokeDasharray=\"1\"\n        className={`[stroke-dashoffset:0] transition-[stroke-dashoffset] delay-100 duration-300 ${ease} starting:[stroke-dashoffset:1] motion-reduce:transition-none`}\n      />\n    </svg>\n  );\n}\n\nconst iconButton = cx(\n  \"flex size-7 shrink-0 cursor-default items-center justify-center rounded-md text-zinc-500 dark:text-zinc-400\",\n  \"hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white\",\n  \"transition-colors duration-150 ease-out motion-reduce:transition-none\",\n  \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500 [&_svg]:size-4\",\n);\n\nfunction UploadRow({\n  item,\n  thumbnail,\n  onRemove,\n  onRetry,\n}: {\n  item: FileUploadItem;\n  thumbnail?: string;\n  onRemove?: (id: string) => void;\n  onRetry?: (id: string) => void;\n}) {\n  const uploading = item.status === \"uploading\";\n  const failed = item.status === \"error\";\n  const done = item.status === \"done\";\n  const progress = item.progress == null ? null : Math.max(0, Math.min(100, item.progress));\n  const extension = extensionOf(item.name).toUpperCase();\n\n  return (\n    <motion.li\n      layout=\"position\"\n      initial={{ opacity: 0, y: 6 }}\n      animate={{ opacity: 1, y: 0 }}\n      exit={{ opacity: 0, scale: 0.98, transition: { duration: 0.15, ease: \"easeOut\" } }}\n      transition={{ type: \"spring\", duration: 0.35, bounce: 0 }}\n      data-status={item.status}\n      className={cx(\n        \"relative flex items-center gap-3 overflow-hidden rounded-lg border bg-white py-2 pr-2 pl-2 dark:bg-black\",\n        \"transition-[border-color] duration-200 ease-out motion-reduce:transition-none\",\n        failed ? \"border-red-500/35\" : \"border-zinc-950/10 dark:border-white/10\",\n      )}\n    >\n      {/* The thumbnail develops from a dim grayscale proof into full color when the upload lands. */}\n      <span\n        className={cx(\n          \"relative flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-md text-zinc-500 dark:text-zinc-400\",\n          \"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)]\",\n        )}\n      >\n        {thumbnail ? (\n          <img\n            src={thumbnail}\n            alt=\"\"\n            className={cx(\n              `size-full object-cover transition-[filter,opacity] duration-500 ${ease} motion-reduce:transition-none`,\n              done ? \"opacity-100 grayscale-0\" : \"opacity-60 grayscale\",\n            )}\n          />\n        ) : (\n          <span className=\"flex flex-col items-center gap-0.5\">\n            <FileGlyph />\n            <span className=\"font-mono text-[9px] leading-none font-medium\">{extension.slice(0, 4) || \"FILE\"}</span>\n          </span>\n        )}\n      </span>\n\n      <span className=\"grid min-w-0 flex-1 gap-1\">\n        <span className=\"truncate text-[13px] leading-4 font-medium text-zinc-950 dark:text-white\" title={item.name}>\n          {item.name}\n        </span>\n        <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\")}>\n          <StatusGlyph status={item.status} indeterminate={progress == null} />\n          <span className={failed ? \"min-w-0 break-words\" : \"truncate\"} role={failed ? \"alert\" : undefined}>\n            {failed\n              ? (item.error ?? \"Upload failed\")\n              : uploading\n                ? progress != null\n                  ? `${formatBytes((item.size * progress) / 100)} of ${formatBytes(item.size)}`\n                  : `Uploading, ${formatBytes(item.size)}`\n                : formatBytes(item.size)}\n          </span>\n          {uploading && progress != null ? <span className=\"ms-auto shrink-0 font-mono text-[11px] text-zinc-500\">{Math.round(progress)}%</span> : null}\n        </span>\n        {/* Thin progress line. It fades out as the row settles. */}\n        <span\n          role={uploading ? \"progressbar\" : undefined}\n          aria-label={uploading ? `Uploading ${item.name}` : undefined}\n          aria-valuemin={uploading ? 0 : undefined}\n          aria-valuemax={uploading ? 100 : undefined}\n          aria-valuenow={uploading && progress != null ? Math.round(progress) : undefined}\n          aria-hidden={uploading ? undefined : true}\n          className={cx(\n            \"relative h-0.5 overflow-hidden rounded-full bg-zinc-950/[0.07] dark:bg-white/10\",\n            `transition-opacity duration-300 ${ease} motion-reduce:transition-none`,\n            uploading ? \"opacity-100\" : \"opacity-0\",\n            (failed || (uploading && progress == null)) && \"hidden\",\n          )}\n        >\n          <span\n            className={cx(\n              \"absolute inset-y-0 left-0 w-full origin-left rounded-full\",\n              done ? \"bg-emerald-500\" : \"bg-zinc-950 dark:bg-white\",\n              `transition-[scale,background-color] duration-300 ${ease} motion-reduce:transition-none`,\n            )}\n            style={{ scale: `${done ? 1 : (progress ?? 0) / 100} 1` }}\n          />\n        </span>\n      </span>\n\n      {(failed && onRetry) || onRemove ? (\n        <span className=\"flex shrink-0 items-center self-center\">\n          {failed && onRetry ? (\n            <button type=\"button\" aria-label={`Retry uploading ${item.name}`} onClick={() => onRetry(item.id)} className={iconButton}>\n              <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\">\n                <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\" />\n              </svg>\n            </button>\n          ) : null}\n          {onRemove ? (\n            <button\n              type=\"button\"\n              aria-label={uploading ? `Cancel uploading ${item.name}` : `Remove ${item.name}`}\n              onClick={() => onRemove(item.id)}\n              className={iconButton}\n            >\n              <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\">\n                <path d=\"M5 5l6 6M11 5l-6 6\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n              </svg>\n            </button>\n          ) : null}\n        </span>\n      ) : null}\n    </motion.li>\n  );\n}\n\n/**\n * A drop zone and file list. Click, press Enter or Space, or drag files in. The zone notices a\n * file being dragged anywhere on the page: its dashed outline closes into a solid line as the\n * file gets near, and lights up under the pointer once it is over. Files are checked against\n * `accept`, `maxSize`, and `maxFiles` with inline reasons. You drive each row's progress through\n * `files`; finished rows settle as their thumbnail develops into color.\n */\nexport function FileUpload({\n  files,\n  onFilesAdded,\n  onRemove,\n  onRetry,\n  onReject,\n  accept,\n  maxSize,\n  maxFiles,\n  multiple = true,\n  disabled = false,\n  label,\n  hint,\n  name,\n  id,\n  className,\n}: FileUploadProps) {\n  const generatedId = useId();\n  const zoneId = id ?? generatedId;\n  const hintId = `${zoneId}-hint`;\n  const errorsId = `${zoneId}-errors`;\n  const inputRef = useRef<HTMLInputElement>(null);\n  const zoneRef = useRef<HTMLButtonElement>(null);\n  const [over, setOver] = useState(false);\n  const [incoming, setIncoming] = useState(0);\n  const [rejections, setRejections] = useState<FileUploadRejection[]>([]);\n  const overDepth = useRef(0);\n\n  const full = maxFiles != null && files.length >= maxFiles;\n  const inactive = disabled || full;\n\n  // Object URLs for image thumbnails, made once per row and revoked when the row goes away.\n  const urls = useRef(new Map<string, string>());\n  const [, refresh] = useReducer((count: number) => count + 1, 0);\n  useEffect(() => {\n    let changed = false;\n    for (const item of files) {\n      if (!item.previewUrl && item.file && item.file.type.startsWith(\"image/\") && !urls.current.has(item.id)) {\n        urls.current.set(item.id, URL.createObjectURL(item.file));\n        changed = true;\n      }\n    }\n    for (const [key, url] of urls.current) {\n      if (!files.some((item) => item.id === key)) {\n        URL.revokeObjectURL(url);\n        urls.current.delete(key);\n        changed = true;\n      }\n    }\n    if (changed) refresh();\n  }, [files]);\n  useEffect(() => {\n    const map = urls.current;\n    return () => {\n      for (const url of map.values()) URL.revokeObjectURL(url);\n      map.clear();\n    };\n  }, []);\n\n  // Announces finished and failed uploads once each.\n  const [announcement, setAnnouncement] = useState(\"\");\n  const lastStatus = useRef(new Map<string, FileUploadStatus>());\n  useEffect(() => {\n    const messages: string[] = [];\n    for (const item of files) {\n      const previous = lastStatus.current.get(item.id);\n      if (previous && previous !== item.status) {\n        if (item.status === \"done\") messages.push(`${item.name} uploaded`);\n        if (item.status === \"error\") messages.push(`${item.name} failed${item.error ? `: ${item.error}` : \"\"}`);\n      }\n    }\n    lastStatus.current = new Map(files.map((item) => [item.id, item.status]));\n    if (messages.length) setAnnouncement(messages.join(\". \"));\n  }, [files]);\n\n  // Proximity: while a file is dragged anywhere in the window, --p rises from 0 to 1 as the pointer\n  // nears the zone, and --x / --y track it for the highlight. Written straight to the element so\n  // dragover does not re-render React.\n  useEffect(() => {\n    if (inactive) return;\n    const zone = zoneRef.current;\n    if (!zone) return;\n    let depth = 0;\n    const hasFiles = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes(\"Files\");\n    const reset = () => {\n      depth = 0;\n      overDepth.current = 0;\n      setOver(false);\n      zone.style.setProperty(\"--p\", \"0\");\n      zone.removeAttribute(\"data-armed\");\n    };\n    const onEnter = (event: DragEvent) => {\n      if (!hasFiles(event)) return;\n      depth += 1;\n      zone.setAttribute(\"data-armed\", \"\");\n    };\n    const onLeave = (event: DragEvent) => {\n      if (!hasFiles(event)) return;\n      depth = Math.max(0, depth - 1);\n      if (depth === 0) reset();\n    };\n    const onMove = (event: DragEvent) => {\n      if (!hasFiles(event)) return;\n      const rect = zone.getBoundingClientRect();\n      const dx = Math.max(rect.left - event.clientX, 0, event.clientX - rect.right);\n      const dy = Math.max(rect.top - event.clientY, 0, event.clientY - rect.bottom);\n      const proximity = Math.max(0, Math.min(1, 1 - Math.hypot(dx, dy) / 220));\n      zone.style.setProperty(\"--p\", proximity.toFixed(3));\n      zone.style.setProperty(\"--x\", `${Math.round(Math.min(Math.max(event.clientX - rect.left, 0), rect.width))}px`);\n      zone.style.setProperty(\"--y\", `${Math.round(Math.min(Math.max(event.clientY - rect.top, 0), rect.height))}px`);\n    };\n    window.addEventListener(\"dragenter\", onEnter);\n    window.addEventListener(\"dragleave\", onLeave);\n    window.addEventListener(\"dragover\", onMove);\n    window.addEventListener(\"drop\", reset);\n    window.addEventListener(\"dragend\", reset);\n    return () => {\n      window.removeEventListener(\"dragenter\", onEnter);\n      window.removeEventListener(\"dragleave\", onLeave);\n      window.removeEventListener(\"dragover\", onMove);\n      window.removeEventListener(\"drop\", reset);\n      window.removeEventListener(\"dragend\", reset);\n      reset();\n    };\n  }, [inactive]);\n\n  function take(list: File[]) {\n    if (inactive || list.length === 0) return;\n    const accepted: File[] = [];\n    const turnedAway: FileUploadRejection[] = [];\n    const picked = multiple ? list : list.slice(0, 1);\n    let room = maxFiles == null ? Number.POSITIVE_INFINITY : Math.max(0, maxFiles - files.length);\n    const overflow: File[] = [];\n    for (const file of picked) {\n      if (!fileMatchesAccept(file, accept)) {\n        turnedAway.push({ file, reason: \"type\", message: `${file.name} is not a supported type. Use ${describeAccept(accept ?? \"\")}.` });\n      } else if (maxSize != null && file.size > maxSize) {\n        turnedAway.push({ file, reason: \"size\", message: `${file.name} is ${formatBytes(file.size)}. The limit is ${formatBytes(maxSize)}.` });\n      } else if (room <= 0) {\n        overflow.push(file);\n      } else {\n        accepted.push(file);\n        room -= 1;\n      }\n    }\n    if (overflow.length) {\n      const message = `${overflow.length === 1 ? `${overflow[0]!.name} was` : `${overflow.length} files were`} not added. The limit is ${maxFiles} files.`;\n      for (const file of overflow) turnedAway.push({ file, reason: \"count\", message });\n    }\n    setRejections(turnedAway);\n    if (turnedAway.length) onReject?.(turnedAway);\n    if (accepted.length) onFilesAdded(accepted);\n  }\n\n  function handleInput(event: ChangeEvent<HTMLInputElement>) {\n    take(Array.from(event.target.files ?? []));\n    event.target.value = \"\";\n  }\n\n  function handleDragEnter(event: ReactDragEvent<HTMLButtonElement>) {\n    if (inactive) return;\n    event.preventDefault();\n    overDepth.current += 1;\n    setOver(true);\n    setIncoming(event.dataTransfer.items?.length ?? 0);\n  }\n\n  function handleDragLeave() {\n    overDepth.current = Math.max(0, overDepth.current - 1);\n    if (overDepth.current === 0) setOver(false);\n  }\n\n  function handleDrop(event: ReactDragEvent<HTMLButtonElement>) {\n    event.preventDefault();\n    overDepth.current = 0;\n    setOver(false);\n    take(Array.from(event.dataTransfer.files));\n  }\n\n  const generatedHint = [\n    accept ? describeAccept(accept) : \"Any file\",\n    maxSize != null ? `up to ${formatBytes(maxSize)}${multiple ? \" each\" : \"\"}` : null,\n  ]\n    .filter(Boolean)\n    .join(\", \");\n  const hintText = hint ?? `${generatedHint}.${maxFiles != null && multiple ? ` ${maxFiles} files at most.` : \"\"}`;\n  // De-duplicate the count message, which every overflowed file shares.\n  const messages = [...new Set(rejections.map((rejection) => rejection.message))];\n  const uniqueUrls = urls.current;\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div className={cx(\"grid gap-3\", className)}>\n        {label ? (\n          <label htmlFor={zoneId} className=\"text-sm font-medium text-zinc-900 dark:text-zinc-100\">\n            {label}\n          </label>\n        ) : null}\n        <button\n          ref={zoneRef}\n          id={zoneId}\n          type=\"button\"\n          disabled={inactive}\n          onClick={() => inputRef.current?.click()}\n          onDragEnter={handleDragEnter}\n          onDragOver={(event) => {\n            if (inactive) return;\n            event.preventDefault();\n            event.dataTransfer.dropEffect = \"copy\";\n          }}\n          onDragLeave={handleDragLeave}\n          onDrop={handleDrop}\n          aria-describedby={[hintId, messages.length ? errorsId : null].filter(Boolean).join(\" \")}\n          data-over={over ? \"\" : undefined}\n          className={cx(\n            \"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\",\n            \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n            \"transition-colors duration-200 ease-out motion-reduce:transition-none\",\n            \"data-[over]:bg-sky-500/[0.05] data-[over]:[--p:1]\",\n            \"disabled:cursor-not-allowed\",\n          )}\n        >\n          {/* Dashed outline at rest; it hands over to the solid one as --p rises. */}\n          <span\n            aria-hidden=\"true\"\n            className={cx(\n              \"pointer-events-none absolute inset-0 -z-10 rounded-xl border border-dashed opacity-[calc(1_-_var(--p,0))]\",\n              \"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\",\n              \"group-disabled/zone:border-zinc-950/10 dark:group-disabled/zone:border-white/10\",\n              \"transition-[opacity,border-color] duration-150 ease-out motion-reduce:transition-none\",\n            )}\n          />\n          <span\n            aria-hidden=\"true\"\n            className={cx(\n              \"pointer-events-none absolute inset-0 -z-10 rounded-xl border opacity-[var(--p,0)]\",\n              \"border-zinc-950/40 group-data-[over]/zone:border-sky-500 dark:border-white/45 dark:group-data-[over]/zone:border-sky-400\",\n              \"transition-[opacity,border-color] duration-150 ease-out motion-reduce:transition-none\",\n            )}\n          />\n          {/* A soft light under the pointer, only while a file is over the zone. */}\n          <span\n            aria-hidden=\"true\"\n            className={cx(\n              \"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]\",\n              \"transition-opacity duration-200 ease-out motion-reduce:transition-none\",\n            )}\n            style={{ background: \"radial-gradient(200px circle at var(--x, 50%) var(--y, 50%), currentColor, transparent 70%)\" }}\n          />\n          <span\n            aria-hidden=\"true\"\n            className={cx(\n              \"flex size-10 items-center justify-center rounded-lg border bg-white text-zinc-600 dark:bg-black dark:text-zinc-300\",\n              \"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)]\",\n              \"transition-[color,border-color,scale] duration-200 ease-out motion-reduce:transition-none\",\n              \"group-data-[armed]/zone:text-zinc-950 dark:group-data-[armed]/zone:text-white\",\n              \"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\",\n              \"group-disabled/zone:opacity-50\",\n            )}\n          >\n            <UploadGlyph />\n          </span>\n          <span className=\"grid gap-1\">\n            <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\">\n              {full ? (\n                \"File limit reached\"\n              ) : over ? (\n                incoming > 1 ? `Drop to add ${incoming} files` : \"Drop to add the file\"\n              ) : (\n                <>\n                  Drop files here or{\" \"}\n                  <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\">\n                    browse\n                  </span>\n                </>\n              )}\n            </span>\n            <span id={hintId} className=\"text-xs text-zinc-500 dark:text-zinc-400\">\n              {full ? \"Remove a file to add another.\" : hintText}\n            </span>\n          </span>\n        </button>\n        <input\n          ref={inputRef}\n          type=\"file\"\n          name={name}\n          accept={accept}\n          multiple={multiple}\n          disabled={inactive}\n          onChange={handleInput}\n          tabIndex={-1}\n          aria-hidden=\"true\"\n          className=\"sr-only\"\n        />\n\n        {messages.length ? (\n          <div\n            id={errorsId}\n            role=\"alert\"\n            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\"\n          >\n            <ul className=\"grid min-w-0 flex-1 gap-1\">\n              {messages.map((message) => (\n                <li key={message} className=\"break-words\">\n                  {message}\n                </li>\n              ))}\n            </ul>\n            <button\n              type=\"button\"\n              onClick={() => setRejections([])}\n              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\"\n            >\n              Dismiss\n            </button>\n          </div>\n        ) : null}\n\n        {files.length ? (\n          <ul aria-label=\"Files\" className=\"grid gap-2\">\n            <AnimatePresence initial={false} mode=\"popLayout\">\n              {files.map((item) => (\n                <UploadRow key={item.id} item={item} thumbnail={item.previewUrl ?? uniqueUrls.get(item.id)} onRemove={onRemove} onRetry={onRetry} />\n              ))}\n            </AnimatePresence>\n          </ul>\n        ) : null}\n\n        <p aria-live=\"polite\" className=\"sr-only\">\n          {announcement}\n        </p>\n      </div>\n    </MotionConfig>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { createUploadItem, FileUpload, type FileUploadItem } from \"@/components/shaken/ui/file-upload\";\n\nconst screenshot =\n  \"data:image/svg+xml,\" +\n  encodeURIComponent(\n    `<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>`,\n  );\n\nconst seeded: FileUploadItem[] = [\n  { id: \"seed-report\", name: \"q3-usage-report.pdf\", size: 2_516_582, type: \"application/pdf\", status: \"done\" },\n  { id: \"seed-shot\", name: \"onboarding-step-2.png\", size: 1_183_744, type: \"image/png\", previewUrl: screenshot, status: \"uploading\", progress: 38 },\n  { id: \"seed-export\", name: \"customer-export.csv\", size: 8_912_000, type: \"text/csv\", status: \"error\", error: \"Connection lost at 61%. Retry to resume.\" },\n];\n\nexport default function FileUploadExample() {\n  const [files, setFiles] = useState<FileUploadItem[]>(seeded);\n  const uploading = files.some((file) => file.status === \"uploading\");\n\n  // Stands in for a real upload: nudges every running row forward until it lands.\n  useEffect(() => {\n    if (!uploading) return;\n    const timer = setInterval(() => {\n      setFiles((list) =>\n        list.map((file) => {\n          if (file.status !== \"uploading\") return file;\n          const progress = Math.min(100, (file.progress ?? 0) + 4 + Math.random() * 10);\n          return progress >= 100 ? { ...file, progress: 100, status: \"done\" } : { ...file, progress };\n        }),\n      );\n    }, 220);\n    return () => clearInterval(timer);\n  }, [uploading]);\n\n  return (\n    <FileUpload\n      className=\"w-full max-w-md\"\n      label=\"Attachments\"\n      files={files}\n      accept=\"image/*,.pdf,.csv\"\n      maxSize={10 * 1024 * 1024}\n      maxFiles={6}\n      onFilesAdded={(added) => setFiles((list) => [...list, ...added.map(createUploadItem)])}\n      onRemove={(id) => setFiles((list) => list.filter((file) => file.id !== id))}\n      onRetry={(id) => setFiles((list) => list.map((file) => (file.id === id ? { ...file, status: \"uploading\", progress: 0, error: undefined } : file)))}\n    />\n  );\n}\n"
  }
}
