{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"file-dropzone","type":"registry:component","title":"File dropzone","description":"Its dashed edge marches when a file enters the window and seals solid when it is overhead.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/file-dropzone.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// A demo: files are only read for their name and size, and the \"upload\" is\n// a timer. Nothing is sent anywhere and nothing leaves the browser.\n\ntype Entry = { id: number; name: string; size: number };\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\nconst ENTER = { duration: 0.25, ease: EASE_OUT };\nconst LEAVE = { duration: 0.15, ease: EASE_OUT };\nconst INSTANT = { duration: 0 };\n// One progress update this often, each eased with a 300ms transition, so the\n// bar moves in the uneven surges of a real upload instead of a smooth ramp.\nconst TICK = 280;\n\n// The edge's length in pathLength units: 120 dash-and-gap pairs of one unit\n// each, about 12px apiece on the 440 x 300 zone. A whole number, so the\n// pattern always meets itself cleanly where the path starts and ends.\nconst EDGE_LENGTH = 120;\n// Marching loops, so keyframes; each loop moves the dashes exactly one\n// period, so it repeats without a hitch. Closing the gaps is a transition,\n// so a file that leaves mid-seal reverses from wherever it got to.\nconst CSS = `\n@keyframes dz-march { to { stroke-dashoffset: -1; } }\n.dz-edge {\n  stroke-dasharray: 0.5 0.5;\n  transition: stroke-dasharray 240ms cubic-bezier(0.23, 1, 0.32, 1), color 150ms ease-out;\n}\n@media (hover: hover) and (pointer: fine) {\n  .dz-zone:hover .dz-edge[data-state=\"idle\"] { animation: dz-march 1.6s linear infinite; }\n}\n.dz-edge[data-state=\"dragging\"] { animation: dz-march 0.6s linear infinite; }\n.dz-edge[data-state=\"over\"] { stroke-dasharray: 1 0; }\n@media (prefers-reduced-motion: reduce) {\n  .dz-edge { animation: none !important; }\n}\n`;\n\nfunction formatSize(bytes: number) {\n  if (bytes < 1024) return `${bytes} B`;\n  const units = [\"KB\", \"MB\", \"GB\"];\n  let value = bytes / 1024;\n  let unit = 0;\n  while (value >= 1024 && unit < units.length - 1) {\n    value /= 1024;\n    unit++;\n  }\n  return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;\n}\n\nfunction hasFiles(e: DragEvent | React.DragEvent) {\n  return !!e.dataTransfer?.types.includes(\"Files\");\n}\n\nexport function FileDropzone({\n  onFiles,\n  className,\n}: {\n  onFiles?: (files: File[]) => void;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const hintId = useId();\n  const [entries, setEntries] = useState<Entry[]>([]);\n  // Somewhere on the page vs over the zone itself: a hint, then an invitation.\n  const [dragging, setDragging] = useState(false);\n  const [over, setOver] = useState(false);\n  const [announcement, setAnnouncement] = useState(\"\");\n\n  const zoneRef = useRef<HTMLButtonElement>(null);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const removeRefs = useRef(new Map<number, HTMLButtonElement>());\n  const nextId = useRef(0);\n  // dragenter and dragleave fire for every child crossed, so a boolean\n  // would flicker off and on. Counting them only reaches 0 on a real exit.\n  const zoneDepth = useRef(0);\n\n  useEffect(() => {\n    let depth = 0;\n    const reset = () => {\n      depth = 0;\n      zoneDepth.current = 0;\n      setDragging(false);\n      setOver(false);\n    };\n    const enter = (e: DragEvent) => {\n      if (!hasFiles(e)) return;\n      if (++depth === 1) setDragging(true);\n    };\n    const leave = (e: DragEvent) => {\n      if (!hasFiles(e)) return;\n      depth = Math.max(0, depth - 1);\n      if (depth === 0) reset();\n    };\n    const dragover = (e: DragEvent) => {\n      if (!hasFiles(e)) return;\n      // Without this, a file dropped a few pixels off target would be opened\n      // by the browser, navigating away from the page.\n      e.preventDefault();\n      if (!zoneRef.current?.contains(e.target as Node) && e.dataTransfer) {\n        e.dataTransfer.dropEffect = \"none\";\n      }\n    };\n    const drop = (e: DragEvent) => {\n      if (!hasFiles(e)) return;\n      e.preventDefault();\n      reset();\n    };\n    window.addEventListener(\"dragenter\", enter);\n    window.addEventListener(\"dragleave\", leave);\n    window.addEventListener(\"dragover\", dragover);\n    window.addEventListener(\"drop\", drop);\n    return () => {\n      window.removeEventListener(\"dragenter\", enter);\n      window.removeEventListener(\"dragleave\", leave);\n      window.removeEventListener(\"dragover\", dragover);\n      window.removeEventListener(\"drop\", drop);\n    };\n  }, []);\n\n  const add = (list: FileList | null) => {\n    const files = Array.from(list ?? []);\n    if (files.length === 0) return;\n    setEntries((prev) => [\n      ...prev,\n      ...files.map((f) => ({\n        id: nextId.current++,\n        name: f.name,\n        size: f.size,\n      })),\n    ]);\n    setAnnouncement(\n      files.length === 1\n        ? `Added ${files[0].name}`\n        : `Added ${files.length} files`,\n    );\n    onFiles?.(files);\n  };\n\n  const remove = (entry: Entry) => {\n    const index = entries.findIndex((e) => e.id === entry.id);\n    const next = entries[index + 1] ?? entries[index - 1];\n    setEntries((prev) => prev.filter((e) => e.id !== entry.id));\n    setAnnouncement(`Removed ${entry.name}`);\n    // Focus would otherwise fall to the body with the removed button.\n    (next ? removeRefs.current.get(next.id) : zoneRef.current)?.focus();\n  };\n\n  return (\n    <div className={cn(\"flex w-[min(440px,100%)] flex-col gap-3\", className)}>\n      <button\n        ref={zoneRef}\n        type=\"button\"\n        aria-describedby={hintId}\n        onClick={() => inputRef.current?.click()}\n        onDragEnter={(e) => {\n          if (!hasFiles(e)) return;\n          if (++zoneDepth.current === 1) setOver(true);\n        }}\n        onDragLeave={(e) => {\n          if (!hasFiles(e)) return;\n          zoneDepth.current = Math.max(0, zoneDepth.current - 1);\n          if (zoneDepth.current === 0) setOver(false);\n        }}\n        onDragOver={(e) => {\n          if (!hasFiles(e)) return;\n          e.preventDefault();\n          e.dataTransfer.dropEffect = \"copy\";\n        }}\n        onDrop={(e) => {\n          e.preventDefault();\n          add(e.dataTransfer.files);\n        }}\n        className={cn(\n          \"dz-zone relative flex h-[300px] touch-manipulation flex-col items-center justify-center gap-4 rounded-[24px] px-6 text-center outline-hidden select-none\",\n          \"transition-[background-color,scale] duration-150 ease-out focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.99] motion-reduce:transition-[background-color]\",\n          over ? \"bg-foreground/5\" : dragging ? \"bg-foreground/[0.02]\" : \"\",\n        )}\n      >\n        <style href=\"file-dropzone\" precedence=\"default\">\n          {CSS}\n        </style>\n        {/* The dashed edge is drawn, not a CSS border, so its dashes can\n            move. At rest they sit still; a pointer over the zone sets them\n            slowly marching, a file anywhere on the page makes them hurry,\n            and a file right over the zone closes every gap into one solid\n            line: the zone sealing around what you are about to drop. */}\n        <svg\n          aria-hidden\n          className={cn(\n            \"pointer-events-none absolute inset-0 size-full overflow-visible\",\n            over\n              ? \"text-foreground\"\n              : dragging\n                ? \"text-foreground/45\"\n                : \"text-foreground/20 [.dz-zone:hover_&]:text-foreground/35\",\n          )}\n        >\n          <rect\n            x=\"1\"\n            y=\"1\"\n            rx=\"23\"\n            style={{ width: \"calc(100% - 2px)\", height: \"calc(100% - 2px)\" }}\n            pathLength={EDGE_LENGTH}\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth={2}\n            data-state={over ? \"over\" : dragging ? \"dragging\" : \"idle\"}\n            className=\"dz-edge\"\n          />\n        </svg>\n        {/* Lifts toward the cursor when a file is right over it, as if\n            reaching up to take it. */}\n        <svg\n          viewBox=\"0 0 24 24\"\n          className={cn(\n            \"size-8 text-foreground transition-[translate] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none\",\n            over && \"-translate-y-1.5 motion-reduce:translate-y-0\",\n          )}\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={1.5}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          aria-hidden\n        >\n          <path d=\"M12 15V4.5M7.75 8.5 12 4.25l4.25 4.25\" />\n          <path d=\"M4.75 14.5v3.25a2 2 0 0 0 2 2h10.5a2 2 0 0 0 2-2V14.5\" />\n        </svg>\n        <span className=\"flex flex-col gap-1\">\n          {/* Both labels share one cell and crossfade, so the zone never\n              reflows as a file passes over it. */}\n          <span className=\"grid text-base font-medium text-foreground\">\n            <span\n              className={cn(\n                \"col-start-1 row-start-1 transition-[opacity,filter] duration-150 ease-out\",\n                over && \"opacity-0 blur-[4px]\",\n              )}\n            >\n              Drop files here or click to browse\n            </span>\n            <span\n              aria-hidden\n              className={cn(\n                \"col-start-1 row-start-1 transition-[opacity,filter] duration-150 ease-out\",\n                !over && \"opacity-0 blur-[4px]\",\n              )}\n            >\n              Release to add\n            </span>\n          </span>\n          <span id={hintId} className=\"text-sm text-muted-foreground\">\n            Demo only, files never leave your device\n          </span>\n        </span>\n      </button>\n      <input\n        ref={inputRef}\n        type=\"file\"\n        multiple\n        hidden\n        onChange={(e) => {\n          add(e.target.files);\n          // Cleared so picking the same file again still fires a change.\n          e.target.value = \"\";\n        }}\n      />\n\n      {/* Grows downward from under the zone; past four rows it scrolls, so\n          the demo never grows without bound. */}\n      <motion.div\n        layoutScroll\n        className=\"max-h-[264px] overflow-y-auto overscroll-contain [scrollbar-width:thin]\"\n      >\n        <ul aria-label=\"Files\" className=\"relative flex flex-col\">\n          <AnimatePresence mode=\"popLayout\" initial={false}>\n            {entries.map((entry) => (\n              <motion.li\n                key={entry.id}\n                layout=\"position\"\n                initial={\n                  reduceMotion\n                    ? { opacity: 0 }\n                    : { opacity: 0, y: 6, filter: \"blur(4px)\" }\n                }\n                animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n                exit={\n                  reduceMotion\n                    ? { opacity: 0, transition: LEAVE }\n                    : { opacity: 0, scale: 0.98, transition: LEAVE }\n                }\n                transition={{\n                  ...ENTER,\n                  layout: reduceMotion ? INSTANT : ENTER,\n                }}\n              >\n                <FileRow\n                  entry={entry}\n                  reduceMotion={reduceMotion}\n                  removeRef={(el) => {\n                    if (el) removeRefs.current.set(entry.id, el);\n                    else removeRefs.current.delete(entry.id);\n                  }}\n                  onRemove={() => remove(entry)}\n                  onDone={() => setAnnouncement(`Uploaded ${entry.name}`)}\n                />\n              </motion.li>\n            ))}\n          </AnimatePresence>\n        </ul>\n      </motion.div>\n\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {announcement}\n      </span>\n    </div>\n  );\n}\n\nfunction FileRow({\n  entry,\n  reduceMotion,\n  removeRef,\n  onRemove,\n  onDone,\n}: {\n  entry: Entry;\n  reduceMotion: boolean | null;\n  removeRef: (el: HTMLButtonElement | null) => void;\n  onRemove: () => void;\n  onDone: () => void;\n}) {\n  const [progress, setProgress] = useState(0);\n  const [done, setDone] = useState(false);\n  const onDoneRef = useRef(onDone);\n\n  useEffect(() => {\n    onDoneRef.current = onDone;\n  });\n\n  useEffect(() => {\n    // Bigger files take more ticks: about one per 400 KB, between 5 and 16,\n    // so a small file is done in about 1.5s and none take more than ~5s.\n    const ticks = Math.min(16, Math.max(5, entry.size / 400_000));\n    let p = 0;\n    let timer: ReturnType<typeof setTimeout>;\n    const step = () => {\n      // One tick in six stalls, the way real uploads hang on a slow packet,\n      // and chunks shrink toward the end as the server finishes up.\n      const stall = Math.random() < 1 / 6;\n      const chunk = stall\n        ? 0\n        : ((0.6 + Math.random() * 0.8) / ticks) * (1.2 - p * 0.5);\n      p = Math.min(1, p + chunk);\n      setProgress(p);\n      if (p < 1) {\n        timer = setTimeout(step, TICK);\n      } else {\n        // Lets the bar finish its last surge before the check replaces it.\n        timer = setTimeout(() => {\n          setDone(true);\n          onDoneRef.current();\n        }, 300);\n      }\n    };\n    timer = setTimeout(step, 150);\n    return () => clearTimeout(timer);\n  }, [entry.size]);\n\n  const hidden = reduceMotion\n    ? { scale: 1, opacity: 0, filter: \"blur(0px)\" }\n    : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" };\n\n  return (\n    <div className=\"flex h-16 items-center gap-3 rounded-2xl pr-1 pl-3.5 transition-[background-color] duration-150 ease-out hover:bg-muted\">\n      <div className=\"flex min-w-0 flex-1 flex-col gap-1\">\n        <span className=\"truncate text-[15px] leading-5 font-medium text-foreground\">\n          {entry.name}\n        </span>\n        <div className=\"flex h-5 items-center gap-3 text-[13px] text-muted-foreground\">\n          <span className=\"shrink-0 tabular-nums\">\n            {formatSize(entry.size)}\n          </span>\n          {/* The bar and \"Uploaded\" share one cell and crossfade. */}\n          <span className=\"grid flex-1 items-center\">\n            <span\n              role=\"progressbar\"\n              aria-label={`Uploading ${entry.name}`}\n              aria-valuemin={0}\n              aria-valuemax={100}\n              aria-valuenow={Math.round(progress * 100)}\n              className={cn(\n                \"col-start-1 row-start-1 h-1 overflow-hidden rounded-full bg-foreground/10 transition-[opacity] duration-200 ease-out\",\n                done && \"opacity-0\",\n              )}\n            >\n              <span\n                className=\"block h-full origin-left rounded-full bg-foreground transition-[scale] duration-300 ease-[cubic-bezier(0.23,1,0.32,1)]\"\n                style={{ scale: `${progress} 1` }}\n              />\n            </span>\n            <span\n              className={cn(\n                \"col-start-1 row-start-1 transition-[opacity,filter] duration-200 ease-out\",\n                !done && \"opacity-0 blur-[4px]\",\n              )}\n            >\n              Uploaded\n            </span>\n          </span>\n        </div>\n      </div>\n\n      {/* Percentage while uploading, then the check, in one cell. */}\n      <span className=\"grid w-9 shrink-0 place-items-center text-[13px] text-muted-foreground tabular-nums\">\n        <span\n          aria-hidden\n          className={cn(\n            \"col-start-1 row-start-1 transition-[opacity,filter] duration-150 ease-out\",\n            done && \"opacity-0 blur-[4px]\",\n          )}\n        >\n          {Math.round(progress * 100)}%\n        </span>\n        <motion.svg\n          viewBox=\"0 0 16 16\"\n          className=\"col-start-1 row-start-1 size-4 text-foreground\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={1.5}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          aria-hidden\n          initial={false}\n          animate={\n            done ? { scale: 1, opacity: 1, filter: \"blur(0px)\" } : hidden\n          }\n          transition={ICON_SWAP}\n        >\n          <path d=\"m3.5 8.5 3 3 6-7\" />\n        </motion.svg>\n      </span>\n\n      <button\n        ref={removeRef}\n        type=\"button\"\n        aria-label={`Remove ${entry.name}`}\n        onClick={onRemove}\n        className=\"flex size-9 shrink-0 touch-manipulation items-center justify-center rounded-full text-muted-foreground outline-hidden transition-[scale,color,background-color] duration-150 ease-out select-none hover:bg-foreground/5 hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color,background-color]\"\n      >\n        <svg\n          viewBox=\"0 0 16 16\"\n          className=\"size-4\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={1.5}\n          strokeLinecap=\"round\"\n          aria-hidden\n        >\n          <path d=\"m4.75 4.75 6.5 6.5M11.25 4.75l-6.5 6.5\" />\n        </svg>\n      </button>\n    </div>\n  );\n}\n\nexport default function FileDropzoneDemo() {\n  return <FileDropzone />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/file-dropzone"}