For the complete documentation index, see llms.txt. Markdown variants are available by appending .md to any URL or sending an Accept: text/markdown header. An agent skill is available at /.well-known/agent-skills/site-skill.md.
FrakmentFrakment

Message

Chat primitives for message layout, bubbles, scroll behavior, and streamed reply animations.

Web
Frakment
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...
message.tsx
"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,
};

Message ships every primitive a chat UI needs. Layout primitives (Message, MessageGroup) handle alignment and avatar placement. Bubble provides the rounded visual box with variant colors. MessageScroller anchors the viewport, follows streamed replies, and restores position on refresh. MessageAnimated fades in an incoming UIMessage with one line.

Installation

Usage

message.tsx
import { Bubble, BubbleContent, Message, MessageAvatar, MessageContent, MessageGroup } from "@/components/ui/message";
tsx
<MessageGroup>
  <Message align="start">
    <MessageAvatar>AI</MessageAvatar>
    <MessageContent>
      <Bubble variant="muted">
        <BubbleContent>Hello from the assistant.</BubbleContent>
      </Bubble>
    </MessageContent>
  </Message>
  <Message align="end">
    <MessageContent>
      <Bubble variant="default">
        <BubbleContent>Hi! How can I help?</BubbleContent>
      </Bubble>
    </MessageContent>
  </Message>
</MessageGroup>

Anatomy

tsx
<MessageScrollerProvider>
  <MessageScroller>
    <MessageScrollerViewport>
      <MessageScrollerContent>
        <MessageScrollerItem messageId="1">
          <Message align="start">
            <MessageAvatar />
            <MessageContent>
              <MessageHeader />
              <Bubble>
                <BubbleContent />
                <BubbleReactions />
              </Bubble>
              <MessageFooter />
            </MessageContent>
          </Message>
        </MessageScrollerItem>
      </MessageScrollerContent>
    </MessageScrollerViewport>
    <MessageScrollerButton direction="end" />
  </MessageScroller>
</MessageScrollerProvider>

Scroll container

  • MessageScrollerProvider - owns scroll state, item registry, visibility, and reduced-motion awareness
  • MessageScroller - relative container with overflow-hidden
  • MessageScrollerViewport - scrollable area; pass preserveScrollOnPrepend to keep position when prepending
  • MessageScrollerContent - content wrapper that expands as messages arrive
  • MessageScrollerItem - one message; pass messageId for anchors and scrollAnchor for turn anchoring
  • MessageScrollerButton - scroll-to-end/start button; direction="end" (default) or "start"

Message layout

  • MessageGroup - vertical stack of messages
  • Message - one row; align="start" | "end" for side
  • MessageAvatar - avatar slot; auto-positions when a footer is present
  • MessageContent - content column between avatar and bubble
  • MessageHeader - small text above the bubble (name, timestamp)
  • MessageFooter - small text below the bubble (actions, timestamp)

Bubble

  • BubbleGroup - vertical stack of bubbles inside a Message
  • Bubble - rounded visual box; variant + align
  • BubbleContent - inner text box; accepts as for anchor or router link
  • BubbleReactions - absolute-positioned reaction strip; align="start" | "end", side="top" | "bottom"

Animated

  • MessageAnimated - reads a UIMessage, extracts text parts, fades the bubble in on mount

Examples

With avatar

Wrap <Avatar> inside MessageAvatar to show identity next to the bubble.

OL
The build failed during dependency installation.
ME
Can you share the exact error?
OL
Here is the error from the logs.
Something went wrong with the build. The libraries are not installed correctly. Try running the build again.
message-avatar-demo.tsx
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Bubble,
  BubbleContent,
  BubbleGroup,
  Message,
  MessageAvatar,
  MessageContent,
} from "@/components/ui/message";

export function MessageAvatarDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-6 py-12">
      <Message>
        <MessageAvatar>
          <Avatar>
            <AvatarImage alt="@oliver" src="/avatars/male-r.avif" />
            <AvatarFallback>OL</AvatarFallback>
          </Avatar>
        </MessageAvatar>
        <MessageContent>
          <Bubble variant="muted">
            <BubbleContent>
              The build failed during dependency installation.
            </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>Can you share the exact error?</BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
      <Message>
        <MessageAvatar>
          <Avatar>
            <AvatarImage alt="@oliver" src="/avatars/male-r.avif" />
            <AvatarFallback>OL</AvatarFallback>
          </Avatar>
        </MessageAvatar>
        <MessageContent>
          <BubbleGroup>
            <Bubble variant="muted">
              <BubbleContent>Here is the error from the logs.</BubbleContent>
            </Bubble>
            <Bubble variant="muted">
              <BubbleContent>
                Something went wrong with the build. The libraries are not
                installed correctly. Try running the build again.
              </BubbleContent>
            </Bubble>
          </BubbleGroup>
        </MessageContent>
      </Message>
    </div>
  );
}

