{
  "name": "ai-upload",
  "type": "registry:component",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "files": [
    {
      "type": "registry:component",
      "content": "\"use client\";\n\n/**\n * @author: @kokonutui\n * @description: AI Upload\n * @version: 1.0.0\n * @date: 2026-11-28\n * @license: MIT\n * @website: https://kokonutui.com\n * @github: https://github.com/kokonut-labs/kokonutui\n */\n\nimport { Check, Film, ImageIcon, LoaderCircle, X } from \"lucide-react\";\nimport { AnimatePresence, MotionConfig, motion } from \"motion/react\";\nimport { type DragEvent, useEffect, useRef, useState } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\n/** Where a file is: going up, ready to use, or refused. */\nexport type UploadStatus = \"uploading\" | \"done\" | \"error\";\n\nexport interface UploadItem {\n  id: string;\n  name: string;\n  /** In bytes. */\n  size: number;\n  status: UploadStatus;\n  /** 0 to 1, while uploading. */\n  progress: number;\n  isVideo: boolean;\n  /** Where the file lives once uploaded. */\n  url?: string;\n  /** A local preview for images, revoked when the row goes. */\n  preview?: string;\n  error?: string;\n}\n\nexport interface AIUploadProps {\n  /** What the assistant says above the card. */\n  message?: string;\n  /** Images allowed in one post. A video always goes alone. */\n  maxFiles?: number;\n  /**\n   * Sends one file and resolves with its URL. Call `onProgress` with 0 to 1\n   * as it goes. Leave it out and the card fakes the upload, for the demo.\n   */\n  upload?: (\n    file: File,\n    onProgress: (progress: number) => void\n  ) => Promise<string>;\n  /** Called with every uploaded URL when the user hands them to the chat. */\n  onUse?: (urls: string[]) => void;\n  className?: string;\n}\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n\nconst DEMO_MESSAGE =\n  \"Drop the photos for the launch post here. I'll attach them once they're up.\";\n\nconst DEMO_ITEMS: UploadItem[] = [\n  {\n    id: \"demo-1\",\n    name: \"launch-hero.png\",\n    size: 1_840_000,\n    status: \"done\",\n    progress: 1,\n    isVideo: false,\n    url: \"https://example.com/launch-hero.png\",\n  },\n  {\n    id: \"demo-2\",\n    name: \"editor-dark.png\",\n    size: 962_000,\n    status: \"uploading\",\n    progress: 0.2,\n    isVideo: false,\n  },\n];\n\nconst BAR: Record<UploadStatus, string> = {\n  uploading: \"bg-blue-600 dark:bg-blue-500\",\n  done: \"bg-emerald-500\",\n  error: \"bg-red-500\",\n};\n\n/** How the fake upload moves: a step of progress every tick. */\nconst FAKE_TICK_MS = 90;\nconst FAKE_STEP = 0.07;\n\nfunction formatSize(bytes: number): string {\n  if (bytes >= 1024 * 1024) {\n    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n  }\n  return `${Math.max(1, Math.round(bytes / 1024))} KB`;\n}\n\n/** Why a file can't join the ones already here, or null when it can. */\nfunction refuse(\n  file: File,\n  items: UploadItem[],\n  maxFiles: number\n): string | null {\n  const isVideo = file.type.startsWith(\"video/\");\n  if (!(isVideo || file.type.startsWith(\"image/\"))) {\n    return `${file.name} isn't a photo or a video.`;\n  }\n  if (items.some((item) => item.isVideo)) {\n    return \"A video goes on its own. Remove it to add photos.\";\n  }\n  if (isVideo && items.length > 0) {\n    return \"A video goes on its own. Remove the photos first.\";\n  }\n  if (items.length >= maxFiles) {\n    return `Up to ${maxFiles} photos per post.`;\n  }\n  return null;\n}\n\n/** The files in the card, and the uploads that move them along. */\nfunction useUploads(\n  upload: AIUploadProps[\"upload\"],\n  maxFiles: number,\n  isDemo: boolean\n) {\n  const [items, setItems] = useState<UploadItem[]>(isDemo ? DEMO_ITEMS : []);\n  const [error, setError] = useState<string | null>(null);\n  const timers = useRef(new Map<string, ReturnType<typeof setInterval>>());\n  const previews = useRef(new Set<string>());\n  const nextId = useRef(0);\n\n  const patch = (id: string, change: Partial<UploadItem>) =>\n    setItems((rows) =>\n      rows.map((row) => (row.id === id ? { ...row, ...change } : row))\n    );\n\n  const fake = (id: string) => {\n    let progress = 0;\n    const timer = setInterval(() => {\n      progress = Math.min(1, progress + FAKE_STEP);\n      if (progress < 1) {\n        patch(id, { progress });\n        return;\n      }\n      clearInterval(timer);\n      timers.current.delete(id);\n      patch(id, {\n        progress: 1,\n        status: \"done\",\n        url: `https://example.com/${id}`,\n      });\n    }, FAKE_TICK_MS);\n    timers.current.set(id, timer);\n  };\n\n  const send = (id: string, file: File) => {\n    if (!upload) {\n      fake(id);\n      return;\n    }\n    upload(file, (progress) => patch(id, { progress }))\n      .then((url) => patch(id, { status: \"done\", progress: 1, url }))\n      .catch((reason: unknown) =>\n        patch(id, {\n          status: \"error\",\n          error: reason instanceof Error ? reason.message : \"Upload failed.\",\n        })\n      );\n  };\n\n  // The demo's second file is mid-upload when the card appears.\n  // biome-ignore lint/correctness/useExhaustiveDependencies: on mount only\n  useEffect(() => {\n    const running = timers.current;\n    const urls = previews.current;\n    if (isDemo) {\n      fake(\"demo-2\");\n    }\n    return () => {\n      for (const timer of running.values()) {\n        clearInterval(timer);\n      }\n      for (const url of urls) {\n        URL.revokeObjectURL(url);\n      }\n    };\n  }, []);\n\n  const addFiles = (files: File[]) => {\n    setError(null);\n    const added: UploadItem[] = [];\n    for (const file of files) {\n      const reason = refuse(file, [...items, ...added], maxFiles);\n      if (reason) {\n        setError(reason);\n        break;\n      }\n      const isVideo = file.type.startsWith(\"video/\");\n      const preview = isVideo ? undefined : URL.createObjectURL(file);\n      if (preview) {\n        previews.current.add(preview);\n      }\n      nextId.current += 1;\n      const item: UploadItem = {\n        id: `file-${nextId.current}`,\n        name: file.name,\n        size: file.size,\n        status: \"uploading\",\n        progress: 0,\n        isVideo,\n        preview,\n      };\n      added.push(item);\n      send(item.id, file);\n    }\n    if (added.length > 0) {\n      setItems((rows) => [...rows, ...added]);\n    }\n  };\n\n  const remove = (id: string) => {\n    clearInterval(timers.current.get(id));\n    timers.current.delete(id);\n    const preview = items.find((item) => item.id === id)?.preview;\n    if (preview) {\n      URL.revokeObjectURL(preview);\n      previews.current.delete(preview);\n    }\n    setError(null);\n    setItems((rows) => rows.filter((row) => row.id !== id));\n  };\n\n  return { items, error, addFiles, remove };\n}\n\nexport default function AIUpload({\n  message,\n  maxFiles = 4,\n  upload,\n  onUse,\n  className,\n}: AIUploadProps) {\n  const isDemo = upload === undefined;\n  const uploads = useUploads(upload, maxFiles, isDemo);\n  const [sent, setSent] = useState(false);\n\n  const urls = uploads.items.flatMap((item) =>\n    item.status === \"done\" && item.url ? [item.url] : []\n  );\n  const isUploading = uploads.items.some((item) => item.status === \"uploading\");\n  const isFull =\n    uploads.items.some((item) => item.isVideo) ||\n    uploads.items.length >= maxFiles;\n  const shownMessage = message ?? (isDemo ? DEMO_MESSAGE : undefined);\n\n  const use = () => {\n    onUse?.(urls);\n    setSent(true);\n  };\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div className={cn(\"flex w-full max-w-md flex-col gap-4\", className)}>\n        {shownMessage ? (\n          <p className=\"text-pretty text-[15px] text-zinc-800 leading-7 dark:text-zinc-200\">\n            {shownMessage}\n          </p>\n        ) : null}\n\n        <div className=\"rounded-[22px] bg-black/[0.04] p-1 dark:bg-white/[0.06]\">\n          <div className=\"flex h-8 items-center justify-between gap-3 px-3 text-[12px] text-zinc-500 dark:text-zinc-400\">\n            <span className=\"font-medium text-zinc-700 dark:text-zinc-300\">\n              Media\n            </span>\n            <span className=\"tabular-nums\">\n              {countLabel(uploads.items, maxFiles)}\n            </span>\n          </div>\n\n          <div className=\"flex flex-col gap-3 rounded-[18px] bg-white p-3 shadow-[0_1px_2px_rgb(0_0_0/0.04)] ring-1 ring-black/[0.06] dark:bg-zinc-900 dark:ring-white/[0.08]\">\n            <DropZone\n              disabled={sent || isFull}\n              maxFiles={maxFiles}\n              onFiles={uploads.addFiles}\n            />\n\n            <AnimatePresence initial={false}>\n              {uploads.error ? (\n                <motion.p\n                  animate={{ opacity: 1, height: \"auto\" }}\n                  className=\"overflow-hidden px-1 text-[12.5px] text-red-600 dark:text-red-400\"\n                  exit={{ opacity: 0, height: 0 }}\n                  initial={{ opacity: 0, height: 0 }}\n                  role=\"alert\"\n                  transition={{ duration: 0.2, ease: EASE_OUT }}\n                >\n                  {uploads.error}\n                </motion.p>\n              ) : null}\n            </AnimatePresence>\n\n            {uploads.items.length > 0 ? (\n              <ul className=\"flex flex-col\">\n                <AnimatePresence initial={false}>\n                  {uploads.items.map((item) => (\n                    <UploadRow\n                      canRemove={!sent}\n                      item={item}\n                      key={item.id}\n                      onRemove={() => uploads.remove(item.id)}\n                    />\n                  ))}\n                </AnimatePresence>\n              </ul>\n            ) : null}\n\n            <div className=\"flex items-center gap-3 border-black/[0.06] border-t pt-3 dark:border-white/[0.08]\">\n              <p className=\"min-w-0 flex-1 text-[12px] text-zinc-500 dark:text-zinc-400\">\n                {sent\n                  ? \"Sent to the chat.\"\n                  : \"Nothing is posted until you confirm in the chat.\"}\n              </p>\n              <button\n                className=\"h-8 shrink-0 rounded-full bg-blue-600 px-3.5 font-medium text-[12.5px] text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.2),0_1px_2px_rgb(29_78_216/0.35)] outline-hidden transition-[background-color,opacity] duration-150 hover:bg-blue-700 focus-visible:ring-2 focus-visible:ring-blue-500/50 focus-visible:ring-offset-2 active:bg-blue-800 disabled:pointer-events-none disabled:opacity-50 dark:bg-blue-500 dark:active:bg-blue-700 dark:focus-visible:ring-offset-zinc-900 dark:hover:bg-blue-600\"\n                disabled={sent || isUploading || urls.length === 0}\n                onClick={use}\n                type=\"button\"\n              >\n                {buttonLabel(sent, isUploading)}\n              </button>\n            </div>\n          </div>\n        </div>\n      </div>\n    </MotionConfig>\n  );\n}\n\nfunction countLabel(items: UploadItem[], maxFiles: number) {\n  return items.some((item) => item.isVideo)\n    ? \"1 video\"\n    : `${items.length} of ${maxFiles}`;\n}\n\nfunction buttonLabel(sent: boolean, isUploading: boolean) {\n  if (sent) {\n    return \"Sent\";\n  }\n  return isUploading ? \"Uploading…\" : \"Use these files\";\n}\n\n/**\n * A label around a hidden file input: a click opens the picker, and keyboard\n * users get the input's own focus.\n */\nfunction DropZone({\n  disabled,\n  maxFiles,\n  onFiles,\n}: {\n  disabled: boolean;\n  maxFiles: number;\n  onFiles: (files: File[]) => void;\n}) {\n  const [isOver, setIsOver] = useState(false);\n\n  const onDrop = (event: DragEvent) => {\n    event.preventDefault();\n    setIsOver(false);\n    if (!disabled) {\n      onFiles(Array.from(event.dataTransfer.files));\n    }\n  };\n\n  return (\n    // biome-ignore lint/a11y/noNoninteractiveElementInteractions: the drag handlers only add a drop target; the file input inside is the keyboard path.\n    <label\n      className={cn(\n        \"flex cursor-pointer flex-col items-center gap-0.5 rounded-xl border border-zinc-300 border-dashed px-4 py-5 text-center text-[13px] transition-[border-color,background-color,opacity] duration-150 ease-out has-focus-visible:border-blue-500 dark:border-zinc-700\",\n        isOver && \"border-blue-500 bg-blue-500/[0.05] dark:border-blue-400\",\n        disabled && \"pointer-events-none opacity-50\"\n      )}\n      onDragLeave={() => setIsOver(false)}\n      onDragOver={(event) => {\n        event.preventDefault();\n        setIsOver(true);\n      }}\n      onDrop={onDrop}\n    >\n      <span className=\"text-zinc-500 dark:text-zinc-400\">\n        <span className=\"font-medium text-zinc-900 dark:text-zinc-100\">\n          Drop photos or a video\n        </span>{\" \"}\n        or click to choose\n      </span>\n      <span className=\"text-[12px] text-zinc-500 dark:text-zinc-400\">\n        Up to {maxFiles} images, or 1 video\n      </span>\n      <input\n        accept=\"image/*,video/*\"\n        className=\"sr-only\"\n        disabled={disabled}\n        multiple\n        onChange={(event) => {\n          onFiles(Array.from(event.target.files ?? []));\n          event.target.value = \"\";\n        }}\n        type=\"file\"\n      />\n    </label>\n  );\n}\n\n/** One file: a thumbnail, its name, then progress or size. */\nfunction UploadRow({\n  item,\n  canRemove,\n  onRemove,\n}: {\n  item: UploadItem;\n  canRemove: boolean;\n  onRemove: () => void;\n}) {\n  const Kind = item.isVideo ? Film : ImageIcon;\n  return (\n    <motion.li\n      animate={{ opacity: 1, height: \"auto\" }}\n      className=\"overflow-hidden\"\n      exit={{ opacity: 0, height: 0 }}\n      initial={{ opacity: 0, height: 0 }}\n      transition={{ duration: 0.22, ease: EASE_OUT }}\n    >\n      <div className=\"flex items-center gap-3 py-1.5\">\n        <span className=\"relative flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-zinc-100 text-zinc-400 ring-1 ring-black/[0.06] dark:bg-zinc-800 dark:text-zinc-500 dark:ring-white/[0.08]\">\n          {item.preview ? (\n            // biome-ignore lint/performance/noImgElement: a local blob preview, no image host to optimize.\n            <img\n              alt=\"\"\n              className=\"size-full object-cover\"\n              draggable={false}\n              height={36}\n              src={item.preview}\n              width={36}\n            />\n          ) : (\n            <Kind aria-hidden=\"true\" className=\"size-4\" />\n          )}\n        </span>\n        <span className=\"min-w-0 flex-1\">\n          <span className=\"block truncate font-medium text-[13px] text-zinc-900 leading-5 dark:text-zinc-100\">\n            {item.name}\n          </span>\n          <span className=\"relative mt-1 block h-[3px] overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800\">\n            <span\n              className={cn(\n                \"absolute inset-0 origin-left rounded-full transition-[scale,background-color] duration-150 ease-out\",\n                BAR[item.status]\n              )}\n              style={{\n                scale: `${item.status === \"error\" ? 1 : item.progress} 1`,\n              }}\n            />\n          </span>\n        </span>\n        <span className=\"flex h-5 w-16 shrink-0 items-center justify-end gap-1 text-[12px] text-zinc-500 tabular-nums dark:text-zinc-400\">\n          <RowStatus item={item} />\n        </span>\n        {canRemove && item.status !== \"uploading\" ? (\n          <button\n            aria-label={`Remove ${item.name}`}\n            className=\"flex size-6 shrink-0 items-center justify-center rounded-md text-zinc-400 outline-hidden transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-700 focus-visible:ring-2 focus-visible:ring-blue-500/50 dark:hover:bg-zinc-800 dark:hover:text-zinc-200\"\n            onClick={onRemove}\n            type=\"button\"\n          >\n            <X aria-hidden=\"true\" className=\"size-3.5\" />\n          </button>\n        ) : (\n          <span className=\"size-6 shrink-0\" />\n        )}\n      </div>\n      {item.error ? (\n        <p className=\"pb-1.5 pl-12 text-[12px] text-red-600 leading-snug dark:text-red-400\">\n          {item.error}\n        </p>\n      ) : null}\n    </motion.li>\n  );\n}\n\nfunction RowStatus({ item }: { item: UploadItem }) {\n  if (item.status === \"uploading\") {\n    return (\n      <>\n        <LoaderCircle\n          aria-hidden=\"true\"\n          className=\"size-3 animate-spin motion-reduce:animate-none\"\n        />\n        {Math.round(item.progress * 100)}%\n      </>\n    );\n  }\n  if (item.status === \"error\") {\n    return <span className=\"text-red-600 dark:text-red-400\">Failed</span>;\n  }\n  return (\n    <>\n      <Check\n        aria-hidden=\"true\"\n        className=\"size-3 text-emerald-600 dark:text-emerald-400\"\n        strokeWidth={2.5}\n      />\n      {formatSize(item.size)}\n    </>\n  );\n}\n",
      "path": "/components/kokonutui/ai-upload.tsx",
      "target": "components/kokonutui/ai-upload.tsx"
    }
  ]
}