- Accordion
- Attachment
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Card
- Checkbox
- Code Block
- Collapsible
- Dialog
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input
- Input Group
- Input OTP
- Item
- Label
- Marker
- Message
- Number Flow
- Pagination
- Popover
- Progress
- Radio Group
- Select
- Slider
- Sonner
- Spinner
- Switch
- Tooltip
- Separator
- Sheet
- Tabs
- Textarea
- Toggle
- Toggle Group
- Trace
Next.js streams a route in chunks, so the page shows up before every request finishes.
Wrap a slow part of the page in a Suspense boundary and React sends the fallback first. When the data resolves, the finished HTML streams into the same response and replaces the fallback, with no extra request from the browser. Server Components help here, because their code never ships to the browser.
A loading.tsx file does the same for a whole route segment. It all runs over chunked transfer encoding, so there is nothing extra to set up.
"use client";
import { Button } from "@/components/ui/button";
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/components/ui/hover-card";
interface Source {
description: string;
title: string;
url: string;
}
const sources = {
chunked: {
description: "Send a response as a series of chunks.",
title: "Transfer-Encoding",
url: "https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Transfer-Encoding",
},
loading: {
description: "Show an instant loading state for a route segment.",
title: "loading.js",
url: "https://nextjs.org/docs/app/api-reference/file-conventions/loading",
},
serverComponents: {
description: "Components that render ahead of time, on the server.",
title: "Server Components",
url: "https://react.dev/reference/rsc/server-components",
},
streaming: {
description: "How the App Router streams a route to the browser.",
title: "Linking and Navigating",
url: "https://nextjs.org/docs/app/getting-started/linking-and-navigating#streaming",
},
suspense: {
description: "Display a fallback until its children have finished loading.",
title: "<Suspense>",
url: "https://react.dev/reference/react/Suspense",
},
} satisfies Record<string, Source>;
function hostname(url: string) {
return new URL(url).hostname.replace(/^www\./u, "");
}
function Citation({ source }: { source: Source }) {
const host = hostname(source.url);
return (
<HoverCard closeDelay={100} openDelay={10}>
<HoverCardTrigger
as={Button}
className="h-5 rounded-full px-2 text-xs font-medium"
size="sm"
variant="secondary"
>
{host}
</HoverCardTrigger>
<HoverCardContent className="flex w-64 flex-col gap-1">
<div className="font-medium">{source.title}</div>
<p className="text-muted-foreground">{source.description}</p>
<a
className="text-muted-foreground text-xs underline-offset-4 hover:underline"
href={source.url}
rel="noreferrer"
target="_blank"
>
{host}
<span className="sr-only"> (opens in a new tab)</span>
</a>
</HoverCardContent>
</HoverCard>
);
}
export function InlineCitationDemo() {
return (
<div className="mx-auto flex max-w-sm flex-col gap-3 py-6 text-sm leading-relaxed">
<p>
Next.js streams a route in chunks, so the page shows up before every
request finishes. <Citation source={sources.streaming} />
</p>
<p>
Wrap a slow part of the page in a Suspense boundary and React sends the
fallback first. When the data resolves, the finished HTML streams into
the same response and replaces the fallback, with no extra request from
the browser. <Citation source={sources.suspense} /> Server Components
help here, because their code never ships to the browser.
<Citation source={sources.serverComponents} />
</p>
<p>
A loading.tsx file does the same for a whole route segment.
<Citation source={sources.loading} /> It all runs over chunked transfer
encoding, so there is nothing extra to set up.
<Citation source={sources.chunked} />
</p>
</div>
);
}Inline Citation is a compact source badge that expands into a HoverCard with the title, description, and a link to the original page. It composes HoverCard and Button, so the badge inherits the button's focus and the card's portal behavior.
Inline Citation is a composition, not a primitive. Install the two primitives it uses, then wire it the same way the demo does.
Installation
$ bunx --bun frakment add hover-card button$ npx frakment add hover-card button$ pnpm dlx frakment add hover-card button$ yarn dlx frakment add hover-card button
Install the following dependencies:
$ bun add radix-ui$ npm install radix-ui$ pnpm add radix-ui$ yarn add radix-ui
Install the required registry primitives:
"use client";
import * as React from "react";
import { createPortal } from "react-dom";
import { cn } from "@/lib/utils";
type Side = "top" | "right" | "bottom" | "left";
type Align = "start" | "center" | "end";
interface HoverCardContextValue {
contentRef: React.RefObject<HTMLDivElement | null>;
open: boolean;
scheduleClose: () => void;
scheduleOpen: () => void;
setOpen: (open: boolean) => void;
triggerRef: React.RefObject<HTMLElement | null>;
}
const HoverCardContext = React.createContext<HoverCardContextValue | null>(
null
);
function useHoverCardContext(): HoverCardContextValue {
const ctx = React.useContext(HoverCardContext);
if (!ctx) {
throw new Error("HoverCard components must be used within <HoverCard>.");
}
return ctx;
}
interface HoverCardProps {
children?: React.ReactNode;
closeDelay?: number;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
open?: boolean;
openDelay?: number;
}
function HoverCard({
children,
open: openProp,
defaultOpen = false,
onOpenChange,
openDelay = 700,
closeDelay = 300,
}: HoverCardProps) {
const isControlled = openProp !== undefined;
const [uncontrolled, setUncontrolled] = React.useState(defaultOpen);
const open = isControlled ? openProp : uncontrolled;
const triggerRef = React.useRef<HTMLElement | null>(null);
const contentRef = React.useRef<HTMLDivElement | null>(null);
const openTimerRef = React.useRef<number | null>(null);
const closeTimerRef = React.useRef<number | null>(null);
const clearTimers = React.useCallback(() => {
if (openTimerRef.current !== null) {
window.clearTimeout(openTimerRef.current);
openTimerRef.current = null;
}
if (closeTimerRef.current !== null) {
window.clearTimeout(closeTimerRef.current);
closeTimerRef.current = null;
}
}, []);
const setOpen = React.useCallback(
(next: boolean) => {
if (!isControlled) {
setUncontrolled(next);
}
onOpenChange?.(next);
},
[isControlled, onOpenChange]
);
const scheduleOpen = React.useCallback(() => {
if (closeTimerRef.current !== null) {
window.clearTimeout(closeTimerRef.current);
closeTimerRef.current = null;
}
if (open) {
return;
}
openTimerRef.current = window.setTimeout(() => {
openTimerRef.current = null;
setOpen(true);
}, openDelay);
}, [open, openDelay, setOpen]);
const scheduleClose = React.useCallback(() => {
if (openTimerRef.current !== null) {
window.clearTimeout(openTimerRef.current);
openTimerRef.current = null;
}
if (!open) {
return;
}
closeTimerRef.current = window.setTimeout(() => {
closeTimerRef.current = null;
setOpen(false);
}, closeDelay);
}, [open, closeDelay, setOpen]);
React.useEffect(() => clearTimers, [clearTimers]);
const ctx = React.useMemo<HoverCardContextValue>(
() => ({
contentRef,
open,
scheduleClose,
scheduleOpen,
setOpen,
triggerRef,
}),
[open, setOpen, scheduleOpen, scheduleClose]
);
return (
<HoverCardContext.Provider value={ctx}>
{children}
</HoverCardContext.Provider>
);
}
type HoverCardTriggerProps = Omit<
React.ComponentPropsWithoutRef<"button">,
"ref"
> &
Record<string, unknown> & {
as?: React.ElementType;
asChild?: boolean;
ref?: React.Ref<HTMLElement>;
};
function HoverCardTrigger({
as,
asChild,
children,
onBlur,
onFocus,
onPointerEnter,
onPointerLeave,
ref,
...props
}: HoverCardTriggerProps) {
const ctx = useHoverCardContext();
const setRef = React.useCallback(
(node: HTMLElement | null) => {
ctx.triggerRef.current = node;
if (typeof ref === "function") {
ref(node);
} else if (ref) {
(ref as React.MutableRefObject<HTMLElement | null>).current = node;
}
},
[ctx.triggerRef, ref]
);
const handlers = {
onBlur: (e: React.FocusEvent<HTMLElement>) => {
onBlur?.(e as never);
if (!e.defaultPrevented) {
ctx.scheduleClose();
}
},
onFocus: (e: React.FocusEvent<HTMLElement>) => {
onFocus?.(e as never);
if (!e.defaultPrevented) {
ctx.scheduleOpen();
}
},
onPointerEnter: (e: React.PointerEvent<HTMLElement>) => {
onPointerEnter?.(e as never);
if (!e.defaultPrevented) {
ctx.scheduleOpen();
}
},
onPointerLeave: (e: React.PointerEvent<HTMLElement>) => {
onPointerLeave?.(e as never);
if (!e.defaultPrevented) {
ctx.scheduleClose();
}
},
};
const state = ctx.open ? "open" : "closed";
if (asChild && React.isValidElement(children)) {
const child = children as React.ReactElement<Record<string, unknown>>;
return React.cloneElement(child, {
...props,
...handlers,
"data-slot": "hover-card-trigger",
"data-state": state,
ref: setRef,
} as never);
}
const Component = (as ?? "button") as React.ElementType;
const isNativeButton = !as;
return (
<Component
data-slot="hover-card-trigger"
data-state={state}
{...props}
{...(isNativeButton ? { type: "button" as const } : {})}
{...handlers}
ref={setRef}
>
{children}
</Component>
);
}
type HoverCardContentProps = React.ComponentPropsWithoutRef<"div"> & {
align?: Align;
side?: Side;
sideOffset?: number;
ref?: React.Ref<HTMLDivElement>;
};
interface Position {
left: number;
side: Side;
top: number;
}
function computePosition(
trigger: HTMLElement,
content: HTMLElement,
side: Side,
align: Align,
offset: number
): Position {
const t = trigger.getBoundingClientRect();
const c = content.getBoundingClientRect();
const vw = window.innerWidth;
const vh = window.innerHeight;
let actualSide: Side = side;
if (
side === "bottom" &&
t.bottom + offset + c.height > vh &&
t.top > vh - t.bottom
) {
actualSide = "top";
} else if (
side === "top" &&
t.top - offset - c.height < 0 &&
vh - t.bottom > t.top
) {
actualSide = "bottom";
} else if (
side === "right" &&
t.right + offset + c.width > vw &&
t.left > vw - t.right
) {
actualSide = "left";
} else if (
side === "left" &&
t.left - offset - c.width < 0 &&
vw - t.right > t.left
) {
actualSide = "right";
}
let top = 0;
let left = 0;
if (actualSide === "bottom") {
top = t.bottom + offset;
} else if (actualSide === "top") {
top = t.top - c.height - offset;
} else if (actualSide === "right") {
top = t.top + (t.height - c.height) / 2;
} else {
top = t.top + (t.height - c.height) / 2;
}
if (actualSide === "bottom" || actualSide === "top") {
if (align === "start") {
left = t.left;
} else if (align === "end") {
left = t.right - c.width;
} else {
left = t.left + (t.width - c.width) / 2;
}
} else if (actualSide === "right") {
left = t.right + offset;
} else {
left = t.left - c.width - offset;
}
left = Math.max(8, Math.min(left, vw - c.width - 8));
top = Math.max(8, Math.min(top, vh - c.height - 8));
return { left, side: actualSide, top };
}
function HoverCardContent({
align = "center",
children,
className,
ref,
side = "bottom",
sideOffset = 4,
style,
...props
}: HoverCardContentProps) {
const ctx = useHoverCardContext();
const { open, setOpen, triggerRef, contentRef, scheduleOpen, scheduleClose } =
ctx;
const [mounted, setMounted] = React.useState(open);
const [pos, setPos] = React.useState<Position>({ left: 0, side, top: 0 });
const setRef = React.useCallback(
(node: HTMLDivElement | null) => {
contentRef.current = node;
if (typeof ref === "function") {
ref(node);
} else if (ref) {
(ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
}
},
[contentRef, ref]
);
const [entered, setEntered] = React.useState(false);
React.useEffect(() => {
if (open) {
setMounted(true);
const raf1 = requestAnimationFrame(() => {
const raf2 = requestAnimationFrame(() => setEntered(true));
return () => cancelAnimationFrame(raf2);
});
return () => cancelAnimationFrame(raf1);
}
setEntered(false);
const timer = window.setTimeout(() => setMounted(false), 100);
return () => window.clearTimeout(timer);
}, [open]);
React.useLayoutEffect(() => {
if (!mounted) {
return;
}
const trigger = triggerRef.current;
const content = contentRef.current;
if (!(trigger && content)) {
return;
}
const update = () =>
setPos(computePosition(trigger, content, side, align, sideOffset));
update();
const ro = new ResizeObserver(update);
ro.observe(trigger);
ro.observe(content);
window.addEventListener("scroll", update, true);
window.addEventListener("resize", update);
return () => {
ro.disconnect();
window.removeEventListener("scroll", update, true);
window.removeEventListener("resize", update);
};
}, [mounted, align, side, sideOffset, triggerRef, contentRef]);
React.useEffect(() => {
if (!open) {
return;
}
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
setOpen(false);
}
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [open, setOpen]);
if (!mounted || typeof document === "undefined") {
return null;
}
return createPortal(
<div
data-side={pos.side}
data-slot="hover-card-content"
data-state={open ? "open" : "closed"}
{...props}
className={cn(
"bg-popover dark:bg-card text-popover-foreground ring-foreground/10 fixed z-50 w-64 rounded-lg p-3 text-sm shadow-sm ring-1 outline-hidden",
className
)}
onPointerEnter={() => scheduleOpen()}
onPointerLeave={() => scheduleClose()}
ref={setRef}
style={{
left: pos.left,
opacity: entered ? 1 : 0,
top: pos.top,
transform: `scale(${entered ? 1 : 0.95})`,
transition: "opacity 100ms ease-out, transform 100ms ease-out",
...style,
}}
>
{children}
</div>,
document.body
);
}
export { HoverCard, HoverCardContent, HoverCardTrigger };"use client";
import type { VariantProps } from "class-variance-authority";
import * as React from "react";
import {
getTransition,
parseMotion,
useMotionGuard,
useReducedMotion,
} from "@/lib/motion";
import { buttonVariants, cn } from "@/lib/utils";
export interface ButtonBaseProps extends VariantProps<typeof buttonVariants> {
anchorRef?: React.Ref<HTMLAnchorElement>;
as?: React.ElementType;
children?: React.ReactNode;
className?: string;
download?: string | boolean;
href?: string;
motion?: string;
rel?: string;
target?: React.HTMLAttributeAnchorTarget;
}
// biome-ignore lint/suspicious/noExplicitAny: loose polymorphic props for the `as` escape hatch
export type ButtonProps = ButtonBaseProps & Record<string, any>;
function Button({
as,
className,
variant,
size,
href,
target,
rel,
download,
ref,
anchorRef,
motion,
style,
children,
...props
}: ButtonProps) {
const reduce = useReducedMotion();
const internalRef = React.useRef<HTMLElement | null>(null);
const motionEnabled = motion !== undefined && !reduce;
let resolvedStyle = style as React.CSSProperties | undefined;
if (reduce) {
resolvedStyle = { ...resolvedStyle, transition: "none" };
} else if (motion !== undefined) {
const transition = getTransition(parseMotion(motion));
if (transition) {
resolvedStyle = { ...resolvedStyle, transition };
}
}
const styleFingerprint = JSON.stringify(resolvedStyle ?? null);
const yielded = useMotionGuard(internalRef, motionEnabled, styleFingerprint);
if (yielded && !reduce) {
resolvedStyle = { ...resolvedStyle, transition: "none" };
}
const setRef = React.useCallback(
(el: HTMLElement | null) => {
internalRef.current = el;
if (href !== undefined && anchorRef) {
if (typeof anchorRef === "function") {
anchorRef(el as HTMLAnchorElement | null);
} else {
(
anchorRef as React.MutableRefObject<HTMLAnchorElement | null>
).current = el as HTMLAnchorElement | null;
}
}
if (typeof ref === "function") {
(ref as (el: HTMLElement | null) => void)(el);
} else if (ref && typeof ref === "object") {
(ref as React.MutableRefObject<HTMLElement | null>).current = el;
}
},
[href, ref, anchorRef]
);
const classes = cn(buttonVariants({ className, size, variant }));
const attrs = {
"data-inline": true,
"data-size": size,
"data-slot": "button",
"data-variant": variant,
} as const;
if (as !== undefined) {
const allProps: Record<string, unknown> = {
...attrs,
...props,
className: classes,
ref: setRef,
style: resolvedStyle,
};
if (href !== undefined) {
allProps.href = href;
}
if (download !== undefined) {
allProps.download = download;
}
if (rel !== undefined) {
allProps.rel = rel;
}
if (target !== undefined) {
allProps.target = target;
}
return React.createElement(as, allProps, children);
}
if (href !== undefined) {
const {
type: _t,
disabled: _d,
form: _f,
formAction: _fa,
formEncType: _fe,
formMethod: _fm,
formNoValidate: _fnv,
formTarget: _ft,
name: _n,
value: _v,
...anchorRest
} = props as React.ButtonHTMLAttributes<HTMLButtonElement>;
return (
<a
className={classes}
download={download}
href={href}
ref={setRef}
rel={rel}
style={resolvedStyle}
target={target}
{...attrs}
{...(anchorRest as React.AnchorHTMLAttributes<HTMLAnchorElement>)}
>
{children}
</a>
);
}
return (
<button
className={classes}
ref={setRef}
style={resolvedStyle}
{...attrs}
{...(props as React.ButtonHTMLAttributes<HTMLButtonElement>)}
>
{children}
</button>
);
}
export { Button };Update the import paths to match your project setup.
Usage
import { Button } from "@/components/ui/button";
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/components/ui/hover-card";
<HoverCard>
<HoverCardTrigger asChild>
<Button className="h-5 rounded-full px-2 text-xs font-medium" size="sm" variant="secondary">{host}</Button>
</HoverCardTrigger>
<HoverCardContent className="flex w-64 flex-col gap-1">
<div className="font-medium">{source.title}</div>
<p className="text-muted-foreground">{source.description}</p>
<a href={source.url} target="_blank" rel="noreferrer">
{host}
</a>
</HoverCardContent>
</HoverCard>Anatomy
<HoverCard>
<HoverCardTrigger asChild>
<Button className="h-5 rounded-full px-2 text-xs font-medium" size="sm" variant="secondary">{host}</Button>
</HoverCardTrigger>
<HoverCardContent>
<span>{title}</span>
<p>{description}</p>
<a href={url}>{host}</a>
</HoverCardContent>
</HoverCard>- HoverCardTrigger — a compact
Buttonthat shows the source hostname. - HoverCardContent — a small card with title, description, and a link to the original page.
Formatting the hostname
The badge shows the hostname without www.. Strip it with new URL(url).hostname and a single replace:
function hostname(url: string) {
return new URL(url).hostname.replace(/^www\./u, "");
}Best Practices
- Always link to the source. A citation without a clickable link is a dead end.
- Open in a new tab.
target="_blank"andrel="noreferrer"so the reader doesn't lose the conversation. - Include
(opens in a new tab)for screen readers. Use a visually hidden<span className="sr-only">. - Keep descriptions short. Two lines at most; the full context lives on the linked page.
- Do not nest citations. Each claim gets one badge.
Accessibility
HoverCardTrigger asChildcomposes with a focusableButton, so keyboard users can open the preview with Tab and Enter.- The description is plain text and read after the title.
- The link inside
HoverCardContentis a real anchor with a visible label and a screen-reader suffix. - Do not rely on hover alone; the trigger being a button ensures touch and keyboard users can open it.
Next
- Chat — full streaming chat surface.
- Context — context window indicator.
- Hover Card — rich content on hover.