{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dropzone",
  "title": "Dropzone",
  "author": "gridcn",
  "description": "Dependency-free file dropzone: drag and drop or click to choose, with accept, size, and count checks and a compact variant. Used by the data-grid-io import dialog.",
  "dependencies": [
    "lucide-react@^1.46.0"
  ],
  "files": [
    {
      "path": "registry/default/blocks/dropzone/dropzone.tsx",
      "content": "\"use client\";\n\nimport { createContext, useCallback, useContext, useId, useRef, useState, type DragEvent, type KeyboardEvent, type ReactNode } from \"react\";\nimport { Upload } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\n/** Maps a MIME type to the file extensions that count as a match, e.g. `{ \"text/csv\": [\".csv\"] }`. */\nexport type DropzoneAccept = Record<string, string[]>;\n\n/** The extensions `accept` lists once each, or its MIME types when it lists no extension. */\nexport function acceptedTypeNames(accept: DropzoneAccept): string[] {\n  const extensions = [...new Set(Object.values(accept).flat())];\n  return extensions.length > 0 ? extensions : Object.keys(accept);\n}\n\n/** The MIME types and extensions of `accept` for a native file input's `accept` attribute. */\nfunction inputAcceptValue(accept: DropzoneAccept): string | undefined {\n  const tokens = [...new Set([...Object.keys(accept), ...Object.values(accept).flat()])];\n  return tokens.length > 0 ? tokens.join(\",\") : undefined;\n}\n\n/** One reason a file was rejected; a file can carry more than one. */\nexport type DropzoneRejectionReason = \"accept\" | \"maxSize\" | \"minSize\" | \"maxFiles\";\n\n/** A file `Dropzone` rejected, with every rule it failed. */\nexport type DropzoneRejection = { file: File; reasons: DropzoneRejectionReason[] };\n\n/** True when `file` matches `accept` by MIME type (exact or `type/*` wildcard) or by extension. */\nexport function matchesAccept(file: File, accept: DropzoneAccept): boolean {\n  if (Object.keys(accept).length === 0) return true;\n  const name = file.name.toLowerCase();\n  const type = file.type.toLowerCase();\n  for (const [mime, extensions] of Object.entries(accept)) {\n    if (mime === \"*/*\") return true;\n    if (mime.endsWith(\"/*\") && type.startsWith(mime.slice(0, -1))) return true;\n    if (type !== \"\" && type === mime.toLowerCase()) return true;\n    if (extensions.some((ext) => name.endsWith(ext.toLowerCase()))) return true;\n  }\n  return false;\n}\n\n/** Options for {@link filterFiles}. */\nexport type FilterFilesOptions = {\n  accept?: DropzoneAccept;\n  maxSize?: number;\n  minSize?: number;\n  maxFiles?: number;\n};\n\n/** Result of {@link filterFiles}. */\nexport type FilterFilesResult = { accepted: File[]; rejections: DropzoneRejection[] };\n\n/**\n * Splits `files` into accepted and rejected by `accept` (MIME or extension), `minSize`/`maxSize`\n * (bytes), and `maxFiles` (a count over the limit rejects the excess files, keeping file order).\n */\nexport function filterFiles(files: readonly File[], options: FilterFilesOptions = {}): FilterFilesResult {\n  const { accept, maxSize, minSize, maxFiles } = options;\n  const accepted: File[] = [];\n  const rejections: DropzoneRejection[] = [];\n\n  for (const file of files) {\n    const reasons: DropzoneRejectionReason[] = [];\n    if (accept && !matchesAccept(file, accept)) reasons.push(\"accept\");\n    if (maxSize !== undefined && file.size > maxSize) reasons.push(\"maxSize\");\n    if (minSize !== undefined && file.size < minSize) reasons.push(\"minSize\");\n    if (reasons.length > 0) {\n      rejections.push({ file, reasons });\n      continue;\n    }\n    accepted.push(file);\n  }\n\n  if (maxFiles !== undefined && accepted.length > maxFiles) {\n    const overflow = accepted.splice(maxFiles);\n    rejections.push(...overflow.map((file) => ({ file, reasons: [\"maxFiles\"] as DropzoneRejectionReason[] })));\n  }\n\n  return { accepted, rejections };\n}\n\ntype DropzoneContextValue = {\n  files?: File[];\n  isDragActive: boolean;\n  disabled: boolean;\n  accept?: DropzoneAccept;\n  maxSize?: number;\n};\n\nconst DropzoneContext = createContext<DropzoneContextValue | null>(null);\n\nfunction useDropzoneContext(component: string): DropzoneContextValue {\n  const context = useContext(DropzoneContext);\n  if (!context) throw new Error(`${component} must be rendered inside <Dropzone>`);\n  return context;\n}\n\nfunction defaultDescription(typeNames: string[], maxSize: number | undefined): string {\n  const types = typeNames.length > 0 ? `Accepted file types: ${typeNames.join(\", \")}.` : \"All file types accepted.\";\n  return maxSize === undefined ? types : `${types} Up to ${formatBytes(maxSize)}.`;\n}\n\n/** Props for {@link Dropzone}. */\nexport type DropzoneProps = {\n  className?: string;\n  children?: ReactNode;\n  /** MIME-to-extensions map filtering which files are accepted; omit to accept every file. */\n  accept?: DropzoneAccept;\n  /** Maximum number of files accepted per drop/pick; also sets the file input's `multiple` (true unless this is 1). Default unlimited. */\n  maxFiles?: number;\n  /** Maximum file size in bytes. */\n  maxSize?: number;\n  /** Minimum file size in bytes. */\n  minSize?: number;\n  disabled?: boolean;\n  /** Called with accepted files and any rejections after a drop or a file-picker selection. */\n  onDrop?: (acceptedFiles: File[], rejections: DropzoneRejection[]) => void;\n  /** Currently held files, for `DropzoneContent`'s default rendering. */\n  files?: File[];\n  /** Screen-reader description of the accepted file types and the size limit. Default: an English text built from `accept` and `maxSize`. */\n  accessibleDescription?: string;\n  /** Accessible name for the drop surface. */\n  \"aria-label\"?: string;\n  /** Id of the element that names the drop surface; used instead of `aria-label` when both are set. */\n  \"aria-labelledby\"?: string;\n  /** Single-row layout (icon + content inline) instead of the tall centered box — for reuse in a compact spot, e.g. next to an existing preview. Default false. */\n  compact?: boolean;\n};\n\n/**\n * Dependency-free file drop zone: native HTML5 drag-and-drop plus a hidden file input, no\n * react-dropzone. Renders `children` (default {@link DropzoneEmptyState} and\n * {@link DropzoneContent}) inside a focusable `role=\"button\"` surface. Click or Enter/Space opens\n * the native picker; a drag-enter/leave depth counter keeps the active state from flickering when\n * the pointer crosses a child element.\n */\nexport function Dropzone(props: DropzoneProps): ReactNode {\n  const { className, children, accept, maxFiles, maxSize, minSize, disabled = false, onDrop, files, accessibleDescription, compact = false, ...rest } = props;\n  const [isDragActive, setIsDragActive] = useState(false);\n  const dragDepthRef = useRef(0);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const inputId = useId();\n  const typeNames = accept ? acceptedTypeNames(accept) : [];\n\n  const emit = useCallback(\n    (picked: FileList | null) => {\n      if (!picked || picked.length === 0) return;\n      const { accepted, rejections } = filterFiles(Array.from(picked), { accept, maxSize, minSize, maxFiles });\n      onDrop?.(accepted, rejections);\n    },\n    [accept, maxSize, minSize, maxFiles, onDrop],\n  );\n\n  const openPicker = useCallback(() => {\n    if (disabled) return;\n    inputRef.current?.click();\n  }, [disabled]);\n\n  const onKeyDown = useCallback(\n    (event: KeyboardEvent<HTMLDivElement>) => {\n      if (event.key !== \"Enter\" && event.key !== \" \") return;\n      event.preventDefault();\n      openPicker();\n    },\n    [openPicker],\n  );\n\n  const onDragEnter = useCallback(\n    (event: DragEvent<HTMLDivElement>) => {\n      event.preventDefault();\n      if (disabled) return;\n      dragDepthRef.current += 1;\n      setIsDragActive(true);\n    },\n    [disabled],\n  );\n\n  const onDragOver = useCallback(\n    (event: DragEvent<HTMLDivElement>) => {\n      event.preventDefault();\n    },\n    [],\n  );\n\n  const onDragLeave = useCallback(\n    (event: DragEvent<HTMLDivElement>) => {\n      event.preventDefault();\n      dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);\n      if (dragDepthRef.current === 0) setIsDragActive(false);\n    },\n    [],\n  );\n\n  const onDropHandler = useCallback(\n    (event: DragEvent<HTMLDivElement>) => {\n      event.preventDefault();\n      dragDepthRef.current = 0;\n      setIsDragActive(false);\n      if (disabled) return;\n      emit(event.dataTransfer?.files ?? null);\n    },\n    [disabled, emit],\n  );\n\n  return (\n    <DropzoneContext.Provider value={{ files, isDragActive, disabled, accept, maxSize }}>\n      <div\n        role=\"button\"\n        tabIndex={disabled ? -1 : 0}\n        aria-disabled={disabled}\n        aria-label={rest[\"aria-label\"]}\n        aria-labelledby={rest[\"aria-labelledby\"]}\n        aria-describedby={`${inputId}-description`}\n        onClick={openPicker}\n        onKeyDown={onKeyDown}\n        onDragEnter={onDragEnter}\n        onDragOver={onDragOver}\n        onDragLeave={onDragLeave}\n        onDrop={onDropHandler}\n        data-drag-active={isDragActive || undefined}\n        data-disabled={disabled || undefined}\n        className={cn(\n          \"flex w-full cursor-pointer rounded-md border border-dashed border-input outline-none transition-colors\",\n          compact\n            ? \"min-h-9 flex-row items-center gap-2 px-2 py-1.5 text-start\"\n            : \"min-h-40 flex-col items-center justify-center gap-2 p-6 text-center\",\n          \"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2\",\n          isDragActive && \"border-primary bg-primary/5 ring-2 ring-primary/20\",\n          disabled && \"cursor-not-allowed opacity-50\",\n          className,\n        )}\n      >\n        <input\n          ref={inputRef}\n          id={inputId}\n          type=\"file\"\n          className=\"hidden\"\n          disabled={disabled}\n          multiple={maxFiles !== 1}\n          accept={accept ? inputAcceptValue(accept) : undefined}\n          // input.click() bubbles a real click back up to this element's own onClick=openPicker —\n          // without stopping it here, opening the picker fires it a second time.\n          onClick={(event) => event.stopPropagation()}\n          onChange={(event) => {\n            emit(event.target.files);\n            event.target.value = \"\";\n          }}\n        />\n        <span id={`${inputId}-description`} className=\"sr-only\">\n          {accessibleDescription ?? defaultDescription(typeNames, maxSize)}\n        </span>\n        {children ?? (\n          <>\n            <DropzoneEmptyState />\n            <DropzoneContent />\n          </>\n        )}\n      </div>\n    </DropzoneContext.Provider>\n  );\n}\n\n/** Formats a byte count as a short human-readable size (e.g. \"1.5 MB\"). */\nfunction formatBytes(bytes: number): string {\n  if (bytes < 1024) return `${bytes} B`;\n  const units = [\"KB\", \"MB\", \"GB\"];\n  let value = bytes / 1024;\n  let unitIndex = 0;\n  while (value >= 1024 && unitIndex < units.length - 1) {\n    value /= 1024;\n    unitIndex += 1;\n  }\n  return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unitIndex]}`;\n}\n\n/** Props for {@link DropzoneEmptyState}. */\nexport type DropzoneEmptyStateProps = { title?: string; description?: string };\n\n/** Default idle-state contents of {@link Dropzone}: icon, title, and an accepted-types/size caption. */\nexport function DropzoneEmptyState(props: DropzoneEmptyStateProps): ReactNode {\n  const { title = \"Upload a file\", description } = props;\n  const { files, accept, maxSize } = useDropzoneContext(\"DropzoneEmptyState\");\n  const typeNames = accept ? acceptedTypeNames(accept) : [];\n  if (files && files.length > 0) return null;\n\n  const caption =\n    description ??\n    [\n      \"Drag and drop or click to upload\",\n      typeNames.length > 0 ? typeNames.join(\", \") : undefined,\n      maxSize !== undefined ? `up to ${formatBytes(maxSize)}` : undefined,\n    ]\n      .filter(Boolean)\n      .join(\" — \");\n\n  return (\n    <>\n      <Upload className=\"size-8 text-muted-foreground\" aria-hidden=\"true\" />\n      <p className=\"text-sm font-medium text-foreground\">{title}</p>\n      <p className=\"text-xs text-muted-foreground\">{caption}</p>\n    </>\n  );\n}\n\n/** Props for {@link DropzoneContent}. */\nexport type DropzoneContentProps = { children?: ReactNode };\n\n/** Default held-files contents of {@link Dropzone}: one line per file in `files`, hidden until `files` is non-empty. */\nexport function DropzoneContent(props: DropzoneContentProps): ReactNode {\n  const { children } = props;\n  const { files } = useDropzoneContext(\"DropzoneContent\");\n  if (!files || files.length === 0) return null;\n  if (children) return <>{children}</>;\n\n  return (\n    <ul className=\"flex w-full flex-col gap-1 text-start\">\n      {files.map((file, index) => (\n        <li key={`${file.name}-${index}`} className=\"truncate text-sm text-foreground\">\n          <span>{file.name}</span> <span className=\"text-xs text-muted-foreground\">({formatBytes(file.size)})</span>\n        </li>\n      ))}\n    </ul>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dropzone/dropzone.tsx"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}