Message group

MessageGroup stacks consecutive messages from the same speaker with a shared avatar position.

OL
I checked the registry addresses.
OL
The component and example JSON now live under the UI registry.
message-group-demo.tsx
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Bubble,
  BubbleContent,
  Message,
  MessageAvatar,
  MessageContent,
  MessageGroup,
} from "@/components/ui/message";

export function MessageGroupDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-6 py-12">
      <MessageGroup>
        <Message>
          <MessageAvatar>
            <Avatar>
              <AvatarImage alt="@oliver" src="/avatars/male-l.avif" />
              <AvatarFallback>OL</AvatarFallback>
            </Avatar>
          </MessageAvatar>
          <MessageContent>
            <Bubble variant="muted">
              <BubbleContent>I checked the registry addresses.</BubbleContent>
            </Bubble>
          </MessageContent>
        </Message>
        <Message>
          <MessageAvatar>
            <Avatar>
              <AvatarImage alt="@oliver" src="/avatars/male-l.avif" />
              <AvatarFallback>OL</AvatarFallback>
            </Avatar>
          </MessageAvatar>
          <MessageContent>
            <Bubble variant="muted">
              <BubbleContent>
                The component and example JSON now live under the UI registry.
              </BubbleContent>
            </Bubble>
          </MessageContent>
        </Message>
      </MessageGroup>
    </div>
  );
}

MessageHeader labels the sender above the bubble. MessageFooter carries status, actions, or timestamps below.

Olivia
I already checked the logs.
Send the report to the team. Ping @oliver if you need help.
Read Yesterday
message-header-footer-demo.tsx
import {
  Bubble,
  BubbleContent,
  Message,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";

export function MessageHeaderFooterDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-8 py-12">
      <Message>
        <MessageContent>
          <MessageHeader>Olivia</MessageHeader>
          <Bubble variant="muted">
            <BubbleContent>I already checked the logs.</BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
      <Message align="end">
        <MessageContent>
          <Bubble>
            <BubbleContent>
              Send the report to the team. Ping @oliver if you need help.
            </BubbleContent>
          </Bubble>
          <MessageFooter>
            <div>
              Read <span className="font-normal">Yesterday</span>
            </div>
          </MessageFooter>
        </MessageContent>
      </Message>
    </div>
  );
}

Message actions

Put copy, like, dislike, and retry buttons in MessageFooter. Error states use the destructive text token.

The install failure is coming from the workspace package.
Okay drop me a link. Taking a look...
Failed to send
message-actions-demo.tsx
"use client";

import {
  CopyIcon,
  RefreshCcwIcon,
  ThumbsDownIcon,
  ThumbsUpIcon,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Bubble,
  BubbleContent,
  Message,
  MessageContent,
  MessageFooter,
} from "@/components/ui/message";

export function MessageActionsDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-6 py-6">
      <Message>
        <MessageContent>
          <Bubble variant="muted">
            <BubbleContent>
              The install failure is coming from the workspace package.
            </BubbleContent>
          </Bubble>
          <MessageFooter>
            <Button
              aria-label="Copy"
              size="icon-sm"
              title="Copy"
              variant="ghost"
            >
              <CopyIcon />
            </Button>
            <Button
              aria-label="Like"
              size="icon-sm"
              title="Like"
              variant="ghost"
            >
              <ThumbsUpIcon />
            </Button>
            <Button
              aria-label="Dislike"
              size="icon-sm"
              title="Dislike"
              variant="ghost"
            >
              <ThumbsDownIcon />
            </Button>
          </MessageFooter>
        </MessageContent>
      </Message>
      <Message align="end">
        <MessageContent>
          <Bubble>
            <BubbleContent>Okay drop me a link. Taking a look...</BubbleContent>
          </Bubble>
          <MessageFooter className="gap-2">
            <span className="text-destructive font-normal">Failed to send</span>
            <Button
              aria-label="Retry"
              size="icon-xs"
              title="Retry"
              variant="ghost"
            >
              <RefreshCcwIcon />
            </Button>
          </MessageFooter>
        </MessageContent>
      </Message>
    </div>
  );
}

Attachments

Attachment renders media or files inside a message. Vertical for images, horizontal for files with title, description, and actions.

Workspace
Here is the image. Can you add it to the PDF? Use it for the cover page.
Done. Here is the PDF with the image added as the cover page.
sales-dashboard.pdfPDF - 2.4 MB
Thanks. Looks good.
message-attachment-demo.tsx
import { DownloadIcon, FileTextIcon } from "lucide-react";
import {
  Attachment,
  AttachmentAction,
  AttachmentActions,
  AttachmentContent,
  AttachmentDescription,
  AttachmentMedia,
  AttachmentTitle,
} from "@/components/ui/attachment";
import {
  Bubble,
  BubbleContent,
  Message,
  MessageContent,
} from "@/components/ui/message";

