{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "file-drop",
  "type": "registry:ui",
  "title": "File Drop",
  "description": "A place to hand over files: drop them on it or press it to pick, see what was chosen, take one back out. For a document with a request, photos for a gallery, a sheet to import.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "form",
    "primitive"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/cn.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/file-drop.tsx",
      "target": "components/ui/file-drop.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/file-drop v1.0.2 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/file-drop\n// What changed since: https://ds.interlace.tools/c/file-drop#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — FileDrop\n *\n * A place to hand over files: drop them on it or press it to pick, see what\n * was chosen, take one back out. For a document with a request, photos for a\n * gallery, a sheet to import.\n *\n * ## Content first\n *\n * Underneath is a real `<input type=\"file\">` inside a `<label>`, so the\n * picker opens on a press or on Enter and Space, a screen reader announces a\n * file field with its label, and the chosen files post with the form under\n * `name`. The drop area is that label, drawn larger: dropping files there is\n * a shortcut to the same field, never the only way in.\n *\n * ## Rules\n *\n * `accept`, `maxSize` and `maxFiles` are checked again on every pick and\n * drop by `file-model` (the picker's own filter only suggests, and a drop\n * skips it). A file that breaks a rule is not added; the reason is said in a\n * polite live region under the field (\"photo.heic isn't a type this field\n * takes\"), in words `messages` can replace. The same model can check the\n * files again on the server.\n *\n * ## The list\n *\n * Each chosen file is a row with its name, its size (`formatBytes`, in the\n * reader's locale) and a Remove button named for the file. Removing a file\n * moves focus to the next Remove button, or back to the field when the list\n * empties, so focus never falls to the page.\n *\n * ## Motion\n *\n * The drop area's border and tint answer a drag over it, timed by\n * `--duration-fast` on `--ease-enter`. Nothing else moves.\n *\n * ## MIN_VIEWPORT — 320\n *\n * ## Anatomy\n *\n *   FileDrop                      (div — data-slot=\"file-drop\", data-min-viewport=320)\n *     ├─ label                    (data-slot=\"file-drop-area\", data-dragging, data-disabled)\n *     │   ├─ input[type=file]     (unseen, laid over the area, which draws its focus ring)\n *     │   ├─ icon                 (aria-hidden)\n *     │   ├─ label text           (data-slot=\"file-drop-label\")\n *     │   └─ hint?                (data-slot=\"file-drop-hint\": what it takes, linked as the description)\n *     ├─ status                   (p aria-live=polite — data-slot=\"file-drop-status\": why a file was turned away)\n *     └─ ul?                      (data-slot=\"file-drop-list\")\n *         └─ li × n               (data-slot=\"file-drop-item\": name, size, Remove)\n *\n * | Rule | Concept                          | Where in this file                                     |\n * | ---- | -------------------------------- | ------------------------------------------------------ |\n * | R4   | Extends native el                | `div` props; the input is a native file input           |\n * | R6   | data-slot per part               | file-drop / -area / -label / -hint / -status / -list / -item |\n * | R7   | cn + ...rest                     | `cn(BASE, className)` + `{...props}`                    |\n * | R14  | Declares min viewport            | `data-min-viewport` + exported const                    |\n * | R19  | Tokens only                      | `--border` / `--input` / `--primary` / `--duration-*`   |\n * | R25  | Client component                 | drag state and the chosen files live in the browser     |\n * | R26  | A11y from native el              | label + file input; live status; named Remove buttons   |\n */\n\nimport { FileIcon, UploadIcon, XIcon } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { Button } from '@/components/ui/button';\nimport { checkFiles, formatBytes, type FileRejection, type FileRules } from '@/components/ui/file-model';\n\nexport { acceptsFile, checkFiles, formatBytes } from '@/components/ui/file-model';\nexport type { FileLike, FileRejection, FileRejectionReason, FileRules } from '@/components/ui/file-model';\n\n/** Smallest viable viewport (CSS px) for this primitive. */\nexport const MIN_VIEWPORT = 320 as const;\n\nexport interface FileDropMessages {\n  /** A file of a type the field doesn't take. */\n  type?: (file: File) => string;\n  /** A file over `maxSize`. */\n  size?: (file: File, maxSize: number) => string;\n  /** A file past `maxFiles`. */\n  count?: (file: File, maxFiles: number) => string;\n  /** The Remove button's name for one file. */\n  remove?: (file: File) => string;\n}\n\nconst DEFAULT_MESSAGES: Required<FileDropMessages> = {\n  type: (file) => `${file.name} isn't a type this field takes.`,\n  size: (file, max) => `${file.name} is larger than ${formatBytes(max)}.`,\n  count: (file, max) => `${file.name} wasn't added: this field takes ${max} ${max === 1 ? 'file' : 'files'}.`,\n  remove: (file) => `Remove ${file.name}`,\n};\n\nexport interface FileDropProps\n  extends Omit<React.ComponentPropsWithoutRef<'div'>, 'defaultValue' | 'onChange'>, FileRules {\n  /** What the area says, e.g. \"Drop a photo here, or choose one\". */\n  label: React.ReactNode;\n  /** One line under it on what the field takes, e.g. \"PNG or JPG, up to 5 MB\". */\n  hint?: React.ReactNode;\n  /** The field name the files post under with a form. */\n  name?: string;\n  /** Take more than one file. */\n  multiple?: boolean;\n  disabled?: boolean;\n  required?: boolean;\n  /** The chosen files (controlled). */\n  value?: File[];\n  /** The files chosen at first (uncontrolled). */\n  defaultValue?: File[];\n  /** Called with every chosen file after a pick, a drop or a removal. */\n  onValueChange?: (files: File[]) => void;\n  /** Called with the files a pick or drop turned away, and why. */\n  onReject?: (rejections: FileRejection<File>[]) => void;\n  /** The sentences said when a file is turned away, and the Remove button's name. */\n  messages?: FileDropMessages;\n  /** Locale for file sizes. Defaults to the reader's. */\n  locale?: string;\n}\n\n/** Put `files` on the input, so a form posts what the list shows. Skipped where DataTransfer can't be built. */\nfunction syncInput(input: HTMLInputElement | null, files: File[]) {\n  if (!input || typeof DataTransfer === 'undefined') return;\n  const transfer = new DataTransfer();\n  for (const file of files) transfer.items.add(file);\n  input.files = transfer.files;\n}\n\nexport function FileDrop({\n  label,\n  hint,\n  name,\n  multiple = false,\n  disabled = false,\n  required,\n  accept,\n  maxSize,\n  maxFiles,\n  value,\n  defaultValue,\n  onValueChange,\n  onReject,\n  messages,\n  locale,\n  className,\n  ...props\n}: FileDropProps) {\n  const id = React.useId();\n  const input = React.useRef<HTMLInputElement>(null);\n  const list = React.useRef<HTMLUListElement>(null);\n  const [own, setOwn] = React.useState<File[]>(defaultValue ?? []);\n  const files = value ?? own;\n  const [dragging, setDragging] = React.useState(false);\n  const [status, setStatus] = React.useState('');\n  const say = { ...DEFAULT_MESSAGES, ...messages };\n  const limit = multiple ? maxFiles : 1;\n\n  const commit = (next: File[]) => {\n    if (value === undefined) setOwn(next);\n    syncInput(input.current, next);\n    onValueChange?.(next);\n  };\n\n  const add = (incoming: File[]) => {\n    // One file at a time replaces the last; several add to the list.\n    const held = multiple ? files : [];\n    const { accepted, rejected } = checkFiles(incoming, { accept, maxSize, maxFiles: limit }, held.length);\n    commit([...held, ...accepted]);\n    setStatus(\n      rejected\n        .map(({ file, reason }) =>\n          reason === 'type' ? say.type(file) : reason === 'size' ? say.size(file, maxSize!) : say.count(file, limit!),\n        )\n        .join(' '),\n    );\n    if (rejected.length > 0) onReject?.(rejected);\n  };\n\n  const remove = (index: number) => {\n    const next = files.filter((_, i) => i !== index);\n    commit(next);\n    setStatus('');\n    // Focus the Remove button that takes this row's place, or the field when the list is empty.\n    requestFocus(index, next.length);\n  };\n\n  const [focusTarget, setFocusTarget] = React.useState<number | null>(null);\n  const requestFocus = (index: number, length: number) =>\n    setFocusTarget(length === 0 ? -1 : Math.min(index, length - 1));\n  React.useEffect(() => {\n    if (focusTarget === null) return;\n    const buttons = list.current?.querySelectorAll<HTMLButtonElement>('[data-slot=\"file-drop-remove\"]');\n    (focusTarget === -1 ? input.current : buttons?.[focusTarget])?.focus();\n    setFocusTarget(null);\n  }, [focusTarget]);\n\n  const hintId = hint ? `${id}-hint` : undefined;\n  const statusId = `${id}-status`;\n\n  return (\n    <div\n      data-slot=\"file-drop\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('flex flex-col gap-2', className)}\n      {...props}\n    >\n      <label\n        data-slot=\"file-drop-area\"\n        data-dragging={dragging ? '' : undefined}\n        data-disabled={disabled ? '' : undefined}\n        onDragEnter={(event) => {\n          if (disabled) return;\n          event.preventDefault();\n          setDragging(true);\n        }}\n        onDragOver={(event) => {\n          if (disabled) return;\n          // Without this the browser opens the file instead of dropping it here.\n          event.preventDefault();\n        }}\n        onDragLeave={(event) => {\n          if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;\n          setDragging(false);\n        }}\n        onDrop={(event) => {\n          if (disabled) return;\n          event.preventDefault();\n          setDragging(false);\n          add(Array.from(event.dataTransfer.files));\n        }}\n        className={cn(\n          'border-input bg-background text-foreground relative flex cursor-pointer flex-col items-center justify-center gap-1 rounded-xl border border-dashed px-4 py-8 text-center',\n          'transition-[border-color,background-color] duration-(--duration-fast) ease-enter hover:border-ring/60 hover:bg-muted/40',\n          'has-[input:focus-visible]:ring-2 has-[input:focus-visible]:ring-ring has-[input:focus-visible]:ring-offset-2 has-[input:focus-visible]:ring-offset-background',\n          'data-[dragging]:border-primary data-[dragging]:bg-primary/6',\n          'data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50',\n        )}\n      >\n        <input\n          ref={input}\n          type=\"file\"\n          name={name}\n          accept={accept}\n          multiple={multiple}\n          disabled={disabled}\n          required={required && files.length === 0}\n          aria-describedby={cn(hintId, status ? statusId : undefined) || undefined}\n          // Laid over the whole area, unseen, so the area's ring is the field's own focus ring and a\n          // check that looks around the focused element finds it.\n          className=\"absolute inset-0 size-full cursor-pointer opacity-0 disabled:cursor-not-allowed\"\n          onChange={(event) => {\n            const picked = Array.from(event.currentTarget.files ?? []);\n            if (picked.length > 0) add(picked);\n            else syncInput(event.currentTarget, files);\n          }}\n        />\n        <UploadIcon aria-hidden=\"true\" className=\"text-muted-foreground mb-1 size-6\" />\n        <span data-slot=\"file-drop-label\" className=\"font-medium\">\n          {label}\n        </span>\n        {hint ? (\n          <span id={hintId} data-slot=\"file-drop-hint\" className=\"text-muted-foreground text-sm\">\n            {hint}\n          </span>\n        ) : null}\n      </label>\n\n      <p\n        id={statusId}\n        data-slot=\"file-drop-status\"\n        aria-live=\"polite\"\n        className={cn('text-destructive text-sm', !status && 'sr-only')}\n      >\n        {status}\n      </p>\n\n      {files.length > 0 ? (\n        <ul ref={list} data-slot=\"file-drop-list\" className=\"flex flex-col gap-2\">\n          {files.map((file, index) => (\n            <li\n              key={`${file.name}-${file.size}-${index}`}\n              data-slot=\"file-drop-item\"\n              className=\"border-border bg-card text-card-foreground flex min-w-0 items-center gap-3 rounded-lg border py-2 ps-3 pe-2\"\n            >\n              <FileIcon aria-hidden=\"true\" className=\"text-muted-foreground size-4 shrink-0\" />\n              <span className=\"min-w-0 flex-1 break-words text-sm\">{file.name}</span>\n              <span className=\"text-muted-foreground shrink-0 text-sm tabular-nums\">\n                {formatBytes(file.size, locale)}\n              </span>\n              <Button\n                type=\"button\"\n                variant=\"ghost\"\n                size=\"icon-sm\"\n                data-slot=\"file-drop-remove\"\n                aria-label={say.remove(file)}\n                disabled={disabled}\n                onClick={() => remove(index)}\n              >\n                <XIcon aria-hidden=\"true\" />\n              </Button>\n            </li>\n          ))}\n        </ul>\n      ) : null}\n    </div>\n  );\n}\n"
    },
    {
      "path": "registry/interlace-ui/file-model.ts",
      "target": "components/ui/file-model.ts",
      "type": "registry:ui",
      "content": "export interface FileLike {\n  name: string;\n  size: number;\n  type: string;\n}\n\nexport type FileRejectionReason = 'type' | 'size' | 'count';\n\nexport interface FileRejection<F extends FileLike = FileLike> {\n  file: F;\n  reason: FileRejectionReason;\n}\n\nexport interface FileRules {\n  /** The `accept` attribute's value. Empty or missing takes every file. */\n  accept?: string;\n  /** The largest file, in bytes. Missing means no limit. */\n  maxSize?: number;\n  /** How many files the field holds in all. Missing means no limit. */\n  maxFiles?: number;\n}\n\nexport interface FileCheck<F extends FileLike = FileLike> {\n  accepted: F[];\n  rejected: FileRejection<F>[];\n}\n\n/** Whether `file` matches the `accept` attribute value. */\nexport function acceptsFile(file: FileLike, accept: string | undefined): boolean {\n  const patterns = (accept ?? '')\n    .split(',')\n    .map((p) => p.trim().toLowerCase())\n    .filter(Boolean);\n  if (patterns.length === 0) return true;\n  const name = file.name.toLowerCase();\n  const type = file.type.toLowerCase();\n  return patterns.some((pattern) => {\n    if (pattern.startsWith('.')) return name.endsWith(pattern);\n    if (pattern.endsWith('/*')) return type.startsWith(pattern.slice(0, -1));\n    return type === pattern;\n  });\n}\n\n/**\n * Sorts new files into those the field takes and those it turns away, and\n * why. `held` is how many files the field already holds, so `maxFiles`\n * counts them too. Files are taken in order until the field is full.\n */\nexport function checkFiles<F extends FileLike>(files: readonly F[], rules: FileRules = {}, held = 0): FileCheck<F> {\n  const accepted: F[] = [];\n  const rejected: FileRejection<F>[] = [];\n  for (const file of files) {\n    if (!acceptsFile(file, rules.accept)) rejected.push({ file, reason: 'type' });\n    else if (rules.maxSize !== undefined && file.size > rules.maxSize) rejected.push({ file, reason: 'size' });\n    else if (rules.maxFiles !== undefined && held + accepted.length >= rules.maxFiles)\n      rejected.push({ file, reason: 'count' });\n    else accepted.push(file);\n  }\n  return { accepted, rejected };\n}\n\nconst UNITS = ['byte', 'kilobyte', 'megabyte', 'gigabyte'] as const;\n\n/** A size as a person reads it: `512 bytes`, `2.4 MB`, in decimal units. */\nexport function formatBytes(bytes: number, locale?: string): string {\n  let value = Math.max(0, bytes);\n  let unit = 0;\n  while (value >= 1000 && unit < UNITS.length - 1) {\n    value /= 1000;\n    unit += 1;\n  }\n  return new Intl.NumberFormat(locale, {\n    style: 'unit',\n    unit: UNITS[unit],\n    unitDisplay: unit === 0 ? 'long' : 'short',\n    maximumFractionDigits: unit === 0 || value >= 100 ? 0 : 1,\n  }).format(value);\n}\n\n/**\n * @interlace/ui — file-model\n *\n * The rules a file picker applies before anything is uploaded: does the file\n * match what the field accepts, is it small enough, and is there room for\n * another. Pure, so a server can apply the same rules to the same files and\n * a reader is never told \"yes\" in the browser and \"no\" by the server.\n *\n * ## accept\n *\n * The same string the `accept` attribute takes, so one value serves both the\n * native picker and this check: comma-separated extensions (`.png`), exact\n * types (`image/png`) and wildcards (`image/*`). The native picker only\n * suggests; a drop, or a picker set to \"All files\", can hand over anything,\n * which is why the check runs again here. An empty `accept` takes every file.\n *\n * ## Sizes\n *\n * `formatBytes` writes a size the way a person reads one (`2.4 MB`), in\n * decimal units like the operating systems' own file browsers, in the\n * reader's locale.\n */\n\n/** What a file has that the rules read. A browser `File` fits. */\n\n// @interlace/file-model v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/file-model\n// What changed since: https://ds.interlace.tools/c/file-model#history\n// Generated banner — keep it, the upgrade diff reads this version.\n"
    }
  ],
  "meta": {
    "tier": "primitive",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.2",
    "since": null
  },
  "docs": "## @interlace/file-drop\n\nInstalled to `components/ui/file-drop.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/file-drop';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/file-drop\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
