- 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
"use client";
import { Button } from "@/components/ui/button";
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/components/ui/hover-card";
import { Progress } from "@/components/ui/progress";
const usage = {
input: 8420,
limit: 128_000,
output: 1260,
reasoning: 980,
};
const used = usage.input + usage.output + usage.reasoning;
const percent = Math.round((used / usage.limit) * 100);
function formatTokens(value: number) {
if (value < 1000) {
return String(value);
}
return `${(value / 1000).toFixed(1).replace(/\.0$/, "")}k`;
}
const rows = [
{ label: "Input", value: usage.input },
{ label: "Output", value: usage.output },
{ label: "Reasoning", value: usage.reasoning },
];
export function ContextDemo() {
return (
<div className="flex justify-center py-12">
<HoverCard closeDelay={100} openDelay={10}>
<HoverCardTrigger as={Button} size="sm" variant="outline">
{percent}% context
</HoverCardTrigger>
<HoverCardContent className="flex w-64 flex-col gap-3">
<div className="flex items-center justify-between gap-3 text-sm">
<span className="font-medium">Context</span>
<span className="text-muted-foreground">
{formatTokens(used)} / {formatTokens(usage.limit)}
</span>
</div>
<Progress aria-label="Context used" value={percent} />
<div className="flex flex-col gap-1 text-sm">
{rows.map((row) => (
<div className="flex justify-between gap-3" key={row.label}>
<span className="text-muted-foreground">{row.label}</span>
<span>{formatTokens(row.value)}</span>
</div>
))}
</div>
</HoverCardContent>
</HoverCard>
</div>
);
}Context is a small composition that shows how much of the model's context window is in use. Hovering the badge reveals a breakdown of input, output, and reasoning tokens against the limit.
Context is a composition, not a primitive. Install the three primitives it uses, then wire it the same way the demo does.
Installation
$ bunx --bun frakment add hover-card progress button$ npx frakment add hover-card progress button$ pnpm dlx frakment add hover-card progress button$ yarn dlx frakment add hover-card progress 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 * as React from "react";
import {
getTransition,
parseMotion,
useMotionGuard,
useReducedMotion,
} from "@/lib/motion";
import { cn } from "@/lib/utils";
const ProgressContext = React.createContext<{ value?: number }>({});
type ProgressProps = Omit<React.ComponentProps<"div">, "role"> & {
"aria-label"?: string;
children?: React.ReactNode;
max?: number;
min?: number;
motion?: string;
value?: number;
};
function useProgressIndicatorStyle(
value: number,
min: number,
max: number,
motion: string | undefined,
internalRef: React.RefObject<HTMLDivElement | null>
): React.CSSProperties {
const reduce = useReducedMotion();
const clamped = Math.min(Math.max(value, min), max);
const range = Math.max(max - min, 1);
const percent = ((clamped - min) / range) * 100;
let style: React.CSSProperties = {
transform: `translateX(-${100 - percent}%)`,
};
if (reduce) {
style.transition = "none";
} else if (motion !== undefined) {
const transition = getTransition(parseMotion(motion));
if (transition) {
style.transition = transition;
}
}
const motionEnabled = motion !== undefined && !reduce;
const fingerprint = JSON.stringify(style);
const yielded = useMotionGuard(internalRef, motionEnabled, fingerprint);
if (yielded && !reduce) {
style = { ...style, transition: "none" };
}
return style;
}
function ProgressBar({
className,
max = 100,
min = 0,
motion,
value,
...props
}: ProgressProps) {
const internalRef = React.useRef<HTMLDivElement | null>(null);
const safeValue = value ?? 0;
const indicatorStyle = useProgressIndicatorStyle(
safeValue,
min,
max,
motion,
internalRef
);
return (
<div
aria-valuemax={max}
aria-valuemin={min}
aria-valuenow={safeValue}
className={cn(
"bg-primary/20 relative flex h-1 w-full items-center overflow-x-hidden rounded-full",
className
)}
data-slot="progress"
role="progressbar"
{...props}
>
<div
className={cn(
"bg-primary size-full flex-1",
motion === undefined && "transition-transform duration-500 ease-out"
)}
data-slot="progress-indicator"
ref={internalRef}
style={indicatorStyle}
/>
</div>
);
}
function Progress({ className, value, children, ...props }: ProgressProps) {
const normalizedValue = value ?? 0;
if (!children) {
return (
<ProgressBar className={className} value={normalizedValue} {...props} />
);
}
return (
<ProgressContext.Provider value={{ value: normalizedValue }}>
<div className={cn("flex flex-col gap-2", className)}>
<div className="flex items-center justify-between gap-2">
{children}
</div>
<ProgressBar value={normalizedValue} {...props} />
</div>
</ProgressContext.Provider>
);
}
function ProgressLabel({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
className={cn("text-sm font-medium", className)}
data-slot="progress-label"
{...props}
/>
);
}
function ProgressValue({ className, ...props }: React.ComponentProps<"span">) {
const { value } = React.useContext(ProgressContext);
return (
<span
className={cn("text-muted-foreground text-sm tabular-nums", className)}
data-slot="progress-value"
{...props}
>
{value ?? 0}%
</span>
);
}
export { Progress, ProgressLabel, ProgressValue };"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";
import { Progress } from "@/components/ui/progress";
const used = usage.input + usage.output + usage.reasoning;
const percent = Math.round((used / usage.limit) * 100);
<HoverCard closeDelay={100} openDelay={10}>
<HoverCardTrigger asChild>
<Button size="sm" variant="outline">
{percent}% context
</Button>
</HoverCardTrigger>
<HoverCardContent className="flex w-64 flex-col gap-3">
<div className="flex items-center justify-between gap-3 text-sm">
<span className="font-medium">Context</span>
<span className="text-muted-foreground">
{formatTokens(used)} / {formatTokens(usage.limit)}
</span>
</div>
<Progress aria-label="Context used" value={percent} />
</HoverCardContent>
</HoverCard>Anatomy
<HoverCard>
<HoverCardTrigger asChild>
<Button>{"{percent}"}% context</Button>
</HoverCardTrigger>
<HoverCardContent>
<span>{"{used}"} / {"{limit}"}</span>
<Progress value={percent} />
<span>Input {"{input}"}</span>
<span>Output {"{output}"}</span>
<span>Reasoning {"{reasoning}"}</span>
</HoverCardContent>
</HoverCard>- HoverCardTrigger — a compact
Buttonshowing the current percentage. - HoverCardContent — a 64-unit card with a header row, a
Progressbar, and a per-category breakdown. - Progress — the visual fill representing
percentof the context limit.
Token breakdown
Split the total into input, output, and reasoning so users can see where the tokens go. The demo formats each value with formatTokens:
function formatTokens(value: number) {
if (value < 1000) return String(value);
return `${(value / 1000).toFixed(1).replace(/\.0$/, "")}k`;
}8_420 tokens renders as 8.4k, 1_260 as 1.3k, 980 as 980. The denominator uses the same formatter, so the header reads 10.7k / 128k.
Updating the value
Recalculate used and percent whenever the transcript changes. The Progress component animates smoothly over 500ms by default, so passing the new value is enough — no manual transition wiring.
const used = usage.input + usage.output + usage.reasoning;
const percent = Math.round((used / usage.limit) * 100);Best Practices
- Show the denominator. "8%" is ambiguous. "10.7k / 128k" tells the user how close they are to the limit.
- Split the breakdown. Input, output, and reasoning have different costs. Showing the split helps users diagnose spikes.
- Keep the trigger visible. A floating "context" badge without a label is easy to miss. Use a compact
Buttonwith the percentage. - Use HoverCard, not a tooltip. The card contains a progress bar and a multi-row table; a tooltip is too small.
- Do not put interactive content inside. The trigger opens a preview; for controls, use a Popover instead.
Accessibility
HoverCardTrigger asChildcomposes with a focusableButton, so keyboard users can open the card with Tab and Enter.Progressexposesrole="progressbar"witharia-valuenowautomatically. Addaria-label="Context used"so screen readers announce the purpose.- The breakdown rows are plain text; screen readers read them in order after the progress bar.
- Do not rely on the hover interaction alone. Make the trigger a real button so touch and keyboard users can open the card.
Next
- Chat — full streaming chat surface.
- Checkpoint — restore points in a conversation.
- Hover Card — rich content on hover.
- Progress — task completion indicator.