export function MessageAttachmentDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-6 py-6">
      <Message align="end">
        <MessageContent>
          <Attachment orientation="vertical">
            <AttachmentMedia variant="image">
              <img alt="Workspace" src="/examples/attachment/workspace.avif" />
            </AttachmentMedia>
          </Attachment>
          <Bubble>
            <BubbleContent>
              Here is the image. Can you add it to the PDF? Use it for the cover
              page.
            </BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
      <Message>
        <MessageContent>
          <Bubble variant="muted">
            <BubbleContent>
              Done. Here is the PDF with the image added as the cover page.
            </BubbleContent>
          </Bubble>
          <Attachment>
            <AttachmentMedia>
              <FileTextIcon />
            </AttachmentMedia>
            <AttachmentContent>
              <AttachmentTitle>sales-dashboard.pdf</AttachmentTitle>
              <AttachmentDescription>PDF - 2.4 MB</AttachmentDescription>
            </AttachmentContent>
            <AttachmentActions>
              <AttachmentAction
                aria-label="Download"
                size="icon-sm"
                title="Download"
                type="button"
                variant="secondary"
              >
                <DownloadIcon />
              </AttachmentAction>
            </AttachmentActions>
          </Attachment>
        </MessageContent>
      </Message>
      <Message align="end">
        <MessageContent>
          <Bubble>
            <BubbleContent>Thanks. Looks good.</BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
    </div>
  );
}

Bubble variants

Bubble supports seven variants: default, secondary, destructive, outline, ghost, muted, and tinted.

This is the default primary bubble.
This is the secondary variant.
This one is muted. It uses a lower emphasis color for the chat bubble.
This one is tinted. The tint is a softer color derived from the primary color.
We can also use an outlined variant.
Or a destructive variant with a reaction.

Ghost bubbles work for assistant text, markdown, and other content that should not be framed.

bubble-variants-demo.tsx
import { Markdown } from "@/components/ui/markdown";
import {
  Bubble,
  BubbleContent,
  BubbleReactions,
} from "@/components/ui/message";

export function BubbleVariantsDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-8 py-6">
      <Bubble>
        <BubbleContent>This is the default primary bubble.</BubbleContent>
      </Bubble>
      <Bubble align="end" variant="secondary">
        <BubbleContent>This is the secondary variant.</BubbleContent>
      </Bubble>
      <Bubble variant="muted">
        <BubbleContent>
          This one is muted. It uses a lower emphasis color for the chat bubble.
        </BubbleContent>
        <BubbleReactions aria-label="Reaction: thumbs up" role="img">
          <span>👍</span>
        </BubbleReactions>
      </Bubble>
      <Bubble align="end" variant="tinted">
        <BubbleContent>
          This one is tinted. The tint is a softer color derived from the
          primary color.
        </BubbleContent>
      </Bubble>
      <Bubble variant="outline">
        <BubbleContent>We can also use an outlined variant.</BubbleContent>
      </Bubble>
      <Bubble align="end" variant="destructive">
        <BubbleContent>Or a destructive variant with a reaction.</BubbleContent>
        <BubbleReactions aria-label="Reaction: fire" role="img">
          <span>🔥</span>
        </BubbleReactions>
      </Bubble>
      <Bubble variant="ghost">
        <BubbleContent>
          <Markdown>
            {
              "Ghost bubbles work for assistant text, **markdown**, and other content that should not be framed."
            }
          </Markdown>
        </BubbleContent>
      </Bubble>
    </div>
  );
}

Bubble alignment

align="end" anchors a bubble to the right; the default align="start" sits left.

This bubble is aligned to the start. This is the default alignment.
This bubble is aligned to the end. Use this for user messages.
bubble-alignment-demo.tsx
import { Bubble, BubbleContent } from "@/components/ui/message";

export function BubbleAlignmentDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-6 py-6">
      <Bubble variant="muted">
        <BubbleContent>
          This bubble is aligned to the start. This is the default alignment.
        </BubbleContent>
      </Bubble>
      <Bubble align="end">
        <BubbleContent>
          This bubble is aligned to the end. Use this for user messages.
        </BubbleContent>
      </Bubble>
    </div>
  );
}

Bubble group

BubbleGroup stacks consecutive bubbles from the same speaker with consistent alignment.

Can you tell me what is the issue?
You tell me!
It worked yesterday. You broke it!
Find the bug and fix it.
👀
Want me to diff yesterday against today? It is a bit embarrassing.
bubble-group-demo.tsx
import {
  Bubble,
  BubbleContent,
  BubbleGroup,
  BubbleReactions,
} from "@/components/ui/message";

