{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sources",
  "title": "Sources",
  "description": "Agent answer with inline citation chips that show the source on hover, and a collapsible list of the sources behind it. Reads [1]-style markers and AI SDK source-url parts.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "registry/components/sources.tsx",
      "content": "\"use client\";\n\nimport { Fragment, useEffect, useId, useRef, useState } from \"react\";\nimport { ChevronDown, ExternalLink } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\n/** One source the agent read. Matches the AI SDK `source-url` part: `{ url, title }`. */\nexport type Source = {\n  url: string;\n  title?: string;\n  /** A line from the page that backs the claim. */\n  snippet?: string;\n};\n\nexport type SourcesProps = {\n  /** Answer text. Markers like [1] or [2][3] become citation chips that point into `sources`. */\n  answer?: string;\n  /** The sources, in citation order: [1] is sources[0]. */\n  sources?: Source[];\n  /** Label of the list toggle. Defaults to \"N sources\". */\n  label?: string;\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  /** Stream the answer, pop in the citations and open the list, on a loop while on screen. */\n  autoPlay?: boolean;\n  className?: string;\n};\n\nconst DEMO_ANSWER =\n  \"Agent interfaces earn trust by showing their work [1]. Streaming each tool call with its arguments lets people follow along while the agent runs [2], and asking before side effects keeps them in control [3]. A citation beside each claim makes the answer easy to check [1][3].\";\n\nconst DEMO_SOURCES: Source[] = [\n  {\n    url: \"https://nextui.dev/components/tool-call\",\n    title: \"Tool call\",\n    snippet: \"Show the tool name, the arguments as they stream in, a running state, then the result.\",\n  },\n  {\n    url: \"https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-tool-usage\",\n    title: \"Chatbot tool usage\",\n    snippet: \"Tool parts carry their state, so the UI can render input while it streams and output when it lands.\",\n  },\n  {\n    url: \"https://nextui.dev/components/tool-approval\",\n    title: \"Tool approval\",\n    snippet: \"Stop before anything hard to undo and show the exact arguments that will run.\",\n  },\n];\n\n// Demo loop, in ms.\nconst WORD_MS = 70;\nconst START = 400;\nconst TICK = 50;\n\n/** \"https://www.example.com/a/b\" → \"example.com\" */\nexport function domainOf(url: string): string {\n  try {\n    return new URL(url).hostname.replace(/^www\\./, \"\");\n  } catch {\n    return url;\n  }\n}\n\nfunction Favicon({ url, className }: { url: string; className?: string }) {\n  const domain = domainOf(url);\n  return (\n    <span\n      className={cn(\n        \"grid size-4 shrink-0 place-items-center rounded-[5px] bg-foreground text-[9px] font-semibold uppercase leading-none text-background\",\n        className,\n      )}\n      aria-hidden\n    >\n      {domain.charAt(0)}\n    </span>\n  );\n}\n\nexport type CitationProps = {\n  /** 1-based number shown in the chip. */\n  n: number;\n  source?: Source;\n  /** Highlight the chip, e.g. while its row in the list is hovered. */\n  active?: boolean;\n  onHoverChange?: (hovered: boolean) => void;\n  className?: string;\n};\n\n/** An inline citation chip. Hover or focus it to see the source. */\nexport function Citation({ n, source, active, onHoverChange, className }: CitationProps) {\n  const reduce = useReducedMotion();\n  const [hover, setHover] = useState(false);\n  const [below, setBelow] = useState(false);\n  const wrapRef = useRef<HTMLSpanElement>(null);\n  const tipId = useId();\n  const show = (v: boolean) => {\n    // Open below the chip when there is no room above it.\n    if (v) setBelow((wrapRef.current?.getBoundingClientRect().top ?? 999) < 150);\n    setHover(v);\n    onHoverChange?.(v);\n  };\n\n  const chip = cn(\n    \"relative ml-1 inline-grid h-[1.15rem] min-w-[1.15rem] -translate-y-px place-items-center rounded-full px-1 align-middle font-mono text-[10px] font-medium leading-none tabular-nums transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n    active || hover ? \"bg-foreground text-background\" : \"bg-muted text-muted-foreground hover:bg-foreground hover:text-background\",\n    className,\n  );\n\n  if (!source) return <span className={chip}>{n}</span>;\n\n  return (\n    <span ref={wrapRef} className=\"relative inline-block\" onMouseEnter={() => show(true)} onMouseLeave={() => show(false)}>\n      <a\n        href={source.url}\n        target=\"_blank\"\n        rel=\"noreferrer\"\n        aria-describedby={hover ? tipId : undefined}\n        aria-label={`Source ${n}: ${source.title ?? domainOf(source.url)}`}\n        onFocus={() => show(true)}\n        onBlur={() => show(false)}\n        className={chip}\n      >\n        {n}\n      </a>\n      <AnimatePresence>\n        {hover && (\n          <motion.span\n            id={tipId}\n            role=\"tooltip\"\n            initial={reduce ? false : { opacity: 0, y: below ? -4 : 4, scale: 0.98 }}\n            animate={{ opacity: 1, y: 0, scale: 1 }}\n            exit={reduce ? undefined : { opacity: 0, y: below ? -2 : 2 }}\n            transition={{ duration: 0.16, ease: [0.22, 1, 0.36, 1] }}\n            className={cn(\n              \"pointer-events-none absolute left-1/2 z-20 block w-64 -translate-x-1/2 rounded-lg border bg-popover p-3 text-left text-popover-foreground shadow-lg\",\n              below ? \"top-full mt-2\" : \"bottom-full mb-2\",\n            )}\n          >\n            <span className=\"flex items-center gap-1.5 text-[11px] text-muted-foreground\">\n              <Favicon url={source.url} />\n              {domainOf(source.url)}\n            </span>\n            {source.title && <span className=\"mt-1.5 block text-xs font-medium leading-snug\">{source.title}</span>}\n            {source.snippet && (\n              <span className=\"mt-1 line-clamp-3 block text-xs leading-relaxed text-muted-foreground\">{source.snippet}</span>\n            )}\n          </motion.span>\n        )}\n      </AnimatePresence>\n    </span>\n  );\n}\n\ntype Piece = { kind: \"text\"; text: string } | { kind: \"cite\"; n: number };\n\n/** Split \"text [1][2] more\" into text and citation pieces. */\nexport function parseCitations(text: string): Piece[] {\n  const out: Piece[] = [];\n  const re = /\\s?\\[(\\d+)\\]/g;\n  let last = 0;\n  for (let m = re.exec(text); m; m = re.exec(text)) {\n    if (m.index > last) out.push({ kind: \"text\", text: text.slice(last, m.index) });\n    out.push({ kind: \"cite\", n: Number(m[1]) });\n    last = m.index + m[0].length;\n  }\n  if (last < text.length) out.push({ kind: \"text\", text: text.slice(last) });\n  return out;\n}\n\n/** An answer with inline citation chips, and a collapsible list of the sources behind it. */\nexport function Sources({\n  answer,\n  sources,\n  label,\n  open: openProp,\n  defaultOpen = false,\n  onOpenChange,\n  autoPlay = false,\n  className,\n}: SourcesProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const listId = useId();\n  const reduce = useReducedMotion();\n  const [visible, setVisible] = useState(false);\n  const [tick, setTick] = useState(0);\n  const [innerOpen, setInnerOpen] = useState(defaultOpen);\n  const [active, setActive] = useState<number | null>(null);\n\n  const text = answer ?? DEMO_ANSWER;\n  const list = sources ?? DEMO_SOURCES;\n  const pieces = parseCitations(text);\n\n  // Word count drives the demo timing.\n  const words = text.replace(/\\s?\\[\\d+\\]/g, \"\").split(/\\s+/).filter(Boolean).length;\n  const STREAMED = START + words * WORD_MS;\n  const OPEN_AT = STREAMED + 700;\n  const LOOP = OPEN_AT + 4200;\n\n  useEffect(() => {\n    const el = ref.current;\n    if (!el || !autoPlay) return;\n    const io = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    io.observe(el);\n    return () => io.disconnect();\n  }, [autoPlay]);\n\n  useEffect(() => {\n    if (!autoPlay || !visible || reduce) return;\n    const id = setInterval(() => setTick((t) => (t + TICK) % LOOP), TICK);\n    return () => clearInterval(id);\n  }, [autoPlay, visible, reduce, LOOP]);\n\n  const playing = autoPlay && !reduce;\n  const shownWords = playing ? Math.max(0, Math.floor((tick - START) / WORD_MS)) : Infinity;\n  const open = openProp ?? (playing ? innerOpen || tick >= OPEN_AT : innerOpen);\n  const streaming = playing && shownWords < words;\n\n  function toggle() {\n    const next = !open;\n    if (openProp === undefined) setInnerOpen(next);\n    onOpenChange?.(next);\n  }\n\n  // Render the answer, cutting it off at the streamed word count.\n  let budget = shownWords;\n  const body: React.ReactNode[] = [];\n  for (let i = 0; i < pieces.length; i++) {\n    const p = pieces[i];\n    if (p.kind === \"text\") {\n      if (budget <= 0) break;\n      const parts = p.text.split(/(\\s+)/);\n      let acc = \"\";\n      let cut = false;\n      for (const part of parts) {\n        if (part.trim() === \"\") {\n          acc += part;\n          continue;\n        }\n        if (budget <= 0) {\n          cut = true;\n          break;\n        }\n        acc += part;\n        budget--;\n      }\n      body.push(<Fragment key={i}>{acc}</Fragment>);\n      if (cut) break;\n    } else {\n      const src = list[p.n - 1];\n      body.push(\n        <motion.span\n          key={i}\n          initial={playing ? { scale: 0.4, opacity: 0 } : false}\n          animate={{ scale: 1, opacity: 1 }}\n          transition={{ type: \"spring\", stiffness: 520, damping: 22 }}\n          className=\"inline-block\"\n        >\n          <Citation\n            n={p.n}\n            source={src}\n            active={active === p.n - 1}\n            onHoverChange={(h) => setActive(h ? p.n - 1 : null)}\n          />\n        </motion.span>,\n      );\n    }\n  }\n\n  return (\n    <div ref={ref} className={cn(\"w-full max-w-md text-foreground\", className)}>\n      <p className=\"text-sm leading-relaxed\">\n        {body}\n        {streaming && <span className=\"ml-0.5 inline-block h-3.5 w-1.5 translate-y-0.5 animate-pulse rounded-sm bg-foreground/70\" aria-hidden />}\n      </p>\n\n      {list.length > 0 && (\n        <div className=\"mt-3 rounded-xl bg-muted p-1\">\n          <button\n            type=\"button\"\n            onClick={toggle}\n            aria-expanded={open}\n            aria-controls={listId}\n            className=\"flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs font-medium outline-none transition-colors hover:bg-background/60 focus-visible:ring-2 focus-visible:ring-ring\"\n          >\n            <span className=\"flex -space-x-1\">\n              {list.slice(0, 4).map((s, i) => (\n                <Favicon key={i} url={s.url} className=\"ring-2 ring-muted\" />\n              ))}\n            </span>\n            <span>{label ?? `${list.length} ${list.length === 1 ? \"source\" : \"sources\"}`}</span>\n            <ChevronDown\n              className={cn(\"ml-auto size-3.5 text-muted-foreground transition-transform duration-200\", open && \"rotate-180\")}\n              aria-hidden\n            />\n          </button>\n          <AnimatePresence initial={false}>\n            {open && (\n              <motion.div\n                id={listId}\n                initial={reduce ? false : { height: 0, opacity: 0 }}\n                animate={{ height: \"auto\", opacity: 1 }}\n                exit={reduce ? undefined : { height: 0, opacity: 0 }}\n                transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}\n                className=\"overflow-hidden\"\n              >\n                <ol className=\"mt-1 divide-y rounded-lg border bg-card\">\n                  {list.map((s, i) => (\n                    <li key={i}>\n                      <a\n                        href={s.url}\n                        target=\"_blank\"\n                        rel=\"noreferrer\"\n                        onMouseEnter={() => setActive(i)}\n                        onMouseLeave={() => setActive(null)}\n                        onFocus={() => setActive(i)}\n                        onBlur={() => setActive(null)}\n                        className={cn(\n                          \"group flex items-center gap-2.5 px-3 py-2 text-xs outline-none transition-colors focus-visible:bg-muted\",\n                          active === i && \"bg-muted\",\n                        )}\n                      >\n                        <span className=\"w-3 shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground\">{i + 1}</span>\n                        <Favicon url={s.url} />\n                        <span className=\"min-w-0 flex-1 truncate font-medium\">{s.title ?? domainOf(s.url)}</span>\n                        <span className=\"shrink-0 text-muted-foreground\">{domainOf(s.url)}</span>\n                        <ExternalLink className=\"size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100\" aria-hidden />\n                      </a>\n                    </li>\n                  ))}\n                </ol>\n              </motion.div>\n            )}\n          </AnimatePresence>\n        </div>\n      )}\n    </div>\n  );\n}\n\nexport default function SourcesDemo() {\n  return <Sources autoPlay />;\n}\n",
      "type": "registry:component",
      "target": "components/nextui/sources.tsx"
    }
  ],
  "meta": {
    "kind": "component",
    "category": "ai",
    "previewHeight": 360,
    "new": true,
    "free": true,
    "openSource": true,
    "added": "2026-10-31"
  },
  "categories": [
    "ai"
  ],
  "type": "registry:component"
}