Citations
Inline citation markers paired with a collapsible, progressively rendered reference collection for grounded agent responses.
Preview
"use client";
import { RotateCcw } from "lucide-react";
import { useReducedMotion } from "motion/react";
import { useEffect, useState } from "react";
import {
Citation,
Citations,
type CitationItem,
} from "@/components/agents/citations";
const CITATION_ITEMS: CitationItem[] = [
{
id: "motion",
title: "Motion documentation",
domain: "motion.dev",
url: "https://motion.dev/docs/react",
},
{
id: "wai",
title: "WAI accessibility patterns",
domain: "w3.org",
url: "https://www.w3.org/WAI/ARIA/apg/",
},
{
id: "react",
title: "React documentation",
domain: "react.dev",
url: "https://react.dev/learn",
},
];
function CitationsDemo() {
const reduce = useReducedMotion() ?? false;
const [visible, setVisible] = useState(reduce ? CITATION_ITEMS.length : 0);
useEffect(() => {
if (reduce) return;
const timers = CITATION_ITEMS.map((_, index) =>
window.setTimeout(() => setVisible(index + 1), 500 + index * 700),
);
return () => timers.forEach(window.clearTimeout);
}, [reduce]);
return (
<div className="space-y-4">
<p className="text-sm leading-6 text-foreground/90">
Use layout-aware motion for newly appended results{" "}
<Citation citationId="motion" index={1} idPrefix="preview-source" /> and preserve accessible
disclosure behavior <Citation citationId="wai" index={2} idPrefix="preview-source" /> as the list
grows.
</p>
<Citations
idPrefix="preview-source"
citations={CITATION_ITEMS.slice(0, visible)}
defaultOpen
/>
</div>
);
}
export function CitationsPreview() {
const [run, setRun] = useState(0);
return (
<div className="relative h-[410px] w-full max-w-lg">
<CitationsDemo key={run} />
<button
type="button"
onClick={() => setRun((value) => value + 1)}
className="absolute bottom-0 left-0 inline-flex items-center gap-1.5 rounded-md px-2 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"
>
<RotateCcw className="size-3" />
Replay
</button>
</div>
);
}
"use client";
// beui.dev/components/agents/citations
import { BookOpenText, ChevronDown, ExternalLink, Globe2 } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
type ReactNode,
useCallback,
useId,
useState,
} from "react";
import { AgentDisclosure } from "@/components/agents/agent-disclosure";
import { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from "@/lib/ease";
import { useFavicon } from "@/lib/hooks/use-favicon";
import { cn } from "@/lib/utils";
export interface CitationItem {
id: string;
title: ReactNode;
domain?: ReactNode;
url?: string;
}
export interface CitationsProps {
citations: CitationItem[];
title?: ReactNode;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
idPrefix?: string;
className?: string;
}
export interface CitationProps {
citationId: string;
index: number;
/** Must match the related Citations idPrefix. */
idPrefix: string;
className?: string;
}
export interface CitationListProps {
citations: CitationItem[];
idPrefix?: string;
className?: string;
}
export interface CitationStackProps {
citations: CitationItem[];
limit?: number;
className?: string;
}
function citationTargetId(prefix: string, citationId: string) {
return `${prefix}-${citationId.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
}
export function Citation({
citationId,
index,
idPrefix,
className,
}: CitationProps) {
return (
<a
href={`#${citationTargetId(idPrefix, citationId)}`}
aria-label={`View citation ${index}`}
className={cn(
"mx-0.5 inline-flex min-w-4 -translate-y-0.5 items-center justify-center rounded-md bg-muted/60 px-1 py-0.5 text-[10px] font-semibold leading-none text-muted-foreground no-underline outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
className,
)}
>
{index}
</a>
);
}
export function CitationFavicon({
url,
className,
}: {
url?: string;
className?: string;
}) {
const favicon = useFavicon(url);
return (
<span
aria-hidden="true"
className={cn(
"grid size-5 shrink-0 place-items-center text-muted-foreground",
className,
)}
>
{favicon.src ? (
// biome-ignore lint/performance/noImgElement: Dynamic cross-site favicons keep this framework-agnostic registry component portable.
<img
ref={favicon.ref}
src={favicon.src}
alt=""
width={16}
height={16}
referrerPolicy="no-referrer"
className="size-4 rounded-sm object-contain"
/>
) : (
<Globe2 className="size-3.5" />
)}
</span>
);
}
export function CitationStack({
citations,
limit = 3,
className,
}: CitationStackProps) {
return (
<span
aria-hidden="true"
className={cn("flex -space-x-1.5", className)}
>
{citations.slice(0, limit).map((citation) => (
<CitationFavicon
key={citation.id}
url={citation.url}
className="size-6 rounded-full bg-background ring-2 ring-background"
/>
))}
</span>
);
}
function CitationRow({
citation,
index,
idPrefix,
}: {
citation: CitationItem;
index: number;
idPrefix: string;
}) {
const content = (
<>
<CitationFavicon url={citation.url} />
<span className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5">
<span className="truncate text-sm font-medium text-foreground/80 transition-colors group-hover/citation:text-foreground">
{citation.title}
</span>
{citation.domain ? (
<span className="min-w-0 truncate text-xs text-muted-foreground/60">
{citation.domain}
</span>
) : null}
</span>
<span className="flex shrink-0 items-center gap-1.5">
<span className="grid size-5 place-items-center rounded-md bg-foreground/[0.05] text-[10px] font-semibold tabular-nums text-muted-foreground">
{index}
</span>
{citation.url ? (
<ExternalLink className="size-3.5 text-muted-foreground/40 transition-colors group-hover/citation:text-muted-foreground" />
) : null}
</span>
</>
);
const className =
"group/citation flex items-center gap-2 rounded-md px-1.5 py-1 outline-none focus-visible:ring-2 focus-visible:ring-ring";
const id = citationTargetId(idPrefix, citation.id);
return citation.url ? (
<a
id={id}
href={citation.url}
target="_blank"
rel="noreferrer noopener"
className={className}
>
{content}
</a>
) : (
<div id={id} className={className}>
{content}
</div>
);
}
export function CitationList({
citations,
idPrefix,
className,
}: CitationListProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const resolvedPrefix =
idPrefix ?? `citation-list-${baseId.replace(/:/g, "")}`;
return (
<div className={cn("grid gap-0.5", className)}>
<AnimatePresence mode="popLayout">
{citations.map((citation, index) => (
<motion.div
layout="position"
key={citation.id}
initial={reduce ? { opacity: 1 } : { opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3 }}
transition={
reduce
? { duration: 0 }
: {
opacity: { duration: 0.18, ease: EASE_OUT },
y: SPRING_LAYOUT,
layout: SPRING_LAYOUT,
}
}
>
<CitationRow
citation={citation}
index={index + 1}
idPrefix={resolvedPrefix}
/>
</motion.div>
))}
</AnimatePresence>
</div>
);
}
export function Citations({
citations,
title = "Sources",
open,
defaultOpen = false,
onOpenChange,
idPrefix,
className,
}: CitationsProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const contentId = `${baseId}-content`;
const resolvedPrefix =
idPrefix ?? `citation-${baseId.replace(/:/g, "")}`;
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const currentOpen = open ?? internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (open === undefined) setInternalOpen(next);
onOpenChange?.(next);
},
[onOpenChange, open],
);
return (
<div className={cn("w-full text-sm", className)}>
<button
type="button"
aria-expanded={currentOpen}
aria-controls={contentId}
onClick={() => setOpen(!currentOpen)}
className="group -ml-1 flex min-h-8 items-center gap-2 rounded-lg px-1 text-left text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<BookOpenText className="size-4" />
<span className="font-medium">{title}</span>
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-semibold tabular-nums">
{citations.length}
</span>
<motion.span
aria-hidden="true"
animate={{ rotate: currentOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="text-muted-foreground/60"
>
<ChevronDown className="size-3.5" />
</motion.span>
</button>
<AgentDisclosure
id={contentId}
open={currentOpen}
>
<CitationList
citations={citations}
idPrefix={resolvedPrefix}
className="mt-1"
/>
</AgentDisclosure>
</div>
);
}
Install
Add it with the shadcn CLI, or copy the source manually.
shadcn init? You are set. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
"use client";
import { useCallback, useState } from "react";
import { getFaviconUrl } from "@/lib/favicon";
/**
* Resolves a site favicon and drops it once it is known to be unusable, so
* callers can draw their own glyph instead of a broken image. Plenty of sites
* answer `/favicon.ico` with a 403 or 404, and `onError` is not enough to catch
* it: an image the browser starts loading from server-rendered HTML usually
* fails before React attaches a handler, and that event is never replayed.
* `decode()` settles on the image's final state instead of relying on an event
* firing at the right moment.
*/
export function useFavicon(url?: string) {
const resolved = url ? getFaviconUrl(url) : null;
const [failedSrc, setFailedSrc] = useState<string | null>(null);
const src = resolved && resolved !== failedSrc ? resolved : null;
const ref = useCallback(
(img: HTMLImageElement | null) => {
if (!img || !src) return;
let released = false;
img.decode().catch(() => {
if (!released) setFailedSrc(src);
});
// The node is going away or the source changed; a late rejection then
// describes an image we are no longer showing.
return () => {
released = true;
};
},
[src],
);
return { src, ref };
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
/** Resolve a website URL to its conventional root favicon location. */
export function getFaviconUrl(value: string) {
try {
return new URL("/favicon.ico", value).toString();
} catch {
return null;
}
}
Copy the source code
"use client";
// beui.dev/components/agents/citations
import { BookOpenText, ChevronDown, ExternalLink, Globe2 } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
type ReactNode,
useCallback,
useId,
useState,
} from "react";
import { AgentDisclosure } from "@/components/agents/agent-disclosure";
import { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from "@/lib/ease";
import { useFavicon } from "@/lib/hooks/use-favicon";
import { cn } from "@/lib/utils";
export interface CitationItem {
id: string;
title: ReactNode;
domain?: ReactNode;
url?: string;
}
export interface CitationsProps {
citations: CitationItem[];
title?: ReactNode;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
idPrefix?: string;
className?: string;
}
export interface CitationProps {
citationId: string;
index: number;
/** Must match the related Citations idPrefix. */
idPrefix: string;
className?: string;
}
export interface CitationListProps {
citations: CitationItem[];
idPrefix?: string;
className?: string;
}
export interface CitationStackProps {
citations: CitationItem[];
limit?: number;
className?: string;
}
function citationTargetId(prefix: string, citationId: string) {
return `${prefix}-${citationId.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
}
export function Citation({
citationId,
index,
idPrefix,
className,
}: CitationProps) {
return (
<a
href={`#${citationTargetId(idPrefix, citationId)}`}
aria-label={`View citation ${index}`}
className={cn(
"mx-0.5 inline-flex min-w-4 -translate-y-0.5 items-center justify-center rounded-md bg-muted/60 px-1 py-0.5 text-[10px] font-semibold leading-none text-muted-foreground no-underline outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
className,
)}
>
{index}
</a>
);
}
export function CitationFavicon({
url,
className,
}: {
url?: string;
className?: string;
}) {
const favicon = useFavicon(url);
return (
<span
aria-hidden="true"
className={cn(
"grid size-5 shrink-0 place-items-center text-muted-foreground",
className,
)}
>
{favicon.src ? (
// biome-ignore lint/performance/noImgElement: Dynamic cross-site favicons keep this framework-agnostic registry component portable.
<img
ref={favicon.ref}
src={favicon.src}
alt=""
width={16}
height={16}
referrerPolicy="no-referrer"
className="size-4 rounded-sm object-contain"
/>
) : (
<Globe2 className="size-3.5" />
)}
</span>
);
}
export function CitationStack({
citations,
limit = 3,
className,
}: CitationStackProps) {
return (
<span
aria-hidden="true"
className={cn("flex -space-x-1.5", className)}
>
{citations.slice(0, limit).map((citation) => (
<CitationFavicon
key={citation.id}
url={citation.url}
className="size-6 rounded-full bg-background ring-2 ring-background"
/>
))}
</span>
);
}
function CitationRow({
citation,
index,
idPrefix,
}: {
citation: CitationItem;
index: number;
idPrefix: string;
}) {
const content = (
<>
<CitationFavicon url={citation.url} />
<span className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5">
<span className="truncate text-sm font-medium text-foreground/80 transition-colors group-hover/citation:text-foreground">
{citation.title}
</span>
{citation.domain ? (
<span className="min-w-0 truncate text-xs text-muted-foreground/60">
{citation.domain}
</span>
) : null}
</span>
<span className="flex shrink-0 items-center gap-1.5">
<span className="grid size-5 place-items-center rounded-md bg-foreground/[0.05] text-[10px] font-semibold tabular-nums text-muted-foreground">
{index}
</span>
{citation.url ? (
<ExternalLink className="size-3.5 text-muted-foreground/40 transition-colors group-hover/citation:text-muted-foreground" />
) : null}
</span>
</>
);
const className =
"group/citation flex items-center gap-2 rounded-md px-1.5 py-1 outline-none focus-visible:ring-2 focus-visible:ring-ring";
const id = citationTargetId(idPrefix, citation.id);
return citation.url ? (
<a
id={id}
href={citation.url}
target="_blank"
rel="noreferrer noopener"
className={className}
>
{content}
</a>
) : (
<div id={id} className={className}>
{content}
</div>
);
}
export function CitationList({
citations,
idPrefix,
className,
}: CitationListProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const resolvedPrefix =
idPrefix ?? `citation-list-${baseId.replace(/:/g, "")}`;
return (
<div className={cn("grid gap-0.5", className)}>
<AnimatePresence mode="popLayout">
{citations.map((citation, index) => (
<motion.div
layout="position"
key={citation.id}
initial={reduce ? { opacity: 1 } : { opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3 }}
transition={
reduce
? { duration: 0 }
: {
opacity: { duration: 0.18, ease: EASE_OUT },
y: SPRING_LAYOUT,
layout: SPRING_LAYOUT,
}
}
>
<CitationRow
citation={citation}
index={index + 1}
idPrefix={resolvedPrefix}
/>
</motion.div>
))}
</AnimatePresence>
</div>
);
}
export function Citations({
citations,
title = "Sources",
open,
defaultOpen = false,
onOpenChange,
idPrefix,
className,
}: CitationsProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const contentId = `${baseId}-content`;
const resolvedPrefix =
idPrefix ?? `citation-${baseId.replace(/:/g, "")}`;
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const currentOpen = open ?? internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (open === undefined) setInternalOpen(next);
onOpenChange?.(next);
},
[onOpenChange, open],
);
return (
<div className={cn("w-full text-sm", className)}>
<button
type="button"
aria-expanded={currentOpen}
aria-controls={contentId}
onClick={() => setOpen(!currentOpen)}
className="group -ml-1 flex min-h-8 items-center gap-2 rounded-lg px-1 text-left text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<BookOpenText className="size-4" />
<span className="font-medium">{title}</span>
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-semibold tabular-nums">
{citations.length}
</span>
<motion.span
aria-hidden="true"
animate={{ rotate: currentOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="text-muted-foreground/60"
>
<ChevronDown className="size-3.5" />
</motion.span>
</button>
<AgentDisclosure
id={contentId}
open={currentOpen}
>
<CitationList
citations={citations}
idPrefix={resolvedPrefix}
className="mt-1"
/>
</AgentDisclosure>
</div>
);
}
"use client";
import { motion, type HTMLMotionProps, useReducedMotion } from "motion/react";
import type { CSSProperties } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface AgentDisclosureProps
extends Omit<HTMLMotionProps<"div">, "animate" | "initial"> {
open: boolean;
openHeight?: CSSProperties["height"];
}
/** Shared transform-only reveal for collapsible agent content. */
export function AgentDisclosure({
open,
openHeight = "auto",
className,
style,
transition,
...props
}: AgentDisclosureProps) {
const reduce = useReducedMotion() ?? false;
return (
<motion.div
{...props}
aria-hidden={!open}
inert={!open}
initial={false}
animate={
reduce
? { opacity: open ? 1 : 0 }
: {
opacity: open ? 1 : 0,
clipPath: open ? "inset(0 0 0% 0)" : "inset(0 0 100% 0)",
y: open ? 0 : -4,
}
}
transition={
transition ?? {
duration: reduce ? 0 : open ? 0.22 : 0.14,
ease: EASE_OUT,
}
}
className={cn("overflow-hidden", className)}
style={{
...style,
height: open ? openHeight : 0,
pointerEvents: open ? undefined : "none",
transformOrigin: "top",
}}
/>
);
}
API Reference
Citation
citationIdstring—indexnumber—idPrefixstringMust match the related Citations idPrefix.
—className?string—CitationFavicon
url?string—className?string—CitationStack
citationsCitationItem[]—limit?number3className?string—CitationList
citationsCitationItem[]—idPrefix?string—className?string—Citations
citationsCitationItem[]—title?ReactNodeSourcesopen?boolean—defaultOpen?booleanfalseonOpenChange?((open: boolean) => void)—idPrefix?string—className?string—Composition
Pair inline citation markers with a source disclosure owned by the same response.
StreamingResponse
├── Citation
└── Citations
├── CitationStack
└── CitationListNote: Streaming Response reveals the source summary when the answer completes. Message keeps cited answers within a semantic conversation row.
How it works
Citations connect a claim to supporting material without interrupting the answer. Inline markers should stay lightweight while the source collection provides enough information to inspect the evidence.
Related components
Message
Composable conversation primitives for message rows, grouped bubbles, avatars, metadata, live markers, and a mount-only trailing-edge pop-up for newly sent rows.
Todo List
A collapsible agent task plan with morphing status marks, a completion count, compact metadata, and smooth list updates.
Streaming Response
A stable response surface with completion actions, rendered content, and an expandable source summary.
Updated