export function BubbleGroupDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-6 py-6">
      <Bubble variant="muted">
        <BubbleContent>Can you tell me what is the issue?</BubbleContent>
      </Bubble>
      <BubbleGroup>
        <Bubble align="end">
          <BubbleContent>You tell me!</BubbleContent>
        </Bubble>
        <Bubble align="end">
          <BubbleContent>It worked yesterday. You broke it!</BubbleContent>
        </Bubble>
        <Bubble align="end">
          <BubbleContent>Find the bug and fix it.</BubbleContent>
          <BubbleReactions align="start" aria-label="Reactions: eyes">
            <span>👀</span>
          </BubbleReactions>
        </Bubble>
      </BubbleGroup>
      <Bubble variant="muted">
        <BubbleContent>
          Want me to diff yesterday against today? It is a bit embarrassing.
        </BubbleContent>
      </Bubble>
    </div>
  );
}

Bubble reactions

BubbleReactions sits on the edge of a bubble. Use align="start" for a top-right pin, side="top" for the lower edge. Children can be emoji or interactive buttons.

I do not need tests, I know my code works.
Bold. Fine I will add some tests. I will let you know when they are done.
Tests passed on the first try. All 142 of them. Looking good!
Are you sure I can run this command?
bubble-reactions-demo.tsx
"use client";

import * as React from "react";
import { Button } from "@/components/ui/button";
import {
  Bubble,
  BubbleContent,
  BubbleReactions,
} from "@/components/ui/message";

export function BubbleReactionsDemo() {
  const [status, setStatus] = React.useState("idle");
  return (
    <div className="flex w-full max-w-sm flex-col gap-10 py-6">
      <Bubble align="end" variant="muted">
        <BubbleContent>
          I do not need tests, I know my code works.
        </BubbleContent>
        <BubbleReactions
          align="start"
          aria-label="Reactions: thumbs up, surprised"
          role="img"
        >
          <span>👍</span>
          <span>😮</span>
        </BubbleReactions>
      </Bubble>
      <Bubble variant="muted">
        <BubbleContent>
          Bold. Fine I will add some tests. I will let you know when they are
          done.
        </BubbleContent>
        <BubbleReactions
          aria-label="Reactions: eyes, rocket, and 2 more"
          role="img"
        >
          <span>👀</span>
          <span>🚀</span>
          <span>+2</span>
        </BubbleReactions>
      </Bubble>
      <Bubble align="end">
        <BubbleContent>
          Tests passed on the first try. All 142 of them. Looking good!
        </BubbleContent>
        <BubbleReactions
          align="start"
          aria-label="Reactions: party popper, clapping hands"
          role="img"
          side="top"
        >
          <span>🎉</span>
          <span>👏</span>
        </BubbleReactions>
      </Bubble>
      <Bubble variant="destructive">
        <BubbleContent>Are you sure I can run this command?</BubbleContent>
        <BubbleReactions>
          <Button
            className="rounded-full"
            onClick={() => setStatus(status === "idle" ? "confirmed" : "idle")}
            size="xs"
            variant="ghost"
          >
            {status === "idle" ? "Yes, run it" : "Confirmed"}
          </Button>
        </BubbleReactions>
      </Bubble>
    </div>
  );
}

Collapsible bubble

Long content can collapse into a preview. The trigger lives inside the bubble itself.

How can I help you today?
The accessibility review found two focus states that were visually too subtle in dark mode. I checked the dialog, menu, and drawer paths because each one renders focusable controls...
inside a layered surface. The dialog and drawer are fine. The menu needs the hover and focus tokens split so keyboard focus stays visible when the pointer is not involved.
bubble-collapsible-demo.tsx
"use client";

import { ChevronDownIcon } from "lucide-react";
import * as React from "react";
import { Button } from "@/components/ui/button";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Bubble, BubbleContent } from "@/components/ui/message";

const text =
  "The accessibility review found two focus states that were visually too subtle in dark mode. I checked the dialog, menu, and drawer paths because each one renders focusable controls inside a layered surface. The dialog and drawer are fine. The menu needs the hover and focus tokens split so keyboard focus stays visible when the pointer is not involved.";

const previewLength = 180;

