Preview
"use client";
import { FileText, 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: "guidelines",
title: "Motion guidelines",
domain: "Design handbook · PDF",
icon: <FileText />,
},
];
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, keeping exits shorter than entrances{" "}
<Citation
citationId="guidelines"
index={3}
idPrefix="preview-source"
label="Citation 3: Motion guidelines"
/>
.
</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-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"
>
<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,
useEffect,
useId,
useLayoutEffect,
useRef,
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 { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export const citationsMessages = {
title: "Sources",
viewCitation: "View citation {index}",
};
export type CitationsMessages = typeof citationsMessages;
export interface CitationItem {
/** Unique key for the source, matched by a `Citation` marker's `citationId`. */
id: string;
/** Source name shown as the row's main text. */
title: ReactNode;
/** Muted text after the title, such as the site's host. */
domain?: ReactNode;
/** Link opened in a new tab and the favicon source. Omit for a plain row. */
url?: string;
/**
* Replaces the URL favicon, e.g. a document icon for non-web sources. An svg
* child is sized to match the favicon; falsy values fall back to the favicon.
*/
icon?: ReactNode;
}
export interface CitationsProps {
/** Sources listed in order, numbered from 1. */
citations: CitationItem[];
/** Text of the toggle button. Default: "Sources" */
title?: ReactNode;
/** Whether the list is expanded, for controlled use. */
open?: boolean;
/** Whether the list starts expanded when uncontrolled. Default: false */
defaultOpen?: boolean;
/** Called with the new state when the list expands or collapses. */
onOpenChange?: (open: boolean) => void;
/** Prefix for row ids that `Citation` markers link to. Generated when omitted. */
idPrefix?: string;
/** Classes merged onto the root element. */
className?: string;
/** Override any built-in string. */
labels?: Partial<CitationsMessages>;
}
export interface CitationProps {
/** Id of the `CitationItem` this marker links to. */
citationId: string;
/** Number shown on the marker. */
index: number;
/** Must match the related Citations idPrefix. */
idPrefix: string;
/**
* Accessible name for the marker. Defaults to `View citation {index}`. Include
* the index so voice control users can say the number they see.
*/
label?: string;
/** Classes merged onto the marker link. */
className?: string;
}
export interface CitationListProps {
/** Sources listed in order, numbered from 1. */
citations: CitationItem[];
/** Prefix for row ids that `Citation` markers link to. Generated when omitted. */
idPrefix?: string;
/** The citation a marker just led to; its row is lit. */
highlightedId?: string;
/** Classes merged onto the root element. */
className?: string;
}
export interface CitationStackProps {
/** Sources whose favicons are stacked. */
citations: CitationItem[];
/** Most favicons to show. Default: 3 */
limit?: number;
/** Classes merged onto the root element. */
className?: string;
}
function citationTargetId(prefix: string, citationId: string) {
return `${prefix}-${citationId.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
}
export function Citation({
citationId,
index,
idPrefix,
label,
className,
}: CitationProps) {
const t = useMessages("citations", citationsMessages);
return (
<a
href={`#${citationTargetId(idPrefix, citationId)}`}
aria-label={label ?? t("viewCitation", { index })}
className={cn(
// A foreground tint, not bg-muted: muted is the bubble colour, so a
// muted marker would vanish inside a soft bubble.
"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",
className,
)}
>
{index}
</a>
);
}
export function CitationFavicon({
url,
icon,
className,
}: {
/** Page whose site favicon is shown. A globe icon shows when absent or broken. */
url?: string;
/** Drawn instead of the favicon when truthy. */
icon?: ReactNode;
className?: string;
}) {
const favicon = useFavicon(icon ? undefined : url);
return (
<span
aria-hidden="true"
className={cn(
"grid size-5 shrink-0 place-items-center text-muted-foreground [&>svg]:size-3.5",
className,
)}
>
{icon ? (
icon
) : favicon.src ? (
<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}
icon={citation.icon}
className="size-6 rounded-full bg-background ring-2 ring-background"
/>
))}
</span>
);
}
function CitationRow({
citation,
index,
idPrefix,
highlighted,
}: {
citation: CitationItem;
index: number;
idPrefix: string;
highlighted: boolean;
}) {
const content = (
<>
<CitationFavicon url={citation.url} icon={citation.icon} />
<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-full bg-foreground/[0.05] text-[11px] font-medium 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>
</>
);
// The row a marker just led to is lit, so the reader sees which source they
// landed on: `highlighted` from Citations, or `:target` after a plain jump.
const className = cn(
"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]",
highlighted && "bg-foreground/[0.07] hover:bg-foreground/[0.07]",
);
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,
highlightedId,
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}
highlighted={citation.id === highlightedId}
/>
</motion.div>
))}
</AnimatePresence>
</div>
);
}
export function Citations({
citations,
title,
open,
defaultOpen = false,
onOpenChange,
idPrefix,
className,
labels,
}: CitationsProps) {
const t = useMessages("citations", citationsMessages, labels);
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],
);
// A marker links to its source row. While the list is folded that row is
// hidden, so the jump would land on nothing: open the list, then bring the
// row into view once it is shown.
const [highlightedId, setHighlightedId] = useState<string>();
const latest = useRef({ currentOpen, setOpen, citations, reduce });
useLayoutEffect(() => {
latest.current = { currentOpen, setOpen, citations, reduce };
});
useEffect(() => {
// Returns true when the hash names one of this list's sources.
const reveal = (hash: string) => {
const now = latest.current;
const citation = now.citations.find(
(item) => citationTargetId(resolvedPrefix, item.id) === hash,
);
if (!citation) return false;
if (!now.currentOpen) now.setOpen(true);
setHighlightedId(citation.id);
// After the list has opened, bring the row just into view: no jump to
// the top of the page, where a sticky header would cover it.
window.setTimeout(() => {
document.getElementById(hash)?.scrollIntoView({
block: "nearest",
behavior: now.reduce ? "auto" : "smooth",
});
}, 0);
return true;
};
const onHash = () => reveal(decodeURIComponent(window.location.hash.slice(1)));
// Marker clicks are handled here rather than as a plain jump, which
// lands on nothing while the list is folded and pins the row under the
// page header when it is open.
const onClick = (event: MouseEvent) => {
const link = (event.target as Element | null)?.closest?.("a[href^='#']");
if (!link) return;
if (reveal(decodeURIComponent(link.getAttribute("href")?.slice(1) ?? ""))) {
event.preventDefault();
}
};
window.addEventListener("hashchange", onHash);
document.addEventListener("click", onClick);
return () => {
window.removeEventListener("hashchange", onHash);
document.removeEventListener("click", onClick);
};
}, [resolvedPrefix]);
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-full 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 ?? t("title")}</span>
<span className="rounded-full bg-foreground/[0.06] px-1.5 py-0.5 text-[11px] font-medium 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}
highlightedId={highlightedId}
className="mt-1"
/>
</AgentDisclosure>
</div>
);
}
Add it with the shadcn CLI, or copy the source manually.
npx shadcn add https://beui.dev/r/theme.json. 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;
/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */
export const EASE_IN = [0.55, 0, 1, 0.45] 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;
/** Shared-surface morphs: a trigger growing into its panel and back on one
* weighted spring, so opening and closing travel the same path. */
export const SPRING_MORPH = {
type: "spring",
duration: 0.5,
bounce: 0.22,
} 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 };
}
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useMemo,
} from "react";
/**
* A component's messages. Plain strings with `{name}` placeholders, so a
* dictionary stays JSON-serializable and can be passed from a server layout.
* There are no plural forms: write messages that read correctly for any count.
*/
export type Messages = Record<string, string>;
/** A language file: component namespace → any subset of that component's messages. */
export type LocaleMessages = Record<string, Partial<Messages>>;
type LocaleContextValue = {
locale?: string;
messages: LocaleMessages;
};
const NO_MESSAGES: LocaleMessages = {};
const LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });
/** Without a locale, digits stay plain so server and client render the same text. */
export function formatNumber(value: number, locale?: string) {
return locale ? new Intl.NumberFormat(locale).format(value) : String(value);
}
export interface LocaleProviderProps {
/** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */
locale: string;
/**
* Component namespace → translated strings. Missing keys fall back to English.
* Pass a stable object (a module constant, imported JSON or a memoized value):
* a new object each render gives every translated component a new `t`.
*/
messages?: LocaleMessages;
children: ReactNode;
}
export function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {
const value = useMemo(() => ({ locale, messages }), [locale, messages]);
return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;
}
export function useLocale(): { locale?: string } {
return { locale: useContext(LocaleContext).locale };
}
/**
* Resolves a component's strings: `labels` prop, then the provider's
* messages for `namespace`, then the component's English `defaults`.
* Numbers passed as values are formatted for the provider's locale.
*/
export function useMessages<T extends Messages>(
namespace: string,
defaults: T,
labels?: Partial<T>,
) {
const { locale, messages } = useContext(LocaleContext);
const provided = messages[namespace];
// Inline `labels={{ … }}` is a new object every render. Keying it by content
// keeps `t` one identity until a label changes, so effects and memos that
// depend on `t` don't re-run per render, and render-time reads never lag.
const labelsKey = labels ? JSON.stringify(labels) : "";
const stableLabels = useMemo(
() => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),
[labelsKey],
);
return useCallback(
(key: keyof T & string, values?: Record<string, string | number>) => {
const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];
if (!values) return template;
return template.replace(/\{(\w+)\}/g, (match, name: string) => {
const value = values[name];
if (value === undefined) return match;
return typeof value === "number" ? formatNumber(value, locale) : value;
});
},
[defaults, stableLabels, locale, provided],
);
}
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,
useEffect,
useId,
useLayoutEffect,
useRef,
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 { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export const citationsMessages = {
title: "Sources",
viewCitation: "View citation {index}",
};
export type CitationsMessages = typeof citationsMessages;
export interface CitationItem {
/** Unique key for the source, matched by a `Citation` marker's `citationId`. */
id: string;
/** Source name shown as the row's main text. */
title: ReactNode;
/** Muted text after the title, such as the site's host. */
domain?: ReactNode;
/** Link opened in a new tab and the favicon source. Omit for a plain row. */
url?: string;
/**
* Replaces the URL favicon, e.g. a document icon for non-web sources. An svg
* child is sized to match the favicon; falsy values fall back to the favicon.
*/
icon?: ReactNode;
}
export interface CitationsProps {
/** Sources listed in order, numbered from 1. */
citations: CitationItem[];
/** Text of the toggle button. Default: "Sources" */
title?: ReactNode;
/** Whether the list is expanded, for controlled use. */
open?: boolean;
/** Whether the list starts expanded when uncontrolled. Default: false */
defaultOpen?: boolean;
/** Called with the new state when the list expands or collapses. */
onOpenChange?: (open: boolean) => void;
/** Prefix for row ids that `Citation` markers link to. Generated when omitted. */
idPrefix?: string;
/** Classes merged onto the root element. */
className?: string;
/** Override any built-in string. */
labels?: Partial<CitationsMessages>;
}
export interface CitationProps {
/** Id of the `CitationItem` this marker links to. */
citationId: string;
/** Number shown on the marker. */
index: number;
/** Must match the related Citations idPrefix. */
idPrefix: string;
/**
* Accessible name for the marker. Defaults to `View citation {index}`. Include
* the index so voice control users can say the number they see.
*/
label?: string;
/** Classes merged onto the marker link. */
className?: string;
}
export interface CitationListProps {
/** Sources listed in order, numbered from 1. */
citations: CitationItem[];
/** Prefix for row ids that `Citation` markers link to. Generated when omitted. */
idPrefix?: string;
/** The citation a marker just led to; its row is lit. */
highlightedId?: string;
/** Classes merged onto the root element. */
className?: string;
}
export interface CitationStackProps {
/** Sources whose favicons are stacked. */
citations: CitationItem[];
/** Most favicons to show. Default: 3 */
limit?: number;
/** Classes merged onto the root element. */
className?: string;
}
function citationTargetId(prefix: string, citationId: string) {
return `${prefix}-${citationId.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
}
export function Citation({
citationId,
index,
idPrefix,
label,
className,
}: CitationProps) {
const t = useMessages("citations", citationsMessages);
return (
<a
href={`#${citationTargetId(idPrefix, citationId)}`}
aria-label={label ?? t("viewCitation", { index })}
className={cn(
// A foreground tint, not bg-muted: muted is the bubble colour, so a
// muted marker would vanish inside a soft bubble.
"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",
className,
)}
>
{index}
</a>
);
}
export function CitationFavicon({
url,
icon,
className,
}: {
/** Page whose site favicon is shown. A globe icon shows when absent or broken. */
url?: string;
/** Drawn instead of the favicon when truthy. */
icon?: ReactNode;
className?: string;
}) {
const favicon = useFavicon(icon ? undefined : url);
return (
<span
aria-hidden="true"
className={cn(
"grid size-5 shrink-0 place-items-center text-muted-foreground [&>svg]:size-3.5",
className,
)}
>
{icon ? (
icon
) : favicon.src ? (
<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}
icon={citation.icon}
className="size-6 rounded-full bg-background ring-2 ring-background"
/>
))}
</span>
);
}
function CitationRow({
citation,
index,
idPrefix,
highlighted,
}: {
citation: CitationItem;
index: number;
idPrefix: string;
highlighted: boolean;
}) {
const content = (
<>
<CitationFavicon url={citation.url} icon={citation.icon} />
<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-full bg-foreground/[0.05] text-[11px] font-medium 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>
</>
);
// The row a marker just led to is lit, so the reader sees which source they
// landed on: `highlighted` from Citations, or `:target` after a plain jump.
const className = cn(
"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]",
highlighted && "bg-foreground/[0.07] hover:bg-foreground/[0.07]",
);
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,
highlightedId,
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}
highlighted={citation.id === highlightedId}
/>
</motion.div>
))}
</AnimatePresence>
</div>
);
}
export function Citations({
citations,
title,
open,
defaultOpen = false,
onOpenChange,
idPrefix,
className,
labels,
}: CitationsProps) {
const t = useMessages("citations", citationsMessages, labels);
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],
);
// A marker links to its source row. While the list is folded that row is
// hidden, so the jump would land on nothing: open the list, then bring the
// row into view once it is shown.
const [highlightedId, setHighlightedId] = useState<string>();
const latest = useRef({ currentOpen, setOpen, citations, reduce });
useLayoutEffect(() => {
latest.current = { currentOpen, setOpen, citations, reduce };
});
useEffect(() => {
// Returns true when the hash names one of this list's sources.
const reveal = (hash: string) => {
const now = latest.current;
const citation = now.citations.find(
(item) => citationTargetId(resolvedPrefix, item.id) === hash,
);
if (!citation) return false;
if (!now.currentOpen) now.setOpen(true);
setHighlightedId(citation.id);
// After the list has opened, bring the row just into view: no jump to
// the top of the page, where a sticky header would cover it.
window.setTimeout(() => {
document.getElementById(hash)?.scrollIntoView({
block: "nearest",
behavior: now.reduce ? "auto" : "smooth",
});
}, 0);
return true;
};
const onHash = () => reveal(decodeURIComponent(window.location.hash.slice(1)));
// Marker clicks are handled here rather than as a plain jump, which
// lands on nothing while the list is folded and pins the row under the
// page header when it is open.
const onClick = (event: MouseEvent) => {
const link = (event.target as Element | null)?.closest?.("a[href^='#']");
if (!link) return;
if (reveal(decodeURIComponent(link.getAttribute("href")?.slice(1) ?? ""))) {
event.preventDefault();
}
};
window.addEventListener("hashchange", onHash);
document.addEventListener("click", onClick);
return () => {
window.removeEventListener("hashchange", onHash);
document.removeEventListener("click", onClick);
};
}, [resolvedPrefix]);
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-full 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 ?? t("title")}</span>
<span className="rounded-full bg-foreground/[0.06] px-1.5 py-0.5 text-[11px] font-medium 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}
highlightedId={highlightedId}
className="mt-1"
/>
</AgentDisclosure>
</div>
);
}
"use client";
import { motion, type HTMLMotionProps, useReducedMotion } from "motion/react";
import { type CSSProperties, useState } 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 reveal for collapsible agent content: a clip, fade and short drop,
* never an animated height. The box takes its height as soon as it opens and
* gives it up only once the closing reveal has played, so the exit is seen
* and mirrors the entrance.
*/
export function AgentDisclosure({
open,
openHeight = "auto",
className,
style,
transition,
onAnimationComplete,
...props
}: AgentDisclosureProps) {
const reduce = useReducedMotion() ?? false;
const [collapsed, setCollapsed] = useState(!open);
if (open && collapsed) setCollapsed(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,
}
}
onAnimationComplete={(definition) => {
if (!open) setCollapsed(true);
onAnimationComplete?.(definition);
}}
className={cn("overflow-hidden", className)}
style={{
...style,
height: collapsed ? 0 : openHeight,
pointerEvents: open ? undefined : "none",
transformOrigin: "top",
}}
/>
);
}
citationIdstringId of the `CitationItem` this marker links to.
indexnumberNumber shown on the marker.
idPrefixstringMust match the related Citations idPrefix.
label?stringAccessible name for the marker. Defaults to `View citation {index}`. Include the index so voice control users can say the number they see.
className?stringClasses merged onto the marker link.
url?stringPage whose site favicon is shown. A globe icon shows when absent or broken.
icon?ReactNodeDrawn instead of the favicon when truthy.
className?stringClasses merged onto the root element.
citationsCitationItem[]Sources whose favicons are stacked.
limit?numberMost favicons to show. Default: 3
3className?stringClasses merged onto the root element.
citationsCitationItem[]Sources listed in order, numbered from 1.
idPrefix?stringPrefix for row ids that `Citation` markers link to. Generated when omitted.
highlightedId?stringThe citation a marker just led to; its row is lit.
className?stringClasses merged onto the root element.
citationsCitationItem[]Sources listed in order, numbered from 1.
title?ReactNodeText of the toggle button. Default: "Sources"
open?booleanWhether the list is expanded, for controlled use.
defaultOpen?booleanWhether the list starts expanded when uncontrolled. Default: false
falseonOpenChange?((open: boolean) => void)Called with the new state when the list expands or collapses.
idPrefix?stringPrefix for row ids that `Citation` markers link to. Generated when omitted.
className?stringClasses merged onto the root element.
labels?Partial<{ title: string; viewCitation: string; }>Override any built-in string.
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.
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.
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