{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "file-upload",
  "title": "File Upload",
  "description": "Drop zone and file list for choosing files to upload.",
  "dependencies": [
    "class-variance-authority@^0.7.1",
    "lucide-react@^1.27.0"
  ],
  "registryDependencies": [
    "@pestoui/button",
    "@pestoui/progress",
    "@pestoui/style",
    "@pestoui/utils"
  ],
  "files": [
    {
      "path": "pestoui/ui/file-upload.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { FileIcon, UploadIcon, XIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport { Progress } from \"@/components/ui/progress\"\n\n/* ------------------------------------------------------------------ utils */\n\nconst BYTE_UNITS = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\"]\n\nfunction formatBytes(bytes: number) {\n  if (!Number.isFinite(bytes) || bytes <= 0) return \"0 KB\"\n  let value = bytes\n  let unit = 0\n  while (value >= 1024 && unit < BYTE_UNITS.length - 1) {\n    value /= 1024\n    unit += 1\n  }\n  const rounded =\n    value >= 10 || Number.isInteger(value)\n      ? Math.round(value)\n      : Math.round(value * 10) / 10\n  return `${rounded} ${BYTE_UNITS[unit]}`\n}\n\n/* Mirrors the browser's own `accept` matching: extensions, `type/subtype`\n   and wildcard `type/*` tokens. We re-run it after a drop because the native\n   filter only applies to the file picker, never to dragged files. */\nfunction matchesAccept(file: File, accept?: string) {\n  const tokens = (accept ?? \"\")\n    .split(\",\")\n    .map((token) => token.trim().toLowerCase())\n    .filter(Boolean)\n  if (tokens.length === 0) return true\n\n  const name = file.name.toLowerCase()\n  const type = file.type.toLowerCase()\n\n  return tokens.some((token) => {\n    if (token === \"*\" || token === \"*/*\") return true\n    if (token.startsWith(\".\")) return name.endsWith(token)\n    if (token.endsWith(\"/*\")) return type.startsWith(token.slice(0, -1))\n    return type === token\n  })\n}\n\nfunction formatAcceptLabel(accept?: string) {\n  const labels = (accept ?? \"\")\n    .split(\",\")\n    .map((token) => token.trim())\n    .filter(Boolean)\n    .map((token) => {\n      if (token.startsWith(\".\")) return token.slice(1)\n      if (token.endsWith(\"/*\")) return token.slice(0, -2)\n      return token.split(\"/\").pop() ?? token\n    })\n    .map((label) => label.toUpperCase())\n\n  const unique = labels.filter((label, i) => labels.indexOf(label) === i)\n  return unique.length > 0 ? unique.join(\", \") : null\n}\n\nfunction fileExtension(name: string) {\n  const dot = name.lastIndexOf(\".\")\n  if (dot < 1 || dot === name.length - 1) return null\n  const ext = name.slice(dot + 1)\n  return ext.length <= 4 ? ext.toUpperCase() : null\n}\n\n/* ------------------------------------------------------------- FileUpload */\n\n/* Motion: drag-over is the one state here that has to be unmistakable, because\n   the pointer is carrying something and the user needs to know this box will\n   catch it. So it is the only state that gets more than colour — the surface\n   swells by one percent on the press spring, which reads as the box reaching\n   for the payload. Leaving runs back on the short base tween, so the reach is\n   deliberate and the release is not.\n\n   The click press is deliberately smaller than a button's: this surface is\n   large, and the same ratio that feels crisp on a control reads as the whole\n   panel lurching. */\nconst fileUploadVariants = cva(\n  \"group/file-upload flex w-full flex-col items-center justify-center rounded-xl border border-dashed border-border bg-card text-center transition-[color,background-color,border-color,box-shadow,scale] duration-fast ease-out-expo outline-none select-none hover:bg-accent/50 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:scale-99 active:duration-spring-press active:ease-spring-press disabled:pointer-events-none disabled:opacity-55 data-[dragging=true]:scale-101 data-[dragging=true]:border-selected data-[dragging=true]:bg-selected/8 data-[dragging=true]:duration-spring-press data-[dragging=true]:ease-spring-press dark:bg-input/30 dark:hover:bg-input/50 dark:data-[dragging=true]:bg-selected/12\",\n  {\n    variants: {\n      size: {\n        sm: \"gap-2 px-5 py-6\",\n        default: \"gap-3 px-6 py-9\",\n        lg: \"gap-4 px-8 py-14\",\n      },\n    },\n    defaultVariants: {\n      size: \"default\",\n    },\n  }\n)\n\nfunction FileUpload({\n  className,\n  size = \"default\",\n  accept,\n  multiple = false,\n  maxSize,\n  onFilesChange,\n  disabled = false,\n  hint,\n  children,\n  ...props\n}: Omit<React.ComponentProps<\"button\">, \"type\"> &\n  VariantProps<typeof fileUploadVariants> & {\n    accept?: string\n    multiple?: boolean\n    maxSize?: number\n    onFilesChange?: (files: File[]) => void\n    hint?: React.ReactNode\n  }) {\n  const inputRef = React.useRef<HTMLInputElement>(null)\n  /* dragenter/dragleave also fire for descendants, so a plain boolean flickers.\n     Counting entries keeps the state stable while the pointer crosses children. */\n  const dragDepth = React.useRef(0)\n  const [dragging, setDragging] = React.useState(false)\n  const [errors, setErrors] = React.useState<string[]>([])\n\n  function processFiles(incoming: File[]) {\n    if (incoming.length === 0) return\n\n    if (!multiple && incoming.length > 1) {\n      setErrors([\"Only one file can be uploaded at a time.\"])\n      return\n    }\n\n    const accepted: File[] = []\n    const rejected: string[] = []\n\n    for (const file of incoming) {\n      if (!matchesAccept(file, accept)) {\n        rejected.push(`${file.name} is not an accepted file type.`)\n        continue\n      }\n      if (maxSize != null && file.size > maxSize) {\n        rejected.push(\n          `${file.name} is ${formatBytes(file.size)} — the limit is ${formatBytes(maxSize)}.`\n        )\n        continue\n      }\n      accepted.push(file)\n    }\n\n    setErrors(rejected)\n    if (accepted.length > 0) onFilesChange?.(accepted)\n  }\n\n  function handleChange(event: React.ChangeEvent<HTMLInputElement>) {\n    processFiles(Array.from(event.target.files ?? []))\n    /* Reset so picking the same file twice still fires a change. */\n    event.target.value = \"\"\n  }\n\n  function handleDragEnter(event: React.DragEvent<HTMLButtonElement>) {\n    event.preventDefault()\n    if (disabled) return\n    dragDepth.current += 1\n    setDragging(true)\n  }\n\n  function handleDragOver(event: React.DragEvent<HTMLButtonElement>) {\n    event.preventDefault()\n    if (disabled || !event.dataTransfer) return\n    event.dataTransfer.dropEffect = \"copy\"\n  }\n\n  function handleDragLeave(event: React.DragEvent<HTMLButtonElement>) {\n    event.preventDefault()\n    if (disabled) return\n    dragDepth.current = Math.max(0, dragDepth.current - 1)\n    if (dragDepth.current === 0) setDragging(false)\n  }\n\n  function handleDrop(event: React.DragEvent<HTMLButtonElement>) {\n    event.preventDefault()\n    dragDepth.current = 0\n    setDragging(false)\n    if (disabled) return\n    processFiles(Array.from(event.dataTransfer?.files ?? []))\n  }\n\n  const acceptLabel = formatAcceptLabel(accept)\n  const resolvedHint =\n    hint ??\n    [acceptLabel, maxSize != null ? `max. ${formatBytes(maxSize)}` : null]\n      .filter(Boolean)\n      .join(\" · \")\n\n  return (\n    <div data-slot=\"file-upload\" className=\"flex w-full flex-col gap-2\">\n      <input\n        ref={inputRef}\n        data-slot=\"file-upload-input\"\n        type=\"file\"\n        accept={accept}\n        multiple={multiple}\n        disabled={disabled}\n        tabIndex={-1}\n        aria-hidden=\"true\"\n        className=\"sr-only\"\n        onChange={handleChange}\n      />\n\n      {/* The zone itself is the button: click, Enter and Space all open the\n          picker for free, and the focus ring lands on the visible box. */}\n      <button\n        data-slot=\"file-upload-dropzone\"\n        type=\"button\"\n        data-size={size}\n        data-dragging={dragging ? \"true\" : \"false\"}\n        disabled={disabled}\n        className={cn(fileUploadVariants({ size }), className)}\n        {...props}\n        onClick={() => inputRef.current?.click()}\n        onDragEnter={handleDragEnter}\n        onDragOver={handleDragOver}\n        onDragLeave={handleDragLeave}\n        onDrop={handleDrop}\n      >\n        {children ?? (\n          <>\n            {/* Explicit radius — a token radius would round this into a circle. */}\n            <span\n              data-slot=\"file-upload-tile\"\n              aria-hidden=\"true\"\n              className=\"flex size-12 shrink-0 items-center justify-center rounded-[14px] bg-secondary text-muted-foreground shadow-soft ring-1 ring-foreground/[0.035] transition-colors duration-fast ease-out-expo group-data-[size=lg]/file-upload:size-14 group-data-[size=lg]/file-upload:rounded-[16px] group-data-[size=sm]/file-upload:size-10 group-data-[size=sm]/file-upload:rounded-[12px] group-data-[dragging=true]/file-upload:bg-selected/12 group-data-[dragging=true]/file-upload:text-selected group-data-[dragging=true]/file-upload:duration-spring-press group-data-[dragging=true]/file-upload:ease-spring-press [&_svg]:size-5 group-data-[size=lg]/file-upload:[&_svg]:size-6 group-data-[size=sm]/file-upload:[&_svg]:size-4.5\"\n            >\n              <UploadIcon />\n            </span>\n            <span className=\"text-body leading-snug font-medium text-foreground\">\n              Click to upload{\" \"}\n              <span className=\"font-normal text-muted-foreground\">\n                or drag and drop\n              </span>\n            </span>\n            {resolvedHint ? (\n              <span\n                data-slot=\"file-upload-hint\"\n                className=\"text-caption leading-snug text-muted-foreground\"\n              >\n                {resolvedHint}\n              </span>\n            ) : null}\n          </>\n        )}\n      </button>\n\n      {/* Always in the DOM so the live region is registered before it fills —\n          role=\"alert\" already implies assertive, so no aria-live beside it. */}\n      <div data-slot=\"file-upload-error\" role=\"alert\" className=\"empty:hidden\">\n        {errors.length > 0 ? (\n          <ul className=\"flex flex-col gap-1\">\n            {errors.map((message, index) => (\n              <li\n                key={`${index}-${message}`}\n                className=\"text-caption leading-snug text-destructive animate-in fade-in-0 slide-in-from-top-[3px] blur-in-[3px] duration-spring-swap ease-spring-swap\"\n              >\n                {message}\n              </li>\n            ))}\n          </ul>\n        ) : null}\n      </div>\n    </div>\n  )\n}\n\n/* --------------------------------------------------------- FileUploadItem */\n\n/* Arrival for a row that has genuinely just landed — a drop resolving, a pick\n   coming back. Enter only: the row leaves when the consumer drops it from its\n   own state, and by then the node is already gone, so there is nothing left in\n   here for CSS to hold on to.\n\n   Opt-in for the same reason the badge entrance is. A list that was already on\n   screen when the page painted has not arrived, and a stack of rows dealing\n   themselves in on first load is the failure mode. Reach for it when the row\n   appears in response to something the user just did. */\nconst fileUploadItemAppear =\n  \"animate-in fade-in-0 slide-in-from-top-[6px] blur-in-[3px] duration-spring-swap ease-spring-swap\"\n\n/* A row in the uploaded-file list — belongs inside a <ul>. */\nfunction FileUploadItem({\n  className,\n  name,\n  size,\n  progress,\n  status,\n  error,\n  appear = false,\n  onRemove,\n  children,\n  ...props\n}: React.ComponentProps<\"li\"> & {\n  name: string\n  size?: number\n  progress?: number\n  status?: \"uploading\" | \"complete\" | \"error\"\n  error?: string\n  /* Play the entrance on mount. For rows that arrive, not ones that were\n     already listed when the page loaded. */\n  appear?: boolean\n  onRemove?: () => void\n}) {\n  const state =\n    status ??\n    (error\n      ? \"error\"\n      : progress != null && progress < 100\n        ? \"uploading\"\n        : \"complete\")\n  const percent = Math.min(100, Math.max(0, progress ?? 0))\n  const sizeLabel = typeof size === \"number\" ? formatBytes(size) : null\n  const meta =\n    state === \"uploading\" && progress != null\n      ? [sizeLabel, `${Math.round(percent)}%`].filter(Boolean).join(\" · \")\n      : (sizeLabel ?? \"\")\n  const extension = fileExtension(name)\n\n  return (\n    <li\n      data-slot=\"file-upload-item\"\n      data-status={state}\n      className={cn(\n        \"group/file-upload-item flex w-full list-none items-center gap-3 rounded-xl border border-border bg-card p-3 shadow-soft transition-colors duration-base ease-out-expo data-[status=error]:border-destructive/25 data-[status=error]:bg-destructive/5\",\n        appear && fileUploadItemAppear,\n        className\n      )}\n      {...props}\n    >\n      {/* File-type squircle — explicit radius so it never reads as a circle. */}\n      <span\n        data-slot=\"file-upload-item-tile\"\n        aria-hidden=\"true\"\n        className=\"flex size-10 shrink-0 items-center justify-center rounded-[12px] bg-secondary text-micro font-semibold tracking-[0.02em] text-muted-foreground ring-1 ring-foreground/[0.035] transition-colors duration-base ease-out-expo group-data-[status=error]/file-upload-item:bg-destructive/10 group-data-[status=error]/file-upload-item:text-destructive group-data-[status=uploading]/file-upload-item:bg-selected/10 group-data-[status=uploading]/file-upload-item:text-selected [&_svg]:size-5\"\n      >\n        {extension ?? <FileIcon />}\n      </span>\n\n      <div className=\"flex min-w-0 flex-1 flex-col gap-1.5\">\n        <div className=\"flex items-baseline gap-2\">\n          <span className=\"truncate text-body leading-snug font-medium text-foreground\">\n            {name}\n          </span>\n          <span className=\"ml-auto shrink-0 text-caption tabular-nums text-muted-foreground empty:hidden\">\n            {meta}\n          </span>\n        </div>\n\n        {state === \"uploading\" ? (\n          <Progress\n            value={percent}\n            aria-label={`Uploading ${name}`}\n            className=\"h-1.5\"\n          />\n        ) : null}\n\n        {state === \"error\" && error ? (\n          <span className=\"text-caption leading-snug text-destructive\">\n            {error}\n          </span>\n        ) : null}\n\n        {children}\n      </div>\n\n      {onRemove ? (\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"icon-sm\"\n          className=\"shrink-0 text-muted-foreground hover:text-foreground\"\n          onClick={onRemove}\n          aria-label={`Remove ${name}`}\n        >\n          <XIcon />\n        </Button>\n      ) : null}\n    </li>\n  )\n}\n\nexport { FileUpload, FileUploadItem, fileUploadVariants }\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}