{"slug":"citations","name":"Citations","description":"Inline citation markers paired with a collapsible, progressively rendered reference collection for grounded agent responses.","category":"agents","source_url":"https://beui.dev/r/citations/raw","detail_url":"https://beui.dev/r/citations","raw_url":"https://beui.dev/r/citations/raw","page_url":"https://beui.dev/components/agents/citations","markdown_url":"https://beui.dev/components/agents/citations.md","published_at":"2026-08-01","updated_at":"2026-11-25","dependencies":["clsx","lucide-react","motion","react","tailwind-merge"],"internal":["@/components/agents/agent-disclosure","@/components/agents/citations","@/lib/ease","@/lib/favicon","@/lib/hooks/use-favicon","@/lib/i18n","@/lib/utils"],"install_slugs":["citations"],"requires_theme":false,"props":[{"displayName":"Citation","props":[{"name":"citationId","type":"string","required":true,"defaultValue":null,"description":"Id of the `CitationItem` this marker links to."},{"name":"index","type":"number","required":true,"defaultValue":null,"description":"Number shown on the marker."},{"name":"idPrefix","type":"string","required":true,"defaultValue":null,"description":"Must match the related Citations idPrefix."},{"name":"label","type":"string","required":false,"defaultValue":null,"description":"Accessible name for the marker. Defaults to `View citation {index}`. Include\nthe index so voice control users can say the number they see."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the marker link."}]},{"displayName":"CitationFavicon","props":[{"name":"url","type":"string","required":false,"defaultValue":null,"description":"Page whose site favicon is shown. A globe icon shows when absent or broken."},{"name":"icon","type":"ReactNode","required":false,"defaultValue":null,"description":"Drawn instead of the favicon when truthy."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"CitationStack","props":[{"name":"citations","type":"CitationItem[]","required":true,"defaultValue":null,"description":"Sources whose favicons are stacked."},{"name":"limit","type":"number","required":false,"defaultValue":"3","description":"Most favicons to show. Default: 3"},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"CitationList","props":[{"name":"citations","type":"CitationItem[]","required":true,"defaultValue":null,"description":"Sources listed in order, numbered from 1."},{"name":"idPrefix","type":"string","required":false,"defaultValue":null,"description":"Prefix for row ids that `Citation` markers link to. Generated when omitted."},{"name":"highlightedId","type":"string","required":false,"defaultValue":null,"description":"The citation a marker just led to; its row is lit."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"Citations","props":[{"name":"citations","type":"CitationItem[]","required":true,"defaultValue":null,"description":"Sources listed in order, numbered from 1."},{"name":"title","type":"ReactNode","required":false,"defaultValue":null,"description":"Text of the toggle button. Default: \"Sources\""},{"name":"open","type":"boolean","required":false,"defaultValue":null,"description":"Whether the list is expanded, for controlled use."},{"name":"defaultOpen","type":"boolean","required":false,"defaultValue":"false","description":"Whether the list starts expanded when uncontrolled. Default: false"},{"name":"onOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the new state when the list expands or collapses."},{"name":"idPrefix","type":"string","required":false,"defaultValue":null,"description":"Prefix for row ids that `Citation` markers link to. Generated when omitted."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."},{"name":"labels","type":"Partial<{ title: string; viewCitation: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."}]}],"types":[{"name":"CitationItem","file":"components/agents/citations.tsx","fields":[{"name":"id","type":"string","required":true,"description":"Unique key for the source, matched by a `Citation` marker's `citationId`."},{"name":"title","type":"ReactNode","required":true,"description":"Source name shown as the row's main text."},{"name":"domain","type":"ReactNode","required":false,"description":"Muted text after the title, such as the site's host."},{"name":"url","type":"string","required":false,"description":"Link opened in a new tab and the favicon source. Omit for a plain row."},{"name":"icon","type":"ReactNode","required":false,"description":"Replaces the URL favicon, e.g. a document icon for non-web sources. An svg\nchild is sized to match the favicon; falsy values fall back to the favicon."}]}],"files":[{"path":"components/agents/citations.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/citations\n\nimport { BookOpenText, ChevronDown, ExternalLink, Globe2 } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { AgentDisclosure } from \"@/components/agents/agent-disclosure\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useFavicon } from \"@/lib/hooks/use-favicon\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport const citationsMessages = {\n  title: \"Sources\",\n  viewCitation: \"View citation {index}\",\n};\n\nexport type CitationsMessages = typeof citationsMessages;\n\nexport interface CitationItem {\n  /** Unique key for the source, matched by a `Citation` marker's `citationId`. */\n  id: string;\n  /** Source name shown as the row's main text. */\n  title: ReactNode;\n  /** Muted text after the title, such as the site's host. */\n  domain?: ReactNode;\n  /** Link opened in a new tab and the favicon source. Omit for a plain row. */\n  url?: string;\n  /**\n   * Replaces the URL favicon, e.g. a document icon for non-web sources. An svg\n   * child is sized to match the favicon; falsy values fall back to the favicon.\n   */\n  icon?: ReactNode;\n}\n\nexport interface CitationsProps {\n  /** Sources listed in order, numbered from 1. */\n  citations: CitationItem[];\n  /** Text of the toggle button. Default: \"Sources\" */\n  title?: ReactNode;\n  /** Whether the list is expanded, for controlled use. */\n  open?: boolean;\n  /** Whether the list starts expanded when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new state when the list expands or collapses. */\n  onOpenChange?: (open: boolean) => void;\n  /** Prefix for row ids that `Citation` markers link to. Generated when omitted. */\n  idPrefix?: string;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Override any built-in string. */\n  labels?: Partial<CitationsMessages>;\n}\n\nexport interface CitationProps {\n  /** Id of the `CitationItem` this marker links to. */\n  citationId: string;\n  /** Number shown on the marker. */\n  index: number;\n  /** Must match the related Citations idPrefix. */\n  idPrefix: string;\n  /**\n   * Accessible name for the marker. Defaults to `View citation {index}`. Include\n   * the index so voice control users can say the number they see.\n   */\n  label?: string;\n  /** Classes merged onto the marker link. */\n  className?: string;\n}\n\nexport interface CitationListProps {\n  /** Sources listed in order, numbered from 1. */\n  citations: CitationItem[];\n  /** Prefix for row ids that `Citation` markers link to. Generated when omitted. */\n  idPrefix?: string;\n  /** The citation a marker just led to; its row is lit. */\n  highlightedId?: string;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nexport interface CitationStackProps {\n  /** Sources whose favicons are stacked. */\n  citations: CitationItem[];\n  /** Most favicons to show. Default: 3 */\n  limit?: number;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nfunction citationTargetId(prefix: string, citationId: string) {\n  return `${prefix}-${citationId.replace(/[^a-zA-Z0-9_-]/g, \"-\")}`;\n}\n\nexport function Citation({\n  citationId,\n  index,\n  idPrefix,\n  label,\n  className,\n}: CitationProps) {\n  const t = useMessages(\"citations\", citationsMessages);\n  return (\n    <a\n      href={`#${citationTargetId(idPrefix, citationId)}`}\n      aria-label={label ?? t(\"viewCitation\", { index })}\n      className={cn(\n        // A foreground tint, not bg-muted: muted is the bubble colour, so a\n        // muted marker would vanish inside a soft bubble.\n        \"mx-0.5 inline-flex min-w-4 -translate-y-0.5 items-center justify-center rounded-full bg-foreground/[0.07] px-1 py-0.5 text-[11px] font-medium leading-none text-muted-foreground no-underline outline-none transition-colors hover:bg-foreground/[0.12] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n        className,\n      )}\n    >\n      {index}\n    </a>\n  );\n}\n\nexport function CitationFavicon({\n  url,\n  icon,\n  className,\n}: {\n  /** Page whose site favicon is shown. A globe icon shows when absent or broken. */\n  url?: string;\n  /** Drawn instead of the favicon when truthy. */\n  icon?: ReactNode;\n  className?: string;\n}) {\n  const favicon = useFavicon(icon ? undefined : url);\n\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={cn(\n        \"grid size-5 shrink-0 place-items-center text-muted-foreground [&>svg]:size-3.5\",\n        className,\n      )}\n    >\n      {icon ? (\n        icon\n      ) : favicon.src ? (\n        <img\n          ref={favicon.ref}\n          src={favicon.src}\n          alt=\"\"\n          width={16}\n          height={16}\n          referrerPolicy=\"no-referrer\"\n          className=\"size-4 rounded-sm object-contain\"\n        />\n      ) : (\n        <Globe2 className=\"size-3.5\" />\n      )}\n    </span>\n  );\n}\n\nexport function CitationStack({\n  citations,\n  limit = 3,\n  className,\n}: CitationStackProps) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={cn(\"flex -space-x-1.5\", className)}\n    >\n      {citations.slice(0, limit).map((citation) => (\n        <CitationFavicon\n          key={citation.id}\n          url={citation.url}\n          icon={citation.icon}\n          className=\"size-6 rounded-full bg-background ring-2 ring-background\"\n        />\n      ))}\n    </span>\n  );\n}\n\nfunction CitationRow({\n  citation,\n  index,\n  idPrefix,\n  highlighted,\n}: {\n  citation: CitationItem;\n  index: number;\n  idPrefix: string;\n  highlighted: boolean;\n}) {\n  const content = (\n    <>\n      <CitationFavicon url={citation.url} icon={citation.icon} />\n      <span className=\"flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5\">\n        <span className=\"truncate text-sm font-medium text-foreground/80 transition-colors group-hover/citation:text-foreground\">\n          {citation.title}\n        </span>\n        {citation.domain ? (\n          <span className=\"min-w-0 truncate text-xs text-muted-foreground/60\">\n            {citation.domain}\n          </span>\n        ) : null}\n      </span>\n      <span className=\"flex shrink-0 items-center gap-1.5\">\n        <span className=\"grid size-5 place-items-center rounded-full bg-foreground/[0.05] text-[11px] font-medium tabular-nums text-muted-foreground\">\n          {index}\n        </span>\n        {citation.url ? (\n          <ExternalLink className=\"size-3.5 text-muted-foreground/40 transition-colors group-hover/citation:text-muted-foreground\" />\n        ) : null}\n      </span>\n    </>\n  );\n  // The row a marker just led to is lit, so the reader sees which source they\n  // landed on: `highlighted` from Citations, or `:target` after a plain jump.\n  const className = cn(\n    \"group/citation flex scroll-my-3 items-center gap-2 rounded-lg px-1.5 py-1 outline-none transition-colors duration-200 hover:bg-foreground/[0.04] focus-visible:ring-2 focus-visible:ring-ring target:bg-foreground/[0.07]\",\n    highlighted && \"bg-foreground/[0.07] hover:bg-foreground/[0.07]\",\n  );\n  const id = citationTargetId(idPrefix, citation.id);\n\n  return citation.url ? (\n    <a\n      id={id}\n      href={citation.url}\n      target=\"_blank\"\n      rel=\"noreferrer noopener\"\n      className={className}\n    >\n      {content}\n    </a>\n  ) : (\n    <div id={id} className={className}>\n      {content}\n    </div>\n  );\n}\n\nexport function CitationList({\n  citations,\n  idPrefix,\n  highlightedId,\n  className,\n}: CitationListProps) {\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const resolvedPrefix =\n    idPrefix ?? `citation-list-${baseId.replace(/:/g, \"\")}`;\n\n  return (\n    <div className={cn(\"grid gap-0.5\", className)}>\n      <AnimatePresence mode=\"popLayout\">\n        {citations.map((citation, index) => (\n          <motion.div\n            layout=\"position\"\n            key={citation.id}\n            initial={reduce ? { opacity: 1 } : { opacity: 0, y: 6 }}\n            animate={{ opacity: 1, y: 0 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3 }}\n            transition={\n              reduce\n                ? { duration: 0 }\n                : {\n                    opacity: { duration: 0.18, ease: EASE_OUT },\n                    y: SPRING_LAYOUT,\n                    layout: SPRING_LAYOUT,\n                  }\n            }\n          >\n            <CitationRow\n              citation={citation}\n              index={index + 1}\n              idPrefix={resolvedPrefix}\n              highlighted={citation.id === highlightedId}\n            />\n          </motion.div>\n        ))}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nexport function Citations({\n  citations,\n  title,\n  open,\n  defaultOpen = false,\n  onOpenChange,\n  idPrefix,\n  className,\n  labels,\n}: CitationsProps) {\n  const t = useMessages(\"citations\", citationsMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const contentId = `${baseId}-content`;\n  const resolvedPrefix =\n    idPrefix ?? `citation-${baseId.replace(/:/g, \"\")}`;\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const currentOpen = open ?? internalOpen;\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (open === undefined) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [onOpenChange, open],\n  );\n\n  // A marker links to its source row. While the list is folded that row is\n  // hidden, so the jump would land on nothing: open the list, then bring the\n  // row into view once it is shown.\n  const [highlightedId, setHighlightedId] = useState<string>();\n  const latest = useRef({ currentOpen, setOpen, citations, reduce });\n  useLayoutEffect(() => {\n    latest.current = { currentOpen, setOpen, citations, reduce };\n  });\n  useEffect(() => {\n    // Returns true when the hash names one of this list's sources.\n    const reveal = (hash: string) => {\n      const now = latest.current;\n      const citation = now.citations.find(\n        (item) => citationTargetId(resolvedPrefix, item.id) === hash,\n      );\n      if (!citation) return false;\n      if (!now.currentOpen) now.setOpen(true);\n      setHighlightedId(citation.id);\n      // After the list has opened, bring the row just into view: no jump to\n      // the top of the page, where a sticky header would cover it.\n      window.setTimeout(() => {\n        document.getElementById(hash)?.scrollIntoView({\n          block: \"nearest\",\n          behavior: now.reduce ? \"auto\" : \"smooth\",\n        });\n      }, 0);\n      return true;\n    };\n    const onHash = () => reveal(decodeURIComponent(window.location.hash.slice(1)));\n    // Marker clicks are handled here rather than as a plain jump, which\n    // lands on nothing while the list is folded and pins the row under the\n    // page header when it is open.\n    const onClick = (event: MouseEvent) => {\n      const link = (event.target as Element | null)?.closest?.(\"a[href^='#']\");\n      if (!link) return;\n      if (reveal(decodeURIComponent(link.getAttribute(\"href\")?.slice(1) ?? \"\"))) {\n        event.preventDefault();\n      }\n    };\n    window.addEventListener(\"hashchange\", onHash);\n    document.addEventListener(\"click\", onClick);\n    return () => {\n      window.removeEventListener(\"hashchange\", onHash);\n      document.removeEventListener(\"click\", onClick);\n    };\n  }, [resolvedPrefix]);\n\n  return (\n    <div className={cn(\"w-full text-sm\", className)}>\n      <button\n        type=\"button\"\n        aria-expanded={currentOpen}\n        aria-controls={contentId}\n        onClick={() => setOpen(!currentOpen)}\n        className=\"group -ml-1 flex min-h-8 items-center gap-2 rounded-full px-1 text-left text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n      >\n        <BookOpenText className=\"size-4\" />\n        <span className=\"font-medium\">{title ?? t(\"title\")}</span>\n        <span className=\"rounded-full bg-foreground/[0.06] px-1.5 py-0.5 text-[11px] font-medium tabular-nums\">\n          {citations.length}\n        </span>\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: currentOpen ? 180 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n          className=\"text-muted-foreground/60\"\n        >\n          <ChevronDown className=\"size-3.5\" />\n        </motion.span>\n      </button>\n\n      <AgentDisclosure\n        id={contentId}\n        open={currentOpen}\n      >\n        <CitationList\n          citations={citations}\n          idPrefix={resolvedPrefix}\n          highlightedId={highlightedId}\n          className=\"mt-1\"\n        />\n      </AgentDisclosure>\n    </div>\n  );\n}\n"},{"path":"components/agents/agent-disclosure.tsx","type":"util","content":"\"use client\";\n\nimport { motion, type HTMLMotionProps, useReducedMotion } from \"motion/react\";\nimport { type CSSProperties, useState } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface AgentDisclosureProps\n  extends Omit<HTMLMotionProps<\"div\">, \"animate\" | \"initial\"> {\n  open: boolean;\n  openHeight?: CSSProperties[\"height\"];\n}\n\n/**\n * Shared reveal for collapsible agent content: a clip, fade and short drop,\n * never an animated height. The box takes its height as soon as it opens and\n * gives it up only once the closing reveal has played, so the exit is seen\n * and mirrors the entrance.\n */\nexport function AgentDisclosure({\n  open,\n  openHeight = \"auto\",\n  className,\n  style,\n  transition,\n  onAnimationComplete,\n  ...props\n}: AgentDisclosureProps) {\n  const reduce = useReducedMotion() ?? false;\n  const [collapsed, setCollapsed] = useState(!open);\n  if (open && collapsed) setCollapsed(false);\n\n  return (\n    <motion.div\n      {...props}\n      aria-hidden={!open}\n      inert={!open}\n      initial={false}\n      animate={\n        reduce\n          ? { opacity: open ? 1 : 0 }\n          : {\n              opacity: open ? 1 : 0,\n              clipPath: open ? \"inset(0 0 0% 0)\" : \"inset(0 0 100% 0)\",\n              y: open ? 0 : -4,\n            }\n      }\n      transition={\n        transition ?? {\n          duration: reduce ? 0 : open ? 0.22 : 0.14,\n          ease: EASE_OUT,\n        }\n      }\n      onAnimationComplete={(definition) => {\n        if (!open) setCollapsed(true);\n        onAnimationComplete?.(definition);\n      }}\n      className={cn(\"overflow-hidden\", className)}\n      style={{\n        ...style,\n        height: collapsed ? 0 : openHeight,\n        pointerEvents: open ? undefined : \"none\",\n        transformOrigin: \"top\",\n      }}\n    />\n  );\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps - label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances - modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides - pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/hooks/use-favicon.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useState } from \"react\";\nimport { getFaviconUrl } from \"@/lib/favicon\";\n\n/**\n * Resolves a site favicon and drops it once it is known to be unusable, so\n * callers can draw their own glyph instead of a broken image. Plenty of sites\n * answer `/favicon.ico` with a 403 or 404, and `onError` is not enough to catch\n * it: an image the browser starts loading from server-rendered HTML usually\n * fails before React attaches a handler, and that event is never replayed.\n * `decode()` settles on the image's final state instead of relying on an event\n * firing at the right moment.\n */\nexport function useFavicon(url?: string) {\n  const resolved = url ? getFaviconUrl(url) : null;\n  const [failedSrc, setFailedSrc] = useState<string | null>(null);\n  const src = resolved && resolved !== failedSrc ? resolved : null;\n\n  const ref = useCallback(\n    (img: HTMLImageElement | null) => {\n      if (!img || !src) return;\n\n      let released = false;\n      img.decode().catch(() => {\n        if (!released) setFailedSrc(src);\n      });\n\n      // The node is going away or the source changed; a late rejection then\n      // describes an image we are no longer showing.\n      return () => {\n        released = true;\n      };\n    },\n    [src],\n  );\n\n  return { src, ref };\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"lib/favicon.ts","type":"util","content":"/** Resolve a website URL to its conventional root favicon location. */\nexport function getFaviconUrl(value: string) {\n  try {\n    return new URL(\"/favicon.ico\", value).toString();\n  } catch {\n    return null;\n  }\n}\n"},{"path":"components/previews/agents/citations.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { FileText, RotateCcw } from \"lucide-react\";\nimport { useReducedMotion } from \"motion/react\";\nimport { useEffect, useState } from \"react\";\nimport {\n  Citation,\n  Citations,\n  type CitationItem,\n} from \"@/components/agents/citations\";\n\nconst CITATION_ITEMS: CitationItem[] = [\n  {\n    id: \"motion\",\n    title: \"Motion documentation\",\n    domain: \"motion.dev\",\n    url: \"https://motion.dev/docs/react\",\n  },\n  {\n    id: \"wai\",\n    title: \"WAI accessibility patterns\",\n    domain: \"w3.org\",\n    url: \"https://www.w3.org/WAI/ARIA/apg/\",\n  },\n  {\n    id: \"guidelines\",\n    title: \"Motion guidelines\",\n    domain: \"Design handbook · PDF\",\n    icon: <FileText />,\n  },\n];\n\nfunction CitationsDemo() {\n  const reduce = useReducedMotion() ?? false;\n  const [visible, setVisible] = useState(reduce ? CITATION_ITEMS.length : 0);\n\n  useEffect(() => {\n    if (reduce) return;\n    const timers = CITATION_ITEMS.map((_, index) =>\n      window.setTimeout(() => setVisible(index + 1), 500 + index * 700),\n    );\n    return () => timers.forEach(window.clearTimeout);\n  }, [reduce]);\n\n  return (\n    <div className=\"space-y-4\">\n      <p className=\"text-sm leading-6 text-foreground/90\">\n        Use layout-aware motion for newly appended results{\" \"}\n        <Citation citationId=\"motion\" index={1} idPrefix=\"preview-source\" /> and preserve accessible\n        disclosure behavior <Citation citationId=\"wai\" index={2} idPrefix=\"preview-source\" /> as the list\n        grows, keeping exits shorter than entrances{\" \"}\n        <Citation\n          citationId=\"guidelines\"\n          index={3}\n          idPrefix=\"preview-source\"\n          label=\"Citation 3: Motion guidelines\"\n        />\n        .\n      </p>\n      <Citations\n        idPrefix=\"preview-source\"\n        citations={CITATION_ITEMS.slice(0, visible)}\n        defaultOpen\n      />\n    </div>\n  );\n}\n\nexport function CitationsPreview() {\n  const [run, setRun] = useState(0);\n\n  return (\n    <div className=\"relative h-[410px] w-full max-w-lg\">\n      <CitationsDemo key={run} />\n      <button\n        type=\"button\"\n        onClick={() => setRun((value) => value + 1)}\n        className=\"absolute bottom-0 left-0 inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n      >\n        <RotateCcw className=\"size-3\" />\n        Replay\n      </button>\n    </div>\n  );\n}\n"}]}