{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"file-upload","type":"registry:block","title":"File upload","description":"A dropzone with click-to-browse, size validation, and file rows that animate a simulated upload to completion.","dependencies":["motion","lucide-react"],"registryDependencies":["utils"],"files":[{"path":"registry/prequel/file-upload/file-upload.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState, type ChangeEvent, type DragEvent } from \"react\";\nimport {\n  AnimatePresence,\n  MotionConfig,\n  motion,\n  useInView,\n  useReducedMotion,\n} from \"motion/react\";\nimport { Check, FileText, Upload, X } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\nconst MAX_SIZE = 25 * 1024 * 1024;\n\n/* ------------------------------------------------------------------ */\n/* types                                                               */\n/* ------------------------------------------------------------------ */\n\nexport type UploadFile = {\n  id: string;\n  name: string;\n  /** Size in bytes. */\n  size: number;\n  /** Upload progress from 0 to 100. */\n  progress: number;\n};\n\nexport type FileUploadProps = {\n  className?: string;\n  title?: string;\n  description?: string;\n  /** Comma-separated extensions or MIME types. */\n  accept?: string;\n  multiple?: boolean;\n  /** Maximum size per file, in bytes. */\n  maxSize?: number;\n  initialFiles?: UploadFile[];\n  /** Called when files are added or removed. */\n  onFilesChange?: (files: UploadFile[]) => void;\n};\n\n/* ------------------------------------------------------------------ */\n/* demo data                                                           */\n/* ------------------------------------------------------------------ */\n\nconst DEFAULT_FILES: UploadFile[] = [\n  {\n    id: \"northwind-q4-revenue\",\n    name: \"northwind-q4-revenue.csv\",\n    size: 248_320,\n    progress: 100,\n  },\n  {\n    id: \"brand-assets\",\n    name: \"brand-assets.zip\",\n    size: 8_412_160,\n    progress: 64,\n  },\n];\n\n/* ------------------------------------------------------------------ */\n/* helpers                                                             */\n/* ------------------------------------------------------------------ */\n\nfunction formatBytes(bytes: number) {\n  if (bytes <= 0) return \"0 B\";\n  const units = [\"B\", \"KB\", \"MB\", \"GB\"];\n  const index = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));\n  const value = bytes / Math.pow(1024, index);\n  return `${value >= 10 || index === 0 ? Math.round(value) : value.toFixed(1)} ${units[index]}`;\n}\n\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.startsWith(\".\")) return name.endsWith(token);\n    if (token.endsWith(\"/*\")) return type.startsWith(token.slice(0, -1));\n    return type === token;\n  });\n}\n\n/* ------------------------------------------------------------------ */\n/* block                                                               */\n/* ------------------------------------------------------------------ */\n\nexport function FileUpload({\n  className,\n  title = \"Upload documents\",\n  description = \"Contracts, invoices and exports, all in one place.\",\n  accept = \".csv,.pdf,.zip\",\n  multiple = true,\n  maxSize = MAX_SIZE,\n  initialFiles = DEFAULT_FILES,\n  onFilesChange,\n}: FileUploadProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const nextId = useRef(0);\n  const inView = useInView(ref, { once: true, margin: \"-10% 0px\" });\n  const reduce = Boolean(useReducedMotion());\n\n  const [files, setFiles] = useState<UploadFile[]>(initialFiles);\n  const [dragging, setDragging] = useState(false);\n  const [error, setError] = useState<string | null>(null);\n\n  const hasPending = files.some((file) => file.progress < 100);\n  const totalSize = files.reduce((sum, file) => sum + file.size, 0);\n\n  useEffect(() => {\n    if (!hasPending) return;\n    const timer = setInterval(() => {\n      setFiles((current) =>\n        current.map((file) =>\n          file.progress >= 100 ? file : { ...file, progress: Math.min(100, file.progress + 9) }\n        )\n      );\n    }, 450);\n    return () => clearInterval(timer);\n  }, [hasPending]);\n\n  const addFiles = (list: FileList | File[]) => {\n    const incoming = Array.from(list);\n    const accepted: UploadFile[] = [];\n    let rejection: string | null = null;\n\n    for (const file of incoming) {\n      if (file.size > maxSize) {\n        rejection = `${file.name} is ${formatBytes(file.size)} — the limit is ${formatBytes(maxSize)}.`;\n        continue;\n      }\n      if (!matchesAccept(file, accept)) {\n        rejection = `${file.name} is not an accepted file type.`;\n        continue;\n      }\n      nextId.current += 1;\n      accepted.push({\n        id: `${file.name}-${nextId.current}`,\n        name: file.name,\n        size: file.size,\n        progress: 0,\n      });\n    }\n\n    if (accepted.length === 0) {\n      setError(rejection);\n      return;\n    }\n\n    const next = multiple ? [...accepted, ...files] : accepted.slice(0, 1);\n    setFiles(next);\n    setError(rejection);\n    onFilesChange?.(next);\n  };\n\n  const removeFile = (id: string) => {\n    const next = files.filter((file) => file.id !== id);\n    setFiles(next);\n    setError(null);\n    onFilesChange?.(next);\n  };\n\n  const handleInput = (event: ChangeEvent<HTMLInputElement>) => {\n    if (event.target.files) addFiles(event.target.files);\n    event.target.value = \"\";\n  };\n\n  const handleDrop = (event: DragEvent<HTMLButtonElement>) => {\n    event.preventDefault();\n    setDragging(false);\n    if (event.dataTransfer.files.length > 0) addFiles(event.dataTransfer.files);\n  };\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div ref={ref} className={cn(\"w-full\", className)}>\n        <motion.div\n          initial={{ opacity: 0, y: reduce ? 0 : 16 }}\n          animate={{ opacity: inView ? 1 : 0, y: 0 }}\n          transition={{ duration: reduce ? 0 : 0.55, ease: EASE }}\n          className=\"rounded-xl border border-border bg-card p-5 text-card-foreground shadow-sm sm:p-6\"\n        >\n          <div className=\"flex flex-wrap items-start justify-between gap-x-4 gap-y-2\">\n            <div className=\"min-w-0\">\n              <h2 className=\"text-[15px] font-semibold tracking-tight\">{title}</h2>\n              <p className=\"mt-0.5 text-[12.5px] leading-5 text-muted-foreground\">{description}</p>\n            </div>\n            <p className=\"shrink-0 text-[11.5px] tabular-nums text-muted-foreground\">\n              {files.length} {files.length === 1 ? \"file\" : \"files\"} · {formatBytes(totalSize)}\n            </p>\n          </div>\n\n          <input\n            ref={inputRef}\n            type=\"file\"\n            accept={accept}\n            multiple={multiple}\n            onChange={handleInput}\n            className=\"hidden\"\n          />\n\n          <motion.button\n            type=\"button\"\n            onClick={() => inputRef.current?.click()}\n            onDragOver={(event) => {\n              event.preventDefault();\n              setDragging(true);\n            }}\n            onDragLeave={() => setDragging(false)}\n            onDrop={handleDrop}\n            initial={{ opacity: 0, y: reduce ? 0 : 8 }}\n            animate={{ opacity: inView ? 1 : 0, y: 0 }}\n            transition={{ duration: reduce ? 0 : 0.5, ease: EASE, delay: reduce ? 0 : 0.08 }}\n            className={cn(\n              \"mt-4 flex w-full flex-col items-center justify-center rounded-lg border border-dashed px-4 py-7 text-center transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card\",\n              dragging\n                ? \"border-foreground/40 bg-muted/60\"\n                : \"border-border bg-muted/20 hover:border-foreground/25 hover:bg-muted/40\"\n            )}\n          >\n            <span className=\"flex h-9 w-9 items-center justify-center rounded-full border border-border bg-background text-foreground\">\n              <Upload className=\"h-4 w-4\" aria-hidden=\"true\" />\n            </span>\n            <span className=\"mt-2.5 text-[13px] font-medium text-foreground\">\n              Drop files here, or browse\n            </span>\n            <span className=\"mt-0.5 text-[11.5px] text-muted-foreground\">\n              {accept.replace(/\\./g, \"\").replace(/,/g, \", \").toUpperCase()} · up to{\" \"}\n              {formatBytes(maxSize)} each\n            </span>\n          </motion.button>\n\n          <div className=\"min-h-[18px]\" aria-live=\"polite\">\n            {error ? (\n              <p role=\"alert\" className=\"mt-2 text-[11.5px] leading-5 text-destructive\">\n                {error}\n              </p>\n            ) : null}\n          </div>\n\n          {files.length > 0 ? (\n            <ul className=\"mt-1 flex flex-col gap-2\">\n              <AnimatePresence initial={false}>\n                {files.map((file) => {\n                  const complete = file.progress >= 100;\n                  return (\n                    <motion.li\n                      key={file.id}\n                      layout\n                      initial={reduce ? false : { opacity: 0, y: 6 }}\n                      animate={{ opacity: 1, y: 0 }}\n                      exit={{ opacity: 0 }}\n                      transition={{ duration: reduce ? 0 : 0.3, ease: EASE }}\n                      className=\"flex items-center gap-3 rounded-md border border-border bg-background px-3 py-2.5\"\n                    >\n                      <span\n                        className={cn(\n                          \"flex h-8 w-8 shrink-0 items-center justify-center rounded-md border\",\n                          complete\n                            ? \"border-success/25 bg-success/10 text-success\"\n                            : \"border-border bg-muted/40 text-muted-foreground\"\n                        )}\n                      >\n                        {complete ? (\n                          <Check className=\"h-4 w-4\" strokeWidth={3} aria-hidden=\"true\" />\n                        ) : (\n                          <FileText className=\"h-4 w-4\" aria-hidden=\"true\" />\n                        )}\n                      </span>\n\n                      <div className=\"min-w-0 flex-1\">\n                        <div className=\"flex items-baseline justify-between gap-3\">\n                          <p className=\"truncate text-[12.5px] font-medium text-foreground\">\n                            {file.name}\n                          </p>\n                          <span className=\"shrink-0 text-[11px] tabular-nums text-muted-foreground\">\n                            {formatBytes(file.size)}\n                          </span>\n                        </div>\n\n                        <div className=\"mt-1.5 flex items-center gap-2\">\n                          <div className=\"h-1 min-w-0 flex-1 overflow-hidden rounded-full bg-muted\">\n                            <motion.div\n                              aria-hidden=\"true\"\n                              initial={false}\n                              animate={{ scaleX: file.progress / 100 }}\n                              transition={{ duration: reduce ? 0 : 0.3, ease: EASE }}\n                              style={{ transformOrigin: \"left center\" }}\n                              className={cn(\n                                \"h-full rounded-full\",\n                                complete ? \"bg-success\" : \"bg-foreground\"\n                              )}\n                            />\n                          </div>\n                          <span\n                            className={cn(\n                              \"w-10 shrink-0 text-right text-[10.5px] tabular-nums\",\n                              complete ? \"text-success\" : \"text-muted-foreground\"\n                            )}\n                          >\n                            {complete ? \"Done\" : `${file.progress}%`}\n                          </span>\n                        </div>\n                      </div>\n\n                      <button\n                        type=\"button\"\n                        onClick={() => removeFile(file.id)}\n                        aria-label={`Remove ${file.name}`}\n                        className=\"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card\"\n                      >\n                        <X className=\"h-3.5 w-3.5\" aria-hidden=\"true\" />\n                      </button>\n                    </motion.li>\n                  );\n                })}\n              </AnimatePresence>\n            </ul>\n          ) : (\n            <p className=\"mt-2 text-center text-[11.5px] text-muted-foreground\">\n              Nothing uploaded yet.\n            </p>\n          )}\n\n          <p className=\"mt-4 border-t border-border pt-3 text-[11px] text-muted-foreground\">\n            Files are private to this workspace and expire after 30 days.\n          </p>\n        </motion.div>\n      </div>\n    </MotionConfig>\n  );\n}\n\nexport default FileUpload;\n"}]}