{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "file-drop-zone",
  "type": "registry:ui",
  "title": "File Drop Zone",
  "author": "Rishabh Bose <https://theb0se.vercel.app/>",
  "description": "An illustrated file upload card built around an animated folder. The folder opens when you drag a file over it, the paper sinks in as the upload progresses, and a green check pops on when it finishes.",
  "dependencies": [
    "framer-motion"
  ],
  "files": [
    {
      "path": "components/ui/file-drop-zone.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { DragEvent, KeyboardEvent } from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"framer-motion\";\n\n/**\n * FolderDropzone — a file upload card built around an illustrated folder.\n *\n * idle       dashed card, folder closed, a sliver of paper peeking out\n * dragging   card goes solid, folder opens, the paper rises out of it\n * rejected   rose border pulse, unsupported file type feedback\n * uploading  progress traces the card border, the paper sinks in as bytes land\n * done       paper is inside, a green check pops onto the folder\n * error      rose border, click to retry\n *\n * Works out of the box with a simulated upload. Pass `onUpload` to wire a real one.\n */\n\ntype Status = \"idle\" | \"dragging\" | \"rejected\" | \"uploading\" | \"done\" | \"error\";\n\nexport interface FileDropzoneProps {\n  /**\n   * Perform the real upload. Call `onProgress(loadedBytes)` as bytes are sent.\n   * Resolve when finished, reject to show the error state.\n   * Omit it to get a simulated upload.\n   */\n  onUpload?: (\n    files: File[],\n    onProgress: (loadedBytes: number) => void,\n    signal: AbortSignal\n  ) => Promise<void>;\n  /** Passed to the native file input, e.g. \"image/*,.pdf\" */\n  accept?: string;\n  multiple?: boolean;\n  /** Show the \"or try sample files\" link under the card */\n  showSamples?: boolean;\n  /** ms to wait on the success state before going back to idle. 0 keeps it. */\n  resetAfter?: number;\n  className?: string;\n}\n\n/* ---------- palette (folder illustration) ---------- */\n\nconst BACK = \"#3a63d8\";\nconst LIP = \"#2f55c0\";\nconst FRONT_TOP = \"#5d8cf2\";\nconst FRONT_BOTTOM = \"#4a7be6\";\nconst SUCCESS = \"#1f6b3a\";\n\n/* ---------- helpers ---------- */\n\nconst plural = (n: number) => (n === 1 ? \"1 file\" : `${n} files`);\n\nconst formatBytes = (bytes: number) => {\n  if (bytes < 1024) return `${bytes} B`;\n  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;\n  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n};\n\nconst wait = (ms: number, signal: AbortSignal) =>\n  new Promise<void>((resolve, reject) => {\n    const id = setTimeout(resolve, ms);\n    signal.addEventListener(\"abort\", () => {\n      clearTimeout(id);\n      reject(new DOMException(\"Aborted\", \"AbortError\"));\n    });\n  });\n\n/**\n * Parse the `accept` prop into a set of MIME types and extensions for\n * client-side validation. Handles wildcards like `image/*`.\n */\nfunction parseAccept(accept: string | undefined): {\n  mimeTypes: string[];\n  extensions: string[];\n  wildcards: string[];\n} | null {\n  if (!accept) return null;\n  const parts = accept\n    .split(\",\")\n    .map((s) => s.trim().toLowerCase())\n    .filter(Boolean);\n  if (!parts.length) return null;\n\n  const mimeTypes: string[] = [];\n  const extensions: string[] = [];\n  const wildcards: string[] = [];\n\n  for (const part of parts) {\n    if (part.startsWith(\".\")) {\n      extensions.push(part);\n    } else if (part.endsWith(\"/*\")) {\n      wildcards.push(part.replace(\"/*\", \"/\"));\n    } else {\n      mimeTypes.push(part);\n    }\n  }\n  return { mimeTypes, extensions, wildcards };\n}\n\n/**\n * Return `true` when at least one file in `items` would be accepted.\n * During `dragenter`/`dragover` we only have access to `DataTransferItem`,\n * which exposes `type` (MIME) but not the file name / extension — so\n * extension-only filters can't be fully validated until drop.\n */\nfunction dragItemsMatchAccept(\n  items: DataTransferItemList | undefined,\n  parsed: ReturnType<typeof parseAccept>\n): boolean {\n  if (!parsed || !items || items.length === 0) return true;\n\n  // If the accept list is extension-only we can't validate during drag\n  if (!parsed.mimeTypes.length && !parsed.wildcards.length) return true;\n\n  for (let i = 0; i < items.length; i++) {\n    const t = items[i].type.toLowerCase();\n    if (!t) continue; // type unknown during drag — don't reject\n    if (parsed.mimeTypes.includes(t)) return true;\n    if (parsed.wildcards.some((w) => t.startsWith(w))) return true;\n  }\n  return false;\n}\n\nfunction filesMatchAccept(\n  files: File[],\n  parsed: ReturnType<typeof parseAccept>\n): boolean {\n  if (!parsed || !files.length) return true;\n\n  for (const file of files) {\n    const t = file.type.toLowerCase();\n    const name = file.name.toLowerCase();\n    const ext = name.includes(\".\") ? `.${name.split(\".\").pop()}` : \"\";\n\n    if (parsed.mimeTypes.includes(t)) return true;\n    if (parsed.wildcards.some((w) => t.startsWith(w))) return true;\n    if (ext && parsed.extensions.includes(ext)) return true;\n  }\n  return false;\n}\n\n/** Human-readable label from the `accept` prop, e.g. \"images, .pdf\" */\nfunction humanAccept(accept: string | undefined): string {\n  if (!accept) return \"files\";\n  const parts = accept\n    .split(\",\")\n    .map((s) => s.trim())\n    .filter(Boolean);\n\n  return parts\n    .map((p) => {\n      if (p.startsWith(\".\")) return p;\n      if (p === \"image/*\") return \"images\";\n      if (p === \"video/*\") return \"videos\";\n      if (p === \"audio/*\") return \"audio\";\n      if (p === \"application/pdf\") return \".pdf\";\n      if (p === \"text/*\") return \"text files\";\n      return p;\n    })\n    .join(\", \");\n}\n\n/** Fake upload: eases to 100% over ~2.6s, then \"finishes\" for a beat. */\nasync function simulateUpload(\n  total: number,\n  onProgress: (loaded: number) => void,\n  signal: AbortSignal\n) {\n  const duration = 2600;\n  const startedAt = performance.now();\n  await new Promise<void>((resolve, reject) => {\n    const tick = () => {\n      if (signal.aborted) return reject(new DOMException(\"Aborted\", \"AbortError\"));\n      const p = Math.min(1, (performance.now() - startedAt) / duration);\n      onProgress(Math.round(total * (1 - Math.pow(1 - p, 1.6))));\n      if (p < 1) requestAnimationFrame(tick);\n      else resolve();\n    };\n    requestAnimationFrame(tick);\n  });\n  await wait(700, signal);\n}\n\n/* ---------- component ---------- */\n\nexport function FileDropzone({\n  onUpload,\n  accept,\n  multiple = true,\n  showSamples = true,\n  resetAfter = 2500,\n  className = \"\",\n}: FileDropzoneProps) {\n  const reduceMotion = useReducedMotion();\n  const inputRef = useRef<HTMLInputElement>(null);\n  const abortRef = useRef<AbortController | null>(null);\n  const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const dragDepth = useRef(0);\n\n  const [status, setStatus] = useState<Status>(\"idle\");\n  const [dragCount, setDragCount] = useState(1);\n  const [info, setInfo] = useState({ count: 0, total: 0 });\n  const [loaded, setLoaded] = useState(0);\n\n  const parsedAccept = parseAccept(accept);\n\n  useEffect(\n    () => () => {\n      abortRef.current?.abort();\n      if (resetTimer.current) clearTimeout(resetTimer.current);\n    },\n    []\n  );\n\n  const start = useCallback(\n    async (incoming: File[]) => {\n      const files = multiple ? incoming : incoming.slice(0, 1);\n      if (!files.length) return;\n\n      // Validate file types on drop / file-pick\n      if (!filesMatchAccept(files, parsedAccept)) {\n        setStatus(\"rejected\");\n        if (resetTimer.current) clearTimeout(resetTimer.current);\n        resetTimer.current = setTimeout(() => setStatus(\"idle\"), 2200);\n        return;\n      }\n\n      const total = files.reduce((sum, f) => sum + f.size, 0) || 1;\n      if (resetTimer.current) clearTimeout(resetTimer.current);\n      abortRef.current?.abort();\n      const ctrl = new AbortController();\n      abortRef.current = ctrl;\n\n      setInfo({ count: files.length, total });\n      setLoaded(0);\n      setStatus(\"uploading\");\n\n      try {\n        if (onUpload) await onUpload(files, setLoaded, ctrl.signal);\n        else await simulateUpload(total, setLoaded, ctrl.signal);\n\n        setLoaded(total);\n        setStatus(\"done\");\n        if (resetAfter > 0) {\n          resetTimer.current = setTimeout(() => setStatus(\"idle\"), resetAfter);\n        }\n      } catch (err) {\n        if ((err as Error)?.name === \"AbortError\") return;\n        setStatus(\"error\");\n      }\n    },\n    [multiple, onUpload, resetAfter, parsedAccept]\n  );\n\n  /* ----- drag & drop ----- */\n\n  const busy = status === \"uploading\";\n\n  const onDragEnter = (e: DragEvent<HTMLDivElement>) => {\n    e.preventDefault();\n    if (busy) return;\n    dragDepth.current += 1;\n    const itemCount = Math.max(1, e.dataTransfer?.items?.length ?? 1);\n    setDragCount(itemCount);\n\n    // Check file types during drag\n    if (!dragItemsMatchAccept(e.dataTransfer?.items, parsedAccept)) {\n      setStatus(\"rejected\");\n    } else {\n      setStatus(\"dragging\");\n    }\n  };\n\n  const onDragOver = (e: DragEvent<HTMLDivElement>) => e.preventDefault();\n\n  const onDragLeave = (e: DragEvent<HTMLDivElement>) => {\n    e.preventDefault();\n    if (busy) return;\n    dragDepth.current = Math.max(0, dragDepth.current - 1);\n    if (dragDepth.current === 0) setStatus(\"idle\");\n  };\n\n  const onDrop = (e: DragEvent<HTMLDivElement>) => {\n    e.preventDefault();\n    dragDepth.current = 0;\n    if (busy) return;\n    start(Array.from(e.dataTransfer.files));\n  };\n\n  /* ----- click / keyboard ----- */\n\n  const browse = () => {\n    if (!busy) inputRef.current?.click();\n  };\n\n  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n    if (e.key === \"Enter\" || e.key === \" \") {\n      e.preventDefault();\n      browse();\n    }\n  };\n\n  const trySamples = () => {\n    if (busy) return;\n    const sample = new File([new Uint8Array(230 * 1024)], \"sample-photo.jpg\", {\n      type: \"image/jpeg\",\n    });\n    start([sample]);\n  };\n\n  /* ----- derived values ----- */\n\n  const pct = Math.min(1, loaded / info.total || 0);\n  const finishing = status === \"uploading\" && pct >= 1;\n  const acceptLabel = humanAccept(accept);\n\n  const [title, subtitle] = {\n    idle: [\n      multiple ? \"drop files to upload\" : \"drop a file to upload\",\n      \"or click to browse\",\n    ],\n    dragging: [`drop ${plural(dragCount)}`, \"let go to upload\"],\n    rejected: [\n      \"unsupported file type\",\n      `only ${acceptLabel} allowed`,\n    ],\n    uploading: [\n      `uploading ${plural(info.count)}`,\n      finishing\n        ? \"finishing\"\n        : `${Math.round(pct * 100)}%, ${formatBytes(loaded)} of ${formatBytes(info.total)}`,\n    ],\n    done: [`${plural(info.count)} uploaded`, formatBytes(info.total)],\n    error: [\"upload failed\", \"click to try again\"],\n  }[status];\n\n  const open = status === \"dragging\";\n  const docY =\n    status === \"dragging\"\n      ? 2\n      : status === \"uploading\"\n        ? 6 + pct * 32\n        : status === \"done\"\n          ? 38\n          : 27; // idle / error / rejected: just a sliver above the flap\n\n  const cardTone = {\n    idle: \"border-dashed border-zinc-300 dark:border-zinc-700\",\n    dragging:\n      \"border-solid border-zinc-400 shadow-xl shadow-zinc-300/40 scale-[1.015] dark:border-zinc-500 dark:shadow-black/40\",\n    rejected:\n      \"border-solid border-rose-400 shadow-lg shadow-rose-200/30 animate-[shake_0.35s_ease-in-out] dark:border-rose-500 dark:shadow-rose-900/30\",\n    uploading: \"border-solid border-zinc-200 dark:border-zinc-800\",\n    done: \"border-solid border-emerald-700/40 dark:border-emerald-500/40\",\n    error: \"border-solid border-rose-400 dark:border-rose-500\",\n  }[status];\n\n  const spring = reduceMotion\n    ? { duration: 0 }\n    : { type: \"spring\" as const, stiffness: 260, damping: 24 };\n\n  return (\n    <div className={`flex w-full max-w-xs sm:max-w-sm flex-col items-center gap-3 sm:gap-4 ${className}`}>\n      <div\n        role=\"button\"\n        tabIndex={0}\n        aria-disabled={busy}\n        aria-label=\"Upload files. Drop files here or press Enter to browse.\"\n        onClick={browse}\n        onKeyDown={onKeyDown}\n        onDragEnter={onDragEnter}\n        onDragOver={onDragOver}\n        onDragLeave={onDragLeave}\n        onDrop={onDrop}\n        className={[\n          \"relative flex aspect-[3/2] w-full select-none flex-col items-center justify-center\",\n          \"rounded-2xl sm:rounded-[22px] border-[1.5px] bg-white shadow-sm dark:bg-zinc-900\",\n          \"outline-none transition-[border-color,box-shadow,transform] duration-200\",\n          \"focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2\",\n          busy ? \"cursor-default\" : \"cursor-pointer\",\n          cardTone,\n        ].join(\" \")}\n      >\n        {/* progress traced around the border */}\n        <svg\n          className=\"pointer-events-none absolute inset-0 h-full w-full\"\n          viewBox=\"0 0 280 190\"\n          preserveAspectRatio=\"none\"\n          fill=\"none\"\n          aria-hidden=\"true\"\n        >\n          <motion.rect\n            x={0.75}\n            y={0.75}\n            width={278.5}\n            height={188.5}\n            rx={21.5}\n            strokeWidth={1.5}\n            strokeLinecap=\"round\"\n            className=\"stroke-zinc-500 dark:stroke-zinc-300\"\n            initial={false}\n            animate={{\n              pathLength: status === \"uploading\" ? pct : 0,\n              opacity: status === \"uploading\" ? 1 : 0,\n            }}\n            transition={{ duration: reduceMotion ? 0 : 0.2, ease: \"linear\" }}\n          />\n        </svg>\n\n        {/* folder */}\n        <motion.svg\n          viewBox=\"0 0 120 100\"\n          className=\"w-[38%] sm:w-[43%] overflow-visible\"\n          aria-hidden=\"true\"\n          animate={status === \"done\" && !reduceMotion ? { y: [0, -4, 0] } : { y: 0 }}\n          transition={{ duration: 0.45, ease: \"easeOut\" }}\n        >\n          <defs>\n            <linearGradient id=\"fd-front\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n              <stop offset=\"0\" stopColor={FRONT_TOP} />\n              <stop offset=\"1\" stopColor={FRONT_BOTTOM} />\n            </linearGradient>\n          </defs>\n\n          {/* ground shadow */}\n          <ellipse cx={60} cy={89} rx={40} ry={3} fill=\"#000\" opacity={0.07} />\n\n          {/* back panel with tab */}\n          <path\n            fill={BACK}\n            d=\"M14 76 V20 A5 5 0 0 1 19 15 H40 A5 5 0 0 1 43.5 16.5 L47 20 A5 5 0 0 0 50.5 21.5 H101 A5 5 0 0 1 106 26.5 V76 Z\"\n          />\n\n          {/* paper */}\n          <motion.g initial={false} animate={{ y: docY }} transition={spring}>\n            <rect\n              x={28}\n              y={0}\n              width={64}\n              height={40}\n              rx={3}\n              fill=\"#ffffff\"\n              stroke=\"#dfe5f2\"\n              strokeWidth={0.6}\n            />\n            <rect x={34} y={7} width={6} height={6} rx={1.5} fill={BACK} />\n            <rect x={45} y={7.5} width={26} height={1.8} rx={0.9} fill=\"#c9d2e6\" />\n            <rect x={45} y={11.5} width={16} height={1.4} rx={0.7} fill=\"#e0e5f0\" />\n            <rect x={34} y={21} width={52} height={1.6} rx={0.8} fill=\"#e0e5f0\" />\n            <rect x={34} y={26} width={40} height={1.6} rx={0.8} fill=\"#e0e5f0\" />\n          </motion.g>\n\n          {/* darker lip, only visible when the flap lowers */}\n          <motion.rect\n            x={10}\n            y={74}\n            width={100}\n            height={9}\n            rx={4}\n            fill={LIP}\n            initial={false}\n            animate={{ opacity: open ? 1 : 0 }}\n            transition={{ duration: 0.2 }}\n          />\n\n          {/* front flap */}\n          <motion.rect\n            x={10}\n            y={32}\n            width={100}\n            height={48}\n            rx={7}\n            fill=\"url(#fd-front)\"\n            style={{ originY: 0 }}\n            initial={false}\n            animate={{ scaleY: open ? 0.93 : 1 }}\n            transition={spring}\n          />\n\n          {/* success badge */}\n          <AnimatePresence>\n            {status === \"done\" && (\n              <motion.g\n                key=\"badge\"\n                style={{ originX: 0.5, originY: 0.5 }}\n                initial={{ scale: 0, opacity: 0 }}\n                animate={{ scale: 1, opacity: 1 }}\n                exit={{ scale: 0, opacity: 0 }}\n                transition={\n                  reduceMotion ? { duration: 0 } : { type: \"spring\", stiffness: 420, damping: 18 }\n                }\n              >\n                <circle cx={60} cy={57} r={10} fill={SUCCESS} stroke=\"#fff\" strokeWidth={2} />\n                <motion.path\n                  d=\"M55 57.5 L58.5 61 L65 53.5\"\n                  fill=\"none\"\n                  stroke=\"#fff\"\n                  strokeWidth={2.2}\n                  strokeLinecap=\"round\"\n                  strokeLinejoin=\"round\"\n                  initial={{ pathLength: 0 }}\n                  animate={{ pathLength: 1 }}\n                  transition={{ delay: reduceMotion ? 0 : 0.12, duration: reduceMotion ? 0 : 0.25 }}\n                />\n              </motion.g>\n            )}\n          </AnimatePresence>\n\n          {/* rejected X badge */}\n          <AnimatePresence>\n            {status === \"rejected\" && (\n              <motion.g\n                key=\"rejected-badge\"\n                style={{ originX: 0.5, originY: 0.5 }}\n                initial={{ scale: 0, opacity: 0 }}\n                animate={{ scale: 1, opacity: 1 }}\n                exit={{ scale: 0, opacity: 0 }}\n                transition={\n                  reduceMotion ? { duration: 0 } : { type: \"spring\", stiffness: 420, damping: 18 }\n                }\n              >\n                <circle cx={60} cy={57} r={10} fill=\"#e11d48\" stroke=\"#fff\" strokeWidth={2} />\n                <motion.path\n                  d=\"M55.5 52.5 L64.5 61.5 M64.5 52.5 L55.5 61.5\"\n                  fill=\"none\"\n                  stroke=\"#fff\"\n                  strokeWidth={2.2}\n                  strokeLinecap=\"round\"\n                  initial={{ pathLength: 0 }}\n                  animate={{ pathLength: 1 }}\n                  transition={{ delay: reduceMotion ? 0 : 0.08, duration: reduceMotion ? 0 : 0.2 }}\n                />\n              </motion.g>\n            )}\n          </AnimatePresence>\n        </motion.svg>\n\n        {/* copy */}\n        <div className=\"mt-2 sm:mt-3 flex flex-col items-center px-3 text-center\" aria-live=\"polite\">\n          <AnimatePresence mode=\"wait\" initial={false}>\n            <motion.span\n              key={`t-${status}`}\n              className={[\n                \"text-[13px] sm:text-[15px] font-medium leading-5\",\n                status === \"rejected\"\n                  ? \"text-rose-600 dark:text-rose-400\"\n                  : \"text-zinc-800 dark:text-zinc-100\",\n              ].join(\" \")}\n              initial={{ opacity: 0, y: 4 }}\n              animate={{ opacity: 1, y: 0 }}\n              exit={{ opacity: 0, y: -4 }}\n              transition={{ duration: reduceMotion ? 0 : 0.14 }}\n            >\n              {title}\n            </motion.span>\n          </AnimatePresence>\n          <AnimatePresence mode=\"wait\" initial={false}>\n            <motion.span\n              key={`s-${status}-${finishing}`}\n              className={[\n                \"mt-0.5 text-[11px] sm:text-[13px] leading-5 tabular-nums\",\n                status === \"rejected\"\n                  ? \"text-rose-400 dark:text-rose-500\"\n                  : \"text-zinc-400 dark:text-zinc-500\",\n              ].join(\" \")}\n              initial={{ opacity: 0 }}\n              animate={{ opacity: 1 }}\n              exit={{ opacity: 0 }}\n              transition={{ duration: reduceMotion ? 0 : 0.14 }}\n            >\n              {subtitle}\n            </motion.span>\n          </AnimatePresence>\n        </div>\n\n        <input\n          ref={inputRef}\n          type=\"file\"\n          className=\"hidden\"\n          tabIndex={-1}\n          multiple={multiple}\n          accept={accept}\n          onClick={(e) => e.stopPropagation()}\n          onChange={(e) => {\n            start(Array.from(e.target.files ?? []));\n            e.target.value = \"\";\n          }}\n        />\n      </div>\n\n      {showSamples && (\n        <button\n          type=\"button\"\n          onClick={trySamples}\n          disabled={busy}\n          className=\"rounded text-[12px] sm:text-[13px] text-zinc-400 transition-colors hover:text-zinc-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500 disabled:pointer-events-none disabled:opacity-50 dark:text-zinc-500 dark:hover:text-zinc-300\"\n        >\n          or try sample files\n        </button>\n      )}\n\n      {/* shake keyframes injected once */}\n      <style>{`\n        @keyframes shake {\n          0%, 100% { transform: translateX(0); }\n          20% { transform: translateX(-4px); }\n          40% { transform: translateX(4px); }\n          60% { transform: translateX(-3px); }\n          80% { transform: translateX(2px); }\n        }\n      `}</style>\n    </div>\n  );\n}\n\nexport { FileDropzone as FileDropZone };\nexport default FileDropzone;\n",
      "type": "registry:ui",
      "target": "components/ui/file-drop-zone.tsx"
    }
  ]
}
