{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "file-upload-13",
  "title": "Upload with progress",
  "description": "Each added file shows a progress bar until its simulated upload ends.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/progress.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-file-upload.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/file-upload/file-upload-13.tsx",
      "content": "'use client';\n\nimport {\n  AnimatePresence,\n  motion,\n  type Transition,\n  type Variants,\n} from 'motion/react';\nimport { useEffect, useRef, useState } from 'react';\n\nimport {\n  type FileMetadata,\n  type FileWithPreview,\n  formatBytes,\n  useFileUpload,\n} from '@/registry/ndeko/hooks/use-file-upload';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  CircleAlertIcon,\n  FileArchiveIcon,\n  FileIcon,\n  FileSpreadsheetIcon,\n  FileTextIcon,\n  HeadphonesIcon,\n  ImageIcon,\n  Trash2Icon,\n  UploadIcon,\n  VideoIcon,\n  XIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Progress } from '@/registry/ndeko/ui/progress';\n\nconst MAX_SIZE = 5 * 1024 * 1024;\nconst MAX_FILES = 6;\n\nconst FIRST_CHUNK_DELAY_MS = 100;\nconst MIN_CHUNK_BYTES = 2000;\nconst CHUNK_BYTES_SPREAD = 300000;\nconst MIN_CHUNK_DELAY_MS = 50;\nconst CHUNK_DELAY_SPREAD_MS = 450;\nconst CONGESTION_CHANCE = 0.05;\nconst CONGESTION_DELAY_MS = 500;\nconst FILLED_BAR_PAUSE_MS = 500;\n\nconst INITIAL_FILES: FileMetadata[] = [\n  {\n    name: 'q3-roadmap.zip',\n    size: 252873,\n    type: 'application/zip',\n    url: '',\n    id: 'q3-roadmap',\n  },\n  {\n    name: 'cover-draft.png',\n    size: 1528737,\n    type: 'image/png',\n    url: '',\n    id: 'cover-draft',\n  },\n  {\n    name: 'standup-notes.mp3',\n    size: 1528737,\n    type: 'audio/mpeg',\n    url: '',\n    id: 'standup-notes',\n  },\n];\n\nconst DOCUMENT_EXTENSIONS = ['.pdf', '.doc', '.docx'];\nconst ARCHIVE_EXTENSIONS = ['.zip', '.rar'];\nconst SPREADSHEET_EXTENSIONS = ['.xls', '.xlsx'];\nconst FILE_ICON_CLASS = 'size-4';\n\nconst DROP_ZONE = [\n  'relative flex min-h-52 flex-col items-center overflow-hidden rounded-xl p-4 not-data-files:justify-center',\n  'group hairline-border border-dashed border-foreground/20',\n  'transition-[background-color,border-color,scale] duration-200 ease-(--ease-out-strong)',\n  'data-dragging:scale-[1.01] motion-reduce:data-dragging:scale-100',\n  'data-dragging:border-primary/50 data-dragging:bg-primary/[0.04]',\n  'has-[input:focus-visible]:ring-[3px] has-[input:focus-visible]:ring-ring/25',\n].join(' ');\n\nconst ICON_TILE =\n  'keycap-3d text-muted-foreground mb-3 flex size-10 items-center justify-center rounded-full transition-transform duration-200 ease-(--ease-out-strong) group-data-dragging:-translate-y-0.5 motion-reduce:group-data-dragging:translate-y-0';\n\nconst ROW_ICON_TILE =\n  'keycap-3d text-muted-foreground flex size-10 shrink-0 items-center justify-center rounded-lg';\n\nconst FILE_ROW = 'bg-foreground/[0.04] flex flex-col rounded-xl p-2 pe-3';\n\nconst COUNT =\n  'keycap-3d inline-flex h-5 min-w-5 items-center justify-center rounded-[5px] px-1 text-[11px] font-medium tabular-nums text-muted-foreground';\n\nconst ENTER_TRANSITION: Transition = {\n  duration: 0.2,\n  ease: [0.23, 1, 0.32, 1],\n};\nconst EXIT_TRANSITION: Transition = {\n  duration: 0.15,\n  ease: [0.23, 1, 0.32, 1],\n};\n\nconst ITEM_VARIANTS: Variants = {\n  hidden: { height: 0, opacity: 0, transition: EXIT_TRANSITION },\n  shown: { height: 'auto', opacity: 1, transition: ENTER_TRANSITION },\n};\n\nconst FADE_VARIANTS: Variants = {\n  hidden: { opacity: 0, transition: EXIT_TRANSITION },\n  shown: { opacity: 1, transition: ENTER_TRANSITION },\n};\n\ntype UploadProgress = {\n  fileId: string;\n  progress: number;\n  completed: boolean;\n};\n\nfunction itemVariantsOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return FADE_VARIANTS;\n  }\n  return ITEM_VARIANTS;\n}\n\nfunction presenceOf(isPresent: boolean) {\n  if (isPresent) {\n    return true;\n  }\n  return undefined;\n}\n\nfunction hasExtension(name: string, extensions: string[]) {\n  return extensions.some((extension) => name.endsWith(extension));\n}\n\nfunction isDocument(type: string, name: string) {\n  const isDocumentType = type.includes('pdf') || type.includes('word');\n  const hasDocumentExtension = hasExtension(name, DOCUMENT_EXTENSIONS);\n  return isDocumentType || hasDocumentExtension;\n}\n\nfunction isArchive(type: string, name: string) {\n  const isArchiveType = type.includes('zip') || type.includes('archive');\n  const hasArchiveExtension = hasExtension(name, ARCHIVE_EXTENSIONS);\n  return isArchiveType || hasArchiveExtension;\n}\n\nfunction isSpreadsheet(type: string, name: string) {\n  const isSpreadsheetType = type.includes('excel') || type.includes('xlsx');\n  const hasSpreadsheetExtension = hasExtension(name, SPREADSHEET_EXTENSIONS);\n  return isSpreadsheetType || hasSpreadsheetExtension;\n}\n\nfunction fileIconOf(file: File | FileMetadata) {\n  const type = file.type;\n  const name = file.name.toLowerCase();\n  if (isDocument(type, name)) {\n    return <FileTextIcon className={FILE_ICON_CLASS} />;\n  }\n  if (isArchive(type, name)) {\n    return <FileArchiveIcon className={FILE_ICON_CLASS} />;\n  }\n  if (isSpreadsheet(type, name)) {\n    return <FileSpreadsheetIcon className={FILE_ICON_CLASS} />;\n  }\n  if (type.startsWith('video/')) {\n    return <VideoIcon className={FILE_ICON_CLASS} />;\n  }\n  if (type.startsWith('audio/')) {\n    return <HeadphonesIcon className={FILE_ICON_CLASS} />;\n  }\n  if (type.startsWith('image/')) {\n    return <ImageIcon className={FILE_ICON_CLASS} />;\n  }\n  return <FileIcon className={FILE_ICON_CLASS} />;\n}\n\nfunction nextChunkDelay() {\n  const spread = Math.random() * CHUNK_DELAY_SPREAD_MS;\n  const delay = Math.floor(spread);\n  const isCongested = Math.random() < CONGESTION_CHANCE;\n  if (isCongested) {\n    return MIN_CHUNK_DELAY_MS + delay + CONGESTION_DELAY_MS;\n  }\n  return MIN_CHUNK_DELAY_MS + delay;\n}\n\nfunction simulateUpload(\n  totalBytes: number,\n  onProgress: (progress: number) => void,\n  onComplete: () => void\n) {\n  let timeoutId = 0;\n  let uploadedBytes = 0;\n  let lastReportedProgress = 0;\n\n  function sendChunk() {\n    const spread = Math.random() * CHUNK_BYTES_SPREAD;\n    const chunkSize = Math.floor(spread);\n    const sentBytes = uploadedBytes + MIN_CHUNK_BYTES + chunkSize;\n    uploadedBytes = Math.min(totalBytes, sentBytes);\n    const sentShare = uploadedBytes / totalBytes;\n    const progress = Math.floor(sentShare * 100);\n    if (progress > lastReportedProgress) {\n      lastReportedProgress = progress;\n      onProgress(progress);\n    }\n    if (uploadedBytes < totalBytes) {\n      timeoutId = window.setTimeout(sendChunk, nextChunkDelay());\n      return;\n    }\n    timeoutId = window.setTimeout(onComplete, FILLED_BAR_PAUSE_MS);\n  }\n\n  timeoutId = window.setTimeout(sendChunk, FIRST_CHUNK_DELAY_MS);\n\n  return () => window.clearTimeout(timeoutId);\n}\n\nfunction withProgress(\n  items: UploadProgress[],\n  fileId: string,\n  changes: Partial<UploadProgress>\n) {\n  return items.map((item) => {\n    if (item.fileId !== fileId) {\n      return item;\n    }\n    return { ...item, ...changes };\n  });\n}\n\nfunction isUploadingOf(fileProgress: UploadProgress | undefined) {\n  if (!fileProgress) {\n    return false;\n  }\n  return !fileProgress.completed;\n}\n\nexport default function FileUpload13() {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const itemVariants = itemVariantsOf(shouldReduceMotion);\n  const [uploadProgress, setUploadProgress] = useState<UploadProgress[]>([]);\n  const cancelUploadsRef = useRef(new Map<string, () => void>());\n\n  useEffect(() => {\n    const cancelUploads = cancelUploadsRef.current;\n    return () => {\n      cancelUploads.forEach((cancel) => cancel());\n      cancelUploads.clear();\n    };\n  }, []);\n\n  function startUploads(addedFiles: FileWithPreview[]) {\n    const newItems = addedFiles.map((file) => ({\n      fileId: file.id,\n      progress: 0,\n      completed: false,\n    }));\n    setUploadProgress((current) => [...current, ...newItems]);\n\n    addedFiles.forEach((file) => {\n      const cancel = simulateUpload(\n        file.file.size,\n        (progress) => {\n          setUploadProgress((current) =>\n            withProgress(current, file.id, { progress })\n          );\n        },\n        () => {\n          cancelUploadsRef.current.delete(file.id);\n          setUploadProgress((current) =>\n            withProgress(current, file.id, { completed: true })\n          );\n        }\n      );\n      cancelUploadsRef.current.set(file.id, cancel);\n    });\n  }\n\n  const [\n    { files, isDragging, errors },\n    {\n      handleDragEnter,\n      handleDragLeave,\n      handleDragOver,\n      handleDrop,\n      openFileDialog,\n      removeFile,\n      clearFiles,\n      getInputProps,\n    },\n  ] = useFileUpload({\n    multiple: true,\n    maxFiles: MAX_FILES,\n    maxSize: MAX_SIZE,\n    initialFiles: INITIAL_FILES,\n    onFilesAdded: startUploads,\n  });\n\n  const hasFiles = files.length > 0;\n  const firstError = errors[0];\n\n  function removeUpload(fileId: string) {\n    const cancel = cancelUploadsRef.current.get(fileId);\n    cancel?.();\n    cancelUploadsRef.current.delete(fileId);\n    setUploadProgress((current) =>\n      current.filter((item) => item.fileId !== fileId)\n    );\n    removeFile(fileId);\n  }\n\n  function removeAllUploads() {\n    cancelUploadsRef.current.forEach((cancel) => cancel());\n    cancelUploadsRef.current.clear();\n    setUploadProgress([]);\n    clearFiles();\n  }\n\n  return (\n    <div className='flex w-full flex-col gap-2'>\n      <div\n        onDragEnter={handleDragEnter}\n        onDragLeave={handleDragLeave}\n        onDragOver={handleDragOver}\n        onDrop={handleDrop}\n        data-dragging={presenceOf(isDragging)}\n        data-files={presenceOf(hasFiles)}\n        className={DROP_ZONE}\n      >\n        <input\n          {...getInputProps()}\n          className='sr-only'\n          aria-label='Upload files'\n        />\n        {hasFiles && (\n          <div className='flex w-full flex-col gap-3'>\n            <div className='flex items-center justify-between gap-2'>\n              <h3 className='flex items-center gap-2 text-[13px] font-medium'>\n                Files\n                <span className={COUNT}>{files.length}</span>\n              </h3>\n              <div className='flex gap-2'>\n                <Button variant='outline' size='sm' onClick={openFileDialog}>\n                  <UploadIcon className='-ms-0.5 size-3.5 opacity-60' />\n                  Add files\n                </Button>\n                <Button variant='outline' size='sm' onClick={removeAllUploads}>\n                  <Trash2Icon className='-ms-0.5 size-3.5 opacity-60' />\n                  Remove all\n                </Button>\n              </div>\n            </div>\n            <div className='-my-1 flex w-full flex-col'>\n              <AnimatePresence initial={false}>\n                {files.map((file) => {\n                  const fileProgress = uploadProgress.find(\n                    (item) => item.fileId === file.id\n                  );\n                  const isUploading = isUploadingOf(fileProgress);\n                  const progress = fileProgress?.progress ?? 0;\n\n                  return (\n                    <motion.div\n                      key={file.id}\n                      className='-mx-1 overflow-hidden px-1 py-1'\n                      variants={itemVariants}\n                      initial='hidden'\n                      animate='shown'\n                      exit='hidden'\n                    >\n                      <div\n                        data-uploading={presenceOf(isUploading)}\n                        className={FILE_ROW}\n                      >\n                        <div className='flex items-center justify-between gap-2'>\n                          <div className='flex items-center gap-3 overflow-hidden transition-opacity duration-300 in-data-uploading:opacity-50'>\n                            <div className={ROW_ICON_TILE} aria-hidden='true'>\n                              {fileIconOf(file.file)}\n                            </div>\n                            <div className='flex min-w-0 flex-col gap-0.5'>\n                              <p className='truncate text-[13px] font-medium'>\n                                {file.file.name}\n                              </p>\n                              <p className='text-muted-foreground text-xs tabular-nums'>\n                                {formatBytes(file.file.size)}\n                              </p>\n                            </div>\n                          </div>\n                          <Button\n                            size='icon'\n                            variant='ghost'\n                            className='text-muted-foreground hover:text-foreground -me-2'\n                            onClick={() => removeUpload(file.id)}\n                            aria-label={`Remove ${file.file.name}`}\n                          >\n                            <XIcon />\n                          </Button>\n                        </div>\n                        <AnimatePresence initial={false}>\n                          {isUploading && (\n                            <motion.div\n                              key='progress'\n                              className='overflow-hidden'\n                              variants={itemVariants}\n                              initial='hidden'\n                              animate='shown'\n                              exit='hidden'\n                            >\n                              <Progress\n                                value={progress}\n                                aria-label={`Uploading ${file.file.name}`}\n                                className='flex-row-reverse items-center gap-2 pt-2'\n                              >\n                                <span\n                                  className='text-muted-foreground w-10 shrink-0 text-right text-xs tabular-nums'\n                                  aria-hidden='true'\n                                >\n                                  {progress}%\n                                </span>\n                              </Progress>\n                            </motion.div>\n                          )}\n                        </AnimatePresence>\n                      </div>\n                    </motion.div>\n                  );\n                })}\n              </AnimatePresence>\n            </div>\n          </div>\n        )}\n        {!hasFiles && (\n          <div className='flex flex-col items-center justify-center px-4 py-3 text-center'>\n            <div className={ICON_TILE} aria-hidden='true'>\n              <ImageIcon className='size-4' />\n            </div>\n            <p className='mb-1 text-[13px] font-medium'>Drop your files here</p>\n            <p className='text-muted-foreground text-xs tabular-nums'>\n              Max {MAX_FILES} files · Up to {formatBytes(MAX_SIZE)}\n            </p>\n            <Button variant='outline' className='mt-4' onClick={openFileDialog}>\n              <UploadIcon className='-ms-1 opacity-60' />\n              Select files\n            </Button>\n          </div>\n        )}\n      </div>\n      {firstError && (\n        <p\n          role='alert'\n          className='text-destructive-ink flex items-center gap-1.5 text-xs'\n        >\n          <CircleAlertIcon className='size-3.5 shrink-0' />\n          <span>{firstError}</span>\n        </p>\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "categories": [
    "components",
    "file-upload"
  ],
  "type": "registry:component"
}