{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "file-upload",
  "type": "registry:component",
  "title": "File upload",
  "description": "A dropzone and upload queue with thumbnails, progress, concurrency, cancel and retry, and inline validation.",
  "categories": [
    "forms"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/file-upload.tsx",
      "type": "registry:component",
      "target": "components/overtrue/file-upload.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconAlertCircle,\n  IconCircleCheckFilled,\n  IconClock,\n  IconCloudUpload,\n  IconFile,\n  IconFileCode,\n  IconFileMusic,\n  IconFileSpreadsheet,\n  IconFileText,\n  IconFileTypeDoc,\n  IconFileTypePdf,\n  IconFileZip,\n  IconMovie,\n  IconPhoto,\n  IconPresentation,\n  IconRefresh,\n  IconTrash,\n  IconX,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------ */\n/* Types                                                                     */\n/* ------------------------------------------------------------------------ */\n\n/**\n * idle: picked, with no `upload` function. queued: waiting for a free upload\n * slot. uploading, done, error, and canceled follow the request.\n */\nexport type FileUploadStatus =\n  | \"idle\"\n  | \"queued\"\n  | \"uploading\"\n  | \"done\"\n  | \"error\"\n  | \"canceled\";\n\nexport interface FileUploadItem {\n  id: string;\n  /** The picked file. Items restored from a server can leave it out. */\n  file?: File;\n  name: string;\n  /** Size in bytes. */\n  size: number;\n  /** MIME type, such as \"image/png\". */\n  type: string;\n  status: FileUploadStatus;\n  /** Upload progress from 0 to 1. */\n  progress: number;\n  /** Why the upload failed, shown under the name. */\n  error?: string;\n  /** Thumbnail source. Image files get an object URL automatically. */\n  previewUrl?: string;\n  /** Whatever `upload` resolved with, such as the stored file's URL. */\n  response?: unknown;\n}\n\nexport type FileRejectionReason = \"type\" | \"size\" | \"count\" | \"duplicate\" | \"custom\";\n\nexport interface FileRejection {\n  file: File;\n  reason: FileRejectionReason;\n  message: string;\n}\n\nexport interface FileUploadContext {\n  /** Report progress as a fraction from 0 to 1. */\n  onProgress: (progress: number) => void;\n  /** Aborts when the upload is canceled or removed, or the component unmounts. */\n  signal: AbortSignal;\n  item: FileUploadItem;\n}\n\nexport interface FileUploadLabels {\n  title: string;\n  titleSingle: string;\n  or: string;\n  browse: string;\n  dropActive: (count: number) => string;\n  dropReject: string;\n  limitReached: string;\n  limitHint: string;\n  keyboardHint: string;\n  status: Record<FileUploadStatus, string>;\n  of: string;\n  cancel: (name: string) => string;\n  retry: (name: string) => string;\n  remove: (name: string) => string;\n  retryFailed: string;\n  clearDone: string;\n  dismiss: string;\n  files: string;\n  uploadFailed: string;\n  timeLeft: (seconds: number) => string;\n  summary: (done: number, total: number) => string;\n  count: (count: number, size: string) => string;\n  added: (count: number) => string;\n  uploaded: (name: string) => string;\n  failed: (name: string, reason: string) => string;\n  canceled: (name: string) => string;\n  removed: (name: string) => string;\n  upTo: (size: string, each: boolean) => string;\n  maxFiles: (count: number) => string;\n  rejectType: (name: string, accepted: string) => string;\n  rejectSize: (name: string, max: string) => string;\n  rejectCount: (count: number, max: number) => string;\n  rejectDuplicate: (name: string) => string;\n}\n\nexport interface FileUploadProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"children\" | \"defaultValue\" | \"onChange\"\n> {\n  /** Controlled files. Leave undefined to let the component manage them. */\n  files?: FileUploadItem[];\n  defaultFiles?: FileUploadItem[];\n  onFilesChange?: (files: FileUploadItem[]) => void;\n  /**\n   * Uploads one file. Report progress, honour the signal, and resolve when the\n   * file is stored or reject with an Error whose message explains why. Without\n   * it the component is a picker.\n   */\n  upload?: (file: File, context: FileUploadContext) => Promise<unknown>;\n  /** Uploads running at once. Defaults to 3. */\n  concurrency?: number;\n  /** Same syntax as the input's accept attribute: \".pdf,image/*\". */\n  accept?: string;\n  /** Largest file in bytes. */\n  maxSize?: number;\n  /** Most files in the list. */\n  maxFiles?: number;\n  /** Allow several files. When false, a new pick replaces the current file. */\n  multiple?: boolean;\n  disabled?: boolean;\n  variant?: \"default\" | \"compact\";\n  /** Add files pasted while focus is inside the component. Defaults to true. */\n  paste?: boolean;\n  /** Mirrors picked files into a hidden file input so a native form post includes them. */\n  name?: string;\n  /** Extra validation. Return a message to reject the file. */\n  validate?: (file: File, files: FileUploadItem[]) => string | null | undefined | false;\n  onReject?: (rejections: FileRejection[]) => void;\n  onUploadComplete?: (item: FileUploadItem, response: unknown) => void;\n  onUploadError?: (item: FileUploadItem, error: unknown) => void;\n  /** Called when a file leaves the list through its remove button. */\n  onRemove?: (item: FileUploadItem) => void;\n  /** Replaces the generated dropzone hint, such as \"PDF up to 10 MB\". */\n  hint?: React.ReactNode;\n  /** Show the count and bulk actions above the list. Defaults to true in the default variant. */\n  showSummary?: boolean;\n  locale?: string;\n  formatSize?: (bytes: number) => string;\n  /** Replaces the type icon or thumbnail for a file. */\n  renderIcon?: (item: FileUploadItem) => React.ReactNode;\n  labels?: Partial<FileUploadLabels>;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Helpers                                                                   */\n/* ------------------------------------------------------------------------ */\n\n/** Binary units, so 10 * 1024 * 1024 reads as \"10 MB\". */\nexport function formatBytes(bytes: number, locale?: string) {\n  if (!Number.isFinite(bytes) || bytes < 0) return \"\";\n  const units = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\"];\n  let value = bytes;\n  let unit = 0;\n  while (value >= 1024 && unit < units.length - 1) {\n    value /= 1024;\n    unit += 1;\n  }\n  const digits = unit === 0 ? 0 : value < 10 ? 1 : 0;\n  // A non-breaking space keeps \"50 MB\" together when hints wrap.\n  return `${new Intl.NumberFormat(locale, { maximumFractionDigits: digits }).format(value)}\\u00a0${units[unit]}`;\n}\n\nconst plural = (count: number, word: string) =>\n  `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\nconst defaultLabels: FileUploadLabels = {\n  title: \"Drop files here\",\n  titleSingle: \"Drop a file here\",\n  or: \"or\",\n  browse: \"browse\",\n  dropActive: (count) =>\n    count > 1 ? `Release to add ${count} files` : \"Release to add the file\",\n  dropReject: \"These files can't be added\",\n  limitReached: \"File limit reached\",\n  limitHint: \"Remove a file to add another.\",\n  keyboardHint: \"Press Enter to browse, or paste a file.\",\n  status: {\n    idle: \"Ready\",\n    queued: \"Waiting\",\n    uploading: \"Uploading\",\n    done: \"Uploaded\",\n    error: \"Failed\",\n    canceled: \"Canceled\",\n  },\n  of: \"of\",\n  cancel: (name) => `Cancel upload of ${name}`,\n  retry: (name) => `Retry ${name}`,\n  remove: (name) => `Remove ${name}`,\n  retryFailed: \"Retry failed\",\n  clearDone: \"Clear uploaded\",\n  dismiss: \"Dismiss\",\n  files: \"Files\",\n  uploadFailed: \"Upload failed\",\n  timeLeft: (seconds) =>\n    seconds < 60\n      ? `${Math.max(1, Math.round(seconds))}s left`\n      : `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s left`,\n  summary: (done, total) => `${done} of ${total} uploaded`,\n  count: (count, size) => `${plural(count, \"file\")} · ${size}`,\n  added: (count) => `${plural(count, \"file\")} added`,\n  uploaded: (name) => `${name} uploaded`,\n  failed: (name, reason) => `${name} failed: ${reason}`,\n  canceled: (name) => `${name} canceled`,\n  removed: (name) => `${name} removed`,\n  upTo: (size, each) => `up to ${size}${each ? \" each\" : \"\"}`,\n  maxFiles: (count) => `${count} files max`,\n  rejectType: (name, accepted) =>\n    accepted ? `${name} isn't supported. Use ${accepted}.` : `${name} isn't supported.`,\n  rejectSize: (name, max) => `${name} is larger than ${max}.`,\n  rejectCount: (count, max) =>\n    max === 1\n      ? \"Only one file can be added.\"\n      : `${plural(count, \"file\")} not added: the limit is ${max}.`,\n  rejectDuplicate: (name) => `${name} is already in the list.`,\n};\n\nconst EXTENSION_TYPES: Record<string, string> = {\n  pdf: \"application/pdf\",\n  png: \"image/png\",\n  jpg: \"image/jpeg\",\n  jpeg: \"image/jpeg\",\n  gif: \"image/gif\",\n  webp: \"image/webp\",\n  svg: \"image/svg+xml\",\n  csv: \"text/csv\",\n  txt: \"text/plain\",\n  json: \"application/json\",\n  zip: \"application/zip\",\n  mp4: \"video/mp4\",\n  mov: \"video/quicktime\",\n  mp3: \"audio/mpeg\",\n  xlsx: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n  xls: \"application/vnd.ms-excel\",\n  docx: \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n  doc: \"application/msword\",\n  pptx: \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n  heic: \"image/heic\",\n  webm: \"video/webm\",\n  wav: \"audio/wav\",\n  md: \"text/markdown\",\n};\n\nconst TYPE_NAMES: Record<string, string> = {\n  \"image/*\": \"images\",\n  \"video/*\": \"videos\",\n  \"audio/*\": \"audio\",\n  \"text/*\": \"text files\",\n  \"application/pdf\": \"PDF\",\n  \"image/png\": \"PNG\",\n  \"image/jpeg\": \"JPG\",\n  \"image/gif\": \"GIF\",\n  \"image/webp\": \"WebP\",\n  \"image/svg+xml\": \"SVG\",\n  \"text/csv\": \"CSV\",\n  \"text/plain\": \"TXT\",\n  \"application/json\": \"JSON\",\n  \"application/zip\": \"ZIP\",\n  \"video/mp4\": \"MP4\",\n  \"video/quicktime\": \"MOV\",\n  \"audio/mpeg\": \"MP3\",\n  \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\": \"XLSX\",\n  \"application/vnd.ms-excel\": \"XLS\",\n  \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\": \"DOCX\",\n  \"application/msword\": \"DOC\",\n  \"application/vnd.openxmlformats-officedocument.presentationml.presentation\": \"PPTX\",\n};\n\nfunction parseAccept(accept?: string) {\n  return (accept ?? \"\")\n    .split(\",\")\n    .map((rule) => rule.trim().toLowerCase())\n    .filter(Boolean);\n}\n\nfunction extensionOf(name: string) {\n  const dot = name.lastIndexOf(\".\");\n  return dot > 0 ? name.slice(dot + 1).toLowerCase() : \"\";\n}\n\nfunction matchesType(type: string, rule: string) {\n  const mime = type.toLowerCase();\n  if (rule.endsWith(\"/*\")) return mime.startsWith(rule.slice(0, -1));\n  return mime === rule;\n}\n\nfunction isAccepted(file: { name: string; type: string }, rules: string[]) {\n  if (!rules.length) return true;\n  const ext = extensionOf(file.name);\n  return rules.some((rule) =>\n    rule.startsWith(\".\") ? ext === rule.slice(1) : matchesType(file.type, rule),\n  );\n}\n\n/** While dragging, browsers expose types but not names. True only for a certain mismatch. */\nfunction isCertainlyRejected(type: string, rules: string[]) {\n  if (!rules.length || !type) return false;\n  return !rules.some((rule) => {\n    if (!rule.startsWith(\".\")) return matchesType(type, rule);\n    const known = EXTENSION_TYPES[rule.slice(1)];\n    return known ? known === type.toLowerCase() : true;\n  });\n}\n\nfunction describeAccept(rules: string[], locale?: string) {\n  const names = Array.from(\n    new Set(\n      rules.map((rule) => {\n        if (rule.startsWith(\".\")) {\n          const known = EXTENSION_TYPES[rule.slice(1)];\n          return (known && TYPE_NAMES[known]) ?? rule.slice(1).toUpperCase();\n        }\n        return TYPE_NAMES[rule] ?? rule.split(\"/\").pop()!.toUpperCase();\n      }),\n    ),\n  );\n  if (!names.length) return \"\";\n  try {\n    return new Intl.ListFormat(locale ?? \"en\", {\n      style: \"long\",\n      type: \"disjunction\",\n    }).format(names);\n  } catch {\n    return names.join(\", \");\n  }\n}\n\nconst capitalize = (text: string) => text.charAt(0).toUpperCase() + text.slice(1);\n\ntype Kind = \"image\" | \"video\" | \"audio\" | \"pdf\" | \"archive\" | \"sheet\" | \"doc\" | \"slides\" | \"code\" | \"text\" | \"file\";\n\nfunction kindOf(name: string, type: string): Kind {\n  const ext = extensionOf(name);\n  if (type.startsWith(\"image/\")) return \"image\";\n  if (type.startsWith(\"video/\")) return \"video\";\n  if (type.startsWith(\"audio/\")) return \"audio\";\n  if (type === \"application/pdf\" || ext === \"pdf\") return \"pdf\";\n  if ([\"zip\", \"rar\", \"7z\", \"gz\", \"tar\", \"tgz\"].includes(ext)) return \"archive\";\n  if ([\"xls\", \"xlsx\", \"csv\", \"tsv\", \"numbers\", \"ods\"].includes(ext)) return \"sheet\";\n  if ([\"doc\", \"docx\", \"pages\", \"rtf\", \"odt\"].includes(ext)) return \"doc\";\n  if ([\"ppt\", \"pptx\", \"key\", \"odp\"].includes(ext)) return \"slides\";\n  if (\n    [\"js\", \"ts\", \"tsx\", \"jsx\", \"json\", \"html\", \"css\", \"py\", \"go\", \"rs\", \"rb\", \"sh\", \"yml\", \"yaml\", \"xml\", \"sql\"].includes(ext)\n  )\n    return \"code\";\n  if (type.startsWith(\"text/\") || [\"txt\", \"md\"].includes(ext)) return \"text\";\n  return \"file\";\n}\n\nconst KIND_ICONS: Record<Kind, typeof IconFile> = {\n  image: IconPhoto,\n  video: IconMovie,\n  audio: IconFileMusic,\n  pdf: IconFileTypePdf,\n  archive: IconFileZip,\n  sheet: IconFileSpreadsheet,\n  doc: IconFileTypeDoc,\n  slides: IconPresentation,\n  code: IconFileCode,\n  text: IconFileText,\n  file: IconFile,\n};\n\nlet counter = 0;\nfunction createId() {\n  counter += 1;\n  return `file-${Date.now().toString(36)}-${counter}-${Math.random().toString(36).slice(2, 6)}`;\n}\n\n/** Screenshots arrive as \"image.png\"; give them a name that survives a list of several. */\nfunction namePasted(file: File) {\n  if (!/^image\\.\\w+$/i.test(file.name)) return file;\n  const now = new Date();\n  const pad = (n: number) => String(n).padStart(2, \"0\");\n  const stamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;\n  try {\n    return new File([file], `pasted-image-${stamp}.${extensionOf(file.name)}`, {\n      type: file.type,\n      lastModified: file.lastModified,\n    });\n  } catch {\n    return file;\n  }\n}\n\nconst keyframes = `@keyframes file-upload-in{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}@keyframes file-upload-pop{0%{transform:scale(.4);opacity:0}70%{transform:scale(1.12)}100%{transform:scale(1);opacity:1}}@keyframes file-upload-sheen{from{transform:translateX(-100%)}to{transform:translateX(250%)}}`;\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-0\";\n\n/* ------------------------------------------------------------------------ */\n/* Pieces                                                                    */\n/* ------------------------------------------------------------------------ */\n\n/** Keeps the extension and the end of the name, eliding the middle. */\nfunction MiddleTruncate({ text, className }: { text: string; className?: string }) {\n  const dot = text.lastIndexOf(\".\");\n  const ext = dot > 0 ? text.slice(dot) : \"\";\n  const base = dot > 0 ? text.slice(0, dot) : text;\n  // Keep the last word (\"-final.pdf\", \"_v2.png\") whole when it is short; otherwise 8 characters.\n  const separator = Math.max(base.lastIndexOf(\"-\"), base.lastIndexOf(\"_\"), base.lastIndexOf(\" \"));\n  const keep =\n    separator > 3 && base.length - separator <= 12\n      ? base.length - separator - 1\n      : Math.min(8, Math.max(0, base.length - 4));\n  const head = base.slice(0, base.length - keep);\n  const tail = base.slice(base.length - keep) + ext;\n  return (\n    <span className={cn(\"flex min-w-0\", className)} title={text}>\n      <span className=\"sr-only\">{text}</span>\n      <span aria-hidden=\"true\" className=\"flex min-w-0\">\n        <span className=\"overflow-hidden text-ellipsis whitespace-pre\">{head}</span>\n        <span className=\"shrink-0 whitespace-pre\">{tail}</span>\n      </span>\n    </span>\n  );\n}\n\nfunction ActionButton({\n  label,\n  onClick,\n  children,\n  disabled,\n  tone = \"default\",\n}: {\n  label: string;\n  onClick: () => void;\n  children: React.ReactNode;\n  disabled?: boolean;\n  tone?: \"default\" | \"danger\";\n}) {\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      title={label}\n      disabled={disabled}\n      onClick={onClick}\n      className={cn(\n        \"flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-50 sm:size-7 motion-reduce:transition-none [&_svg]:size-4\",\n        tone === \"danger\" && \"hover:text-rose-700 dark:hover:text-rose-400\",\n        focusRing,\n      )}\n    >\n      {children}\n    </button>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* File upload                                                               */\n/* ------------------------------------------------------------------------ */\n\n/** A dropzone and upload queue with progress, cancellation, retry, and validation. */\nexport function FileUpload({\n  files: filesProp,\n  defaultFiles,\n  onFilesChange,\n  upload,\n  concurrency = 3,\n  accept,\n  maxSize,\n  maxFiles,\n  multiple = true,\n  disabled = false,\n  variant = \"default\",\n  paste = true,\n  name,\n  validate,\n  onReject,\n  onUploadComplete,\n  onUploadError,\n  onRemove,\n  hint,\n  showSummary,\n  locale,\n  formatSize,\n  renderIcon,\n  labels: labelsProp,\n  className,\n  onPaste,\n  ...props\n}: FileUploadProps) {\n  const labels: FileUploadLabels = {\n    ...defaultLabels,\n    ...labelsProp,\n    status: { ...defaultLabels.status, ...labelsProp?.status },\n  };\n  const compact = variant === \"compact\";\n  const size = (bytes: number) => (formatSize ? formatSize(bytes) : formatBytes(bytes, locale));\n  const rules = React.useMemo(() => parseAccept(accept), [accept]);\n  const limit = multiple ? maxFiles : 1;\n\n  const id = React.useId();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const zoneRef = React.useRef<HTMLDivElement>(null);\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const formInputRef = React.useRef<HTMLInputElement>(null);\n\n  /* ---- Files ---- */\n  const [filesState, setFilesState] = React.useState<FileUploadItem[]>(\n    () => defaultFiles ?? [],\n  );\n  const files = filesProp ?? filesState;\n  const filesRef = React.useRef(files);\n  filesRef.current = files;\n  const commit = (next: FileUploadItem[]) => {\n    filesRef.current = next;\n    if (filesProp === undefined) setFilesState(next);\n    onFilesChange?.(next);\n  };\n  const patch = (itemId: string, change: Partial<FileUploadItem>) => {\n    const list = filesRef.current;\n    const index = list.findIndex((item) => item.id === itemId);\n    if (index < 0) return null;\n    const item = { ...list[index], ...change };\n    const next = list.slice();\n    next[index] = item;\n    commit(next);\n    return item;\n  };\n\n  // The latest callbacks, so in-flight uploads never call stale props.\n  const latest = React.useRef({ upload, onUploadComplete, onUploadError, labels });\n  latest.current = { upload, onUploadComplete, onUploadError, labels };\n\n  /* ---- Announcements ---- */\n  const [announcement, setAnnouncement] = React.useState(\"\");\n  const pendingAnnouncements = React.useRef<string[]>([]);\n  const announceTimer = React.useRef<number | undefined>(undefined);\n  const announce = (message: string) => {\n    pendingAnnouncements.current.push(message);\n    window.clearTimeout(announceTimer.current);\n    announceTimer.current = window.setTimeout(() => {\n      setAnnouncement(pendingAnnouncements.current.join(\". \"));\n      pendingAnnouncements.current = [];\n    }, 120);\n  };\n\n  /* ---- Rejections ---- */\n  const [rejections, setRejections] = React.useState<FileRejection[]>([]);\n\n  /* ---- Uploads ---- */\n  const controllers = React.useRef(new Map<string, AbortController>());\n  const timing = React.useRef(new Map<string, { start: number; eta?: number }>());\n  const pendingProgress = React.useRef(new Map<string, number>());\n  const frame = React.useRef<number | null>(null);\n\n  const flushProgress = () => {\n    frame.current = null;\n    const pending = pendingProgress.current;\n    if (!pending.size) return;\n    const now = performance.now();\n    let changed = false;\n    const next = filesRef.current.map((item) => {\n      const value = pending.get(item.id);\n      if (value === undefined || item.status !== \"uploading\" || value === item.progress)\n        return item;\n      changed = true;\n      const time = timing.current.get(item.id);\n      if (time) {\n        const elapsed = (now - time.start) / 1000;\n        if (elapsed > 0.8 && value > 0.04) {\n          const remaining = (elapsed / value) * (1 - value);\n          // Smooth the estimate so the countdown never jitters.\n          time.eta = time.eta === undefined ? remaining : time.eta * 0.7 + remaining * 0.3;\n        }\n      }\n      return { ...item, progress: value };\n    });\n    pending.clear();\n    if (changed) commit(next);\n  };\n\n  const reportProgress = (itemId: string, value: number) => {\n    pendingProgress.current.set(\n      itemId,\n      Math.min(1, Math.max(0, Number.isFinite(value) ? value : 0)),\n    );\n    if (frame.current === null)\n      frame.current = requestAnimationFrame(flushProgress);\n  };\n\n  const start = (item: FileUploadItem) => {\n    const run = latest.current.upload;\n    if (!run || !item.file) return;\n    const controller = new AbortController();\n    controllers.current.set(item.id, controller);\n    timing.current.set(item.id, { start: performance.now() });\n    patch(item.id, { status: \"uploading\", progress: 0, error: undefined });\n    const current = () => controllers.current.get(item.id) === controller && !controller.signal.aborted;\n    let request: Promise<unknown>;\n    try {\n      request = Promise.resolve(\n        run(item.file, {\n          signal: controller.signal,\n          item,\n          onProgress: (value) => {\n            if (current()) reportProgress(item.id, value);\n          },\n        }),\n      );\n    } catch (error) {\n      request = Promise.reject(error);\n    }\n    request.then(\n      (response) => {\n        if (!current()) return;\n        controllers.current.delete(item.id);\n        pendingProgress.current.delete(item.id);\n        const done = patch(item.id, { status: \"done\", progress: 1, response, error: undefined });\n        if (done) {\n          announce(latest.current.labels.uploaded(done.name));\n          latest.current.onUploadComplete?.(done, response);\n        }\n      },\n      (error: unknown) => {\n        if (!current()) return;\n        controllers.current.delete(item.id);\n        pendingProgress.current.delete(item.id);\n        const reason =\n          error instanceof Error && error.message\n            ? error.message\n            : typeof error === \"string\" && error\n              ? error\n              : latest.current.labels.uploadFailed;\n        const failed = patch(item.id, { status: \"error\", error: reason });\n        if (failed) {\n          announce(latest.current.labels.failed(failed.name, reason));\n          latest.current.onUploadError?.(failed, error);\n        }\n      },\n    );\n  };\n\n  const hasUpload = !!upload;\n  const slots = Math.max(1, Math.floor(concurrency));\n  React.useEffect(() => {\n    // Stop requests whose items left the list or stopped uploading elsewhere.\n    for (const [itemId, controller] of controllers.current) {\n      const item = files.find((entry) => entry.id === itemId);\n      if (!item || item.status !== \"uploading\") {\n        controller.abort();\n        controllers.current.delete(itemId);\n      }\n    }\n    if (!hasUpload) return;\n    let active = controllers.current.size;\n    for (const item of files) {\n      if (active >= slots) break;\n      // An uploading item with no request lost it to a remount; start it again.\n      const orphan = item.status === \"uploading\" && !controllers.current.has(item.id);\n      if ((item.status === \"queued\" || orphan) && item.file) {\n        start(item);\n        active += 1;\n      }\n    }\n  }, [files, hasUpload, slots]);\n\n  React.useEffect(() => {\n    const live = controllers.current;\n    return () => {\n      for (const controller of live.values()) controller.abort();\n      live.clear();\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n      frame.current = null;\n      window.clearTimeout(announceTimer.current);\n    };\n  }, []);\n\n  /* ---- Previews ---- */\n  const previews = React.useRef(new Map<string, string>());\n  const [, refreshPreviews] = React.useReducer((n: number) => n + 1, 0);\n  const [broken, setBroken] = React.useState<ReadonlySet<string>>(() => new Set());\n  React.useEffect(() => {\n    let changed = false;\n    const ids = new Set(files.map((item) => item.id));\n    for (const [itemId, url] of previews.current) {\n      if (!ids.has(itemId)) {\n        URL.revokeObjectURL(url);\n        previews.current.delete(itemId);\n        changed = true;\n      }\n    }\n    for (const item of files) {\n      if (\n        item.file &&\n        !item.previewUrl &&\n        item.type.startsWith(\"image/\") &&\n        item.size < 20 * 1024 * 1024 &&\n        !previews.current.has(item.id)\n      ) {\n        previews.current.set(item.id, URL.createObjectURL(item.file));\n        changed = true;\n      }\n    }\n    if (changed) refreshPreviews();\n  }, [files]);\n  React.useEffect(() => {\n    const urls = previews.current;\n    return () => {\n      for (const url of urls.values()) URL.revokeObjectURL(url);\n      urls.clear();\n    };\n  }, []);\n\n  /* ---- Form mirror ---- */\n  React.useEffect(() => {\n    const input = formInputRef.current;\n    if (!name || !input || typeof DataTransfer === \"undefined\") return;\n    try {\n      const transfer = new DataTransfer();\n      for (const item of files)\n        if (item.file && item.status !== \"error\" && item.status !== \"canceled\")\n          transfer.items.add(item.file);\n      input.files = transfer.files;\n    } catch {\n      // Older browsers cannot construct DataTransfer; the form simply omits files.\n    }\n  }, [files, name]);\n\n  /* ---- Adding ---- */\n  const full = limit !== undefined && multiple && files.length >= limit;\n  const acceptText = describeAccept(rules, locale);\n\n  const addFiles = (incoming: File[]) => {\n    if (disabled || !incoming.length) return;\n    const current = filesRef.current;\n    const rejected: FileRejection[] = [];\n    const accepted: File[] = [];\n    for (const file of incoming) {\n      if (!isAccepted(file, rules)) {\n        rejected.push({ file, reason: \"type\", message: labels.rejectType(file.name, acceptText) });\n      } else if (maxSize !== undefined && file.size > maxSize) {\n        rejected.push({ file, reason: \"size\", message: labels.rejectSize(file.name, size(maxSize)) });\n      } else if (\n        multiple &&\n        [...current.map((item) => item.file), ...accepted].some(\n          (other) =>\n            other &&\n            other.name === file.name &&\n            other.size === file.size &&\n            other.lastModified === file.lastModified,\n        )\n      ) {\n        rejected.push({ file, reason: \"duplicate\", message: labels.rejectDuplicate(file.name) });\n      } else {\n        const custom = validate?.(file, current);\n        if (custom) rejected.push({ file, reason: \"custom\", message: custom });\n        else accepted.push(file);\n      }\n    }\n    let base = current;\n    if (!multiple) {\n      // A single-file picker replaces its file.\n      const extra = accepted.splice(1);\n      if (extra.length)\n        rejected.push(...extra.map((file) => ({ file, reason: \"count\" as const, message: labels.rejectCount(extra.length, 1) })));\n      if (accepted.length) {\n        for (const item of base) controllers.current.get(item.id)?.abort();\n        base = [];\n      }\n    } else if (limit !== undefined) {\n      const room = Math.max(0, limit - current.length);\n      const extra = accepted.splice(room);\n      if (extra.length)\n        rejected.push(...extra.map((file) => ({ file, reason: \"count\" as const, message: labels.rejectCount(extra.length, limit) })));\n    }\n    if (accepted.length) {\n      const added: FileUploadItem[] = accepted.map((file) => ({\n        id: createId(),\n        file,\n        name: file.name,\n        size: file.size,\n        type: file.type,\n        status: upload ? \"queued\" : \"idle\",\n        progress: 0,\n      }));\n      commit([...base, ...added]);\n      announce(labels.added(added.length));\n    }\n    setRejections(rejected);\n    if (rejected.length) onReject?.(rejected);\n  };\n\n  const browse = () => {\n    if (disabled || full) return;\n    inputRef.current?.click();\n  };\n\n  /* ---- Row actions ---- */\n  const focusAfter = (index: number) => {\n    requestAnimationFrame(() => {\n      const rows = rootRef.current?.querySelectorAll<HTMLElement>(\"[data-slot=file-upload-item]\");\n      const row = rows?.[Math.min(index, (rows?.length ?? 1) - 1)];\n      (row?.querySelector<HTMLElement>(\"button\") ?? zoneRef.current)?.focus();\n    });\n  };\n  const remove = (item: FileUploadItem) => {\n    const index = filesRef.current.findIndex((entry) => entry.id === item.id);\n    controllers.current.get(item.id)?.abort();\n    controllers.current.delete(item.id);\n    commit(filesRef.current.filter((entry) => entry.id !== item.id));\n    announce(labels.removed(item.name));\n    onRemove?.(item);\n    focusAfter(index);\n  };\n  const cancel = (item: FileUploadItem) => {\n    controllers.current.get(item.id)?.abort();\n    controllers.current.delete(item.id);\n    pendingProgress.current.delete(item.id);\n    patch(item.id, { status: \"canceled\" });\n    announce(labels.canceled(item.name));\n    requestAnimationFrame(() =>\n      rootRef.current\n        ?.querySelector<HTMLElement>(`[data-file-id=\"${CSS.escape(item.id)}\"] button`)\n        ?.focus(),\n    );\n  };\n  const retry = (itemIds: string[]) => {\n    const ids = new Set(itemIds);\n    commit(\n      filesRef.current.map((item) =>\n        ids.has(item.id)\n          ? { ...item, status: upload ? \"queued\" : \"idle\", progress: 0, error: undefined }\n          : item,\n      ),\n    );\n  };\n  const clearDone = () => {\n    const leaving = filesRef.current.filter((item) => item.status === \"done\");\n    commit(filesRef.current.filter((item) => item.status !== \"done\"));\n    for (const item of leaving) onRemove?.(item);\n    requestAnimationFrame(() => zoneRef.current?.focus());\n  };\n\n  /* ---- Drag and drop ---- */\n  const [dragState, setDragState] = React.useState<\"idle\" | \"page\" | \"over\" | \"reject\">(\"idle\");\n  const [dragCount, setDragCount] = React.useState(0);\n  const zoneDepth = React.useRef(0);\n\n  React.useEffect(() => {\n    if (disabled) return;\n    let depth = 0;\n    const hasFiles = (event: DragEvent) =>\n      Array.from(event.dataTransfer?.types ?? []).includes(\"Files\");\n    const enter = (event: DragEvent) => {\n      if (!hasFiles(event)) return;\n      depth += 1;\n      setDragState((state) => (state === \"idle\" ? \"page\" : state));\n    };\n    const leave = (event: DragEvent) => {\n      if (!hasFiles(event)) return;\n      depth = Math.max(0, depth - 1);\n      if (depth === 0) setDragState(\"idle\");\n    };\n    const reset = () => {\n      depth = 0;\n      zoneDepth.current = 0;\n      setDragState(\"idle\");\n    };\n    window.addEventListener(\"dragenter\", enter);\n    window.addEventListener(\"dragleave\", leave);\n    window.addEventListener(\"drop\", reset);\n    window.addEventListener(\"dragend\", reset);\n    return () => {\n      window.removeEventListener(\"dragenter\", enter);\n      window.removeEventListener(\"dragleave\", leave);\n      window.removeEventListener(\"drop\", reset);\n      window.removeEventListener(\"dragend\", reset);\n    };\n  }, [disabled]);\n\n  const assessDrag = (event: React.DragEvent) => {\n    const items = Array.from(event.dataTransfer.items ?? []).filter((item) => item.kind === \"file\");\n    const count = items.length || event.dataTransfer.files.length || 1;\n    const room = limit === undefined ? Infinity : multiple ? limit - filesRef.current.length : 1;\n    const allRejected = items.length > 0 && items.every((item) => isCertainlyRejected(item.type, rules));\n    return { count: Math.min(count, Math.max(room, 0)), reject: disabled || room <= 0 || allRejected };\n  };\n\n  const zoneHandlers = {\n    onDragEnter: (event: React.DragEvent) => {\n      if (!Array.from(event.dataTransfer.types).includes(\"Files\")) return;\n      event.preventDefault();\n      zoneDepth.current += 1;\n      const { count, reject } = assessDrag(event);\n      setDragCount(count);\n      setDragState(reject ? \"reject\" : \"over\");\n    },\n    onDragOver: (event: React.DragEvent) => {\n      if (!Array.from(event.dataTransfer.types).includes(\"Files\")) return;\n      event.preventDefault();\n      event.dataTransfer.dropEffect = dragState === \"reject\" ? \"none\" : \"copy\";\n    },\n    onDragLeave: () => {\n      zoneDepth.current = Math.max(0, zoneDepth.current - 1);\n      if (zoneDepth.current === 0) setDragState(\"page\");\n    },\n    onDrop: (event: React.DragEvent) => {\n      event.preventDefault();\n      zoneDepth.current = 0;\n      setDragState(\"idle\");\n      if (disabled) return;\n      addFiles(Array.from(event.dataTransfer.files));\n    },\n  };\n\n  /* ---- Derived ---- */\n  const uploadable = files.filter((item) => item.status !== \"idle\");\n  const doneCount = files.filter((item) => item.status === \"done\").length;\n  const failedIds = files.filter((item) => item.status === \"error\" || item.status === \"canceled\").map((item) => item.id);\n  const totalSize = files.reduce((sum, item) => sum + item.size, 0);\n  const summaryVisible = (showSummary ?? !compact) && files.length > 1;\n\n  const hintText =\n    hint ??\n    (() => {\n      const parts: string[] = [];\n      const typePart = acceptText ? capitalize(acceptText) : \"\";\n      const sizePart = maxSize !== undefined ? labels.upTo(size(maxSize), multiple) : \"\";\n      const first = [typePart, sizePart].filter(Boolean).join(\", \");\n      if (first) parts.push(capitalize(first));\n      if (multiple && limit !== undefined) parts.push(capitalize(labels.maxFiles(limit)));\n      return parts.join(\" · \");\n    })();\n\n  const titleId = `${id}-title`;\n  const hintId = `${id}-hint`;\n  const keyboardId = `${id}-keyboard`;\n  const zoneDisabled = disabled || full;\n  const zoneState = disabled ? \"disabled\" : full && dragState === \"idle\" ? \"full\" : dragState;\n\n  const title =\n    zoneState === \"over\" ? (\n      labels.dropActive(dragCount)\n    ) : zoneState === \"reject\" ? (\n      labels.dropReject\n    ) : zoneState === \"full\" ? (\n      labels.limitReached\n    ) : (\n      <>\n        {multiple ? labels.title : labels.titleSingle}\n        {/* The compact zone shows a Browse button once there is room, so the phrase steps aside. */}\n        <span className={cn(compact && \"@xs/file-upload:hidden\")}>\n          {` ${labels.or} `}\n          <span className=\"text-primary underline-offset-4 decoration-primary/40 group-hover/zone:underline\">\n            {labels.browse}\n          </span>\n        </span>\n      </>\n    );\n  const subtitle = zoneState === \"full\" ? labels.limitHint : hintText;\n\n  const ZoneIcon = zoneState === \"reject\" ? IconAlertCircle : IconCloudUpload;\n  // The empty state invites with a tall zone; once a queue exists it steps back to one row.\n  const layout = compact ? \"compact\" : files.length > 0 ? \"row\" : \"stacked\";\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"group\"\n      data-slot=\"file-upload\"\n      data-variant={variant}\n      data-disabled={disabled ? \"\" : undefined}\n      data-drag-state={dragState}\n      className={cn(\"@container/file-upload flex w-full min-w-0 flex-col\", compact ? \"gap-2\" : \"gap-3\", className)}\n      onPaste={(event) => {\n        onPaste?.(event);\n        if (event.defaultPrevented || !paste || disabled) return;\n        const pasted = Array.from(event.clipboardData?.files ?? []);\n        if (!pasted.length) return;\n        event.preventDefault();\n        addFiles(pasted.map(namePasted));\n      }}\n      {...props}\n    >\n      <style>{keyframes}</style>\n      <input\n        ref={inputRef}\n        type=\"file\"\n        hidden\n        tabIndex={-1}\n        aria-hidden=\"true\"\n        accept={accept}\n        multiple={multiple}\n        disabled={zoneDisabled}\n        onChange={(event) => {\n          addFiles(Array.from(event.target.files ?? []));\n          event.target.value = \"\";\n        }}\n      />\n      {name && (\n        <input ref={formInputRef} type=\"file\" name={name} multiple={multiple} hidden tabIndex={-1} aria-hidden=\"true\" />\n      )}\n\n      {/* Dropzone */}\n      <div\n        ref={zoneRef}\n        role=\"button\"\n        tabIndex={disabled ? -1 : 0}\n        aria-disabled={zoneDisabled || undefined}\n        aria-labelledby={titleId}\n        aria-describedby={paste ? `${hintId} ${keyboardId}` : hintId}\n        data-slot=\"file-upload-dropzone\"\n        data-state={zoneState}\n        data-layout={layout}\n        onClick={browse}\n        onKeyDown={(event) => {\n          if (event.key === \"Enter\" || event.key === \" \") {\n            event.preventDefault();\n            browse();\n          }\n        }}\n        {...zoneHandlers}\n        className={cn(\n          \"group/zone relative isolate flex cursor-pointer overflow-hidden border border-dashed border-border bg-card text-card-foreground transition-[border-color,background-color,box-shadow] duration-150 motion-reduce:transition-none\",\n          \"outline-none hover:border-foreground/25 hover:bg-[color-mix(in_oklab,var(--color-muted)_45%,var(--color-card))] focus-visible:border-transparent focus-visible:ring-2 focus-visible:ring-ring/50\",\n          \"data-[state=page]:border-primary/45 data-[state=page]:bg-[color-mix(in_oklab,var(--color-primary)_3%,var(--color-card))]\",\n          \"data-[state=over]:border-primary data-[state=over]:bg-[color-mix(in_oklab,var(--color-primary)_6%,var(--color-card))] data-[state=over]:shadow-[0_0_0_4px_color-mix(in_oklab,var(--color-primary)_12%,transparent),0_12px_32px_-16px_color-mix(in_oklab,var(--color-primary)_45%,transparent)]\",\n          \"data-[state=reject]:cursor-no-drop data-[state=reject]:border-destructive/70 data-[state=reject]:bg-[color-mix(in_oklab,var(--color-destructive)_5%,var(--color-card))]\",\n          \"data-[state=full]:cursor-default data-[state=full]:border-border/70 data-[state=full]:bg-[color-mix(in_oklab,var(--color-muted)_45%,var(--color-card))] data-[state=full]:hover:bg-[color-mix(in_oklab,var(--color-muted)_45%,var(--color-card))]\",\n          \"data-[state=disabled]:cursor-not-allowed data-[state=disabled]:opacity-60 data-[state=disabled]:hover:border-border data-[state=disabled]:hover:bg-card\",\n          layout === \"compact\" && \"min-h-14 items-center gap-3 rounded-xl px-3 py-2.5 sm:min-h-13\",\n          layout === \"row\" && \"items-center justify-center gap-3.5 rounded-2xl px-5 py-4\",\n          layout === \"stacked\" && \"flex-col items-center justify-center gap-3 rounded-2xl px-6 py-7 text-center\",\n        )}\n      >\n        {/* The lit drop state: a soft primary glow rising from the bottom edge. */}\n        <span\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-0 -z-10 bg-[radial-gradient(80%_120%_at_50%_120%,color-mix(in_oklab,var(--color-primary)_16%,transparent),transparent_70%)] opacity-0 transition-opacity duration-200 group-data-[state=over]/zone:opacity-100 motion-reduce:transition-none\"\n        />\n        <span\n          aria-hidden=\"true\"\n          className={cn(\n            \"relative flex shrink-0 items-center justify-center bg-card text-muted-foreground ring-1 ring-border/70 transition-[transform,color,box-shadow] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] ring-inset motion-reduce:transition-none\",\n            \"shadow-[0_1px_2px_rgb(0_0_0/0.05),0_4px_12px_-6px_rgb(0_0_0/0.12)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]\",\n            \"group-hover/zone:text-foreground group-data-[state=over]/zone:-translate-y-0.5 group-data-[state=over]/zone:text-primary group-data-[state=over]/zone:shadow-[0_8px_20px_-8px_color-mix(in_oklab,var(--color-primary)_55%,transparent)] group-data-[state=reject]/zone:text-rose-700 dark:group-data-[state=reject]/zone:text-rose-400 group-data-[state=full]/zone:text-muted-foreground\",\n            layout === \"compact\" && \"size-9 rounded-lg [&_svg]:size-[18px]\",\n            layout === \"row\" && \"size-10 rounded-xl [&_svg]:size-5\",\n            layout === \"stacked\" && \"size-11 rounded-xl [&_svg]:size-[22px]\",\n          )}\n        >\n          <span className=\"pointer-events-none absolute inset-x-2 top-0 h-px bg-gradient-to-r from-transparent via-foreground/10 to-transparent\" />\n          <ZoneIcon stroke={1.75} />\n        </span>\n        <span\n          className={cn(\n            \"flex min-w-0 flex-col\",\n            layout === \"compact\" && \"flex-1 gap-0.5\",\n            layout === \"row\" && \"items-start gap-0.5 text-start\",\n            layout === \"stacked\" && \"items-center gap-1\",\n          )}\n        >\n          <span\n            id={titleId}\n            className={cn(\n              \"font-medium tracking-tight text-foreground group-data-[state=reject]/zone:text-rose-700 dark:group-data-[state=reject]/zone:text-rose-400\",\n              compact ? \"truncate text-[13px] leading-5\" : \"text-sm\",\n            )}\n          >\n            {title}\n          </span>\n          <span\n            id={hintId}\n            className={cn(\n              \"text-xs leading-4 text-muted-foreground tabular-nums\",\n              compact && \"truncate\",\n            )}\n          >\n            {subtitle}\n          </span>\n          {paste && (\n            <span\n              id={keyboardId}\n              className={cn(\n                \"hidden text-xs leading-4 text-muted-foreground\",\n                layout === \"stacked\" && \"group-focus-visible/zone:block\",\n              )}\n            >\n              {labels.keyboardHint}\n            </span>\n          )}\n        </span>\n        {compact && (\n          <span\n            aria-hidden=\"true\"\n            className=\"hidden h-7 shrink-0 items-center rounded-md border border-input bg-card px-2.5 text-xs font-medium text-foreground shadow-xs transition-colors duration-150 group-hover/zone:bg-muted group-data-[state=full]/zone:hidden group-data-[state=disabled]/zone:hidden @xs/file-upload:flex\"\n          >\n            {labels.browse.charAt(0).toUpperCase() + labels.browse.slice(1)}\n          </span>\n        )}\n      </div>\n\n      {/* Validation */}\n      <div aria-live=\"assertive\" aria-atomic=\"true\" data-slot=\"file-upload-rejections\" className=\"empty:hidden\">\n        {rejections.length > 0 && (\n          <div className=\"flex items-start gap-2.5 rounded-xl bg-[color-mix(in_oklab,var(--color-destructive)_4%,var(--color-card))] py-2.5 ps-3 pe-1.5 ring-1 ring-destructive/20 ring-inset motion-safe:animate-[file-upload-in_200ms_cubic-bezier(0.22,1,0.36,1)]\">\n            <IconAlertCircle aria-hidden=\"true\" className=\"mt-0.5 size-4 shrink-0 text-rose-700 dark:text-rose-400\" />\n            <ul className=\"m-0 min-w-0 flex-1 list-none space-y-0.5 p-0 text-[13px] leading-5 text-rose-700 dark:text-rose-400\">\n              {(() => {\n                const counted = rejections.filter((r) => r.reason === \"count\");\n                const rest = rejections.filter((r) => r.reason !== \"count\");\n                return [\n                  ...rest.map((rejection, index) => (\n                    <li key={`${rejection.file.name}-${index}`} className=\"break-words\">\n                      {rejection.message}\n                    </li>\n                  )),\n                  counted.length > 0 && <li key=\"count\">{counted[0].message}</li>,\n                ];\n              })()}\n            </ul>\n            <button\n              type=\"button\"\n              aria-label={labels.dismiss}\n              onClick={() => setRejections([])}\n              className={cn(\n                \"-my-1 flex size-7 shrink-0 items-center justify-center rounded-md text-rose-700/80 transition-colors hover:bg-destructive/10 hover:text-rose-700 dark:text-rose-400/80 dark:hover:text-rose-400\",\n                focusRing,\n              )}\n            >\n              <IconX aria-hidden=\"true\" className=\"size-3.5\" />\n            </button>\n          </div>\n        )}\n      </div>\n\n      {/* Queue */}\n      {files.length > 0 && (\n        <div className={cn(\"flex min-w-0 flex-col\", compact ? \"gap-1.5\" : \"gap-2\")}>\n          {summaryVisible && (\n            <div\n              data-slot=\"file-upload-summary\"\n              className=\"flex min-h-7 flex-wrap items-center justify-between gap-x-3 ps-1 text-xs text-muted-foreground tabular-nums\"\n            >\n              <span className=\"whitespace-nowrap\">\n                {uploadable.length\n                  ? labels.summary(doneCount, files.length)\n                  : labels.count(files.length, size(totalSize))}\n              </span>\n              <span className=\"-me-1 ms-auto flex shrink-0 items-center gap-0.5\">\n                {failedIds.length > 0 && (\n                  <button\n                    type=\"button\"\n                    onClick={() => retry(failedIds)}\n                    disabled={disabled}\n                    className={cn(\n                      \"inline-flex h-7 items-center gap-1.5 rounded-md px-1.5 font-medium text-foreground transition-colors duration-150 hover:bg-muted disabled:opacity-50\",\n                      focusRing,\n                    )}\n                  >\n                    <IconRefresh aria-hidden=\"true\" className=\"size-3.5\" />\n                    {labels.retryFailed}\n                  </button>\n                )}\n                {doneCount > 0 && (\n                  <button\n                    type=\"button\"\n                    onClick={clearDone}\n                    disabled={disabled}\n                    className={cn(\n                      \"inline-flex h-7 items-center rounded-md px-1.5 transition-colors duration-150 hover:bg-muted hover:text-foreground disabled:opacity-50\",\n                      focusRing,\n                    )}\n                  >\n                    {labels.clearDone}\n                  </button>\n                )}\n              </span>\n            </div>\n          )}\n          <ul\n            aria-label={labels.files}\n            data-slot=\"file-upload-list\"\n            className={cn(\"m-0 flex list-none flex-col p-0\", compact ? \"gap-1.5\" : \"gap-2\")}\n          >\n            {files.map((item) => (\n              <FileRow\n                key={item.id}\n                item={item}\n                compact={compact}\n                disabled={disabled}\n                labels={labels}\n                size={size}\n                eta={item.status === \"uploading\" ? timing.current.get(item.id)?.eta : undefined}\n                preview={broken.has(item.id) ? undefined : (item.previewUrl ?? previews.current.get(item.id))}\n                onPreviewError={() => setBroken((set) => new Set(set).add(item.id))}\n                icon={renderIcon?.(item)}\n                onCancel={() => cancel(item)}\n                onRetry={() => retry([item.id])}\n                onRemove={() => remove(item)}\n                canRetry={hasUpload && !!item.file}\n              />\n            ))}\n          </ul>\n        </div>\n      )}\n\n      <div aria-live=\"polite\" aria-atomic=\"true\" className=\"sr-only\">\n        {announcement}\n      </div>\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Row                                                                       */\n/* ------------------------------------------------------------------------ */\n\nfunction FileRow({\n  item,\n  compact,\n  disabled,\n  labels,\n  size,\n  eta,\n  preview,\n  onPreviewError,\n  icon,\n  onCancel,\n  onRetry,\n  onRemove,\n  canRetry,\n}: {\n  item: FileUploadItem;\n  compact: boolean;\n  disabled: boolean;\n  labels: FileUploadLabels;\n  size: (bytes: number) => string;\n  eta?: number;\n  preview?: string;\n  onPreviewError: () => void;\n  icon?: React.ReactNode;\n  onCancel: () => void;\n  onRetry: () => void;\n  onRemove: () => void;\n  canRetry: boolean;\n}) {\n  const { status } = item;\n  const active = status === \"queued\" || status === \"uploading\";\n  const percent = Math.round(item.progress * 100);\n  const Icon = KIND_ICONS[kindOf(item.name, item.type)];\n\n  const meta = (() => {\n    switch (status) {\n      case \"uploading\":\n        return (\n          <>\n            <span className=\"font-medium text-foreground\">{percent}%</span>\n            <span aria-hidden=\"true\">·</span>\n            <span className=\"truncate\">\n              {size(item.size * item.progress)} {labels.of} {size(item.size)}\n            </span>\n            {eta !== undefined && eta > 0.5 && (\n              <>\n                <span aria-hidden=\"true\" className=\"@max-xs/file-upload:hidden\">·</span>\n                <span className=\"shrink-0 @max-xs/file-upload:hidden\">{labels.timeLeft(eta)}</span>\n              </>\n            )}\n          </>\n        );\n      case \"queued\":\n        return (\n          <>\n            <IconClock aria-hidden=\"true\" className=\"size-3.5 shrink-0\" />\n            <span>{labels.status.queued}</span>\n            <span aria-hidden=\"true\">·</span>\n            <span>{size(item.size)}</span>\n          </>\n        );\n      case \"done\":\n        return (\n          <>\n            <IconCircleCheckFilled\n              aria-hidden=\"true\"\n              className=\"size-3.5 shrink-0 text-emerald-600 motion-safe:animate-[file-upload-pop_360ms_cubic-bezier(0.22,1,0.36,1)] dark:text-emerald-400\"\n            />\n            <span className=\"text-emerald-700 dark:text-emerald-400\">{labels.status.done}</span>\n            <span aria-hidden=\"true\">·</span>\n            <span>{size(item.size)}</span>\n          </>\n        );\n      case \"error\":\n        return (\n          <>\n            <IconAlertCircle aria-hidden=\"true\" className=\"size-3.5 shrink-0 text-rose-700 dark:text-rose-400\" />\n            <span className=\"truncate text-rose-700 dark:text-rose-400\" title={item.error}>\n              {item.error || labels.status.error}\n            </span>\n          </>\n        );\n      case \"canceled\":\n        return (\n          <>\n            <span>{labels.status.canceled}</span>\n            <span aria-hidden=\"true\">·</span>\n            <span>{size(item.size)}</span>\n          </>\n        );\n      default:\n        return <span>{size(item.size)}</span>;\n    }\n  })();\n\n  return (\n    <li\n      data-slot=\"file-upload-item\"\n      data-file-id={item.id}\n      data-status={status}\n      className={cn(\n        \"group/item relative flex min-w-0 items-center bg-card ring-1 ring-border/60 transition-[box-shadow,background-color] duration-200 ring-inset motion-safe:animate-[file-upload-in_240ms_cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none\",\n        \"shadow-[0_1px_2px_rgb(0_0_0/0.03)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.04)]\",\n        \"data-[status=error]:bg-[color-mix(in_oklab,var(--color-destructive)_3%,var(--color-card))] data-[status=error]:ring-destructive/25\",\n        compact ? \"gap-2.5 rounded-lg py-1.5 ps-1.5 pe-1\" : \"gap-3 rounded-xl py-2.5 ps-2.5 pe-2\",\n      )}\n    >\n      <span\n        aria-hidden=\"true\"\n        data-slot=\"file-upload-thumbnail\"\n        className={cn(\n          \"relative flex shrink-0 items-center justify-center overflow-hidden bg-muted/50 text-muted-foreground ring-1 ring-border/60 ring-inset\",\n          compact ? \"size-8 rounded-md [&_svg]:size-4\" : \"size-10 rounded-lg [&_svg]:size-5\",\n          \"[&_svg]:stroke-[1.75]\",\n        )}\n      >\n        {icon ??\n          (preview ? (\n            <>\n              <img\n                src={preview}\n                alt=\"\"\n                draggable={false}\n                onError={onPreviewError}\n                className=\"size-full object-cover\"\n              />\n              <span className=\"absolute inset-0 rounded-[inherit] ring-1 ring-foreground/10 ring-inset\" />\n            </>\n          ) : (\n            <>\n              <span className=\"pointer-events-none absolute inset-x-1.5 top-0 h-px bg-gradient-to-r from-transparent via-foreground/10 to-transparent\" />\n              <Icon />\n            </>\n          ))}\n      </span>\n\n      <div className=\"min-w-0 flex-1\">\n        <MiddleTruncate\n          text={item.name}\n          className={cn(\n            \"font-medium tracking-tight text-foreground\",\n            compact ? \"text-[13px] leading-5\" : \"text-sm leading-5\",\n            status === \"canceled\" && \"text-muted-foreground\",\n          )}\n        />\n        <div\n          className={cn(\n            \"flex min-w-0 items-center gap-1.5 text-xs leading-4 whitespace-nowrap text-muted-foreground tabular-nums\",\n            compact ? \"mt-px\" : \"mt-0.5\",\n          )}\n        >\n          {meta}\n        </div>\n        {/* The bar collapses away once the upload settles. */}\n        <div\n          className={cn(\n            \"grid transition-[grid-template-rows,opacity] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none\",\n            active ? \"grid-rows-[1fr] opacity-100\" : \"grid-rows-[0fr] opacity-0\",\n          )}\n        >\n          <div className=\"overflow-hidden\">\n            <div\n              role=\"progressbar\"\n              aria-label={`${labels.status[status]} ${item.name}`}\n              aria-valuemin={0}\n              aria-valuemax={100}\n              aria-valuenow={percent}\n              aria-hidden={!active || undefined}\n              data-slot=\"file-upload-progress\"\n              className={cn(\n                \"relative overflow-hidden rounded-full bg-foreground/[0.07]\",\n                compact ? \"mt-1.5 mb-0.5 h-1\" : \"mt-2 mb-0.5 h-1.5\",\n              )}\n            >\n              <div\n                className=\"relative h-full overflow-hidden rounded-full bg-[linear-gradient(90deg,color-mix(in_oklab,var(--color-primary)_70%,transparent),var(--color-primary))] transition-[width] duration-300 ease-out motion-reduce:transition-none\"\n                style={{ width: `${status === \"queued\" ? 0 : Math.max(2, percent)}%` }}\n              >\n                {status === \"uploading\" && (\n                  <span className=\"absolute inset-y-0 start-0 w-1/2 bg-[linear-gradient(90deg,transparent,rgb(255_255_255/0.45),transparent)] motion-safe:animate-[file-upload-sheen_1.6s_ease-in-out_infinite] motion-reduce:hidden dark:bg-[linear-gradient(90deg,transparent,rgb(255_255_255/0.25),transparent)]\" />\n                )}\n              </div>\n            </div>\n          </div>\n        </div>\n      </div>\n\n      <div data-slot=\"file-upload-actions\" className=\"flex shrink-0 items-center gap-0.5 self-center\">\n        {active ? (\n          <ActionButton label={labels.cancel(item.name)} onClick={onCancel} disabled={disabled}>\n            <IconX />\n          </ActionButton>\n        ) : (\n          <>\n            {(status === \"error\" || status === \"canceled\") && canRetry && (\n              <ActionButton label={labels.retry(item.name)} onClick={onRetry} disabled={disabled}>\n                <IconRefresh />\n              </ActionButton>\n            )}\n            <ActionButton label={labels.remove(item.name)} onClick={onRemove} disabled={disabled} tone=\"danger\">\n              {status === \"idle\" ? <IconX /> : <IconTrash />}\n            </ActionButton>\n          </>\n        )}\n      </div>\n    </li>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/file-upload. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
