{
  "name": "ai-attachment",
  "type": "registry:component",
  "dependencies": [
    "motion"
  ],
  "files": [
    {
      "type": "registry:component",
      "content": "\"use client\";\n\n/**\n * @author: @kokonutui\n * @description: AI Attachment\n * @version: 1.1.0\n * @date: 2026-11-05\n * @license: MIT\n * @website: https://kokonutui.com\n * @github: https://github.com/kokonut-labs/kokonutui\n */\n\nimport {\n  AnimatePresence,\n  animate,\n  MotionConfig,\n  type MotionValue,\n  motion,\n  useMotionValue,\n  useReducedMotion,\n  useTransform,\n} from \"motion/react\";\nimport { Fragment, useEffect, useState } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface AttachedFile {\n  name: string;\n  /** In bytes. */\n  size: number;\n  pages: number;\n}\n\n/** A run of text, or a citation to a page (1-based). */\nexport type AnswerPart = string | { page: number };\n\n/** Where the file is: on its way up, being read, read, or failed. */\nexport type AttachmentStatus = \"uploading\" | \"reading\" | \"done\" | \"error\";\n\nexport interface AIAttachmentProps {\n  file?: AttachedFile;\n  /** The user's message under the file. Only the demo draws one by default. */\n  prompt?: string;\n  /** The answer, with page citations. Shown once the file is read; it can stream. */\n  answer?: AnswerPart[];\n  /**\n   * Pass it to drive the card from your upload and parser; leave it out and\n   * the demo plays on `uploadMs` and `pageMs`.\n   */\n  status?: AttachmentStatus;\n  /** Share of the file uploaded, 0 to 1, while `uploading`. */\n  uploaded?: number;\n  /** Pages read so far, while `reading`. */\n  pagesRead?: number;\n  /** Seconds the reading took, shown once it's done. */\n  duration?: number;\n  /** Why it failed, when `status` is `error`. */\n  error?: string;\n  /** Demo only: how long the upload takes, in ms. */\n  uploadMs?: number;\n  /** Demo only: how long each page takes to read, in ms. */\n  pageMs?: number;\n  className?: string;\n}\n\ntype Phase = AttachmentStatus;\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n/** Line widths on a page thumbnail, in %, cycled per page. */\nconst LINES = [92, 100, 84, 96, 70, 100, 88, 60];\n/** Which line of a page a citation points at. */\nconst CITED_LINE = 3;\n\nconst DEMO_FILE: AttachedFile = {\n  name: \"Q3-board-report.pdf\",\n  size: 4_200_000,\n  pages: 12,\n};\n\nconst DEMO_ANSWER: AnswerPart[] = [\n  \"Revenue grew 18% to $4.2M, almost all of it from the new enterprise tier\",\n  { page: 3 },\n  \". Churn fell to 2.1% after the onboarding rework\",\n  { page: 6 },\n  \". The one risk it flags is hiring: two senior roles are still open, which pushed the EU launch to Q1\",\n  { page: 9 },\n  \".\",\n];\n\nconst mb = (bytes: number) => `${(bytes / 1_000_000).toFixed(1)} MB`;\n\nconst DEMO_PROMPT = \"What changed this quarter? Keep it short.\";\n\n/** Uploads, then reads a page at a time, for the demo. */\nfunction usePlayback(\n  pages: number,\n  uploadMs: number,\n  pageMs: number,\n  active: boolean\n) {\n  const [phase, setPhase] = useState<Phase>(\"uploading\");\n  const uploaded = useMotionValue(0);\n  /** Pages read so far; the one being read is at this index. */\n  const [read, setRead] = useState(0);\n\n  // Uploads on a motion value, so the ring and byte count move every frame\n  // without re-rendering the chat.\n  useEffect(() => {\n    if (phase !== \"uploading\" || !active) {\n      return;\n    }\n    const controls = animate(uploaded, 1, {\n      duration: uploadMs / 1000,\n      ease: [0.33, 1, 0.68, 1],\n      onComplete: () => setPhase(\"reading\"),\n    });\n    return () => controls.stop();\n  }, [phase, uploadMs, uploaded, active]);\n\n  // Reads one page at a time.\n  useEffect(() => {\n    if (phase !== \"reading\" || !active) {\n      return;\n    }\n    if (read >= pages) {\n      const t = setTimeout(() => setPhase(\"done\"), 300);\n      return () => clearTimeout(t);\n    }\n    const t = setTimeout(() => setRead((n) => n + 1), pageMs);\n    return () => clearTimeout(t);\n  }, [phase, read, pages, pageMs, active]);\n\n  return { phase, read, uploaded, seconds: (pages * pageMs) / 1000 };\n}\n\n/** Eases the upload ring to the share your upload reports. */\nfunction useUploadValue(target: number | undefined) {\n  const value = useMotionValue(target ?? 0);\n  useEffect(() => {\n    if (target === undefined) {\n      return;\n    }\n    const controls = animate(value, target, { duration: 0.3, ease: \"easeOut\" });\n    return () => controls.stop();\n  }, [target, value]);\n  return value;\n}\n\nexport default function AIAttachment({\n  file = DEMO_FILE,\n  prompt,\n  answer,\n  status,\n  uploaded: uploadedProp,\n  pagesRead,\n  duration,\n  error,\n  uploadMs = 1400,\n  pageMs = 260,\n  className,\n}: AIAttachmentProps) {\n  const driven = status !== undefined;\n  const isDemo = !driven && answer === undefined;\n  const reduce = useReducedMotion();\n  const playback = usePlayback(file.pages, uploadMs, pageMs, !driven);\n  const drivenUpload = useUploadValue(uploadedProp);\n  const phase = status ?? playback.phase;\n  const uploaded = driven ? drivenUpload : playback.uploaded;\n  const read = driven ? (pagesRead ?? 0) : playback.read;\n  const shownPrompt = prompt ?? (isDemo ? DEMO_PROMPT : undefined);\n  const shownAnswer = answer ?? (isDemo ? DEMO_ANSWER : []);\n  const [lit, setLit] = useState<number | null>(null);\n\n  const done = phase === \"done\";\n  const failed = phase === \"error\";\n  const secondsTaken = driven ? duration : playback.seconds;\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div\n        className={cn(\"flex w-full max-w-md flex-col gap-4\", className)}\n        data-state={phase}\n      >\n        <div className=\"flex flex-col items-end gap-1.5\">\n          <FileChip file={file} phase={phase} progress={uploaded} />\n          {shownPrompt ? (\n            <p className=\"max-w-[85%] text-pretty rounded-2xl rounded-br-md bg-zinc-100 px-3.5 py-2 text-[14px] text-zinc-800 leading-snug dark:bg-zinc-800 dark:text-zinc-100\">\n              {shownPrompt}\n            </p>\n          ) : null}\n        </div>\n\n        <AnimatePresence>\n          {phase !== \"uploading\" && (\n            <motion.div\n              animate={{ opacity: 1, y: 0 }}\n              className=\"rounded-[22px] bg-black/[0.04] p-1 dark:bg-white/[0.06]\"\n              initial={{ opacity: 0, y: 6 }}\n              transition={{ duration: 0.35, ease: EASE_OUT }}\n            >\n              <div className=\"flex h-8 items-center gap-2 overflow-hidden px-3 text-[12px]\">\n                <span className=\"relative flex size-3.5 items-center justify-center\">\n                  <AnimatePresence initial={false} mode=\"popLayout\">\n                    {failed ? (\n                      <motion.span\n                        animate={{ opacity: 1 }}\n                        className=\"size-2 rounded-full bg-rose-500\"\n                        initial={{ opacity: 0 }}\n                        key=\"failed\"\n                      />\n                    ) : null}\n                    {done ? (\n                      <motion.svg\n                        animate={{ opacity: 1 }}\n                        aria-hidden=\"true\"\n                        className=\"size-3.5 text-emerald-600 dark:text-emerald-400\"\n                        fill=\"none\"\n                        initial={{ opacity: 0 }}\n                        key=\"done\"\n                        viewBox=\"0 0 16 16\"\n                      >\n                        <motion.path\n                          animate={{ pathLength: 1 }}\n                          d=\"M3.5 8.5l3 3 6-7\"\n                          initial={{ pathLength: 0 }}\n                          stroke=\"currentColor\"\n                          strokeLinecap=\"round\"\n                          strokeLinejoin=\"round\"\n                          strokeWidth=\"2\"\n                          transition={{ duration: 0.35, ease: EASE_OUT }}\n                        />\n                      </motion.svg>\n                    ) : null}\n                    {done || failed ? null : (\n                      <motion.span exit={{ opacity: 0 }} key=\"spin\">\n                        <Spinner />\n                      </motion.span>\n                    )}\n                  </AnimatePresence>\n                </span>\n                <AnimatePresence initial={false} mode=\"popLayout\">\n                  <motion.span\n                    animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n                    className={cn(\n                      \"min-w-0 truncate font-medium\",\n                      failed\n                        ? \"text-rose-600 dark:text-rose-400\"\n                        : \"text-zinc-700 dark:text-zinc-300\"\n                    )}\n                    exit={{ opacity: 0, y: -6, filter: \"blur(2px)\" }}\n                    initial={{ opacity: 0, y: 6, filter: \"blur(2px)\" }}\n                    key={phase}\n                    transition={{ duration: 0.22, ease: EASE_OUT }}\n                  >\n                    {bandLabel(phase, file, error)}\n                  </motion.span>\n                </AnimatePresence>\n                <span className=\"ml-auto shrink-0 font-mono text-[11px] text-zinc-400 tabular-nums dark:text-zinc-500\">\n                  {bandCount(phase, read, file.pages, secondsTaken)}\n                </span>\n              </div>\n\n              <div className=\"grid grid-cols-12 gap-1 rounded-[18px] bg-white p-3 shadow-[0_1px_2px_rgb(0_0_0/0.04)] ring-1 ring-black/[0.06] sm:gap-1.5 dark:bg-zinc-900 dark:ring-white/[0.08]\">\n                {Array.from({ length: file.pages }, (_, i) => (\n                  <Page\n                    index={i}\n                    // biome-ignore lint/suspicious/noArrayIndexKey: pages are a fixed, ordered list\n                    key={i}\n                    lit={lit === i + 1}\n                    pageMs={pageMs}\n                    reduce={Boolean(reduce)}\n                    state={pageState(i, read, phase)}\n                  />\n                ))}\n              </div>\n            </motion.div>\n          )}\n        </AnimatePresence>\n\n        <AnimatePresence>\n          {done && shownAnswer.length > 0 && (\n            <motion.p\n              animate={{ opacity: 1, filter: \"blur(0px)\", y: 0 }}\n              className=\"text-pretty text-[15px] text-zinc-800 leading-7 dark:text-zinc-200\"\n              initial={{ opacity: 0, filter: \"blur(4px)\", y: 4 }}\n              transition={{ duration: 0.4, ease: EASE_OUT, delay: 0.15 }}\n            >\n              {shownAnswer.map((part, i) =>\n                typeof part === \"string\" ? (\n                  // biome-ignore lint/suspicious/noArrayIndexKey: answer parts are static\n                  <Fragment key={i}>{part}</Fragment>\n                ) : (\n                  <Cite\n                    active={lit === part.page}\n                    // biome-ignore lint/suspicious/noArrayIndexKey: answer parts are static\n                    key={i}\n                    onLight={setLit}\n                    page={part.page}\n                  />\n                )\n              )}\n            </motion.p>\n          )}\n        </AnimatePresence>\n        <p aria-live=\"polite\" className=\"sr-only\">\n          {phase === \"uploading\" ? \"\" : bandLabel(phase, file, error)}\n        </p>\n      </div>\n    </MotionConfig>\n  );\n}\n\nconst bandLabel = (phase: Phase, file: AttachedFile, error?: string) => {\n  if (phase === \"done\") {\n    return `Read ${file.pages} pages`;\n  }\n  if (phase === \"error\") {\n    return error ?? `Couldn't read ${file.name}`;\n  }\n  return `Reading ${file.name}`;\n};\n\nconst bandCount = (\n  phase: Phase,\n  read: number,\n  pages: number,\n  seconds?: number\n) => {\n  if (phase === \"done\") {\n    return seconds === undefined ? \"\" : `${seconds.toFixed(1)}s`;\n  }\n  if (phase === \"error\") {\n    return `${read} / ${pages}`;\n  }\n  return `${Math.min(read + 1, pages)} / ${pages}`;\n};\n\ntype PageState = \"waiting\" | \"reading\" | \"read\";\n\nconst pageState = (i: number, read: number, phase: Phase): PageState => {\n  if (phase === \"done\" || i < read) {\n    return \"read\";\n  }\n  return i === read && phase === \"reading\" ? \"reading\" : \"waiting\";\n};\n\nfunction FileChip({\n  file,\n  phase,\n  progress,\n}: {\n  file: AttachedFile;\n  phase: Phase;\n  progress: MotionValue<number>;\n}) {\n  const uploading = phase === \"uploading\";\n  const sent = useTransform(\n    progress,\n    (p) => `${mb(file.size * p)} of ${mb(file.size)}`\n  );\n  return (\n    <div className=\"flex w-60 max-w-[85%] items-center gap-2.5 rounded-2xl bg-white p-2 pr-3 ring-1 ring-black/[0.08] dark:bg-zinc-900 dark:ring-white/10\">\n      <span className=\"relative flex h-10 w-8 shrink-0 items-end justify-center rounded-[6px] bg-red-50 pb-1 ring-1 ring-red-500/15 dark:bg-red-500/10\">\n        <span className=\"absolute top-0 right-0 size-2 rounded-bl-[3px] bg-red-500/20\" />\n        <span className=\"font-bold text-[7.5px] text-red-600 tracking-wide dark:text-red-400\">\n          PDF\n        </span>\n      </span>\n      <span className=\"min-w-0 flex-1\">\n        <span className=\"block truncate font-medium text-[13px] text-zinc-900 dark:text-zinc-100\">\n          {file.name}\n        </span>\n        <span className=\"mt-0.5 block truncate text-[11.5px] text-zinc-500 tabular-nums dark:text-zinc-400\">\n          {uploading ? (\n            <motion.span>{sent}</motion.span>\n          ) : (\n            `${file.pages} pages · ${mb(file.size)}`\n          )}\n        </span>\n      </span>\n      <AnimatePresence initial={false}>\n        {uploading && (\n          <motion.svg\n            aria-hidden=\"true\"\n            className=\"size-4 shrink-0 -rotate-90\"\n            exit={{ opacity: 0, scale: 0.6 }}\n            transition={{ duration: 0.2 }}\n            viewBox=\"0 0 16 16\"\n          >\n            <circle\n              className=\"stroke-zinc-200 dark:stroke-zinc-700\"\n              cx=\"8\"\n              cy=\"8\"\n              fill=\"none\"\n              r=\"7\"\n              strokeWidth=\"1.75\"\n            />\n            <motion.circle\n              className=\"stroke-zinc-900 dark:stroke-zinc-100\"\n              cx=\"8\"\n              cy=\"8\"\n              fill=\"none\"\n              r=\"7\"\n              strokeLinecap=\"round\"\n              strokeWidth=\"1.75\"\n              style={{ pathLength: progress }}\n            />\n          </motion.svg>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n\n/** A page thumbnail. A scan line passes over it while it is read. */\nfunction Page({\n  index,\n  state,\n  lit,\n  pageMs,\n  reduce,\n}: {\n  index: number;\n  state: PageState;\n  lit: boolean;\n  pageMs: number;\n  reduce: boolean;\n}) {\n  const lines = index === 0 ? 5 : 7;\n  return (\n    <motion.div\n      animate={{\n        y: lit && !reduce ? -3 : 0,\n        opacity: state === \"waiting\" ? 0.45 : 1,\n      }}\n      className={cn(\n        \"relative flex aspect-[3/4] min-w-0 flex-col gap-[2px] overflow-hidden rounded-[3px] bg-white p-[3px] ring-1 transition-[box-shadow] duration-200 dark:bg-zinc-800\",\n        state === \"reading\" && \"ring-blue-500/60 dark:ring-blue-400/60\",\n        state !== \"reading\" &&\n          (lit\n            ? \"ring-orange-500 dark:ring-orange-400\"\n            : \"ring-black/[0.1] dark:ring-white/10\")\n      )}\n      initial={false}\n      transition={{ duration: 0.25, ease: EASE_OUT }}\n    >\n      {index === 0 && (\n        <span className=\"mb-[2px] h-[3px] w-3/5 rounded-full bg-zinc-400 dark:bg-zinc-500\" />\n      )}\n      {Array.from({ length: lines }, (_, l) => (\n        <span\n          className={cn(\n            \"h-[1.5px] rounded-full transition-colors duration-300\",\n            state === \"waiting\"\n              ? \"bg-zinc-200 dark:bg-zinc-700\"\n              : \"bg-zinc-300 dark:bg-zinc-600\",\n            lit && l === CITED_LINE && \"bg-orange-500 dark:bg-orange-400\"\n          )}\n          // biome-ignore lint/suspicious/noArrayIndexKey: lines are decoration\n          key={l}\n          style={{ width: `${LINES[(l + index) % LINES.length]}%` }}\n        />\n      ))}\n      {state === \"reading\" && (\n        <motion.span\n          animate={{ y: \"0%\" }}\n          className=\"absolute inset-0 border-blue-500 border-b bg-blue-500/[0.08] dark:border-blue-400 dark:bg-blue-400/10\"\n          initial={{ y: \"-100%\" }}\n          transition={{ duration: pageMs / 1000, ease: \"linear\" }}\n        />\n      )}\n    </motion.div>\n  );\n}\n\n/** A page citation. Hover or focus it to light the page it points at. */\nfunction Cite({\n  page,\n  active,\n  onLight,\n}: {\n  page: number;\n  active: boolean;\n  onLight: (page: number | null) => void;\n}) {\n  return (\n    <button\n      aria-label={`Page ${page}`}\n      className={cn(\n        \"mx-0.5 inline-flex h-5 translate-y-[-1px] items-center rounded-full px-1.5 align-middle font-medium text-[11px] tabular-nums outline-hidden transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-orange-500/40\",\n        active\n          ? \"bg-orange-100 text-orange-900 dark:bg-orange-400/20 dark:text-orange-200\"\n          : \"bg-zinc-100 text-zinc-600 dark:bg-white/[0.08] dark:text-zinc-300\"\n      )}\n      onBlur={() => onLight(null)}\n      onFocus={() => onLight(page)}\n      onPointerEnter={(e) => e.pointerType === \"mouse\" && onLight(page)}\n      onPointerLeave={(e) => e.pointerType === \"mouse\" && onLight(null)}\n      type=\"button\"\n    >\n      p.{page}\n    </button>\n  );\n}\n\nfunction Spinner() {\n  return (\n    <motion.svg\n      animate={{ rotate: 360 }}\n      aria-hidden=\"true\"\n      className=\"size-3.5 text-zinc-700 dark:text-zinc-300\"\n      fill=\"none\"\n      transition={{\n        duration: 0.6,\n        ease: \"linear\",\n        repeat: Number.POSITIVE_INFINITY,\n      }}\n      viewBox=\"0 0 16 16\"\n    >\n      <circle\n        cx=\"8\"\n        cy=\"8\"\n        opacity=\"0.2\"\n        r=\"6.25\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.75\"\n      />\n      <path\n        d=\"M8 1.75a6.25 6.25 0 0 1 6.25 6.25\"\n        stroke=\"currentColor\"\n        strokeLinecap=\"round\"\n        strokeWidth=\"1.75\"\n      />\n    </motion.svg>\n  );\n}\n",
      "path": "/components/kokonutui/ai-attachment.tsx",
      "target": "components/kokonutui/ai-attachment.tsx"
    }
  ]
}