Get Started
Components
- 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
AI Elements
Libraries
Utilities
ME
Deploying to prod real quick.
OL
It is 4:55 PM. On a Friday.
ME
It is a one-line change.
Delivered
OL
It is always a one-line change.
Alright, let me take a look.
👍
Oliver is typing...
"use client";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Marker, MarkerContent } from "@/components/ui/marker";
import {
Bubble,
BubbleContent,
BubbleGroup,
BubbleReactions,
Message,
MessageAvatar,
MessageContent,
MessageFooter,
} from "@/components/ui/message";
export function MessageDemo() {
return (
<div className="flex w-full max-w-sm flex-col gap-6 py-12">
<Message align="end">
<MessageAvatar>
<Avatar>
<AvatarImage alt="@me" src="/avatars/female-l-1.avif" />
<AvatarFallback>ME</AvatarFallback>
</Avatar>
</MessageAvatar>
<MessageContent>
<Bubble>
<BubbleContent>Deploying to prod real quick.</BubbleContent>
</Bubble>
</MessageContent>
</Message>
<Message>
<MessageAvatar>
<Avatar>
<AvatarImage alt="@oliver" src="/avatars/male-r.avif" />
<AvatarFallback>OL</AvatarFallback>
</Avatar>
</MessageAvatar>
<MessageContent>
<Bubble variant="muted">
<BubbleContent>It is 4:55 PM. On a Friday.</BubbleContent>
</Bubble>
</MessageContent>
</Message>
<Message align="end">
<MessageAvatar>
<Avatar>
<AvatarImage alt="@me" src="/avatars/female-l-1.avif" />
<AvatarFallback>ME</AvatarFallback>
</Avatar>
</MessageAvatar>
<MessageContent>
<Bubble>
<BubbleContent>It is a one-line change.</BubbleContent>
</Bubble>
<MessageFooter>Delivered</MessageFooter>
</MessageContent>
</Message>
<Message>
<MessageAvatar>
<Avatar>
<AvatarImage alt="@oliver" src="/avatars/male-r.avif" />
<AvatarFallback>OL</AvatarFallback>
</Avatar>
</MessageAvatar>
<MessageContent>
<BubbleGroup>
<Bubble variant="muted">
<BubbleContent>It is always a one-line change.</BubbleContent>
</Bubble>
<Bubble variant="muted">
<BubbleContent>Alright, let me take a look.</BubbleContent>
<BubbleReactions aria-label="Reactions: thumbs up">
<span>👍</span>
</BubbleReactions>
</Bubble>
</BubbleGroup>
</MessageContent>
</Message>
<Marker role="status">
<MarkerContent className="shimmer">
<span className="font-medium">Oliver</span> is typing...
</MarkerContent>
</Marker>
</div>
);
}Message Pattern shows a user turn and an assistant turn with the pieces that make a real conversation feel finished: markdown content, a copy action, feedback buttons, and a retry action. It composes Message, Bubble, Tooltip, Button, and Markdown.
Message is a composition, not a primitive. Install the five primitives it uses, then wire it the same way the demo does.
Installation
$ bunx --bun frakment add message bubble tooltip button$ npx frakment add message bubble tooltip button$ pnpm dlx frakment add message bubble tooltip button$ yarn dlx frakment add message bubble tooltip button
Install the following dependencies:
$ bun add radix-ui lucide-react$ npm install radix-ui lucide-react$ pnpm add radix-ui lucide-react$ yarn add radix-ui lucide-react
Install the required registry primitives:
"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,
};"use client";
import * as React from "react";
import { createPortal } from "react-dom";
import { parseMotion, useReducedMotion } from "@/lib/motion";
import { cn } from "@/lib/utils";
type TooltipSide = "top" | "right" | "bottom" | "left";
type TooltipAlign = "start" | "center" | "end";
interface TooltipProviderContextValue {
delayDuration: number;
}
const TooltipProviderContext = React.createContext<TooltipProviderContextValue>(
{ delayDuration: 0 }
);
interface TooltipContextValue {
contentId: string;
contentRef: React.RefObject<HTMLDivElement | null>;
onContentEnter: () => void;
onContentLeave: () => void;
onTriggerBlur: () => void;
onTriggerEnter: () => void;
onTriggerFocus: () => void;
onTriggerLeave: () => void;
open: boolean;
setOpen: (open: boolean) => void;
triggerRef: React.RefObject<HTMLElement | null>;
}
const TooltipContext = React.createContext<TooltipContextValue | null>(null);
function useTooltipContext(component: string): TooltipContextValue {
const ctx = React.useContext(TooltipContext);
if (!ctx) {
throw new Error(`${component} must be used within Tooltip`);
}
return ctx;
}
function computeTooltipPosition(
trigger: HTMLElement,
content: HTMLElement,
side: TooltipSide,
align: TooltipAlign,
sideOffset: number,
avoidCollisions: boolean
): { x: number; y: number; side: TooltipSide } {
const t = trigger.getBoundingClientRect();
const c = content.getBoundingClientRect();
const vw = window.innerWidth;
const vh = window.innerHeight;
const place = (s: TooltipSide): { x: number; y: number } => {
let x = 0;
let y = 0;
if (s === "top") {
x = t.left + (t.width - c.width) / 2;
y = t.top - c.height - sideOffset;
} else if (s === "bottom") {
x = t.left + (t.width - c.width) / 2;
y = t.bottom + sideOffset;
} else if (s === "left") {
x = t.left - c.width - sideOffset;
y = t.top + (t.height - c.height) / 2;
} else {
x = t.right + sideOffset;
y = t.top + (t.height - c.height) / 2;
}
if (s === "top" || s === "bottom") {
if (align === "start") {
x = t.left;
} else if (align === "end") {
x = t.right - c.width;
}
} else if (align === "start") {
y = t.top;
} else if (align === "end") {
y = t.bottom - c.height;
}
return { x, y };
};
let resolvedSide = side;
const placed = place(resolvedSide);
let x = placed.x;
let y = placed.y;
if (avoidCollisions) {
const pad = 8;
const over = {
bottom: y + c.height > vh - pad,
left: x < pad,
right: x + c.width > vw - pad,
top: y < pad,
};
const flipMap: Record<TooltipSide, TooltipSide> = {
bottom: "top",
left: "right",
right: "left",
top: "bottom",
};
if (over[resolvedSide]) {
const flipped = flipMap[resolvedSide];
const fp = place(flipped);
const flipOver =
fp.y < pad ||
fp.y + c.height > vh - pad ||
fp.x < pad ||
fp.x + c.width > vw - pad;
if (!flipOver) {
resolvedSide = flipped;
x = fp.x;
y = fp.y;
}
}
if (x < pad) {
x = pad;
}
if (x + c.width > vw - pad) {
x = vw - c.width - pad;
}
if (y < pad) {
y = pad;
}
if (y + c.height > vh - pad) {
y = vh - c.height - pad;
}
}
return { side: resolvedSide, x, y };
}
interface TooltipProviderProps {
children?: React.ReactNode;
delayDuration?: number;
}
function TooltipProvider({
children,
delayDuration = 0,
}: TooltipProviderProps) {
const value = React.useMemo(() => ({ delayDuration }), [delayDuration]);
return (
<TooltipProviderContext.Provider value={value}>
{children}
</TooltipProviderContext.Provider>
);
}
interface TooltipProps {
children?: React.ReactNode;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
open?: boolean;
}
function Tooltip({
children,
defaultOpen = false,
onOpenChange,
open: openProp,
}: TooltipProps) {
const provider = React.useContext(TooltipProviderContext);
const isControlled = openProp !== undefined;
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen);
const open = isControlled ? openProp : uncontrolledOpen;
const contentId = React.useId();
const triggerRef = React.useRef<HTMLButtonElement | null>(null);
const contentRef = React.useRef<HTMLDivElement | null>(null);
const openTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const closeTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const clearTimers = React.useCallback(() => {
if (openTimer.current !== null) {
clearTimeout(openTimer.current);
openTimer.current = null;
}
if (closeTimer.current !== null) {
clearTimeout(closeTimer.current);
closeTimer.current = null;
}
}, []);
const setOpen = React.useCallback(
(next: boolean) => {
if (!isControlled) {
setUncontrolledOpen(next);
}
onOpenChange?.(next);
},
[isControlled, onOpenChange]
);
const onTriggerEnter = React.useCallback(() => {
clearTimers();
if (provider.delayDuration > 0) {
openTimer.current = setTimeout(
() => setOpen(true),
provider.delayDuration
);
} else {
setOpen(true);
}
}, [clearTimers, provider.delayDuration, setOpen]);
const onTriggerLeave = React.useCallback(() => {
clearTimers();
closeTimer.current = setTimeout(() => setOpen(false), 80);
}, [clearTimers, setOpen]);
const onContentEnter = React.useCallback(() => {
clearTimers();
}, [clearTimers]);
const onContentLeave = React.useCallback(() => {
clearTimers();
closeTimer.current = setTimeout(() => setOpen(false), 80);
}, [clearTimers, setOpen]);
const onTriggerFocus = React.useCallback(() => {
clearTimers();
setOpen(true);
}, [clearTimers, setOpen]);
const onTriggerBlur = React.useCallback(() => {
clearTimers();
closeTimer.current = setTimeout(() => setOpen(false), 0);
}, [clearTimers, setOpen]);
React.useEffect(
() => () => {
clearTimers();
},
[clearTimers]
);
React.useEffect(() => {
if (!open) {
return;
}
const onKey = (event: KeyboardEvent) => {
if (event.key === "Escape") {
clearTimers();
setOpen(false);
}
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [open, clearTimers, setOpen]);
const value = React.useMemo<TooltipContextValue>(
() => ({
contentId,
contentRef,
onContentEnter,
onContentLeave,
onTriggerBlur,
onTriggerEnter,
onTriggerFocus,
onTriggerLeave,
open,
setOpen,
triggerRef,
}),
[
contentId,
onContentEnter,
onContentLeave,
onTriggerBlur,
onTriggerEnter,
onTriggerFocus,
onTriggerLeave,
open,
setOpen,
]
);
return (
<TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>
);
}
type TooltipTriggerProps = Omit<React.ComponentProps<"button">, "ref"> & {
as?: React.ElementType;
asChild?: boolean;
ref?: React.Ref<HTMLElement>;
} & Record<string, unknown>;
function TooltipTrigger({
as,
asChild = false,
children,
onBlur,
onFocus,
onPointerEnter,
onPointerLeave,
ref,
...props
}: TooltipTriggerProps) {
const ctx = useTooltipContext("TooltipTrigger");
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: Record<string, unknown> = {
"aria-describedby": ctx.open ? ctx.contentId : undefined,
"data-state": ctx.open ? "open" : "closed",
onBlur: (event: React.FocusEvent<HTMLElement>) => {
(onBlur as ((e: React.FocusEvent<HTMLElement>) => void) | undefined)?.(
event
);
ctx.onTriggerBlur();
},
onFocus: (event: React.FocusEvent<HTMLElement>) => {
(onFocus as ((e: React.FocusEvent<HTMLElement>) => void) | undefined)?.(
event
);
ctx.onTriggerFocus();
},
onPointerEnter: (event: React.PointerEvent<HTMLElement>) => {
(
onPointerEnter as
| ((e: React.PointerEvent<HTMLElement>) => void)
| undefined
)?.(event);
ctx.onTriggerEnter();
},
onPointerLeave: (event: React.PointerEvent<HTMLElement>) => {
(
onPointerLeave as
| ((e: React.PointerEvent<HTMLElement>) => void)
| undefined
)?.(event);
ctx.onTriggerLeave();
},
ref: setRef,
};
if (asChild && React.isValidElement(children)) {
return React.cloneElement(
children as React.ReactElement<Record<string, unknown>>,
handlers
);
}
const Comp = (as ?? "button") as React.ElementType;
const isNativeButton = Comp === "button";
return (
<Comp
data-slot="tooltip-trigger"
type={isNativeButton ? ((props.type as string) ?? "button") : undefined}
{...props}
{...handlers}
>
{children}
</Comp>
);
}
interface TooltipContentProps extends Omit<React.ComponentProps<"div">, "ref"> {
align?: TooltipAlign;
avoidCollisions?: boolean;
motion?: string;
ref?: React.Ref<HTMLDivElement>;
side?: TooltipSide;
sideOffset?: number;
}
const defaultTooltipMotion = "120 ease-out";
function TooltipContent({
align = "center",
avoidCollisions = true,
children,
className,
motion,
ref,
side = "bottom",
sideOffset = 10,
style,
...props
}: TooltipContentProps) {
const ctx = useTooltipContext("TooltipContent");
const reduce = useReducedMotion();
const motionValue = motion ?? defaultTooltipMotion;
const internalRef = React.useRef<HTMLDivElement | null>(null);
const [entered, setEntered] = React.useState(false);
const [present, setPresent] = React.useState(false);
const [resolvedSide, setResolvedSide] = React.useState<TooltipSide>(side);
const [pos, setPos] = React.useState<{ x: number; y: number }>({
x: 0,
y: 0,
});
const setRef = React.useCallback(
(node: HTMLDivElement | null) => {
internalRef.current = node;
ctx.contentRef.current = node;
if (typeof ref === "function") {
ref(node);
} else if (ref) {
(ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
}
},
[ctx.contentRef, ref]
);
React.useLayoutEffect(() => {
if (!present) {
return;
}
const trigger = ctx.triggerRef.current;
const content = internalRef.current;
if (!(trigger && content)) {
return;
}
const update = () => {
const t = ctx.triggerRef.current;
const c = internalRef.current;
if (!(t && c)) {
return;
}
const next = computeTooltipPosition(
t,
c,
side,
align,
sideOffset,
avoidCollisions
);
setPos({ x: next.x, y: next.y });
setResolvedSide(next.side);
};
update();
window.addEventListener("scroll", update, true);
window.addEventListener("resize", update);
let observer: ResizeObserver | undefined;
if (typeof ResizeObserver !== "undefined") {
observer = new ResizeObserver(update);
observer.observe(trigger);
observer.observe(content);
}
return () => {
window.removeEventListener("scroll", update, true);
window.removeEventListener("resize", update);
observer?.disconnect();
};
}, [present, side, align, sideOffset, avoidCollisions, ctx.triggerRef]);
const parsedMotion = parseMotion(motionValue);
const exitDuration =
reduce || parsedMotion?.disabled ? 0 : (parsedMotion?.duration ?? 120);
React.useEffect(() => {
if (ctx.open) {
setPresent(true);
let raf1 = 0;
let raf2 = 0;
raf1 = requestAnimationFrame(() => {
raf2 = requestAnimationFrame(() => setEntered(true));
});
return () => {
if (raf1) {
cancelAnimationFrame(raf1);
}
if (raf2) {
cancelAnimationFrame(raf2);
}
};
}
setEntered(false);
const timer = setTimeout(() => setPresent(false), exitDuration);
return () => clearTimeout(timer);
}, [ctx.open, exitDuration]);
if (!present) {
return null;
}
const baseStyle: React.CSSProperties = {
left: pos.x,
opacity: reduce ? 1 : entered ? 1 : 0,
position: "fixed",
top: pos.y,
...style,
};
if (reduce) {
baseStyle.transition = "none";
} else {
const parsed = parseMotion(motionValue);
if (parsed?.disabled) {
baseStyle.transition = "none";
} else if (parsed) {
baseStyle.transition = `opacity ${parsed.duration}ms ${parsed.easing}`;
} else {
baseStyle.transition = "opacity 120ms ease-out, transform 120ms ease-out";
}
}
const arrowSize = 8;
const arrowStyle: React.CSSProperties = {
background: "var(--foreground)",
height: arrowSize,
position: "absolute",
transform: "rotate(45deg)",
width: arrowSize,
};
if (resolvedSide === "top") {
arrowStyle.bottom = -arrowSize / 4;
if (align === "start") {
arrowStyle.left = 12;
} else if (align === "end") {
arrowStyle.right = 12;
} else {
arrowStyle.left = "50%";
arrowStyle.marginLeft = -arrowSize / 2;
}
} else if (resolvedSide === "bottom") {
arrowStyle.top = -arrowSize / 4;
if (align === "start") {
arrowStyle.left = 12;
} else if (align === "end") {
arrowStyle.right = 12;
} else {
arrowStyle.left = "50%";
arrowStyle.marginLeft = -arrowSize / 2;
}
} else if (resolvedSide === "left") {
arrowStyle.right = -arrowSize / 4;
if (align === "start") {
arrowStyle.top = 12;
} else if (align === "end") {
arrowStyle.bottom = 12;
} else {
arrowStyle.top = "50%";
arrowStyle.marginTop = -arrowSize / 2;
}
} else {
arrowStyle.left = -arrowSize / 4;
if (align === "start") {
arrowStyle.top = 12;
} else if (align === "end") {
arrowStyle.bottom = 12;
} else {
arrowStyle.top = "50%";
arrowStyle.marginTop = -arrowSize / 2;
}
}
return createPortal(
<div
className={cn(
"bg-foreground text-background z-50 inline-flex w-fit max-w-xs items-center gap-1.5 overflow-visible rounded-md px-3 py-1.5 text-xs",
className
)}
data-align={align}
data-side={resolvedSide}
data-slot="tooltip-content"
data-state={ctx.open ? "open" : "closed"}
id={ctx.contentId}
onPointerEnter={ctx.onContentEnter}
onPointerLeave={ctx.onContentLeave}
ref={setRef}
role="tooltip"
style={baseStyle}
{...props}
>
<span aria-hidden="true" style={arrowStyle} />
{children}
</div>,
document.body
);
}
export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };"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 { Markdown } from "@/components/ui/markdown";
import { Bubble, BubbleContent } from "@/components/ui/message";
import { Button } from "@/components/ui/button";
import {
Message,
MessageContent,
MessageFooter,
} from "@/components/ui/message";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
<Message>
<MessageContent className="gap-2">
<Markdown>{reply}</Markdown>
<MessageFooter className="px-0">
<MessageAction label="Copy"><CopyIcon /></MessageAction>
<MessageAction label="Retry"><RefreshCcwIcon /></MessageAction>
</MessageFooter>
</MessageContent>
</Message>Anatomy
<Message align="end">
<MessageContent>
<Bubble align="end" variant="muted">
<BubbleContent>{userText}</BubbleContent>
</Bubble>
<MessageFooter>
<MessageAction label="Copy"><CopyIcon /></MessageAction>
<MessageAction label="Edit"><PencilIcon /></MessageAction>
</MessageFooter>
</MessageContent>
</Message>
<Message>
<MessageContent>
<Markdown>{reply}</Markdown>
<MessageFooter>
<MessageAction label="Copy"><CopyIcon /></MessageAction>
<MessageAction label="Good response"><ThumbsUpIcon /></MessageAction>
<MessageAction label="Bad response"><ThumbsDownIcon /></MessageAction>
<MessageAction label="Retry"><RefreshCcwIcon /></MessageAction>
</MessageFooter>
</MessageContent>
</Message>- Message — the row, with
alignfor user (end) or assistant (start). - MessageContent — vertical stack for bubble + footer.
- Bubble, BubbleContent — the surface for the user message.
- Markdown — renders the assistant reply, including fenced code blocks.
- MessageFooter — horizontal action row aligned to the message.
- MessageAction — a Button wrapped in a Tooltip, with
aria-labelfor the icon.
Copy feedback
The copy action swaps to a checkmark for two seconds after clicking. Wire it with a single state:
const [copied, setCopied] = React.useState(false);
React.useEffect(() => {
if (!copied) return;
const t = setTimeout(() => setCopied(false), 2000);
return () => clearTimeout(t);
}, [copied]);Feedback toggle
Like and dislike are independent toggles. Track a single feedback state and use aria-pressed so screen readers announce the state:
<MessageAction
aria-pressed={feedback === "like"}
label="Good response"
onClick={() => setFeedback(feedback === "like" ? null : "like")}
>
<ThumbsUpIcon className={feedback === "like" ? "fill-current" : undefined} />
</MessageAction>Best Practices
- Only show actions after the response finishes streaming. A copy button on a partially-streamed reply copies incomplete text.
- Use real buttons, not styled text.
MessageActionrenders aButtoninside aTooltip— keep that structure so keyboard users can reach it. - Icon-only actions need a label. Pass
aria-labeland put the same string in the tooltip. - Keep the footer aligned with the message. Do not use
justify-betweento spread the actions; they cluster. - Do not nest interactive content inside Bubble. Actions belong in
MessageFooter.
Accessibility
- Each
MessageActionis a real<button>witharia-labelmatching its tooltip. - Feedback toggles use
aria-pressedso screen readers announce "pressed" or "not pressed". - The copy state is announced via the tooltip and the swapped icon; the button keeps its accessible name throughout.
- Code blocks render inside
Markdownand preserve syntax highlighting for screen readers.