- 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
This release adds the Attachment docs page with six examples, per-variant install commands for Trace, and two CSS utilities: scroll-fade for edge-aware scroll containers and shimmer for animated loading text.
- Attachment: Docs page with six examples.
- Hover Card: Rich content on hover, portal-based.
- Progress: Task completion indicator with smooth transitions.
- Slider: Range input with single, range, and vertical modes.
- Questionnaire: Multi-step form primitive with headless engine.
- Scroll fade: Mask gradient utilities for scroll containers.
- Shimmer: Animated gradient text utility.
Attachment



"use client";
import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { Shimmer } from "@/components/ui/shimmer";
import { cn } from "@/lib/utils";
const attachmentVariants = cva(
"group/attachment bg-card text-card-foreground focus-within:ring-ring/50 has-[>a,>button]:hover:bg-muted/50 data-[state=error]:border-destructive/30 relative flex w-fit max-w-full min-w-0 shrink-0 flex-wrap rounded-xl border transition-colors focus-within:ring-1 data-[state=idle]:border-dashed",
{
variants: {
orientation: {
horizontal: "min-w-40 items-center",
vertical: "w-24 flex-col has-data-[slot=attachment-content]:w-30",
},
size: {
default:
"gap-2 text-sm has-data-[slot=attachment-content]:px-2.5 has-data-[slot=attachment-content]:py-2 has-data-[slot=attachment-media]:p-2",
sm: "gap-2.5 text-xs has-data-[slot=attachment-content]:px-2 has-data-[slot=attachment-content]:py-1.5 has-data-[slot=attachment-media]:p-1.5",
xs: "gap-1.5 rounded-lg text-xs has-data-[slot=attachment-content]:px-1.5 has-data-[slot=attachment-content]:py-1 has-data-[slot=attachment-media]:p-1",
},
},
}
);
const AttachmentContext = React.createContext<{
state?: "idle" | "uploading" | "processing" | "error" | "done";
}>({});
function Attachment({
className,
state = "done",
size = "default",
orientation = "horizontal",
...props
}: React.ComponentProps<"div"> &
VariantProps<typeof attachmentVariants> & {
state?: "idle" | "uploading" | "processing" | "error" | "done";
}) {
return (
<AttachmentContext.Provider value={{ state }}>
<div
className={cn(attachmentVariants({ orientation, size }), className)}
data-orientation={orientation}
data-size={size}
data-slot="attachment"
data-state={state}
{...props}
/>
</AttachmentContext.Provider>
);
}
const attachmentMediaVariants = cva(
"bg-muted text-foreground group-data-[state=error]/attachment:bg-destructive/10 group-data-[state=error]/attachment:text-destructive relative flex aspect-square w-10 shrink-0 items-center justify-center overflow-hidden rounded-lg group-data-[orientation=vertical]/attachment:w-full group-data-[size=sm]/attachment:w-8 group-data-[size=xs]/attachment:w-7 group-data-[size=xs]/attachment:rounded-md group-data-[orientation=vertical]/attachment:*:data-[slot=spinner]:size-6! [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 group-data-[orientation=vertical]/attachment:[&_svg:not([class*='size-'])]:size-6 group-data-[size=xs]/attachment:[&_svg:not([class*='size-'])]:size-3.5",
{
defaultVariants: {
variant: "icon",
},
variants: {
variant: {
icon: "",
image:
"opacity-60 group-data-[state=done]/attachment:opacity-100 group-data-[state=idle]/attachment:opacity-100 *:[img]:aspect-square *:[img]:w-full *:[img]:object-cover",
},
},
}
);
function AttachmentMedia({
className,
variant = "icon",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof attachmentMediaVariants>) {
return (
<div
className={cn(attachmentMediaVariants({ variant }), className)}
data-slot="attachment-media"
data-variant={variant}
{...props}
/>
);
}
function AttachmentContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
className={cn(
"max-w-full min-w-0 flex-1 text-sm leading-tight group-data-[orientation=vertical]/attachment:px-1",
className
)}
data-slot="attachment-content"
{...props}
/>
);
}
function AttachmentTitle({
className,
children,
...props
}: React.ComponentProps<"span">) {
const { state } = React.useContext(AttachmentContext);
const shimmering = state === "processing" || state === "uploading";
const content = shimmering ? <Shimmer>{children}</Shimmer> : children;
return (
<span
className={cn("block max-w-full min-w-0 truncate font-medium", className)}
data-slot="attachment-title"
{...props}
>
{content}
</span>
);
}
function AttachmentDescription({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
className={cn(
"text-muted-foreground group-data-[state=error]/attachment:text-destructive/80 mt-0.5 block min-w-0 truncate text-xs",
"max-w-full",
className
)}
data-slot="attachment-description"
{...props}
/>
);
}
function AttachmentActions({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
className={cn(
"relative z-20 flex shrink-0 items-center group-data-[orientation=vertical]/attachment:absolute group-data-[orientation=vertical]/attachment:top-3 group-data-[orientation=vertical]/attachment:right-3 group-data-[orientation=vertical]/attachment:gap-1",
className
)}
data-slot="attachment-actions"
{...props}
/>
);
}
function AttachmentAction({
className,
variant,
size = "icon-xs",
...props
}: React.ComponentProps<typeof Button>) {
return (
<Button
className={cn(className)}
data-slot="attachment-action"
size={size}
variant={variant ?? "ghost"}
{...props}
/>
);
}
function AttachmentTrigger({
className,
as,
ref,
type,
...props
}: React.ComponentProps<"button"> & {
as?: React.ElementType;
ref?: React.Ref<HTMLButtonElement>;
}) {
const Comp = as ?? "button";
return (
<Comp
className={cn("absolute inset-0 z-10 outline-none", className)}
data-slot="attachment-trigger"
ref={ref}
type={as ? undefined : (type ?? "button")}
{...props}
/>
);
}
function AttachmentGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"flex min-w-0 snap-x snap-mandatory scroll-px-1 scrollbar-none gap-3 overflow-x-auto overscroll-x-contain py-1 *:data-[slot=attachment]:flex-none *:data-[slot=attachment]:snap-start",
className
)}
data-slot="attachment-group"
{...props}
/>
);
}
export {
Attachment,
AttachmentAction,
AttachmentActions,
AttachmentContent,
AttachmentDescription,
AttachmentGroup,
AttachmentMedia,
AttachmentTitle,
AttachmentTrigger,
};Attachment renders a compact file card with media, title, description, and actions. It supports idle, uploading, processing, error, and done states with size variants for dense layouts. Pass variant="image" to render a thumbnail, or wrap with AttachmentTrigger to make the whole card interactive.
Installation
Install the primitive
$ bunx --bun frakment add attachment$ npx frakment add attachment$ pnpm dlx frakment add attachment$ yarn dlx frakment add attachment
Use it in your app
import {
Attachment,
AttachmentContent,
AttachmentDescription,
AttachmentMedia,
AttachmentTitle,
} from "@/components/ui/attachment";Minimal usage
<Attachment>
<AttachmentMedia>
<FileTextIcon />
</AttachmentMedia>
<AttachmentContent>
<AttachmentTitle>report.pdf</AttachmentTitle>
<AttachmentDescription>PDF · 2.4 MB</AttachmentDescription>
</AttachmentContent>
</Attachment>See the Attachment docs for the full API reference.
Scroll fade
export function ScrollFadeOverflow() {
return (
<div className="mx-auto w-full max-w-xs overflow-hidden rounded-2xl border">
<div className="scroll-fade no-scrollbar overflow-y-auto">
<div className="flex flex-col gap-1.5 p-1.5">
{Array.from({ length: 3 }, (_, index) => (
<div
className="bg-muted rounded-lg px-3 py-2.5 text-sm"
key={index}
>
Item {index + 1}
</div>
))}
</div>
</div>
</div>
);
}scroll-fade applies a scroll-aware mask to the edges of a scroll container. The fade tracks the scroll position, only appearing when there is content beyond the visible area. Variants: scroll-fade-x for horizontal, scroll-fade-{t,b,l,r,s,e} for single edges, and scroll-fade-none to disable.
Installation
$ bunx --bun frakment add scroll-fade$ npx frakment add scroll-fade$ pnpm dlx frakment add scroll-fade$ yarn dlx frakment add scroll-fade
Minimal usage
<div className="scroll-fade overflow-y-auto">{/* ... */}</div>See the Scroll Fade docs for the full reference.
Shimmer
Generating response…
export function ShimmerDemo() {
return (
<p className="shimmer text-muted-foreground text-sm">
Generating response…
</p>
);
}shimmer is a CSS utility that animates a gradient over text. Replaces the previous inline-style <Shimmer> component with a class that supports color, duration, spread, and angle modifiers.
Installation
$ bunx --bun frakment add shimmer$ npx frakment add shimmer$ pnpm dlx frakment add shimmer$ yarn dlx frakment add shimmer
Minimal usage
<p className="shimmer">Generating response…</p>See the Shimmer docs for the full reference.
Hover Card
"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 };Hover Card displays rich content in a portal when the user hovers over a trigger. It opens after a short delay, stays open while the pointer is over the card, and closes on mouse leave. Built on Radix HoverCard, it supports side, align, openDelay, and closeDelay.
Installation
Install the primitive
$ bunx --bun frakment add hover-card$ npx frakment add hover-card$ pnpm dlx frakment add hover-card$ yarn dlx frakment add hover-card
Use it in your app
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/components/ui/hover-card";Minimal usage
<HoverCard>
<HoverCardTrigger asChild>
<Button variant="link">@fraktment</Button>
</HoverCardTrigger>
<HoverCardContent>
Registry primitives for React.
</HoverCardContent>
</HoverCard>See the Hover Card docs for the full API reference.
Progress
"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 };Progress shows how much of a task has completed. The indicator animates smoothly on every value change with a 500ms ease-out transform. Optional ProgressLabel and ProgressValue render a header row with the current percentage.
Installation
Install the primitive
$ bunx --bun frakment add progress$ npx frakment add progress$ pnpm dlx frakment add progress$ yarn dlx frakment add progress
Use it in your app
import { Progress } from "@/components/ui/progress";Minimal usage
<Progress value={60} />See the Progress docs for the full API reference.
Slider
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
type SliderOrientation = "horizontal" | "vertical";
interface SliderProps {
"aria-label"?: string;
className?: string;
defaultValue?: number[];
disabled?: boolean;
id?: string;
max?: number;
min?: number;
onValueChange?: (value: number[]) => void;
orientation?: SliderOrientation;
step?: number;
value?: number[];
}
function decimalsFor(step: number): number {
const text = String(step);
const dot = text.indexOf(".");
return dot < 0 ? 0 : text.length - dot - 1;
}
function snapToStep(raw: number, step: number): number {
const decimals = decimalsFor(step);
const factor = 10 ** decimals;
return Math.round(raw * factor) / factor;
}
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
function Slider({
"aria-label": ariaLabel,
className,
defaultValue,
disabled = false,
id,
max = 100,
min = 0,
onValueChange,
orientation = "horizontal",
step = 1,
value: valueProp,
}: SliderProps) {
const isControlled = valueProp !== undefined;
const [uncontrolled, setUncontrolled] = React.useState<number[]>(
() => defaultValue ?? [min, max]
);
const values = isControlled ? valueProp : uncontrolled;
const trackRef = React.useRef<HTMLDivElement | null>(null);
const commit = React.useCallback(
(next: number[]) => {
if (!isControlled) {
setUncontrolled(next);
}
onValueChange?.(next);
},
[isControlled, onValueChange]
);
const percentOf = (v: number) => {
const range = Math.max(max - min, Number.EPSILON);
return ((v - min) / range) * 100;
};
const valueFromPointer = (clientX: number, clientY: number): number => {
const track = trackRef.current;
if (!track) {
return min;
}
const rect = track.getBoundingClientRect();
let ratio: number;
if (orientation === "horizontal") {
ratio = rect.width === 0 ? 0 : (clientX - rect.left) / rect.width;
} else {
ratio = rect.height === 0 ? 0 : 1 - (clientY - rect.top) / rect.height;
}
ratio = clamp(ratio, 0, 1);
return snapToStep(min + ratio * (max - min), step);
};
const boundsFor = (index: number): [number, number] => {
const lower = index === 0 ? min : values[index - 1];
const upper = index === values.length - 1 ? max : values[index + 1];
return [lower, upper];
};
const updateThumb = (index: number, raw: number) => {
const [lo, hi] = boundsFor(index);
const next = values.slice();
next[index] = clamp(raw, lo, hi);
if (next[index] !== values[index]) {
commit(next);
}
};
const handlePointerDown =
(index: number) => (event: React.PointerEvent<HTMLSpanElement>) => {
if (disabled) {
return;
}
event.preventDefault();
event.stopPropagation();
const target = event.currentTarget;
try {
target.setPointerCapture(event.pointerId);
} catch {
// noop
}
updateThumb(index, valueFromPointer(event.clientX, event.clientY));
const onMove = (ev: PointerEvent) => {
updateThumb(index, valueFromPointer(ev.clientX, ev.clientY));
};
const onUp = () => {
target.removeEventListener("pointermove", onMove);
target.removeEventListener("pointerup", onUp);
target.removeEventListener("pointercancel", onUp);
};
target.addEventListener("pointermove", onMove);
target.addEventListener("pointerup", onUp);
target.addEventListener("pointercancel", onUp);
};
const handleKeyDown =
(index: number) => (event: React.KeyboardEvent<HTMLSpanElement>) => {
if (disabled) {
return;
}
const [lo, hi] = boundsFor(index);
const current = values[index];
let next = current;
switch (event.key) {
case "ArrowRight":
case "ArrowUp":
next = clamp(snapToStep(current + step, step), lo, hi);
break;
case "ArrowLeft":
case "ArrowDown":
next = clamp(snapToStep(current - step, step), lo, hi);
break;
case "Home":
next = lo;
break;
case "End":
next = hi;
break;
case "PageUp":
next = clamp(snapToStep(current + step * 10, step), lo, hi);
break;
case "PageDown":
next = clamp(snapToStep(current - step * 10, step), lo, hi);
break;
default:
return;
}
event.preventDefault();
if (next !== current) {
const arr = values.slice();
arr[index] = next;
commit(arr);
}
};
const rangeStart = percentOf(values[0]);
const rangeEnd = percentOf(values.at(-1) ?? min);
const rangeStyle: React.CSSProperties =
orientation === "horizontal"
? { left: `${rangeStart}%`, right: `${100 - rangeEnd}%` }
: { bottom: `${rangeStart}%`, top: `${100 - rangeEnd}%` };
return (
<div
className={cn(
"relative flex w-full touch-none select-none",
orientation === "horizontal"
? "items-center"
: "h-full min-h-40 flex-col items-center",
disabled ? "opacity-50" : undefined,
className
)}
data-disabled={disabled || undefined}
data-orientation={orientation}
data-slot="slider"
id={id}
>
<div
className={cn(
"bg-muted relative grow overflow-hidden rounded-full",
orientation === "horizontal" ? "h-1 w-full" : "h-full w-1"
)}
data-slot="slider-track"
ref={trackRef}
>
<div
className={cn(
"bg-primary absolute select-none",
orientation === "horizontal" ? "inset-y-0" : "inset-x-0"
)}
data-slot="slider-range"
style={rangeStyle}
/>
</div>
{values.map((v, index) => {
const percent = percentOf(v);
const thumbStyle: React.CSSProperties =
orientation === "horizontal"
? {
left: `${percent}%`,
top: "50%",
transform: "translate(-50%, -50%)",
}
: {
bottom: `${percent}%`,
left: "50%",
transform: "translate(-50%, 50%)",
};
return (
<span
aria-disabled={disabled || undefined}
aria-label={ariaLabel}
aria-orientation={orientation}
aria-valuemax={max}
aria-valuemin={min}
aria-valuenow={v}
className={cn(
"border-primary bg-background ring-ring/50 absolute block size-3.5 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] select-none",
"after:absolute after:-inset-2",
"hover:ring-3 focus-visible:ring-3 focus-visible:outline-hidden active:ring-3",
disabled ? "pointer-events-none opacity-50" : "cursor-grab"
)}
data-slot="slider-thumb"
key={`slider-thumb-${index}`}
onKeyDown={handleKeyDown(index)}
onPointerDown={handlePointerDown(index)}
role="slider"
style={thumbStyle}
tabIndex={disabled ? -1 : 0}
/>
);
})}
</div>
);
}
export { Slider };Slider lets the user pick a value or range from a track. It supports single values, ranges with two thumbs, multiple thumbs, and vertical orientation. Built on Radix Slider, it handles keyboard navigation, focus rings, and disabled state out of the box.
Installation
Install the primitive
$ bunx --bun frakment add slider$ npx frakment add slider$ pnpm dlx frakment add slider$ yarn dlx frakment add slider
Use it in your app
import { Slider } from "@/components/ui/slider";Minimal usage
<Slider defaultValue={[50]} max={100} step={1} />See the Slider docs for the full API reference.
Questionnaire
"use client";
import * as React from "react";
import type { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Questionnaire as QuestionnairePrimitive } from "@/lib/questionnaire";
import { buttonVariants, cn } from "@/lib/utils";
function Questionnaire({
className,
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Root>) {
return (
<QuestionnairePrimitive.Root
className={cn("flex w-full min-w-0 flex-col gap-4", className)}
data-slot="questionnaire"
{...props}
/>
);
}
function QuestionnaireProgress({
className,
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Progress>) {
return (
<QuestionnairePrimitive.Progress
className={cn(
"text-muted-foreground min-h-[1lh] w-fit min-w-[14ch] text-xs font-medium tabular-nums",
className
)}
data-slot="questionnaire-progress"
{...props}
/>
);
}
function QuestionnaireItem({
className,
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Item>) {
return (
<QuestionnairePrimitive.Item
className={cn(
"flex min-w-0 flex-col gap-4 border-0 p-0 outline-none",
className
)}
data-slot="questionnaire-item"
{...props}
/>
);
}
function QuestionnaireTitle({
className,
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Title>) {
return (
<QuestionnairePrimitive.Title
className={cn(
"text-base leading-snug font-medium text-pretty [&:not(:has(~[data-slot=questionnaire-description]))]:mb-4",
className
)}
data-slot="questionnaire-title"
{...props}
/>
);
}
function QuestionnaireDescription({
className,
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Description>) {
return (
<QuestionnairePrimitive.Description
className={cn("text-muted-foreground text-sm text-pretty", className)}
data-slot="questionnaire-description"
{...props}
/>
);
}
function QuestionnaireChoices({
className,
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Choices>) {
return (
<QuestionnairePrimitive.Choices
className={cn(
"group/questionnaire-choices grid min-w-0 gap-2",
className
)}
data-slot="questionnaire-choices"
{...props}
/>
);
}
function QuestionnaireChoice({
children,
className,
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Choice>) {
const [checked, setChecked] = React.useState(false);
const [multiple, setMultiple] = React.useState(false);
const inputRef = React.useRef<HTMLInputElement>(null);
React.useEffect(() => {
const input = inputRef.current;
if (!input) {
return;
}
setMultiple(input.type === "checkbox");
setChecked(input.checked);
const sync = () => setChecked(input.checked);
input.addEventListener("change", sync);
return () => input.removeEventListener("change", sync);
}, []);
return (
<QuestionnairePrimitive.Choice
className={cn(
"group/questionnaire-choice border-input hover:bg-muted/50 relative flex min-h-11 cursor-pointer items-start gap-2.5 rounded-lg border bg-transparent px-3 py-2.5 text-start text-sm transition-colors outline-none select-none",
checked && "border-primary bg-muted dark:bg-muted",
className
)}
data-slot="questionnaire-choice"
{...props}
>
<QuestionnairePrimitive.ChoiceInput
className="sr-only"
data-slot="questionnaire-choice-input"
ref={inputRef}
/>
<span
aria-hidden="true"
className="pointer-events-none mt-0.5 flex shrink-0"
data-slot="questionnaire-choice-indicator"
>
{multiple ? (
<Checkbox aria-hidden checked={checked} tabIndex={-1} />
) : (
<RadioGroup
aria-hidden
className="contents"
onValueChange={() => {}}
value={checked ? "on" : ""}
>
<RadioGroupItem
className="pointer-events-none"
tabIndex={-1}
value="on"
/>
</RadioGroup>
)}
</span>
<QuestionnairePrimitive.ChoiceLabel
className="flex min-w-0 flex-1 flex-col gap-0.5 leading-snug"
data-slot="questionnaire-choice-label"
>
{children}
</QuestionnairePrimitive.ChoiceLabel>
<QuestionnairePrimitive.ChoiceShortcut
className="border-input bg-background text-muted-foreground pointer-events-none ms-auto hidden size-5 shrink-0 items-center justify-center rounded-md border font-mono text-[0.625rem] leading-none font-medium group-data-[shortcut]/questionnaire-choice:inline-flex"
data-slot="questionnaire-choice-shortcut"
/>
</QuestionnairePrimitive.Choice>
);
}
function QuestionnaireChoiceDescription({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
className={cn("text-muted-foreground", className)}
data-slot="questionnaire-choice-description"
{...props}
/>
);
}
function QuestionnaireInput({
className,
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Input>) {
return (
<div
className="group/questionnaire-input relative w-full min-w-0"
data-slot="questionnaire-input-wrapper"
>
<QuestionnairePrimitive.Input
className={cn(
"border-input focus-visible:border-ring focus-visible:ring-ring/50 disabled:bg-input/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 h-8 min-h-11 w-full min-w-0 rounded-lg border bg-transparent px-2.5 py-1 text-base transition-[color,box-shadow,background-color] outline-none focus-visible:ring-3 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-3 sm:min-h-0 md:text-sm",
"selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground",
className
)}
data-slot="questionnaire-input"
{...props}
/>
</div>
);
}
function QuestionnaireError({
className,
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Error>) {
return (
<QuestionnairePrimitive.Error
className={cn("text-destructive mt-2 text-sm", className)}
data-slot="questionnaire-error"
{...props}
/>
);
}
function QuestionnaireActions({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
className={cn(
"grid min-h-11 w-full grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-2 sm:min-h-8",
className
)}
data-slot="questionnaire-actions"
{...props}
/>
);
}
function QuestionnairePrevious({
children,
className,
size = "default",
variant = "outline",
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Previous> &
Pick<React.ComponentProps<typeof Button>, "size" | "variant">) {
return (
<QuestionnairePrimitive.Previous
className={cn(
buttonVariants({ size, variant }),
"col-start-1 row-start-1 min-h-11 justify-self-start sm:min-h-0",
className
)}
data-size={size}
data-slot="questionnaire-previous"
data-variant={variant}
{...props}
>
{children ?? "Previous"}
</QuestionnairePrimitive.Previous>
);
}
function QuestionnaireSkip({
children,
className,
size = "default",
variant = "outline",
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Skip> &
Pick<React.ComponentProps<typeof Button>, "size" | "variant">) {
return (
<QuestionnairePrimitive.Skip
className={cn(
buttonVariants({ size, variant }),
"col-start-2 row-start-1 min-h-11 justify-self-end sm:min-h-0",
className
)}
data-size={size}
data-slot="questionnaire-skip"
data-variant={variant}
{...props}
>
{children ?? "Skip"}
</QuestionnairePrimitive.Skip>
);
}
function QuestionnaireNext({
children,
className,
size = "default",
variant = "default",
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Next> &
Pick<React.ComponentProps<typeof Button>, "size" | "variant">) {
return (
<QuestionnairePrimitive.Next
className={cn(
buttonVariants({ size, variant }),
"col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0",
className
)}
data-size={size}
data-slot="questionnaire-next"
data-variant={variant}
{...props}
>
{children ?? "Next"}
</QuestionnairePrimitive.Next>
);
}
function QuestionnaireSubmit({
children,
className,
size = "default",
variant = "default",
...props
}: React.ComponentProps<typeof QuestionnairePrimitive.Submit> &
Pick<React.ComponentProps<typeof Button>, "size" | "variant">) {
return (
<QuestionnairePrimitive.Submit
className={cn(
buttonVariants({ size, variant }),
"col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0",
className
)}
data-size={size}
data-slot="questionnaire-submit"
data-variant={variant}
{...props}
>
{children ?? "Submit"}
</QuestionnairePrimitive.Submit>
);
}
export {
Questionnaire,
QuestionnaireActions,
QuestionnaireChoice,
QuestionnaireChoiceDescription,
QuestionnaireChoices,
QuestionnaireDescription,
QuestionnaireError,
QuestionnaireInput,
QuestionnaireItem,
QuestionnaireNext,
QuestionnairePrevious,
QuestionnaireProgress,
QuestionnaireSkip,
QuestionnaireSubmit,
QuestionnaireTitle,
};Questionnaire is a multi-step form component that bundles a headless engine. Each step renders one question with a title, optional description, a set of choices, optional freeform input, and inline error. Navigation between steps and the final submit are handled by the headless engine in lib/questionnaire, which ships as a registry dependency.
Installation
Install the primitive (pulls the engine automatically)
$ bunx --bun frakment add questionnaire checkbox radio-group button card$ npx frakment add questionnaire checkbox radio-group button card$ pnpm dlx frakment add questionnaire checkbox radio-group button card$ yarn dlx frakment add questionnaire checkbox radio-group button card
Use it in your app
import {
Questionnaire,
QuestionnaireActions,
QuestionnaireChoice,
QuestionnaireChoices,
QuestionnaireItem,
QuestionnaireNext,
QuestionnairePrevious,
QuestionnaireSubmit,
QuestionnaireTitle,
} from "@/components/ui/questionnaire";Minimal usage
<Questionnaire items={items} onSubmit={handleSubmit}>
<QuestionnaireItem name="scope" required>
<QuestionnaireTitle>What should the agent change?</QuestionnaireTitle>
<QuestionnaireChoices>
<QuestionnaireChoice value="component">Component only</QuestionnaireChoice>
<QuestionnaireChoice value="feature">Complete feature</QuestionnaireChoice>
</QuestionnaireChoices>
</QuestionnaireItem>
<QuestionnaireActions>
<QuestionnairePrevious />
<QuestionnaireNext>Next</QuestionnaireNext>
<QuestionnaireSubmit>Save</QuestionnaireSubmit>
</QuestionnaireActions>
</Questionnaire>See the Questionnaire docs for the full API reference.
Context
"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 compact context-window indicator. Hovering the badge reveals a token breakdown and a progress bar showing how much of the model's limit is in use.
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
Minimal usage
<HoverCard>
<HoverCardTrigger asChild>
<Button size="sm" variant="outline">{percent}% context</Button>
</HoverCardTrigger>
<HoverCardContent>
<Progress value={percent} />
</HoverCardContent>
</HoverCard>See the Context docs for the full composition.
Inline Citation, Message, Model Selector
Three AI element tutorials ship: Inline Citation for source badges, Message for a complete message row with actions, and Model Selector for a composer with model and effort pickers. Each is a composition, not a primitive.
Installation
$ bunx --bun frakment add hover-card input-group dropdown-menu message bubble tooltip button markdown$ npx frakment add hover-card input-group dropdown-menu message bubble tooltip button markdown$ pnpm dlx frakment add hover-card input-group dropdown-menu message bubble tooltip button markdown$ yarn dlx frakment add hover-card input-group dropdown-menu message bubble tooltip button markdown
Each tutorial has its own page:
On This Page
AttachmentInstallationMinimal usageScroll fadeInstallationMinimal usageShimmerInstallationMinimal usageHover CardInstallationMinimal usageProgressInstallationMinimal usageSliderInstallationMinimal usageQuestionnaireInstallationMinimal usageContextInstallationMinimal usageInline Citation, Message, Model SelectorInstallation