export function BubbleCollapsibleDemo() {
  const [open, setOpen] = React.useState(false);
  const isLong = text.length > previewLength;

  return (
    <div className="flex w-full max-w-sm flex-col gap-6 py-6">
      <Bubble variant="muted">
        <BubbleContent>How can I help you today?</BubbleContent>
      </Bubble>
      <Bubble align="end" variant="muted">
        <BubbleContent>
          <Collapsible onOpenChange={setOpen} open={open}>
            <div>
              {text.slice(0, previewLength)}
              {!open && isLong ? "..." : ""}
            </div>
            {isLong ? (
              <CollapsibleContent>
                {text.slice(previewLength)}
              </CollapsibleContent>
            ) : null}
            {isLong ? (
              <CollapsibleTrigger
                as={Button}
                className="text-muted-foreground mt-2 h-auto gap-1 p-0 [&[data-state=open]>svg]:rotate-180"
                variant="link"
              >
                {open ? "Show less" : "Show more"}
                <ChevronDownIcon className="size-3 transition-transform" />
              </CollapsibleTrigger>
            ) : null}
          </Collapsible>
        </BubbleContent>
      </Bubble>
    </div>
  );
}

Tooltip in reactions

Place a Tooltip inside BubbleReactions to add hover context to actions.

Did you remove the stale route?
Yes, removed it from the registry.
bubble-tooltip-demo.tsx
import { CheckIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Bubble,
  BubbleContent,
  BubbleReactions,
} from "@/components/ui/message";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";

export function BubbleTooltipDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-4 py-6">
      <Bubble variant="secondary">
        <BubbleContent>Did you remove the stale route?</BubbleContent>
      </Bubble>
      <Bubble align="end">
        <BubbleContent>Yes, removed it from the registry.</BubbleContent>
        <BubbleReactions className="p-0">
          <Tooltip>
            <TooltipTrigger
              aria-label="Read on Jan 5, 2026 at 4:32 PM"
              as={Button}
              className="rounded-full"
              size="icon-xs"
              variant="ghost"
            >
              <CheckIcon />
            </TooltipTrigger>
            <TooltipContent>Read on Jan 5, 2026 at 4:32 PM</TooltipContent>
          </Tooltip>
        </BubbleReactions>
      </Bubble>
    </div>
  );
}

Popover in reactions

Show inline error detail from a bubble without leaving the conversation.

Run the build script.
Failed to run the command.
bubble-popover-demo.tsx
import { InfoIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Bubble,
  BubbleContent,
  BubbleReactions,
} from "@/components/ui/message";
import {
  Popover,
  PopoverContent,
  PopoverDescription,
  PopoverHeader,
  PopoverTitle,
  PopoverTrigger,
} from "@/components/ui/popover";

export function BubblePopoverDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-4 py-6">
      <Bubble align="end">
        <BubbleContent>Run the build script.</BubbleContent>
      </Bubble>
      <Bubble variant="destructive">
        <BubbleContent>Failed to run the command.</BubbleContent>
        <BubbleReactions>
          <Popover>
            <PopoverTrigger
              aria-label="Show error details"
              as={Button}
              className="aria-expanded:text-destructive rounded-full"
              size="icon-xs"
              variant="ghost"
            >
              <InfoIcon />
            </PopoverTrigger>
            <PopoverContent>
              <PopoverHeader>
                <PopoverTitle className="text-sm">
                  Command failed with exit code 1
                </PopoverTitle>
                <PopoverDescription className="text-sm">
                  ENOENT: no such file or directory, open pnpm-lock.yaml
                </PopoverDescription>
              </PopoverHeader>
            </PopoverContent>
          </Popover>
        </BubbleReactions>
      </Bubble>
    </div>
  );
}

Scroll behavior

MessageScroller anchors the viewport, follows streamed replies, and shows a scroll-to-end button when the user scrolls up. Pass messageId on each MessageScrollerItem to support scrollToMessage.

New Chat
How can I help you today?
Morning, frakment!
What are we working on today? Press send to start a new conversation
I'm building a chat for our app and the scroll behavior is driving me nuts. Every time the AI streams a reply, the whole thread jumps around.
Demo is read only. Press send to send messages.
message-scroller-demo.tsx
"use client";

