- 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
Renamed Button to Action in components/ui/button.tsx.
Updated the Button page to say Action.
"use client";
import { useChat } from "@ai-sdk/react";
import type { UIMessage } from "ai";
import { motion, useReducedMotion } from "motion/react";
import { Button } from "@/components/ui/button";
import { Marker, MarkerContent } from "@/components/ui/marker";
import {
Bubble,
BubbleContent,
Message,
MessageContent,
} from "@/components/ui/message";
import { createChat, getMessageText } from "@/lib/ai";
import { messageAnimations } from "@/lib/message-animations";
type ChatMessage = UIMessage<
unknown,
{
checkpoint: {
label: string;
};
}
>;
type CheckpointPart = Extract<
ChatMessage["parts"][number],
{ type: "data-checkpoint" }
>;
const chat = createChat<ChatMessage>()
.user("Rename the button component to action.")
.assistant(({ writer }) => {
writer.text("Renamed Button to Action in components/ui/button.tsx.");
writer.data({
data: { label: "Button renamed" },
id: "rename",
type: "data-checkpoint",
});
})
.user("Update the docs to match.")
.assistant(({ writer }) => {
writer.text("Updated the Button page to say Action.");
});
const transcript = chat.get();
const transport = chat.transport({ delayMs: 20 });
export function CheckpointDemo() {
const { messages, sendMessage, setMessages, status } = useChat<ChatMessage>({
messages: transcript,
transport,
});
const shouldReduceMotion = useReducedMotion();
const nextMessage = chat.next(messages);
const busy = status === "submitted" || status === "streaming";
function restore(messageId: string) {
const index = messages.findIndex((message) => message.id === messageId);
if (index === -1) {
return;
}
setMessages(messages.slice(0, index + 1));
}
return (
<div className="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm">
{messages.map((message) => {
const checkpoint = message.parts.find(
(part): part is CheckpointPart => part.type === "data-checkpoint"
);
const index = messages.findIndex((item) => item.id === message.id);
const canRestore = index < messages.length - 1;
return (
<motion.div
animate={shouldReduceMotion ? undefined : "animate"}
className="flex flex-col gap-4"
initial={shouldReduceMotion ? undefined : "initial"}
key={message.id}
variants={messageAnimations["slide-up"].variants}
>
{message.role === "user" ? (
<Message align="end">
<MessageContent>
<Bubble align="end" variant="muted">
<BubbleContent>{getMessageText(message)}</BubbleContent>
</Bubble>
</MessageContent>
</Message>
) : (
<Message>
<MessageContent>
<p>{getMessageText(message)}</p>
</MessageContent>
</Message>
)}
{checkpoint && (
<motion.div
animate={shouldReduceMotion ? undefined : "animate"}
initial={shouldReduceMotion ? undefined : "initial"}
variants={messageAnimations.fade.variants}
>
<Marker variant="separator">
<MarkerContent className="inline-flex items-center gap-2">
{checkpoint.data.label}
{canRestore && (
<Button
aria-label={`Restore to ${checkpoint.data.label}`}
className="h-6 rounded-full px-2.5 text-xs"
onClick={() => restore(message.id)}
size="sm"
variant="outline"
>
Restore
</Button>
)}
</MarkerContent>
</Marker>
</motion.div>
)}
</motion.div>
);
})}
{!busy && nextMessage && (
<Button
className="mt-auto self-start"
onClick={() => sendMessage(nextMessage)}
size="sm"
variant="outline"
>
Continue
</Button>
)}
</div>
);
}Checkpoint marks a point in a conversation that can be restored. It renders a data-checkpoint part as a separator marker with a restore action, and messages after that point are trimmed when the user clicks it.
Checkpoint is a composition — install the primitives, then wire them together the same way the demo does.
Installation
$ bun add @frakment/ai npx frakment add bubble button marker message$ npm install @frakment/ai npx frakment add bubble button marker message$ pnpm add @frakment/ai npx frakment add bubble button marker message$ yarn add @frakment/ai npx frakment add bubble button marker message
Install the following dependencies:
$ bun add @frakment/ai @ai-sdk/react ai motion$ npm install @frakment/ai @ai-sdk/react ai motion$ pnpm add @frakment/ai @ai-sdk/react ai motion$ yarn add @frakment/ai @ai-sdk/react ai motion
Install the required registry components:
"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 };import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
import type * as React from "react";
import { cn } from "@/lib/utils";
const markerVariants = cva(
"group/marker text-muted-foreground [a]:hover:text-foreground relative flex min-h-4 w-full items-center gap-2 text-left text-sm [&_svg:not([class*='size-'])]:size-4 [a]:underline [a]:underline-offset-3",
{
variants: {
variant: {
border: "border-border border-b pb-2",
default: "",
separator:
"before:bg-border after:bg-border before:mr-1 before:h-px before:min-w-0 before:flex-1 after:ml-1 after:h-px after:min-w-0 after:flex-1",
},
},
}
);
type MarkerProps = Omit<React.ComponentProps<"div">, "ref"> &
VariantProps<typeof markerVariants> & {
as?: React.ElementType;
ref?: React.Ref<HTMLDivElement>;
} & Record<string, unknown>;
function Marker({
className,
variant = "default",
as,
ref,
...props
}: MarkerProps) {
const Comp = as ?? "div";
return (
<Comp
className={cn(markerVariants({ className, variant }))}
data-slot="marker"
data-variant={variant}
ref={ref}
{...props}
/>
);
}
function MarkerIcon({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
aria-hidden="true"
className={cn(
"size-4 shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
data-slot="marker-icon"
{...props}
/>
);
}
function MarkerContent({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
className={cn(
"*:[a]:hover:text-foreground min-w-0 wrap-break-word group-data-[variant=separator]/marker:flex-none group-data-[variant=separator]/marker:text-center *:[a]:underline *:[a]:underline-offset-3",
className
)}
data-slot="marker-content"
{...props}
/>
);
}
export { Marker, MarkerContent, MarkerIcon, markerVariants };"use client";
import { cva, type VariantProps } from "class-variance-authority";
import { ArrowDownIcon } from "lucide-react";
import * as React from "react";
import { Button } from "@/components/ui/button";
import {
getTransition,
parseMotion,
useMotionGuard,
useReducedMotion,
} from "@/lib/motion";
import { cn } from "@/lib/utils";
interface UIMessagePart {
text?: string;
type: string;
}
interface UIMessage {
id: string;
metadata?: unknown;
parts: UIMessagePart[];
role: "user" | "assistant" | "system";
}
function getMessageText(message: UIMessage): string {
if (!Array.isArray(message.parts)) {
return "";
}
return message.parts
.filter(
(part): part is { type: "text"; text: string } =>
part.type === "text" && typeof part.text === "string"
)
.map((part) => part.text)
.join("");
}
function MessageGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("flex min-w-0 flex-col gap-2", className)}
data-slot="message-group"
{...props}
/>
);
}
function Message({
className,
align = "start",
...props
}: React.ComponentProps<"div"> & { align?: "start" | "end" }) {
return (
<div
className={cn(
"group/message relative flex w-full min-w-0 gap-2 text-sm data-[align=end]:flex-row-reverse",
className
)}
data-align={align}
data-slot="message"
{...props}
/>
);
}
function MessageAvatar({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"bg-muted flex w-fit min-w-8 shrink-0 items-center justify-center self-end overflow-hidden rounded-full group-has-data-[slot=message-footer]/message:-translate-y-8",
className
)}
data-slot="message-avatar"
{...props}
/>
);
}
function MessageContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"flex w-full min-w-0 flex-col gap-2.5 wrap-break-word group-data-[align=end]/message:*:data-slot:self-end",
className
)}
data-slot="message-content"
{...props}
/>
);
}
function MessageHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"text-muted-foreground flex max-w-full min-w-0 items-center px-3 text-xs font-medium group-has-data-[variant=ghost]/message:px-0",
className
)}
data-slot="message-header"
{...props}
/>
);
}
function MessageFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"text-muted-foreground flex max-w-full min-w-0 items-center px-3 text-xs font-medium group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end",
className
)}
data-slot="message-footer"
{...props}
/>
);
}
function BubbleGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("flex min-w-0 flex-col gap-2", className)}
data-slot="bubble-group"
{...props}
/>
);
}
const bubbleVariants = cva(
"group/bubble relative flex w-fit max-w-[80%] min-w-0 flex-col gap-1 group-data-[align=end]/message:self-end data-[align=end]:self-end data-[variant=ghost]:max-w-full",
{
defaultVariants: {
variant: "default",
},
variants: {
variant: {
default:
"*:data-[slot=bubble-content]:bg-primary *:data-[slot=bubble-content]:text-primary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-primary/80",
destructive:
"*:data-[slot=bubble-content]:bg-destructive/10 *:data-[slot=bubble-content]:text-destructive dark:*:data-[slot=bubble-content]:bg-destructive/20 [&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/20 dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/30",
ghost:
"[&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted/50 border-none *:data-[slot=bubble-content]:rounded-none *:data-[slot=bubble-content]:bg-transparent *:data-[slot=bubble-content]:p-0",
muted:
"*:data-[slot=bubble-content]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--muted),var(--foreground)_5%)]",
outline:
"*:data-[slot=bubble-content]:border-border *:data-[slot=bubble-content]:bg-background [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-input/30",
secondary:
"*:data-[slot=bubble-content]:bg-secondary *:data-[slot=bubble-content]:text-secondary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)]",
tinted:
"*:data-[slot=bubble-content]:text-foreground *:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.93_calc(c*0.4)_h)] dark:*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.3_calc(c*0.4)_h)] [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.88_calc(c*0.5)_h)] dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.35_calc(c*0.5)_h)]",
},
},
}
);
function Bubble({
variant = "default",
align = "start",
className,
...props
}: React.ComponentProps<"div"> &
VariantProps<typeof bubbleVariants> & {
align?: "start" | "end";
}) {
return (
<div
className={cn(bubbleVariants({ variant }), className)}
data-align={align}
data-slot="bubble"
data-variant={variant}
{...props}
/>
);
}
type BubbleContentProps = Omit<React.ComponentProps<"div">, "ref"> & {
as?: React.ElementType;
ref?: React.Ref<HTMLDivElement>;
} & Record<string, unknown>;
function BubbleContent({ as, className, ref, ...props }: BubbleContentProps) {
const Comp = as ?? "div";
return (
<Comp
className={cn(
"[button,a]:focus-visible:border-ring [button,a]:focus-visible:ring-ring/50 w-fit max-w-full min-w-0 overflow-hidden rounded-xl border border-transparent px-3 py-2 text-sm leading-relaxed wrap-break-word group-data-[align=end]/bubble:self-end [button]:text-left [button,a]:transition-colors [button,a]:outline-none [button,a]:focus-visible:ring-3",
className
)}
data-slot="bubble-content"
ref={ref}
{...props}
/>
);
}
const bubbleReactionsVariants = cva(
"bg-muted ring-card absolute z-10 flex w-fit shrink-0 items-center justify-center gap-1 rounded-full px-1.5 py-0.5 text-sm ring-3 has-[button]:p-0",
{
defaultVariants: {
align: "end",
side: "bottom",
},
variants: {
align: {
end: "right-3",
start: "left-3",
},
side: {
bottom: "bottom-0 translate-y-3/4",
top: "top-0 -translate-y-3/4",
},
},
}
);
function BubbleReactions({
side = "bottom",
align = "end",
className,
...props
}: React.ComponentProps<"div"> & {
align?: "start" | "end";
side?: "top" | "bottom";
}) {
return (
<div
className={cn(bubbleReactionsVariants({ align, side }), className)}
data-align={align}
data-side={side}
data-slot="bubble-reactions"
{...props}
/>
);
}
type ScrollDefaultPosition = "start" | "end" | "last-anchor";
type ScrollButtonDirection = "start" | "end";
type ScrollAlign = "start" | "center" | "end" | "nearest";
interface ScrollOptions {
align?: ScrollAlign;
behavior?: ScrollBehavior;
scrollMargin?: number;
}
interface Scrollable {
end: boolean;
start: boolean;
}
interface VisibilityState {
currentAnchorId: string | null;
visibleMessageIds: string[];
}
interface ScrollerProviderProps {
autoScroll?: boolean;
children?: React.ReactNode;
defaultScrollPosition?: ScrollDefaultPosition;
scrollEdgeThreshold?: number;
scrollMargin?: number;
scrollPreviousItemPeek?: number;
}
type ScrollerProps = React.ComponentProps<"div">;
type ScrollerViewportProps = React.ComponentProps<"div"> & {
preserveScrollOnPrepend?: boolean;
};
type ScrollerContentProps = React.ComponentProps<"div"> & {
spacerClassName?: string;
};
type ScrollerItemProps = React.ComponentProps<"div"> & {
messageId?: string;
scrollAnchor?: boolean;
};
type ScrollerButtonDirection = ScrollButtonDirection;
type ScrollerButtonProps = Omit<
React.ComponentProps<"button">,
"children" | "render"
> & {
children?: React.ReactNode;
behavior?: ScrollBehavior;
direction?: ScrollerButtonDirection;
render?: React.ReactElement;
};
interface ScrollerContextValue {
autoScroll: boolean;
contentRef: React.RefObject<HTMLDivElement | null>;
defaultScrollPosition: ScrollDefaultPosition;
itemElements: Map<string, HTMLDivElement>;
preserveScrollOnPrependRef: React.MutableRefObject<boolean>;
registerItem: (id: string, el: HTMLDivElement) => () => void;
scrollable: Scrollable;
scrollEdgeThreshold: number;
scrollMargin: number;
scrollPreviousItemPeek: number;
scrollToEnd: (opts?: ScrollOptions) => boolean;
scrollToMessage: (messageId: string, opts?: ScrollOptions) => boolean;
scrollToStart: (opts?: ScrollOptions) => boolean;
setContentPresent: (present: boolean) => void;
setPreserveScrollOnPrepend: (v: boolean) => void;
setViewportPresent: (present: boolean) => void;
viewportRef: React.RefObject<HTMLDivElement | null>;
visibility: VisibilityState;
}
const ScrollerContext = React.createContext<ScrollerContextValue | null>(null);
function useScrollerContext(): ScrollerContextValue {
const ctx = React.useContext(ScrollerContext);
if (!ctx) {
throw new Error(
"MessageScroller components must be used within <MessageScroller.Provider>"
);
}
return ctx;
}
function ScrollerProvider({
children,
autoScroll = true,
defaultScrollPosition = "end",
scrollEdgeThreshold = 16,
scrollPreviousItemPeek = 40,
scrollMargin = 0,
}: ScrollerProviderProps) {
const viewportRef = React.useRef<HTMLDivElement | null>(null);
const contentRef = React.useRef<HTMLDivElement | null>(null);
const itemElements = React.useRef<Map<string, HTMLDivElement>>(new Map());
const preserveScrollOnPrependRef = React.useRef(false);
const [contentPresent, setContentPresent] = React.useState(false);
const [viewportPresent, setViewportPresent] = React.useState(false);
const [scrollable, setScrollable] = React.useState<Scrollable>({
end: false,
start: false,
});
const [visibility, setVisibility] = React.useState<VisibilityState>({
currentAnchorId: null,
visibleMessageIds: [],
});
const setPreserveScrollOnPrepend = React.useCallback((v: boolean) => {
preserveScrollOnPrependRef.current = v;
}, []);
const registerItem = React.useCallback((id: string, el: HTMLDivElement) => {
itemElements.current.set(id, el);
return () => {
itemElements.current.delete(id);
};
}, []);
const computeScrollable = React.useCallback(() => {
const vp = viewportRef.current;
if (!vp) {
return;
}
const start = vp.scrollTop > scrollEdgeThreshold;
const end =
vp.scrollHeight - vp.clientHeight - vp.scrollTop > scrollEdgeThreshold;
setScrollable((prev) =>
prev.start === start && prev.end === end ? prev : { end, start }
);
}, [scrollEdgeThreshold]);
const computeVisibility = React.useCallback(() => {
const vp = viewportRef.current;
if (!vp) {
return;
}
const vpRect = vp.getBoundingClientRect();
const visible: string[] = [];
let currentAnchorId: string | null = null;
let bestTop = Number.POSITIVE_INFINITY;
itemElements.current.forEach((el, id) => {
const r = el.getBoundingClientRect();
if (r.bottom > vpRect.top && r.top < vpRect.bottom) {
visible.push(id);
if (r.top >= vpRect.top - 1 && r.top < bestTop) {
bestTop = r.top;
currentAnchorId = id;
}
}
});
setVisibility((prev) => {
if (
prev.currentAnchorId === currentAnchorId &&
prev.visibleMessageIds.length === visible.length &&
prev.visibleMessageIds.every((v, i) => v === visible[i])
) {
return prev;
}
return { currentAnchorId, visibleMessageIds: visible };
});
}, []);
const onScroll = React.useCallback(() => {
computeScrollable();
computeVisibility();
}, [computeScrollable, computeVisibility]);
const scrollToEnd = React.useCallback((opts?: ScrollOptions) => {
const vp = viewportRef.current;
if (!vp) {
return false;
}
vp.scrollTo({ behavior: opts?.behavior ?? "smooth", top: vp.scrollHeight });
return true;
}, []);
const scrollToStart = React.useCallback((opts?: ScrollOptions) => {
const vp = viewportRef.current;
if (!vp) {
return false;
}
vp.scrollTo({ behavior: opts?.behavior ?? "smooth", top: 0 });
return true;
}, []);
const scrollToMessage = React.useCallback(
(messageId: string, opts?: ScrollOptions) => {
const el = itemElements.current.get(messageId);
if (!el) {
return false;
}
el.scrollIntoView({
behavior: opts?.behavior ?? "smooth",
block: opts?.align ?? "start",
inline: "nearest",
});
return true;
},
[]
);
React.useEffect(() => {
const vp = viewportRef.current;
if (!vp) {
return;
}
vp.addEventListener("scroll", onScroll, { passive: true });
computeScrollable();
computeVisibility();
return () => vp.removeEventListener("scroll", onScroll);
}, [onScroll, computeScrollable, computeVisibility, viewportPresent]);
React.useEffect(() => {
if (!contentPresent) {
return;
}
const vp = viewportRef.current;
if (!vp) {
return;
}
if (defaultScrollPosition === "start") {
vp.scrollTop = 0;
} else if (defaultScrollPosition === "end") {
vp.scrollTop = vp.scrollHeight;
}
}, [contentPresent, defaultScrollPosition]);
React.useEffect(() => {
if (!autoScroll) {
return;
}
const vp = viewportRef.current;
const content = contentRef.current;
if (!(vp && content)) {
return;
}
if (typeof ResizeObserver === "undefined") {
return;
}
const observer = new ResizeObserver(() => {
const distance = vp.scrollHeight - vp.clientHeight - vp.scrollTop;
if (distance <= scrollEdgeThreshold) {
vp.scrollTop = vp.scrollHeight;
}
computeScrollable();
});
observer.observe(content);
return () => observer.disconnect();
}, [autoScroll, scrollEdgeThreshold, computeScrollable, viewportPresent]);
const value: ScrollerContextValue = {
autoScroll,
contentRef,
defaultScrollPosition,
itemElements: itemElements.current,
preserveScrollOnPrependRef,
registerItem,
scrollable,
scrollEdgeThreshold,
scrollMargin,
scrollPreviousItemPeek,
scrollToEnd,
scrollToMessage,
scrollToStart,
setContentPresent,
setPreserveScrollOnPrepend,
setViewportPresent,
viewportRef,
visibility,
};
return (
<ScrollerContext.Provider value={value}>
{children}
</ScrollerContext.Provider>
);
}
function ScrollerRoot({ children, ...props }: ScrollerProps) {
return <div {...props}>{children}</div>;
}
function ScrollerViewport({
children,
onScroll,
preserveScrollOnPrepend,
ref,
...props
}: ScrollerViewportProps) {
const ctx = useScrollerContext();
const setRef = React.useCallback(
(node: HTMLDivElement | null) => {
ctx.viewportRef.current = node;
if (typeof ref === "function") {
ref(node);
} else if (ref) {
(ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
}
},
[ctx.viewportRef, ref]
);
React.useEffect(() => {
if (preserveScrollOnPrepend !== undefined) {
ctx.setPreserveScrollOnPrepend(preserveScrollOnPrepend);
}
}, [preserveScrollOnPrepend, ctx]);
const ctxRef = React.useRef(ctx);
ctxRef.current = ctx;
React.useEffect(() => {
ctxRef.current.setViewportPresent(true);
return () => ctxRef.current.setViewportPresent(false);
}, []);
return (
<div onScroll={onScroll} ref={setRef} {...props}>
{children}
</div>
);
}
function ScrollerContent({ children, ...props }: ScrollerContentProps) {
const ctx = useScrollerContext();
React.useEffect(() => {
ctx.setContentPresent(true);
return () => ctx.setContentPresent(false);
}, [ctx]);
return (
<div ref={ctx.contentRef} {...props}>
{children}
</div>
);
}
function ScrollerItem({
messageId,
scrollAnchor,
children,
ref,
...props
}: ScrollerItemProps) {
const ctx = useScrollerContext();
const localRef = React.useRef<HTMLDivElement | null>(null);
const setRef = React.useCallback(
(node: HTMLDivElement | null) => {
localRef.current = node;
if (typeof ref === "function") {
ref(node);
} else if (ref) {
(ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
}
},
[ref]
);
React.useEffect(() => {
if (!(messageId && localRef.current)) {
return;
}
return ctx.registerItem(messageId, localRef.current);
}, [messageId, ctx]);
return (
<div
data-scroll-anchor={scrollAnchor ? "true" : undefined}
ref={setRef}
{...props}
>
{children}
</div>
);
}
function ScrollerButton({
direction = "end",
behavior = "smooth",
onClick,
render,
children,
type = "button",
...props
}: ScrollerButtonProps) {
const ctx = useScrollerContext();
const active =
direction === "end" ? ctx.scrollable.end : ctx.scrollable.start;
const handleClick: React.MouseEventHandler<HTMLButtonElement> = (e) => {
onClick?.(e);
if (e.defaultPrevented) {
return;
}
if (direction === "end") {
ctx.scrollToEnd({ behavior });
} else {
ctx.scrollToStart({ behavior });
}
};
const mergedProps = {
...props,
children,
"data-active": active ? "true" : "false",
"data-direction": direction,
onClick: handleClick,
type,
} as React.ButtonHTMLAttributes<HTMLButtonElement> & Record<string, unknown>;
if (render && React.isValidElement(render)) {
return React.cloneElement(
render as React.ReactElement<Record<string, unknown>>,
mergedProps
);
}
return <button {...mergedProps} />;
}
function useMessageScroller() {
const ctx = useScrollerContext();
return {
scrollToEnd: ctx.scrollToEnd,
scrollToMessage: ctx.scrollToMessage,
scrollToStart: ctx.scrollToStart,
};
}
function useMessageScrollerScrollable() {
return useScrollerContext().scrollable;
}
function useMessageScrollerVisibility() {
return useScrollerContext().visibility;
}
function MessageScrollerProvider(props: ScrollerProviderProps) {
return <ScrollerProvider {...props} />;
}
function MessageScroller({ className, ...props }: React.ComponentProps<"div">) {
return (
<ScrollerRoot
className={cn(
"group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden",
className
)}
data-slot="message-scroller"
{...props}
/>
);
}
function MessageScrollerViewport({
className,
...props
}: React.ComponentProps<"div"> & { preserveScrollOnPrepend?: boolean }) {
return (
<ScrollerViewport
className={cn(
"scroll-fade-b size-full min-h-0 min-w-0 overflow-y-auto overscroll-contain contain-content data-pending-scroll:invisible",
className
)}
data-slot="message-scroller-viewport"
{...props}
/>
);
}
function MessageScrollerContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<ScrollerContent
className={cn("flex h-max min-h-full flex-col gap-6", className)}
data-slot="message-scroller-content"
{...props}
/>
);
}
function MessageScrollerItem({
className,
scrollAnchor = false,
...props
}: React.ComponentProps<"div"> & {
messageId?: string;
scrollAnchor?: boolean;
}) {
return (
<ScrollerItem
className={cn(
"min-w-0 shrink-0 [contain-intrinsic-size:auto_10rem] [content-visibility:auto]",
className
)}
data-slot="message-scroller-item"
scrollAnchor={scrollAnchor}
{...props}
/>
);
}
function MessageScrollerButton({
direction = "end",
className,
children,
render,
variant = "secondary",
size = "icon-sm",
...props
}: React.ComponentProps<"button"> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size"> & {
direction?: "start" | "end";
render?: React.ReactElement;
behavior?: ScrollBehavior;
}) {
return (
<ScrollerButton
className={cn(
"border-border bg-muted text-foreground hover:bg-muted/80 hover:text-foreground absolute inset-s-1/2 -translate-x-1/2 rounded-full transition-[translate,scale,opacity] duration-200 data-[active=false]:pointer-events-none data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=false]:duration-400 data-[active=false]:ease-[cubic-bezier(0.7,0,0.84,0)] data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[active=true]:ease-[cubic-bezier(0.23,1,0.32,1)] data-[direction=end]:bottom-4 data-[direction=end]:data-[active=false]:translate-y-full data-[direction=start]:top-4 data-[direction=start]:data-[active=false]:-translate-y-full rtl:translate-x-1/2 data-[direction=start]:[&_svg]:rotate-180",
className
)}
data-direction={direction}
data-size={size}
data-slot="message-scroller-button"
data-variant={variant}
direction={direction}
render={render ?? <Button size={size} variant={variant} />}
{...props}
>
{children ?? (
<>
<ArrowDownIcon />
<span className="sr-only">
{direction === "end" ? "Scroll to end" : "Scroll to start"}
</span>
</>
)}
</ScrollerButton>
);
}
const defaultMessageAnimatedMotion = "200 ease-out";
interface MessageAnimatedProps {
message: UIMessage;
motion?: string;
scrollAnchor?: boolean;
}
function MessageAnimated({
message,
motion,
scrollAnchor,
}: MessageAnimatedProps) {
const text = getMessageText(message);
const isUser = message.role === "user";
const reduce = useReducedMotion();
const motionValue = motion ?? defaultMessageAnimatedMotion;
const internalRef = React.useRef<HTMLDivElement | null>(null);
const [entered, setEntered] = React.useState(false);
React.useEffect(() => {
let raf1 = 0;
let raf2 = 0;
raf1 = requestAnimationFrame(() => {
raf2 = requestAnimationFrame(() => setEntered(true));
});
return () => {
if (raf1) {
cancelAnimationFrame(raf1);
}
if (raf2) {
cancelAnimationFrame(raf2);
}
};
}, []);
let resolvedStyle: React.CSSProperties = {
opacity: reduce ? 1 : entered ? 1 : 0,
transform: reduce ? "none" : entered ? "translateY(0)" : "translateY(8px)",
};
if (reduce) {
resolvedStyle.transition = "none";
} else {
const transition = getTransition(parseMotion(motionValue));
if (transition) {
resolvedStyle.transition = transition;
}
}
const motionEnabled = !reduce;
const styleFingerprint = JSON.stringify(resolvedStyle);
const yielded = useMotionGuard(internalRef, motionEnabled, styleFingerprint);
if (yielded && !reduce) {
resolvedStyle = { ...resolvedStyle, transition: "none" };
}
return (
<MessageScrollerItem scrollAnchor={scrollAnchor}>
<div className="flex flex-col" ref={internalRef} style={resolvedStyle}>
<Bubble
align={isUser ? "end" : "start"}
variant={isUser ? "muted" : "ghost"}
>
<BubbleContent className="whitespace-pre-wrap">{text}</BubbleContent>
</Bubble>
</div>
</MessageScrollerItem>
);
}
export type { UIMessage, UIMessagePart };
export {
Bubble,
BubbleContent,
BubbleGroup,
BubbleReactions,
Message,
MessageAnimated,
MessageAvatar,
MessageContent,
MessageFooter,
MessageGroup,
MessageHeader,
MessageScroller,
MessageScrollerButton,
MessageScrollerContent,
MessageScrollerItem,
MessageScrollerProvider,
MessageScrollerViewport,
useMessageScroller,
useMessageScrollerScrollable,
useMessageScrollerVisibility,
};Update the import paths to match your project setup.
Usage
Emit a data-checkpoint part from the assistant turn. The part carries a label, which renders as a separator marker in the transcript.
import { createChat } from "@frakment/ai";
import type { UIMessage } from "ai";
type ChatMessage = UIMessage<
unknown,
{ checkpoint: { label: string } }
>;
const chat = createChat<ChatMessage>()
.user("Rename the button component to action.")
.assistant(({ writer }) => {
writer.text("Renamed Button to Action.");
writer.data({
type: "data-checkpoint",
id: "rename",
data: { label: "Button renamed" },
});
});Anatomy
<Message align="end">
<MessageContent>
<Bubble align="end" variant="muted">
<BubbleContent>{userText}</BubbleContent>
</Bubble>
</MessageContent>
</Message>
<Message>
<MessageContent>
<p>{assistantText}</p>
</MessageContent>
</Message>
<Marker variant="separator">
<MarkerContent>
{checkpoint.data.label}
<Button size="xs" variant="outline" onClick={restore}>
Restore
</Button>
</MarkerContent>
</Marker>- Message, Bubble — user and assistant turns.
- Marker with
variant="separator"— the visual checkpoint line. - Button — restore action, only shown when there is a later turn to trim.
Animation
Checkpoint rows animate through the same variants as chat messages.
import { MESSAGE_ANIMATIONS } from "@/lib/message-animations";
import { motion, useReducedMotion } from "motion/react";
const shouldReduceMotion = useReducedMotion();
<motion.div
animate={shouldReduceMotion ? undefined : "animate"}
initial={shouldReduceMotion ? undefined : "initial"}
variants={MESSAGE_ANIMATIONS["slide-up"].variants}
>
...
</motion.div>The checkpoint marker uses the fade variant, so it appears after the message it belongs to.
Restore semantics
restore(messageId) trims every message after the one that carried the checkpoint.
function restore(messageId: string) {
const index = messages.findIndex((m) => m.id === messageId);
if (index === -1) return;
setMessages(messages.slice(0, index + 1));
}The restore button hides when the checkpoint is already the last message. Send the next user turn to branch again from that point.
Next
- Chat — full streaming chat surface.
- Message — message row primitive.
- Bubble — chat bubble surface.
- Marker — separator and status line.
- Button — restore action.
Accessibility
- The checkpoint marker is a separator with a visible label. Provide
aria-labelon the restore button, e.g. "Restore to Button renamed". - Restore buttons are focusable and respond to Enter and Space.
- When the checkpoint is the last message, restore is hidden to avoid a no-op for keyboard users.
- Announce transcript length with
role="status"if you track it elsewhere.
Best Practices
- One checkpoint per logical step. Emit when the state is worth returning to.
- Label with what changed. "Button renamed" beats "Checkpoint 3".
- Hide restore on the last checkpoint. Nothing to trim means no button.
- Combine with confirmation for destructive restores. Restoring over unsaved work should ask first.
- Do not persist checkpoints across sessions. They belong to the current transcript.