import {
  RotateCwIcon as ArrowClockwiseIcon,
  ArrowUpIcon,
  Globe,
  Image,
  MessageCircleDashedIcon,
  Paperclip,
  PlusIcon,
  TelescopeIcon,
} from "lucide-react";
import * as React from "react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Empty,
  EmptyDescription,
  EmptyHeader,
  EmptyMedia,
  EmptyTitle,
} from "@/components/ui/empty";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
} from "@/components/ui/input-group";
import {
  MessageAnimated,
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";

interface DemoMessage {
  id: string;
  parts: Array<{ type: "text"; text: string }>;
  role: "user" | "assistant";
}

interface ScriptTurn {
  role: "user" | "assistant";
  text: string;
}

const SCRIPT: ScriptTurn[] = [
  {
    role: "user",
    text: "I'm building a chat for our app and the scroll behavior is driving me nuts. Every time the AI streams a reply, the whole thread jumps around.",
  },
  {
    role: "assistant",
    text: "That's the classic streaming scroll problem. Wrap your message list in MessageScroller and turn on autoScroll. The viewport pins to the bottom as tokens arrive, so users always see the latest text land in place. It only auto-scrolls while the reader is already at the bottom. The moment they scroll up, auto-scroll backs off and their position is preserved.",
  },
  {
    role: "user",
    text: "Okay, but when someone sends a new message the view still feels jarring, like the whole conversation reloads from the top.",
  },
  {
    role: "assistant",
    text: "MessageScrollerItem fixes that with turn anchoring. Set scrollAnchor on the turn that should settle near the top instead of snapping to the document bottom. It also leaves a small peek of the previous exchange visible above the anchor, so context isn't lost.",
  },
  {
    role: "user",
    text: "And if they've scrolled up to re-read an older answer? I don't want to yank them back down.",
  },
  {
    role: "assistant",
    text: "You won't. Auto-scroll only runs when the viewport is already pinned to the bottom, so scrolling up is a deliberate opt-out. When there is content they haven't seen yet, MessageScrollerButton appears at the bottom. One tap jumps them back to the newest message and re-engages auto-scroll.",
  },
  {
    role: "user",
    text: "Last one, does this work with assistive tech?",
  },
  {
    role: "assistant",
    text: "MessageScrollerContent sets role=log and aria-relevant=additions by default, so screen readers announce new messages as they stream in. The scroll button is a real button with an sr-only label, and it's removed from the tab order when you're already at the bottom.",
  },
];

const INITIAL: DemoMessage[] = [];

export function MessageScrollerDemo() {
  const [messages, setMessages] = React.useState<DemoMessage[]>(INITIAL);
  const [busy, setBusy] = React.useState(false);
  const [pairIndex, setPairIndex] = React.useState(0);

  const streamAssistant = async (id: string, text: string) => {
    const tokens = text.split(/(\s+)/);
    let acc = "";
    for (const token of tokens) {
      await new Promise((r) => setTimeout(r, 25));
      acc += token;
      const snapshot = acc;
      setMessages((m) =>
        m.map((msg) =>
          msg.id === id
            ? { ...msg, parts: [{ text: snapshot, type: "text" }] }
            : msg
        )
      );
    }
  };
  const reset = () => {
    setMessages(INITIAL);
    setPairIndex(0);
    setBusy(false);
  };

  const send = async () => {
    if (busy) {
      return;
    }
    if (pairIndex >= 4) {
      return;
    }
    const userTurn = SCRIPT[pairIndex * 2];
    const assistantTurn = SCRIPT[pairIndex * 2 + 1];
    const uid = `u-${pairIndex}`;
    const aid = `a-${pairIndex}`;
    setBusy(true);
    setMessages((m) => [
      ...m,
      { id: uid, parts: [{ text: userTurn.text, type: "text" }], role: "user" },
    ]);
    await new Promise((r) => setTimeout(r, 400));
    setMessages((m) => [
      ...m,
      { id: aid, parts: [{ text: "", type: "text" }], role: "assistant" },
    ]);
    await streamAssistant(aid, assistantTurn.text);
    setPairIndex(pairIndex + 1);
    setBusy(false);
  };

  const nextUser =
    pairIndex >= 4 ? null : (SCRIPT[pairIndex * 2]?.text ?? null);
  return (
    <MessageScrollerProvider>
      <div className="relative flex flex-col gap-4">
        <Card className="mx-auto h-140 w-full max-w-sm gap-0 rounded-2xl">
          <CardHeader className="gap-1">
            <CardTitle>New Chat</CardTitle>
            <CardDescription>How can I help you today?</CardDescription>
            <CardAction>
              <Tooltip>
                <TooltipTrigger
                  aria-label="Reset conversation"
                  as={Button}
                  className="rounded-full"
                  disabled={busy}
                  onClick={reset}
                  size="icon-sm"
                  variant="outline"
                >
                  <ArrowClockwiseIcon />
                </TooltipTrigger>
                <TooltipContent>
                  <p>Reset</p>
                </TooltipContent>
              </Tooltip>
            </CardAction>
          </CardHeader>
          <CardContent className="flex-1 overflow-hidden p-0">
            {messages.length === 0 ? (
              <Empty className="h-full rounded-2xl">
                <EmptyHeader>
                  <EmptyMedia variant="icon">
                    <MessageCircleDashedIcon />
                  </EmptyMedia>
                  <EmptyTitle>Morning, frakment!</EmptyTitle>
                  <EmptyDescription>
                    What are we working on today? Press send to start a new
                    conversation
                  </EmptyDescription>
                </EmptyHeader>
              </Empty>
            ) : (
              <MessageScroller>
                <MessageScrollerViewport>
                  <MessageScrollerContent
                    aria-busy={busy}
                    className="p-(--card-spacing)"
                  >
                    {messages.map((message) => (
                      <MessageAnimated
                        key={message.id}
                        message={message}
                        scrollAnchor={message.role === "user"}
                      />
                    ))}
                  </MessageScrollerContent>
                </MessageScrollerViewport>
                <MessageScrollerButton />
              </MessageScroller>
            )}
          </CardContent>
          <CardFooter className="flex-col gap-2 border-t-0 bg-transparent">
            <form
              className="w-full"
              onSubmit={(e) => {
                e.preventDefault();
                void send();
              }}
            >
              <InputGroup className="rounded-2xl border-0 focus-within:border-0 focus-within:ring-0">
                <div className="h-14 w-full px-3 py-2.5">
                  <span
                    className="line-clamp-2 opacity-60 data-[status=ready]:opacity-100"
                    data-status={busy ? "streaming" : "ready"}
                  >
                    {nextUser ? (
                      nextUser
                    ) : (
                      <span className="text-muted-foreground">
                        No messages queued. Reset the conversation.
                      </span>
                    )}
                  </span>
                </div>
                <InputGroupAddon align="block-end" className="pt-1">
                  <DropdownMenu>
                    <DropdownMenuTrigger
                      aria-label="Add files"
                      as={InputGroupButton}
                      className="rounded-full"
                      size="icon-sm"
                      type="button"
                      variant="outline"
                    >
                      <PlusIcon />
                    </DropdownMenuTrigger>
                    <DropdownMenuContent
                      align="start"
                      className="w-44"
                      side="top"
                    >
                      <DropdownMenuItem>
                        <Paperclip />
                        Add Photos & Files
                      </DropdownMenuItem>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem>
                        <Image />
                        Create Image
                      </DropdownMenuItem>
                      <DropdownMenuItem>
                        <TelescopeIcon />
                        Deep Research
                      </DropdownMenuItem>
                      <DropdownMenuItem>
                        <Globe />
                        Web Search
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                  <InputGroupButton
                    className="ml-auto rounded-full"
                    disabled={!nextUser || busy}
                    size="icon-sm"
                    type="submit"
                    variant="default"
                  >
                    <ArrowUpIcon />
                    <span className="sr-only">Send</span>
                  </InputGroupButton>
                </InputGroupAddon>
              </InputGroup>
            </form>
          </CardFooter>
        </Card>
        <div className="text-muted-foreground px-0.5 text-center text-xs">
          Demo is read only. Press send to send messages.
        </div>
      </div>
    </MessageScrollerProvider>
  );
}

Streamed reply animation

MessageAnimated reads a UIMessage, extracts its text parts, and fades the bubble in. Pass motion to override the transition.

message-animated-demo.tsx
"use client";

import * as React from "react";
import { Button } from "@/components/ui/button";
import {
  MessageAnimated,
  MessageScroller,
  MessageScrollerContent,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message";

interface DemoMessage {
  id: string;
  parts: Array<{ type: "text"; text: string }>;
  role: "user" | "assistant";
}

const SCRIPT: Array<{ role: "user" | "assistant"; text: string }> = [
  {
    role: "user",
    text: "How does the entrance animation work?",
  },
  {
    role: "assistant",
    text: "Each message fades in and rises 8px when it mounts. Text then streams in token by token, like a real assistant reply.",
  },
];

export function MessageAnimatedDemo() {
  const [messages, setMessages] = React.useState<DemoMessage[]>([]);
  const [busy, setBusy] = React.useState(false);

  const reset = () => {
    setMessages([]);
    setBusy(false);
  };

  const send = async () => {
    if (busy) {
      return;
    }
    if (messages.length >= 2) {
      reset();
      return;
    }
    setBusy(true);
    setMessages([
      {
        id: "u-0",
        parts: [{ text: SCRIPT[0].text, type: "text" }],
        role: "user",
      },
    ]);
    await new Promise((r) => setTimeout(r, 400));
    setMessages((m) => [
      ...m,
      { id: "a-0", parts: [{ text: "", type: "text" }], role: "assistant" },
    ]);
    const tokens = SCRIPT[1].text.split(/(\s+)/);
    let acc = "";
    for (const token of tokens) {
      await new Promise((r) => setTimeout(r, 25));
      acc += token;
      const snapshot = acc;
      setMessages((m) =>
        m.map((msg) =>
          msg.id === "a-0"
            ? { ...msg, parts: [{ text: snapshot, type: "text" }] }
            : msg
        )
      );
    }
    setBusy(false);
  };

  const label = busy
    ? "Streaming..."
    : messages.length >= 2
      ? "Reset"
      : "Send message";

  return (
    <div className="mx-auto flex w-full max-w-sm flex-col items-start gap-4">
      <div className="h-64 w-full">
        <MessageScrollerProvider>
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent className="p-4">
                {messages.map((message) => (
                  <MessageAnimated
                    key={message.id}
                    message={message}
                    scrollAnchor={message.role === "user"}
                  />
                ))}
              </MessageScrollerContent>
            </MessageScrollerViewport>
          </MessageScroller>
        </MessageScrollerProvider>
      </div>
      <Button disabled={busy} onClick={send} size="sm" variant="outline">
        {label}
      </Button>
    </div>
  );
}

API Reference

All layout primitives (MessageGroup, Message, MessageAvatar, MessageContent, MessageHeader, MessageFooter, BubbleGroup, MessageScroller, MessageScrollerViewport, MessageScrollerContent) accept standard div attributes and className.

Message

PropTypeDefaultDescription
align
startend
—Side of the row the message content sits on.

Bubble

PropTypeDefaultDescription
variant
defaultsecondarydestructiveoutlineghostmutedtinted
—Visual style.
align
startend
—Self-align inside a Message row.

BubbleContent

PropTypeDefaultDescription
asReact.ElementType—Render as a different element or component. Defaults to div. Use as='a' or as={Link} for clickable bubbles.

BubbleReactions

PropTypeDefaultDescription
align
startend
—Horizontal anchor side.
side
topbottom
—Vertical anchor side.

MessageScrollerProvider

PropTypeDefaultDescription
autoScrollboolean—Follow new messages automatically when the user is at the end.
defaultScrollPosition
startendlast-anchor
—Initial scroll position on mount.
scrollEdgeThresholdnumber—Pixels from the edge to consider scrollable.
scrollMarginnumber—Offset from the viewport edge.
scrollPreviousItemPeeknumber—Amount of the previous item kept visible when jumping to a message.

MessageScrollerViewport

PropTypeDefaultDescription
preserveScrollOnPrependboolean—Preserve the current scroll offset when items are prepended (e.g. loading older messages).

MessageScrollerItem

PropTypeDefaultDescription
messageIdstring—Anchor id used by scrollToMessage and visibility tracking.
scrollAnchorboolean—Mark this item as the anchor for prepend-scroll preservation.

MessageScrollerButton

PropTypeDefaultDescription
direction
startend
—Jump to the start or end of the transcript.
behavior
smoothautoinstant
—Scroll behavior.
renderReact.ReactElement—Render prop; the target element gets data-active and onClick merged.
variantButton variant—Passed through to the rendered button.
sizeButton size—Passed through to the rendered button.

MessageAnimated

PropTypeDefaultDescription
messageUIMessage—The message to render. Text parts are concatenated.
motionstring—CSS transition override; e.g. 200 ease-out or 300 cubic-bezier(...).
scrollAnchorboolean—Forwarded to the underlying MessageScrollerItem.

Hooks

The three hooks must be called inside <MessageScrollerProvider>. They return values from the nearest provider context.

useMessageScroller()

Returns imperative scroll methods:

  • scrollToEnd(opts?) - scroll the viewport to the bottom; returns true if the viewport exists.
  • scrollToStart(opts?) - scroll to the top.
  • scrollToMessage(messageId, opts?) - scroll a specific item into view by its messageId.

Each method accepts { behavior?: ScrollBehavior, align?: ScrollAlign, scrollMargin?: number }.

useMessageScrollerScrollable()

Returns { start: boolean, end: boolean } - whether the viewport can scroll further in each direction. Useful to render custom scroll buttons or fade edges.

useMessageScrollerVisibility()

Returns { currentAnchorId: string | null, visibleMessageIds: string[] }. currentAnchorId is the topmost visible item; visibleMessageIds lists every item currently inside the viewport.

Accessibility

  • MessageScrollerButton renders a native <button> with an sr-only label (Scroll to end / Scroll to start).
  • MessageScrollerViewport uses overscroll-contain so nested scroll contexts do not chain to the page.
  • MessageScrollerItem sets content-visibility: auto for off-screen performance; screen readers still announce off-screen items when navigating.
  • Bubble renders a plain <div>. Use BubbleContent with as="a" or as={Link} for clickable bubbles; do not nest interactive content inside a non-interactive bubble.

Best Practices

  • Always wrap the scroller in MessageScrollerProvider. The provider owns the scroll context; children throw if the context is missing.
  • Pass messageId on every MessageScrollerItem. Without it, scrollToMessage and visibility tracking cannot find the item.
  • Use MessageAnimated for streamed replies. It expects a UIMessage from the AI SDK and handles text extraction and fade-in.
  • Reduce motion is honored automatically. When the OS requests reduced motion, transitions are disabled; motion values are ignored.
  • Prefer Bubble variants over custom colors. The seven built-in variants cover the common message types.