Message Scroller
Preview
"use client";
import {
Message,
MessageContent,
MessageGroup,
} from "@/components/agents/message";
import {
MessageBubble,
MessageBubbleContent,
} from "@/components/agents/message-bubble";
import { MessageScroller } from "@/components/agents/message-scroller";
const messages = [
{
id: "release-question",
from: "user" as const,
content: "What should the first release include?",
},
{
id: "release-answer",
from: "assistant" as const,
content: "Start with the smallest workflow that still feels complete.",
},
{
id: "states-question",
from: "user" as const,
content: "Include streaming and recovery states too.",
},
{
id: "states-answer",
from: "assistant" as const,
content: "Yes. Those states make the first version feel dependable.",
},
];
export function MessageScrollerUsage() {
return (
<MessageScroller
navigation="rail"
className="h-[420px]"
viewportClassName="px-4 py-5"
contentClassName="min-h-full"
>
<MessageGroup spacing="default">
{messages.map((message) => (
<Message key={message.id} id={message.id} from={message.from}>
<MessageContent>
<MessageBubble
variant={message.from === "user" ? "solid" : "soft"}
>
<MessageBubbleContent>{message.content}</MessageBubbleContent>
</MessageBubble>
</MessageContent>
</Message>
))}
</MessageGroup>
</MessageScroller>
);
}
"use client";
// beui.dev/components/agents/message-scroller
import { useReducedMotion } from "motion/react";
import {
type ComponentPropsWithRef,
type Ref,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
import {
PreviewRail,
type PreviewRailItem,
} from "@/components/motion/preview-rail";
import { cn } from "@/lib/utils";
const PREVIEW_TITLE_LENGTH = 56;
const PREVIEW_DESCRIPTION_LENGTH = 88;
function truncateMessageText(text: string, limit: number) {
if (text.length <= limit) return text;
const excerpt = text.slice(0, limit);
const boundary = excerpt.lastIndexOf(" ");
return `${excerpt.slice(0, boundary > limit * 0.65 ? boundary : limit).trim()}…`;
}
function getMessageText(message: HTMLElement) {
const surface =
message.querySelector<HTMLElement>('[data-slot="message-bubble-content"]') ??
message.querySelector<HTMLElement>('[data-slot="message-content"]') ??
message;
return (surface.textContent ?? "").replace(/\s+/g, " ").trim();
}
function getMessagePreview(
message: HTMLElement,
assistantResponse?: HTMLElement,
) {
const text = getMessageText(message);
if (!text) {
return { label: "Message", description: undefined };
}
if (text.length <= PREVIEW_TITLE_LENGTH) {
const responseText = assistantResponse
? getMessageText(assistantResponse)
: "";
return {
label: text,
description: responseText
? truncateMessageText(responseText, PREVIEW_DESCRIPTION_LENGTH)
: undefined,
};
}
const titleExcerpt = text.slice(0, PREVIEW_TITLE_LENGTH);
const titleBoundary = titleExcerpt.lastIndexOf(" ");
const titleEnd =
titleBoundary > PREVIEW_TITLE_LENGTH * 0.65
? titleBoundary
: PREVIEW_TITLE_LENGTH;
const label = `${text.slice(0, titleEnd).trim()}…`;
const responseText = assistantResponse
? getMessageText(assistantResponse)
: text.slice(titleEnd).trim();
return {
label,
description: responseText
? truncateMessageText(responseText, PREVIEW_DESCRIPTION_LENGTH)
: undefined,
};
}
export interface MessageScrollerProps extends ComponentPropsWithRef<"div"> {
/** Keep streamed output pinned while the reader remains near the end. */
followOutput?: boolean;
/** Distance from the end that still counts as following the output. */
followThreshold?: number;
/** Smoothly follow growing content. */
smooth?: boolean;
/** Reports when the reader leaves or returns to the live edge. */
onFollowChange?: (following: boolean) => void;
/** Accessible label for the scrollable transcript. */
label?: string;
/** Marks the transcript as waiting for more streamed content. */
busy?: boolean;
/** Adds a compact rail for navigating between rendered Message rows. */
navigation?: "rail";
/** Accessible label for the optional message navigation rail. */
navigationLabel?: string;
viewportClassName?: string;
contentClassName?: string;
railClassName?: string;
viewportRef?: Ref<HTMLElement>;
viewportProps?: Omit<
ComponentPropsWithRef<"section">,
"children" | "className" | "ref"
>;
contentProps?: Omit<
ComponentPropsWithRef<"div">,
"children" | "className" | "ref"
>;
}
export function MessageScroller({
followOutput = true,
followThreshold = 56,
smooth = true,
onFollowChange,
label = "Conversation",
busy,
navigation,
navigationLabel = "Message navigation",
viewportClassName,
contentClassName,
railClassName,
viewportRef: externalViewportRef,
viewportProps,
contentProps,
className,
children,
...props
}: MessageScrollerProps) {
const reduce = useReducedMotion() ?? false;
const viewportRef = useRef<HTMLElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const followingRef = useRef(followOutput);
const programmaticScrollRef = useRef(false);
const scrollTimerRef = useRef<number | undefined>(undefined);
const frameRef = useRef<number | undefined>(undefined);
const railFrameRef = useRef<number | undefined>(undefined);
const railIdRef = useRef(new WeakMap<HTMLElement, string>());
const railIdCounterRef = useRef(0);
const railTargetsRef = useRef(new Map<string, HTMLElement>());
const [railItems, setRailItems] = useState<PreviewRailItem[]>([]);
const [activeRailId, setActiveRailId] = useState("");
const [railOverflowing, setRailOverflowing] = useState(false);
const {
onScroll: onViewportScroll,
onWheel: onViewportWheel,
onTouchStart: onViewportTouchStart,
onKeyDown: onViewportKeyDown,
...restViewportProps
} = viewportProps ?? {};
const setViewportRef = useCallback(
(node: HTMLElement | null) => {
viewportRef.current = node;
if (typeof externalViewportRef === "function") {
externalViewportRef(node);
} else if (externalViewportRef) {
externalViewportRef.current = node;
}
},
[externalViewportRef],
);
const setFollowing = useCallback(
(next: boolean) => {
if (followingRef.current === next) return;
followingRef.current = next;
onFollowChange?.(next);
},
[onFollowChange],
);
const updateActiveRailItem = useCallback(() => {
if (navigation !== "rail") return;
const viewport = viewportRef.current;
const targets = [...railTargetsRef.current.entries()];
if (!viewport || targets.length === 0) return;
const viewportRect = viewport.getBoundingClientRect();
if (viewport.scrollTop <= followThreshold) {
const firstId = targets[0]?.[0] ?? "";
setActiveRailId((current) => (current === firstId ? current : firstId));
return;
}
const distanceFromEnd =
viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
if (distanceFromEnd <= followThreshold) {
const lastId = targets.at(-1)?.[0] ?? "";
setActiveRailId((current) => (current === lastId ? current : lastId));
return;
}
const viewportCenter = viewportRect.top + viewportRect.height / 2;
let nearestId = targets[0]?.[0] ?? "";
let nearestDistance = Number.POSITIVE_INFINITY;
for (const [id, element] of targets) {
const rect = element.getBoundingClientRect();
const messageCenter = rect.top + rect.height / 2;
const distance = Math.abs(messageCenter - viewportCenter);
if (distance < nearestDistance) {
nearestDistance = distance;
nearestId = id;
}
}
setActiveRailId((current) =>
current === nearestId ? current : nearestId,
);
}, [followThreshold, navigation]);
const syncRailItems = useCallback(() => {
if (navigation !== "rail") return;
const content = contentRef.current;
const viewport = viewportRef.current;
if (!content || !viewport) return;
const messages = Array.from(
content.querySelectorAll<HTMLElement>('[data-slot="message"]'),
);
const targets = new Map<string, HTMLElement>();
const nextItems = messages.map((message, index) => {
let id = railIdRef.current.get(message);
if (!id) {
railIdCounterRef.current += 1;
id = `message-rail-${railIdCounterRef.current}`;
railIdRef.current.set(message, id);
}
targets.set(id, message);
const sender = message.dataset.from ?? "conversation";
const assistantResponse =
sender === "user"
? messages
.slice(index + 1)
.find((candidate) => candidate.dataset.from === "assistant")
: undefined;
const preview = getMessagePreview(message, assistantResponse);
return {
id,
label: preview.label,
description: preview.description,
ariaLabel: `Go to ${sender} message ${index + 1} of ${messages.length}`,
};
});
railTargetsRef.current = targets;
setRailItems((current) => {
const unchanged =
current.length === nextItems.length &&
current.every(
(item, index) =>
item.id === nextItems[index]?.id &&
item.label === nextItems[index]?.label &&
item.description === nextItems[index]?.description &&
item.ariaLabel === nextItems[index]?.ariaLabel,
);
return unchanged ? current : nextItems;
});
setRailOverflowing(
viewport.scrollHeight > viewport.clientHeight + 1 && messages.length > 1,
);
}, [navigation]);
const scheduleRailSync = useCallback(() => {
if (navigation !== "rail") return;
if (railFrameRef.current) cancelAnimationFrame(railFrameRef.current);
railFrameRef.current = requestAnimationFrame(() => {
syncRailItems();
updateActiveRailItem();
});
}, [navigation, syncRailItems, updateActiveRailItem]);
const scrollToEnd = useCallback((behavior: ScrollBehavior) => {
const viewport = viewportRef.current;
if (!viewport) return;
programmaticScrollRef.current = true;
if (typeof viewport.scrollTo === "function") {
viewport.scrollTo({ top: viewport.scrollHeight, behavior });
} else {
viewport.scrollTop = viewport.scrollHeight;
}
if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);
scrollTimerRef.current = window.setTimeout(() => {
programmaticScrollRef.current = false;
}, behavior === "smooth" ? 320 : 0);
}, []);
const handleScroll = useCallback(() => {
const viewport = viewportRef.current;
if (!viewport || programmaticScrollRef.current) return;
const distance =
viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
setFollowing(distance <= followThreshold);
updateActiveRailItem();
}, [followThreshold, setFollowing, updateActiveRailItem]);
const leaveLiveEdge = useCallback(() => {
programmaticScrollRef.current = false;
}, []);
useLayoutEffect(() => {
followingRef.current = followOutput;
if (!followOutput) return;
frameRef.current = requestAnimationFrame(() => scrollToEnd("auto"));
return () => {
if (frameRef.current) cancelAnimationFrame(frameRef.current);
};
}, [followOutput, scrollToEnd]);
useEffect(() => {
const content = contentRef.current;
if (!content || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => {
scheduleRailSync();
if (!followOutput || !followingRef.current) return;
scrollToEnd(reduce || !smooth ? "auto" : "smooth");
});
observer.observe(content);
return () => observer.disconnect();
}, [followOutput, reduce, scheduleRailSync, scrollToEnd, smooth]);
useEffect(() => {
if (navigation !== "rail") {
railTargetsRef.current.clear();
setRailItems([]);
setRailOverflowing(false);
return;
}
const content = contentRef.current;
const viewport = viewportRef.current;
if (!content || !viewport) return;
scheduleRailSync();
const mutationObserver =
typeof MutationObserver === "undefined"
? null
: new MutationObserver(scheduleRailSync);
mutationObserver?.observe(content, {
childList: true,
characterData: true,
subtree: true,
});
const resizeObserver =
typeof ResizeObserver === "undefined"
? null
: new ResizeObserver(scheduleRailSync);
resizeObserver?.observe(content);
resizeObserver?.observe(viewport);
return () => {
mutationObserver?.disconnect();
resizeObserver?.disconnect();
};
}, [navigation, scheduleRailSync]);
useEffect(
() => () => {
if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);
if (frameRef.current) cancelAnimationFrame(frameRef.current);
if (railFrameRef.current) cancelAnimationFrame(railFrameRef.current);
},
[],
);
const scrollToRailItem = useCallback(
(item: PreviewRailItem) => {
const viewport = viewportRef.current;
const target = railTargetsRef.current.get(item.id);
if (!viewport || !target) return;
const lastItem = railItems.at(-1)?.id === item.id;
setActiveRailId(item.id);
if (lastItem) {
setFollowing(true);
scrollToEnd(reduce || !smooth ? "auto" : "smooth");
return;
}
setFollowing(false);
programmaticScrollRef.current = true;
const viewportRect = viewport.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();
const top =
viewport.scrollTop +
targetRect.top -
viewportRect.top -
(viewport.clientHeight - targetRect.height) / 2;
const behavior = reduce || !smooth ? "auto" : "smooth";
if (typeof viewport.scrollTo === "function") {
viewport.scrollTo({ top, behavior });
} else {
viewport.scrollTop = top;
}
if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);
scrollTimerRef.current = window.setTimeout(() => {
programmaticScrollRef.current = false;
}, behavior === "smooth" ? 320 : 0);
},
[railItems, reduce, scrollToEnd, setFollowing, smooth],
);
const viewport = (
<section
ref={setViewportRef}
aria-label={label}
{...restViewportProps}
onScroll={(event) => {
handleScroll();
onViewportScroll?.(event);
}}
onWheel={(event) => {
leaveLiveEdge();
onViewportWheel?.(event);
}}
onTouchStart={(event) => {
leaveLiveEdge();
onViewportTouchStart?.(event);
}}
onKeyDown={(event) => {
if (["ArrowUp", "PageUp", "Home"].includes(event.key)) {
leaveLiveEdge();
}
onViewportKeyDown?.(event);
}}
className={cn(
"h-full overflow-y-auto overscroll-contain outline-none [overflow-anchor:none] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
navigation === "rail"
? "[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
: "[scrollbar-gutter:stable]",
viewportClassName,
navigation === "rail" && railOverflowing && "pr-10",
)}
>
<div
ref={contentRef}
role="log"
aria-live="polite"
aria-relevant="additions text"
aria-busy={busy}
className={contentClassName}
{...contentProps}
>
{children}
</div>
</section>
);
return (
<div
data-slot="message-scroller"
className={cn("min-h-0", className)}
{...props}
>
{navigation === "rail" ? (
<PreviewRail
items={railOverflowing ? railItems : []}
label={navigationLabel}
activeId={activeRailId}
onItemSelect={scrollToRailItem}
previewSide="before"
highlightActive
itemSize={14}
className="h-full min-h-0 overflow-hidden"
previewContainerClassName="right-8 left-3"
previewClassName="mr-1 w-64 max-w-full [&_[data-slot=preview-rail-card]]:h-20 [&_[data-slot=preview-rail-card]]:overflow-hidden [&_[data-slot=preview-rail-card]]:p-3 [&_[data-slot=preview-rail-title]]:line-clamp-1 [&_[data-slot=preview-rail-title]]:text-xs [&_[data-slot=preview-rail-title]]:leading-4 [&_[data-slot=preview-rail-description]]:line-clamp-2 [&_[data-slot=preview-rail-description]]:text-xs [&_[data-slot=preview-rail-description]]:leading-4"
railClassName={cn(
"absolute inset-y-3 right-1 w-7 content-center py-1 [&_[data-slot=preview-rail-item]]:w-7 [&_[data-slot=preview-rail-item]]:justify-end [&_[data-slot=preview-rail-tick]]:h-px [&_[data-slot=preview-rail-tick]]:w-4 [&_[data-slot=preview-rail-tick]]:origin-right",
railOverflowing
? "pointer-events-auto opacity-100"
: "pointer-events-none opacity-0",
railClassName,
)}
>
{viewport}
</PreviewRail>
) : (
viewport
)}
</div>
);
}
Install
Add it with the shadcn CLI, or copy the source manually.
shadcn init? You are set. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
"use client";
import { type RefObject, useEffect } from "react";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Return true for an outside target that should *not* dismiss. Must be stable. */
ignore?: (target: Element) => boolean;
}
/**
* What every currently open dismiss scope counts as inside itself. A consumed
* dismissal reads this to tell a stray gesture from one that belongs to an
* overlay in front of it: overlays have no shared z-order to consult, but the
* one the gesture landed in has said as much by registering it.
*/
const openScopes = new Set<(target: Element) => boolean>();
function claimedByAnotherScope(
self: (target: Element) => boolean,
target: Element,
) {
for (const scope of openScopes) {
if (scope !== self && scope(target)) return true;
}
return false;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over. `onDismiss` and `ignore` must be stable (wrap in
* useCallback) so the listeners aren't re-bound every render while open.
*/
export function useDismiss(
open: boolean,
onDismiss: () => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
ignore,
}: DismissOptions = {},
) {
useEffect(() => {
if (!open) return;
const inside = (target: Element) =>
Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));
const onKey = (event: KeyboardEvent) => {
if (dismissOnEscape && event.key === "Escape") onDismiss();
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside one that is also open: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !claimedByAnotherScope(inside, target)) {
consumeActivation(event);
}
onDismiss();
};
openScopes.add(inside);
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer, true);
return () => {
openScopes.delete(inside);
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
};
}, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);
}
"use client";
import { useMemo, useRef } from "react";
import { isHoveringPointer } from "@/lib/touch";
interface BoundaryEvent {
pointerId: number;
pointerType: string;
buttons: number;
}
export interface HoverGesture {
/** True when this enter starts a hover: the pointer arrived resting, not pressing. */
enter: (event: BoundaryEvent) => boolean;
/** True when this leave ends a hover that entered as one. */
leave: (event: BoundaryEvent) => boolean;
}
/**
* Pairs a surface's enter with its leave, per pointer.
*
* `isHoveringPointer` answers the question the *enter* asks — is this pointer
* resting on the surface or pressing it — and both boundary cases go wrong if
* the leave is asked the same question again:
*
* - A pen with no hover never rests. It arrives in contact, taps, and the spec
* then requires its boundary events after `pointerup`, so the leave carries
* `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid
* the tap — the panel the pen had just opened closed under it.
* - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.
* Skipping teardown there strands the surface open: the release happens
* outside, and no second leave ever comes.
*
* So the state a hover holds is released by the pointer that took it, whatever
* the buttons say at the boundary, and a pointer that arrived in contact never
* took it in the first place. Contact is the exception tracked here, not
* hover: a leave from a pointer this surface never saw enter — mounted under
* the cursor, say — still counts, since the alternative is state with no way
* out.
*/
export function useHoverGesture(): HoverGesture {
const contact = useRef(new Set<number>());
return useMemo(
() => ({
enter: (event) => {
if (isHoveringPointer(event)) {
contact.current.delete(event.pointerId);
return true;
}
contact.current.add(event.pointerId);
return false;
},
leave: (event) => {
const arrivedInContact = contact.current.delete(event.pointerId);
return !arrivedInContact && event.pointerType !== "touch";
},
}),
[],
);
}
"use client";
import { useMemo, useRef } from "react";
/** What a pointerdown recorded, read back by the click that ends its gesture. */
export interface TapRecord<S> {
/** Which input started the gesture. */
pointerType: string;
/** What the surface was showing when it started. */
state: S;
}
export interface TapGesture<S> {
/** Record the gesture a pointerdown starts, with the state it starts in. */
start: (event: { pointerType: string }, state: S) => void;
/** Read the record and clear it. `null` when no pointer is behind this click. */
take: () => TapRecord<S> | null;
/** Drop the record: this gesture will never spend it on a click. */
drop: () => void;
}
/**
* The pointer gesture behind a click, recorded where the click cannot report
* it. A `click` carries no `pointerType` in the engines that matter, so the
* `pointerdown` before it is the only thing that says which input activated
* the control — and whether one did at all, since keyboard activation
* synthesizes a click with no pointer behind it.
*
* State goes in with the record because a click reports that no better: a
* browser that focuses a control on contact can open the very panel the tap
* was meant to open, and reading "is it open" at click time then undoes it.
* What the gesture started against is what it acts on.
*
* The record is spent by one click and dropped by everything else, because a
* record that outlives its gesture is worse than none:
*
* - A scroll or an OS gesture takes the touch away — `pointercancel`, no click
* ever — and the finger would sit in the record until some later click.
* - That later click is often `Enter` on a keyboard, which arrives with no
* pointerdown of its own and would inherit the abandoned finger. A keydown
* is the start of a keyboard activation and never part of a tap, so it drops
* the record too.
*
* Both ends have to be wired by the surface: `drop` on `onPointerCancel` and
* on `onKeyDown`.
*/
export function useTapGesture<S>(): TapGesture<S> {
const record = useRef<TapRecord<S> | null>(null);
return useMemo(
() => ({
start: (event, state) => {
record.current = { pointerType: event.pointerType, state };
},
take: () => {
const spent = record.current;
record.current = null;
return spent;
},
drop: () => {
record.current = null;
},
}),
[],
);
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
/**
* Elements that can usually take keyboard focus. The selector cannot see
* everything focus() checks (an element under `display: none`, say), so a
* caller that needs certainty tries focus() and checks where it landed.
*/
export const FOCUSABLE_SELECTOR = [
"a[href]",
"button:not(:disabled)",
"input:not(:disabled):not([type='hidden'])",
"select:not(:disabled)",
"textarea:not(:disabled)",
"[tabindex]:not([tabindex='-1'])",
].join(",");
"use client";
import {
type KeyboardEvent,
type RefObject,
useEffect,
useMemo,
useRef,
} from "react";
import { useOnOpen } from "@/lib/hooks/use-on-open";
import { useRowCursor } from "@/lib/hooks/use-row-cursor";
export interface ListboxRow {
id: string;
label: string;
disabled?: boolean;
}
// How long typed characters keep building one typeahead query.
const TYPEAHEAD_MS = 500;
/**
* Keyboard model for a popup listbox whose options are focusable buttons.
*
* The active option is resolved during render through `useRowCursor`, so the
* roving `tabIndex` and the next key press always agree with what is on
* screen. Opening starts on the selected option, or the first enabled one.
* Arrow keys, Home and End move between enabled options, and printable
* characters jump to the next option whose label starts with what was typed.
* DOM focus follows the active option while the list is open; each option
* carries its id in `data-listbox-id` so the list can find it.
*/
export function useListbox({
open,
rows,
selected,
list,
}: {
open: boolean;
rows: readonly ListboxRow[];
selected: string | undefined;
list: RefObject<HTMLElement | null>;
}) {
const enabled = useMemo(() => rows.filter((row) => !row.disabled), [rows]);
const { activeIndex, moveTo, moveActive } = useRowCursor(enabled, "");
useOnOpen(open, () =>
moveTo(enabled.some((row) => row.id === selected) ? (selected ?? null) : null),
);
const activeId = enabled[activeIndex]?.id;
const typed = useRef({ text: "", at: 0 });
// A list rendered open does not take focus from the page on mount; focus
// follows only once it has been opened, or once focus is already inside.
const openedOnMount = useRef(open);
useEffect(() => {
if (!open) openedOnMount.current = false;
}, [open]);
useEffect(() => {
if (!open || activeId === undefined) return;
if (
openedOnMount.current &&
!list.current?.contains(document.activeElement)
)
return;
const option = Array.from(
list.current?.querySelectorAll<HTMLElement>("[data-listbox-id]") ?? [],
).find((element) => element.dataset.listboxId === activeId);
option?.focus({ preventScroll: false });
}, [open, activeId, list]);
const onKeyDown = (event: KeyboardEvent) => {
const { key } = event;
if (key === "ArrowDown" || key === "ArrowUp") {
event.preventDefault();
moveActive(key === "ArrowDown" ? 1 : -1);
} else if (key === "Home" || key === "End") {
event.preventDefault();
const row = key === "Home" ? enabled[0] : enabled[enabled.length - 1];
if (row) moveTo(row.id);
} else if (
key.length === 1 &&
key !== " " &&
!event.ctrlKey &&
!event.metaKey &&
!event.altKey
) {
const now = Date.now();
const char = key.toLowerCase();
const text =
now - typed.current.at < TYPEAHEAD_MS ? typed.current.text + char : char;
typed.current = { text, at: now };
// A repeated single letter cycles through the options that start with it.
const from = text.length === 1 ? activeIndex + 1 : activeIndex;
for (let step = 0; step < enabled.length; step++) {
const row = enabled[(from + step) % enabled.length];
if (row.label.toLowerCase().startsWith(text)) {
moveTo(row.id);
break;
}
}
}
};
return { activeId, onKeyDown };
}
"use client";
import { useCallback, useState } from "react";
import { getFaviconUrl } from "@/lib/favicon";
/**
* Resolves a site favicon and drops it once it is known to be unusable, so
* callers can draw their own glyph instead of a broken image. Plenty of sites
* answer `/favicon.ico` with a 403 or 404, and `onError` is not enough to catch
* it: an image the browser starts loading from server-rendered HTML usually
* fails before React attaches a handler, and that event is never replayed.
* `decode()` settles on the image's final state instead of relying on an event
* firing at the right moment.
*/
export function useFavicon(url?: string) {
const resolved = url ? getFaviconUrl(url) : null;
const [failedSrc, setFailedSrc] = useState<string | null>(null);
const src = resolved && resolved !== failedSrc ? resolved : null;
const ref = useCallback(
(img: HTMLImageElement | null) => {
if (!img || !src) return;
let released = false;
img.decode().catch(() => {
if (!released) setFailedSrc(src);
});
// The node is going away or the source changed; a late rejection then
// describes an image we are no longer showing.
return () => {
released = true;
};
},
[src],
);
return { src, ref };
}
"use client";
import { useEffect, useState } from "react";
/**
* Returns true only on devices that have a true hover (mouse / trackpad).
* Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere
* — gate hover-only effects (scale lifts, magnetic pulls) behind this.
*/
export function useHoverCapable() {
const [canHover, setCanHover] = useState(false);
useEffect(() => {
if (typeof window === "undefined" || !window.matchMedia) return;
const mq = window.matchMedia("(hover: hover) and (pointer: fine)");
const update = () => setCanHover(mq.matches);
update();
mq.addEventListener?.("change", update);
return () => mq.removeEventListener?.("change", update);
}, []);
return canHover;
}
"use client";
import { useState } from "react";
/**
* Runs `start` during the render in which `open` becomes true.
*
* Opening a list starts a fresh session — an empty query, the highlight back at
* the top — and that is a resolution, not a side effect: a passive effect runs
* after the commit, so the new session would carry the last one's state for a
* window in which a key press can land.
*
* `start` may only set state belonging to the calling component. Anything that
* reaches outside it — a consumer's callback, a DOM write, moving focus — is a
* side effect, and React rejects a callback that sets another component's state
* during this one's render. Put those in an effect keyed to `open`.
*/
export function useOnOpen(open: boolean, start: () => void) {
const [wasOpen, setWasOpen] = useState(open);
if (open !== wasOpen) {
setWasOpen(open);
if (open) start();
}
}
"use client";
import { useCallback, useLayoutEffect, useRef, useState } from "react";
/**
* Where the keyboard or the pointer last moved to: the row's id, stamped with
* the query it was placed under.
*/
type RowCursor = { id: string; query: string };
/** The cursor's row, or -1 once the query has moved on or the row has left. */
function indexOfCursor(
rows: readonly { id: string }[],
query: string,
cursor: RowCursor | null,
) {
if (cursor === null || cursor.query !== query) return -1;
return rows.findIndex((row) => row.id === cursor.id);
}
/**
* The highlighted row of a list whose rows can change under it.
*
* Which row is highlighted is resolved during render, never in a passive
* effect: a passive effect runs after the commit, so a list that had just
* changed would carry an `aria-activedescendant` naming a row that has left it,
* and a key pressed in that window would commit the wrong row or nothing at
* all.
*
* The cursor holds the row's id, not its position. A position alone cannot tell
* a list that shrank from one that swapped its rows for a different set of the
* same length, and the second case is the one that silently hands Enter to a
* row the user never chose. A cursor whose row has left the list returns the
* highlight to the first row rather than to the nearest surviving one: the row
* the user aimed at is gone, and the first row is where a new query already
* puts the highlight.
*
* Pass the query the list is filtered by. The cursor is stamped with it and
* dropped when it changes, so a caller cannot forget to clear it — including a
* caller whose query arrives as a prop and so never runs its own handler. Rows
* that come back under a query that has moved on cannot revive it either.
* `moveTo(null)` is for deliberate resets, such as reopening the list.
*
* Both callbacks keep one identity for the life of the component, and read the
* rows and the query through a ref to do it. A caller will put them in an
* effect's dependencies — the exhaustive-deps rule makes it — and a `moveTo`
* rebuilt on every keystroke would re-run that effect on every keystroke.
*/
export function useRowCursor(rows: readonly { id: string }[], query: string) {
const [cursor, setCursor] = useState<RowCursor | null>(null);
// Written after commit, not during render: a render React discards or has not
// finished still runs the component body, and an event handler that read this
// in that window would stamp the cursor with a query the committed tree does
// not have.
const latest = useRef({ rows, query });
useLayoutEffect(() => {
latest.current = { rows, query };
});
const cursorRow = indexOfCursor(rows, query, cursor);
// Cleared rather than ignored: React re-runs this render with the cursor
// already gone, so rows that come back cannot revive a highlight the user has
// stopped aiming at.
if (cursor !== null && cursorRow < 0) setCursor(null);
const moveTo = useCallback(
(id: string | null) =>
setCursor(id === null ? null : { id, query: latest.current.query }),
[],
);
const moveActive = useCallback((direction: 1 | -1) => {
const { rows: live, query: liveQuery } = latest.current;
const last = live.length - 1;
if (last < 0) return;
// Steps from the row the cursor is really on, inside the update, so that
// two keys landing in one batch move two rows rather than one.
setCursor((current) => {
const at = Math.max(indexOfCursor(live, liveQuery, current), 0);
const next = Math.min(Math.max(at + direction, 0), last);
return { id: live[next].id, query: liveQuery };
});
}, []);
return { activeIndex: cursorRow < 0 ? 0 : cursorRow, moveTo, moveActive };
}
/** Resolve a website URL to its conventional root favicon location. */
export function getFaviconUrl(value: string) {
try {
return new URL("/favicon.ico", value).toString();
} catch {
return null;
}
}
Copy the source code
"use client";
// beui.dev/components/agents/message-scroller
import { useReducedMotion } from "motion/react";
import {
type ComponentPropsWithRef,
type Ref,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
import {
PreviewRail,
type PreviewRailItem,
} from "@/components/motion/preview-rail";
import { cn } from "@/lib/utils";
const PREVIEW_TITLE_LENGTH = 56;
const PREVIEW_DESCRIPTION_LENGTH = 88;
function truncateMessageText(text: string, limit: number) {
if (text.length <= limit) return text;
const excerpt = text.slice(0, limit);
const boundary = excerpt.lastIndexOf(" ");
return `${excerpt.slice(0, boundary > limit * 0.65 ? boundary : limit).trim()}…`;
}
function getMessageText(message: HTMLElement) {
const surface =
message.querySelector<HTMLElement>('[data-slot="message-bubble-content"]') ??
message.querySelector<HTMLElement>('[data-slot="message-content"]') ??
message;
return (surface.textContent ?? "").replace(/\s+/g, " ").trim();
}
function getMessagePreview(
message: HTMLElement,
assistantResponse?: HTMLElement,
) {
const text = getMessageText(message);
if (!text) {
return { label: "Message", description: undefined };
}
if (text.length <= PREVIEW_TITLE_LENGTH) {
const responseText = assistantResponse
? getMessageText(assistantResponse)
: "";
return {
label: text,
description: responseText
? truncateMessageText(responseText, PREVIEW_DESCRIPTION_LENGTH)
: undefined,
};
}
const titleExcerpt = text.slice(0, PREVIEW_TITLE_LENGTH);
const titleBoundary = titleExcerpt.lastIndexOf(" ");
const titleEnd =
titleBoundary > PREVIEW_TITLE_LENGTH * 0.65
? titleBoundary
: PREVIEW_TITLE_LENGTH;
const label = `${text.slice(0, titleEnd).trim()}…`;
const responseText = assistantResponse
? getMessageText(assistantResponse)
: text.slice(titleEnd).trim();
return {
label,
description: responseText
? truncateMessageText(responseText, PREVIEW_DESCRIPTION_LENGTH)
: undefined,
};
}
export interface MessageScrollerProps extends ComponentPropsWithRef<"div"> {
/** Keep streamed output pinned while the reader remains near the end. */
followOutput?: boolean;
/** Distance from the end that still counts as following the output. */
followThreshold?: number;
/** Smoothly follow growing content. */
smooth?: boolean;
/** Reports when the reader leaves or returns to the live edge. */
onFollowChange?: (following: boolean) => void;
/** Accessible label for the scrollable transcript. */
label?: string;
/** Marks the transcript as waiting for more streamed content. */
busy?: boolean;
/** Adds a compact rail for navigating between rendered Message rows. */
navigation?: "rail";
/** Accessible label for the optional message navigation rail. */
navigationLabel?: string;
viewportClassName?: string;
contentClassName?: string;
railClassName?: string;
viewportRef?: Ref<HTMLElement>;
viewportProps?: Omit<
ComponentPropsWithRef<"section">,
"children" | "className" | "ref"
>;
contentProps?: Omit<
ComponentPropsWithRef<"div">,
"children" | "className" | "ref"
>;
}
export function MessageScroller({
followOutput = true,
followThreshold = 56,
smooth = true,
onFollowChange,
label = "Conversation",
busy,
navigation,
navigationLabel = "Message navigation",
viewportClassName,
contentClassName,
railClassName,
viewportRef: externalViewportRef,
viewportProps,
contentProps,
className,
children,
...props
}: MessageScrollerProps) {
const reduce = useReducedMotion() ?? false;
const viewportRef = useRef<HTMLElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const followingRef = useRef(followOutput);
const programmaticScrollRef = useRef(false);
const scrollTimerRef = useRef<number | undefined>(undefined);
const frameRef = useRef<number | undefined>(undefined);
const railFrameRef = useRef<number | undefined>(undefined);
const railIdRef = useRef(new WeakMap<HTMLElement, string>());
const railIdCounterRef = useRef(0);
const railTargetsRef = useRef(new Map<string, HTMLElement>());
const [railItems, setRailItems] = useState<PreviewRailItem[]>([]);
const [activeRailId, setActiveRailId] = useState("");
const [railOverflowing, setRailOverflowing] = useState(false);
const {
onScroll: onViewportScroll,
onWheel: onViewportWheel,
onTouchStart: onViewportTouchStart,
onKeyDown: onViewportKeyDown,
...restViewportProps
} = viewportProps ?? {};
const setViewportRef = useCallback(
(node: HTMLElement | null) => {
viewportRef.current = node;
if (typeof externalViewportRef === "function") {
externalViewportRef(node);
} else if (externalViewportRef) {
externalViewportRef.current = node;
}
},
[externalViewportRef],
);
const setFollowing = useCallback(
(next: boolean) => {
if (followingRef.current === next) return;
followingRef.current = next;
onFollowChange?.(next);
},
[onFollowChange],
);
const updateActiveRailItem = useCallback(() => {
if (navigation !== "rail") return;
const viewport = viewportRef.current;
const targets = [...railTargetsRef.current.entries()];
if (!viewport || targets.length === 0) return;
const viewportRect = viewport.getBoundingClientRect();
if (viewport.scrollTop <= followThreshold) {
const firstId = targets[0]?.[0] ?? "";
setActiveRailId((current) => (current === firstId ? current : firstId));
return;
}
const distanceFromEnd =
viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
if (distanceFromEnd <= followThreshold) {
const lastId = targets.at(-1)?.[0] ?? "";
setActiveRailId((current) => (current === lastId ? current : lastId));
return;
}
const viewportCenter = viewportRect.top + viewportRect.height / 2;
let nearestId = targets[0]?.[0] ?? "";
let nearestDistance = Number.POSITIVE_INFINITY;
for (const [id, element] of targets) {
const rect = element.getBoundingClientRect();
const messageCenter = rect.top + rect.height / 2;
const distance = Math.abs(messageCenter - viewportCenter);
if (distance < nearestDistance) {
nearestDistance = distance;
nearestId = id;
}
}
setActiveRailId((current) =>
current === nearestId ? current : nearestId,
);
}, [followThreshold, navigation]);
const syncRailItems = useCallback(() => {
if (navigation !== "rail") return;
const content = contentRef.current;
const viewport = viewportRef.current;
if (!content || !viewport) return;
const messages = Array.from(
content.querySelectorAll<HTMLElement>('[data-slot="message"]'),
);
const targets = new Map<string, HTMLElement>();
const nextItems = messages.map((message, index) => {
let id = railIdRef.current.get(message);
if (!id) {
railIdCounterRef.current += 1;
id = `message-rail-${railIdCounterRef.current}`;
railIdRef.current.set(message, id);
}
targets.set(id, message);
const sender = message.dataset.from ?? "conversation";
const assistantResponse =
sender === "user"
? messages
.slice(index + 1)
.find((candidate) => candidate.dataset.from === "assistant")
: undefined;
const preview = getMessagePreview(message, assistantResponse);
return {
id,
label: preview.label,
description: preview.description,
ariaLabel: `Go to ${sender} message ${index + 1} of ${messages.length}`,
};
});
railTargetsRef.current = targets;
setRailItems((current) => {
const unchanged =
current.length === nextItems.length &&
current.every(
(item, index) =>
item.id === nextItems[index]?.id &&
item.label === nextItems[index]?.label &&
item.description === nextItems[index]?.description &&
item.ariaLabel === nextItems[index]?.ariaLabel,
);
return unchanged ? current : nextItems;
});
setRailOverflowing(
viewport.scrollHeight > viewport.clientHeight + 1 && messages.length > 1,
);
}, [navigation]);
const scheduleRailSync = useCallback(() => {
if (navigation !== "rail") return;
if (railFrameRef.current) cancelAnimationFrame(railFrameRef.current);
railFrameRef.current = requestAnimationFrame(() => {
syncRailItems();
updateActiveRailItem();
});
}, [navigation, syncRailItems, updateActiveRailItem]);
const scrollToEnd = useCallback((behavior: ScrollBehavior) => {
const viewport = viewportRef.current;
if (!viewport) return;
programmaticScrollRef.current = true;
if (typeof viewport.scrollTo === "function") {
viewport.scrollTo({ top: viewport.scrollHeight, behavior });
} else {
viewport.scrollTop = viewport.scrollHeight;
}
if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);
scrollTimerRef.current = window.setTimeout(() => {
programmaticScrollRef.current = false;
}, behavior === "smooth" ? 320 : 0);
}, []);
const handleScroll = useCallback(() => {
const viewport = viewportRef.current;
if (!viewport || programmaticScrollRef.current) return;
const distance =
viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
setFollowing(distance <= followThreshold);
updateActiveRailItem();
}, [followThreshold, setFollowing, updateActiveRailItem]);
const leaveLiveEdge = useCallback(() => {
programmaticScrollRef.current = false;
}, []);
useLayoutEffect(() => {
followingRef.current = followOutput;
if (!followOutput) return;
frameRef.current = requestAnimationFrame(() => scrollToEnd("auto"));
return () => {
if (frameRef.current) cancelAnimationFrame(frameRef.current);
};
}, [followOutput, scrollToEnd]);
useEffect(() => {
const content = contentRef.current;
if (!content || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => {
scheduleRailSync();
if (!followOutput || !followingRef.current) return;
scrollToEnd(reduce || !smooth ? "auto" : "smooth");
});
observer.observe(content);
return () => observer.disconnect();
}, [followOutput, reduce, scheduleRailSync, scrollToEnd, smooth]);
useEffect(() => {
if (navigation !== "rail") {
railTargetsRef.current.clear();
setRailItems([]);
setRailOverflowing(false);
return;
}
const content = contentRef.current;
const viewport = viewportRef.current;
if (!content || !viewport) return;
scheduleRailSync();
const mutationObserver =
typeof MutationObserver === "undefined"
? null
: new MutationObserver(scheduleRailSync);
mutationObserver?.observe(content, {
childList: true,
characterData: true,
subtree: true,
});
const resizeObserver =
typeof ResizeObserver === "undefined"
? null
: new ResizeObserver(scheduleRailSync);
resizeObserver?.observe(content);
resizeObserver?.observe(viewport);
return () => {
mutationObserver?.disconnect();
resizeObserver?.disconnect();
};
}, [navigation, scheduleRailSync]);
useEffect(
() => () => {
if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);
if (frameRef.current) cancelAnimationFrame(frameRef.current);
if (railFrameRef.current) cancelAnimationFrame(railFrameRef.current);
},
[],
);
const scrollToRailItem = useCallback(
(item: PreviewRailItem) => {
const viewport = viewportRef.current;
const target = railTargetsRef.current.get(item.id);
if (!viewport || !target) return;
const lastItem = railItems.at(-1)?.id === item.id;
setActiveRailId(item.id);
if (lastItem) {
setFollowing(true);
scrollToEnd(reduce || !smooth ? "auto" : "smooth");
return;
}
setFollowing(false);
programmaticScrollRef.current = true;
const viewportRect = viewport.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();
const top =
viewport.scrollTop +
targetRect.top -
viewportRect.top -
(viewport.clientHeight - targetRect.height) / 2;
const behavior = reduce || !smooth ? "auto" : "smooth";
if (typeof viewport.scrollTo === "function") {
viewport.scrollTo({ top, behavior });
} else {
viewport.scrollTop = top;
}
if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);
scrollTimerRef.current = window.setTimeout(() => {
programmaticScrollRef.current = false;
}, behavior === "smooth" ? 320 : 0);
},
[railItems, reduce, scrollToEnd, setFollowing, smooth],
);
const viewport = (
<section
ref={setViewportRef}
aria-label={label}
{...restViewportProps}
onScroll={(event) => {
handleScroll();
onViewportScroll?.(event);
}}
onWheel={(event) => {
leaveLiveEdge();
onViewportWheel?.(event);
}}
onTouchStart={(event) => {
leaveLiveEdge();
onViewportTouchStart?.(event);
}}
onKeyDown={(event) => {
if (["ArrowUp", "PageUp", "Home"].includes(event.key)) {
leaveLiveEdge();
}
onViewportKeyDown?.(event);
}}
className={cn(
"h-full overflow-y-auto overscroll-contain outline-none [overflow-anchor:none] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
navigation === "rail"
? "[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
: "[scrollbar-gutter:stable]",
viewportClassName,
navigation === "rail" && railOverflowing && "pr-10",
)}
>
<div
ref={contentRef}
role="log"
aria-live="polite"
aria-relevant="additions text"
aria-busy={busy}
className={contentClassName}
{...contentProps}
>
{children}
</div>
</section>
);
return (
<div
data-slot="message-scroller"
className={cn("min-h-0", className)}
{...props}
>
{navigation === "rail" ? (
<PreviewRail
items={railOverflowing ? railItems : []}
label={navigationLabel}
activeId={activeRailId}
onItemSelect={scrollToRailItem}
previewSide="before"
highlightActive
itemSize={14}
className="h-full min-h-0 overflow-hidden"
previewContainerClassName="right-8 left-3"
previewClassName="mr-1 w-64 max-w-full [&_[data-slot=preview-rail-card]]:h-20 [&_[data-slot=preview-rail-card]]:overflow-hidden [&_[data-slot=preview-rail-card]]:p-3 [&_[data-slot=preview-rail-title]]:line-clamp-1 [&_[data-slot=preview-rail-title]]:text-xs [&_[data-slot=preview-rail-title]]:leading-4 [&_[data-slot=preview-rail-description]]:line-clamp-2 [&_[data-slot=preview-rail-description]]:text-xs [&_[data-slot=preview-rail-description]]:leading-4"
railClassName={cn(
"absolute inset-y-3 right-1 w-7 content-center py-1 [&_[data-slot=preview-rail-item]]:w-7 [&_[data-slot=preview-rail-item]]:justify-end [&_[data-slot=preview-rail-tick]]:h-px [&_[data-slot=preview-rail-tick]]:w-4 [&_[data-slot=preview-rail-tick]]:origin-right",
railOverflowing
? "pointer-events-auto opacity-100"
: "pointer-events-none opacity-0",
railClassName,
)}
>
{viewport}
</PreviewRail>
) : (
viewport
)}
</div>
);
}
"use client";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
type MouseEvent,
type PointerEvent,
type ReactNode,
useCallback,
useId,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_LAYOUT } from "@/lib/ease";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { cn } from "@/lib/utils";
export interface PreviewRailItem {
id: string;
label: string;
ariaLabel?: string;
description?: ReactNode;
href?: string;
target?: "_blank" | "_self" | "_parent" | "_top";
rel?: string;
}
export interface PreviewRailProps {
items: PreviewRailItem[];
label?: string;
orientation?: "vertical" | "horizontal";
activeId?: string;
defaultActiveId?: string;
onActiveChange?: (id: string) => void;
onItemSelect?: (item: PreviewRailItem) => void;
renderPreview?: (item: PreviewRailItem) => ReactNode;
showPreview?: boolean;
previewSide?: "before" | "after";
highlightActive?: boolean;
itemSize?: number;
children?: ReactNode;
className?: string;
railClassName?: string;
previewContainerClassName?: string;
previewClassName?: string;
}
function DefaultPreview({ item }: { item: PreviewRailItem }) {
return (
<div
data-slot="preview-rail-card"
className="rounded-2xl border border-border bg-card p-4 shadow-sm"
>
<p
data-slot="preview-rail-title"
className="font-medium text-card-foreground"
>
{item.label}
</p>
{item.description ? (
<div
data-slot="preview-rail-description"
className="mt-1 text-sm leading-6 text-muted-foreground"
>
{item.description}
</div>
) : null}
</div>
);
}
export function PreviewRail({
items,
label = "Section navigation",
orientation = "vertical",
activeId,
defaultActiveId,
onActiveChange,
onItemSelect,
renderPreview,
showPreview = true,
previewSide = "after",
highlightActive = false,
itemSize = 24,
children,
className,
railClassName,
previewContainerClassName,
previewClassName,
}: PreviewRailProps) {
const uid = useId();
const reduce = useReducedMotion();
const rootRef = useRef<HTMLDivElement>(null);
const [internalActiveId, setInternalActiveId] = useState(
defaultActiveId ?? items[0]?.id ?? "",
);
const [hoveredId, setHoveredId] = useState<string | null>(null);
// A finger cannot hover, so a tap lights the tick instead. Kept apart from
// the hovered one: they end in different ways, and a stray mouse move must
// not clear a tick the keyboard or a tap chose.
const [pinnedId, setPinnedId] = useState<string | null>(null);
const [focusedId, setFocusedId] = useState<string | null>(null);
// A click carries no pointerType, so the pointerdown before it is what says
// whether the activation was a tap. Keyboard activation has none at all.
const tap = useTapGesture<boolean>();
const hover = useHoverGesture();
const clearPinned = useCallback(() => setPinnedId(null), []);
// The next tap outside the rail stands in for the pointer leaving it. The
// card is a preview, so that tap passes through to whatever it landed on.
useDismiss(pinnedId !== null, clearPinned, rootRef);
const requestedActiveId = activeId ?? internalActiveId;
const selectedId = items.some((item) => item.id === requestedActiveId)
? requestedActiveId
: (items[0]?.id ?? "");
const displayedId = hoveredId ?? pinnedId ?? focusedId ?? "";
const highlightedId = displayedId || (highlightActive ? selectedId : "");
const displayedIndex = items.findIndex((item) => item.id === highlightedId);
const rowTemplate = items.length
? `repeat(${items.length}, ${itemSize}px)`
: undefined;
const isHorizontal = orientation === "horizontal";
const selectItem = (id: string) => {
if (activeId === undefined) setInternalActiveId(id);
onActiveChange?.(id);
};
return (
<motion.div
layoutRoot
ref={rootRef}
onBlur={(event) => {
// Both tick sources leave with the focus: a tap does not always land
// focus, but when it does, tabbing away must not strand the card.
if (!event.currentTarget.contains(event.relatedTarget)) {
setFocusedId(null);
setPinnedId(null);
}
}}
className={cn(
"isolate relative flex w-full overflow-visible",
isHorizontal
? "min-h-64 flex-col items-center justify-center"
: "min-h-80",
className,
)}
>
<nav
aria-label={label}
onPointerLeave={(event) => {
// A touch pointer leaves on lift, which would clear the tick the tap
// just chose — that one is cleared by the outside tap instead.
if (hover.leave(event)) setHoveredId(null);
}}
style={
isHorizontal
? { gridTemplateColumns: rowTemplate }
: { gridTemplateRows: rowTemplate }
}
className={cn(
"relative z-10 grid shrink-0",
isHorizontal
? "h-12 w-fit max-w-full self-center justify-center"
: "w-12 content-center",
railClassName,
)}
>
{items.map((item, index) => {
const selected = item.id === selectedId;
const highlighted = item.id === highlightedId;
const distance =
displayedIndex < 0 ? Number.POSITIVE_INFINITY : Math.abs(index - displayedIndex);
const scale = highlighted
? 1
: distance === 1
? 0.68
: distance === 2
? 0.44
: 0.25;
const itemContent = (
<>
<motion.span
data-slot="preview-rail-tick"
aria-hidden="true"
animate={isHorizontal ? { scaleY: scale } : { scaleX: scale }}
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
className={cn(
"block bg-current",
isHorizontal
? "h-12 w-0.5 origin-bottom"
: "h-0.5 w-12 origin-left",
highlighted ? "text-foreground" : undefined,
)}
/>
</>
);
const sharedClassName = cn(
"relative flex text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
isHorizontal
? "h-12 w-6 items-end justify-center"
: "h-6 w-12 items-center",
);
const sharedStyle = isHorizontal
? { width: itemSize }
: { height: itemSize };
const handlePointerEnter = (event: PointerEvent<HTMLElement>) => {
if (hover.enter(event)) setHoveredId(item.id);
};
const handlePointerDown = (event: PointerEvent<HTMLElement>) => {
tap.start(event, pinnedId === item.id);
setFocusedId(null);
};
// A gesture the platform takes away sends no click, and a key press
// starts an activation that never had a pointer behind it: either
// one leaves a record the next click would read as a tap of its own.
const dropGesture = () => tap.drop();
const handleFocus = (currentTarget: HTMLElement) => {
if (currentTarget.matches(":focus-visible")) {
setFocusedId(item.id);
}
};
const handleSelect = (event: MouseEvent<HTMLElement>) => {
const gesture = tap.take();
const tapped =
gesture !== null && gesture.pointerType !== "mouse";
if (tapped) {
// A link would otherwise show its preview and leave the page in
// the same tap, so the card is never read: the first tap lights
// the tick, the second follows the link.
if (item.href && !gesture.state) {
event.preventDefault();
setPinnedId(item.id);
return;
}
setPinnedId(item.id);
}
selectItem(item.id);
onItemSelect?.(item);
};
return item.href ? (
<a
key={item.id}
data-slot="preview-rail-item"
href={item.href}
target={item.target}
rel={
item.rel ??
(item.target === "_blank" ? "noreferrer noopener" : undefined)
}
aria-label={item.ariaLabel ?? item.label}
aria-current={selected ? "page" : undefined}
onPointerEnter={handlePointerEnter}
onPointerDown={handlePointerDown}
onPointerCancel={dropGesture}
onKeyDown={dropGesture}
onFocus={(event) => handleFocus(event.currentTarget)}
onClick={handleSelect}
style={sharedStyle}
className={sharedClassName}
>
{itemContent}
</a>
) : (
<button
key={item.id}
data-slot="preview-rail-item"
type="button"
aria-label={item.ariaLabel ?? item.label}
aria-current={selected ? "location" : undefined}
onPointerEnter={handlePointerEnter}
onPointerDown={handlePointerDown}
onPointerCancel={dropGesture}
onKeyDown={dropGesture}
onFocus={(event) => handleFocus(event.currentTarget)}
onClick={handleSelect}
style={sharedStyle}
className={sharedClassName}
>
{itemContent}
</button>
);
})}
</nav>
{showPreview ? (
<div
aria-hidden="true"
style={
isHorizontal
? { gridTemplateColumns: rowTemplate }
: { gridTemplateRows: rowTemplate }
}
className={cn(
"pointer-events-none absolute z-50 grid",
isHorizontal
? "top-1/2 left-1/2 h-5 w-fit max-w-full -translate-x-1/2 -translate-y-1/2 justify-center"
: previewSide === "before"
? "inset-y-0 right-16 left-4 content-center"
: "inset-y-0 right-4 left-16 content-center",
previewContainerClassName,
)}
>
{items.map((item) => (
<div
key={item.id}
style={
isHorizontal ? { width: itemSize } : { height: itemSize }
}
className={cn(
"relative flex items-center",
isHorizontal ? "justify-center" : undefined,
)}
>
{item.id === displayedId ? (
<div
className={cn(
isHorizontal
? "absolute bottom-12 left-1/2 w-72 -translate-x-1/2"
: cn(
"w-full max-w-sm",
previewSide === "before" && "ml-auto",
),
previewClassName,
)}
>
<motion.div
layoutId={`preview-rail-card-${uid}`}
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
>
<AnimatePresence mode="wait" initial={false}>
<motion.div
key={item.id}
initial={
reduce
? { opacity: 0 }
: { opacity: 0, y: 4, filter: "blur(6px)" }
}
animate={
reduce
? { opacity: 1 }
: { opacity: 1, y: 0, filter: "blur(0px)" }
}
exit={
reduce
? { opacity: 0 }
: {
opacity: 0,
y: -2,
filter: "blur(4px)",
transition: {
duration: 0.12,
ease: EASE_OUT,
},
}
}
transition={{
duration: reduce ? 0 : 0.18,
ease: EASE_OUT,
}}
>
{renderPreview ? (
renderPreview(item)
) : (
<DefaultPreview item={item} />
)}
</motion.div>
</AnimatePresence>
</motion.div>
</div>
) : null}
</div>
))}
</div>
) : null}
{children ? (
<div className="min-h-0 min-w-0 flex-1">{children}</div>
) : null}
</motion.div>
);
}
"use client";
import { Bot, User } from "lucide-react";
import { useReducedMotion } from "motion/react";
import { useCallback, useEffect, useRef, useState } from "react";
import {
Message,
MessageAvatar,
MessageContent,
MessageFooter,
MessageGroup,
MessageHeader,
MessageTyping,
} from "@/components/agents/message";
import {
MessageBubble,
MessageBubbleContent,
type MessageBubbleVariant,
} from "@/components/agents/message-bubble";
import { MessageScroller } from "@/components/agents/message-scroller";
import { PromptInput } from "@/components/agents/prompt-input";
import { StreamingResponse } from "@/components/agents/streaming-response";
import { cn } from "@/lib/utils";
export interface ChatPreviewMessage {
id: string;
from: "user" | "assistant";
content: string;
}
interface RenderedChatMessage extends ChatPreviewMessage {
animateIn: boolean;
streaming?: boolean;
}
export interface ChatPreviewProps {
initialMessages?: ChatPreviewMessage[];
reply?: string | ((prompt: string) => string);
showAvatars?: boolean;
showMetadata?: boolean;
showRail?: boolean;
assistantVariant?: MessageBubbleVariant;
userVariant?: MessageBubbleVariant;
placeholder?: string;
className?: string;
viewportClassName?: string;
}
const DEFAULT_MESSAGES: ChatPreviewMessage[] = [
{
id: "welcome-question",
from: "user",
content: "What should we include in the first release?",
},
{
id: "welcome-answer",
from: "assistant",
content: "Start with the smallest workflow that still feels complete.",
},
];
const DEFAULT_REPLY =
"I’d include composing a prompt, following a streamed answer, recovering from an error, and returning to the latest response without losing the reader’s place.";
const CHARACTERS_PER_SECOND = 96;
const STREAM_DELAY = 140;
export function ChatPreview({
initialMessages = DEFAULT_MESSAGES,
reply = DEFAULT_REPLY,
showAvatars = false,
showMetadata = false,
showRail = false,
assistantVariant = "soft",
userVariant = "solid",
placeholder = "Send a message…",
className,
viewportClassName,
}: ChatPreviewProps) {
const reduce = useReducedMotion() ?? false;
const nextId = useRef(0);
const replyTimer = useRef<number | undefined>(undefined);
const [messages, setMessages] = useState<RenderedChatMessage[]>(() =>
initialMessages.map((message) => ({ ...message, animateIn: false })),
);
const [pending, setPending] = useState(false);
const [activeReply, setActiveReply] = useState<{
id: string;
content: string;
} | null>(null);
const loading = pending || activeReply !== null;
useEffect(() => {
if (!activeReply) return;
if (reduce) {
setMessages((current) =>
current.map((message) =>
message.id === activeReply.id
? { ...message, content: activeReply.content, streaming: false }
: message,
),
);
setActiveReply(null);
return;
}
const startedAt = performance.now() + STREAM_DELAY;
let frame = 0;
const stream = (now: number) => {
const cursor = Math.min(
activeReply.content.length,
Math.floor(
(Math.max(0, now - startedAt) / 1000) * CHARACTERS_PER_SECOND,
),
);
const content = activeReply.content.slice(0, cursor);
setMessages((current) =>
current.map((message) =>
message.id === activeReply.id && message.content !== content
? { ...message, content }
: message,
),
);
if (cursor < activeReply.content.length) {
frame = requestAnimationFrame(stream);
} else {
setMessages((current) =>
current.map((message) =>
message.id === activeReply.id
? { ...message, streaming: false }
: message,
),
);
setActiveReply(null);
}
};
frame = requestAnimationFrame(stream);
return () => cancelAnimationFrame(frame);
}, [activeReply, reduce]);
useEffect(
() => () => {
if (replyTimer.current) window.clearTimeout(replyTimer.current);
},
[],
);
const submit = useCallback(
(prompt: string) => {
if (loading) return;
const run = nextId.current++;
const userId = `sent-user-${run}`;
const assistantId = `sent-assistant-${run}`;
const response = typeof reply === "function" ? reply(prompt) : reply;
setMessages((current) => [
...current,
{ id: userId, from: "user", content: prompt, animateIn: true },
]);
setPending(true);
replyTimer.current = window.setTimeout(() => {
setMessages((current) => [
...current,
{
id: assistantId,
from: "assistant",
content: "",
animateIn: true,
streaming: true,
},
]);
setPending(false);
setActiveReply({ id: assistantId, content: response });
}, reduce ? 0 : 420);
},
[loading, reduce, reply],
);
const stop = useCallback(() => {
if (replyTimer.current) window.clearTimeout(replyTimer.current);
replyTimer.current = undefined;
setPending(false);
setMessages((current) =>
current.map((message) =>
message.streaming ? { ...message, streaming: false } : message,
),
);
setActiveReply(null);
}, []);
return (
<div
className={cn(
"flex h-[440px] w-full max-w-xl flex-col overflow-hidden rounded-2xl border border-border/70 bg-background",
className,
)}
>
<MessageScroller
busy={loading}
navigation={showRail ? "rail" : undefined}
className="min-h-0 flex-1"
viewportClassName={cn("px-3 py-4", viewportClassName)}
contentClassName="min-h-full"
>
<MessageGroup spacing="default">
{messages.map((message) => (
<Message
key={message.id}
id={message.id}
from={message.from}
animateIn={message.from === "user" && message.animateIn}
>
{showAvatars ? (
<MessageAvatar>
{message.from === "user" ? <User /> : <Bot />}
</MessageAvatar>
) : null}
<MessageContent>
{showMetadata ? (
<MessageHeader>
<span className="font-medium text-foreground/70">
{message.from === "user" ? "You" : "Assistant"}
</span>
<span>{message.streaming ? "Responding" : "Now"}</span>
</MessageHeader>
) : null}
<MessageBubble
variant={
message.from === "user" ? userVariant : assistantVariant
}
animateIn={false}
>
<MessageBubbleContent>
{message.from === "assistant" ? (
<StreamingResponse
status={message.streaming ? "streaming" : "complete"}
showActions={false}
announce={false}
>
{message.content || <MessageTyping />}
</StreamingResponse>
) : (
message.content
)}
</MessageBubbleContent>
</MessageBubble>
{showMetadata && message.from === "user" ? (
<MessageFooter>Sent</MessageFooter>
) : null}
</MessageContent>
</Message>
))}
{pending ? (
<Message id="pending-assistant" from="assistant">
{showAvatars ? (
<MessageAvatar>
<Bot />
</MessageAvatar>
) : null}
<MessageContent>
<MessageTyping label="Preparing response" />
</MessageContent>
</Message>
) : null}
</MessageGroup>
</MessageScroller>
<div className="shrink-0 border-t border-border/60 p-2">
<PromptInput
minRows={1}
maxRows={1}
loading={loading}
onSubmit={submit}
onStop={stop}
placeholder={placeholder}
className="border-0 bg-muted shadow-none focus-within:border-transparent"
/>
</div>
</div>
);
}
"use client";
import { motion, useReducedMotion } from "motion/react";
import {
type ComponentPropsWithRef,
createContext,
type ReactNode,
useContext,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { MessageSideContext } from "@/components/agents/message-context";
export {
MessageBubble,
MessageBubbleCollapsible,
MessageBubbleContent,
MessageBubbleGroup,
} from "@/components/agents/message-bubble";
export { MessageScroller } from "@/components/agents/message-scroller";
export type { MessageScrollerProps } from "@/components/agents/message-scroller";
export type MessageFrom = "user" | "assistant";
interface MessageContextValue {
from: MessageFrom;
}
const MessageContext = createContext<MessageContextValue>({
from: "assistant",
});
export interface MessageProps
extends Omit<ComponentPropsWithRef<typeof motion.article>, "children"> {
from: MessageFrom;
/** Plays a trailing-edge pop-up once when this message row mounts. */
animateIn?: boolean;
children: ReactNode;
}
export interface MessageGroupProps extends ComponentPropsWithRef<"div"> {
spacing?: "compact" | "default";
}
export interface MessageAvatarProps extends ComponentPropsWithRef<"div"> {
/** Keep an empty avatar slot so grouped messages remain aligned. */
placeholder?: boolean;
}
export type MessageContentProps = ComponentPropsWithRef<"div">;
export type MessageHeaderProps = ComponentPropsWithRef<"div">;
export type MessageFooterProps = ComponentPropsWithRef<"div">;
export type MessageMarkerProps = ComponentPropsWithRef<"div">;
export interface MessageTypingProps extends ComponentPropsWithRef<"span"> {
label?: string;
}
// A sent row should rise from the live edge without changing measured layout.
const MESSAGE_POP_UP = {
type: "spring",
stiffness: 480,
damping: 32,
mass: 0.62,
} as const;
export function Message({
from,
animateIn = false,
children,
className,
initial,
animate,
transition,
exit,
style,
...props
}: MessageProps) {
const reduce = useReducedMotion() ?? false;
return (
<MessageSideContext.Provider value={from === "user" ? "end" : "start"}>
<MessageContext.Provider value={{ from }}>
<motion.article
data-slot="message"
data-from={from}
aria-label={props["aria-label"] ?? `${from} message`}
initial={
initial ??
(animateIn && !reduce
? {
opacity: 0,
transform: "translateY(8px) scale(0.95)",
}
: false)
}
animate={
animate ??
(animateIn && !reduce
? {
opacity: 1,
transform: "translateY(0px) scale(1)",
}
: { opacity: 1 })
}
exit={
exit ??
(reduce
? { opacity: 0 }
: {
opacity: 0,
transform: "translateY(-3px) scale(0.99)",
})
}
transition={
transition ?? (reduce ? { duration: 0.12 } : MESSAGE_POP_UP)
}
style={{
transformOrigin: from === "user" ? "100% 100%" : "0% 100%",
...style,
}}
className={cn(
"group/message flex w-full items-start gap-2",
from === "user" ? "flex-row-reverse" : "flex-row",
className,
)}
{...props}
>
{children}
</motion.article>
</MessageContext.Provider>
</MessageSideContext.Provider>
);
}
export function MessageGroup({
spacing = "compact",
className,
...props
}: MessageGroupProps) {
return (
<div
data-slot="message-group"
className={cn(
"flex w-full flex-col",
spacing === "compact" ? "gap-1.5" : "gap-4",
className,
)}
{...props}
/>
);
}
export function MessageAvatar({
placeholder = false,
children,
className,
...props
}: MessageAvatarProps) {
return (
<div
data-slot="message-avatar"
aria-hidden={placeholder || undefined}
className={cn(
"grid size-7 shrink-0 place-items-center overflow-hidden rounded-full bg-muted text-xs font-medium text-muted-foreground [&_img]:size-full [&_img]:object-cover [&_svg]:size-3.5",
placeholder && "invisible",
className,
)}
{...props}
>
{children}
</div>
);
}
export function MessageContent({ className, ...props }: MessageContentProps) {
const { from } = useContext(MessageContext);
return (
<div
data-slot="message-content"
className={cn(
"flex min-w-0 flex-1 flex-col gap-1.5",
from === "user" ? "items-end" : "items-start",
className,
)}
{...props}
/>
);
}
export function MessageHeader({ className, ...props }: MessageHeaderProps) {
const { from } = useContext(MessageContext);
return (
<div
data-slot="message-header"
className={cn(
"flex items-center gap-1.5 px-1 text-[11px] leading-none text-muted-foreground",
from === "user" ? "justify-end" : "justify-start",
className,
)}
{...props}
/>
);
}
export function MessageFooter({ className, ...props }: MessageFooterProps) {
const { from } = useContext(MessageContext);
return (
<div
data-slot="message-footer"
className={cn(
"flex min-h-5 items-center gap-1 px-1 text-[11px] text-muted-foreground",
from === "user" ? "justify-end" : "justify-start",
className,
)}
{...props}
/>
);
}
export function MessageMarker({ className, ...props }: MessageMarkerProps) {
return (
<div
data-slot="message-marker"
className={cn(
"mx-auto flex w-fit max-w-[88%] items-center gap-1.5 rounded-full bg-muted/70 px-2.5 py-1 text-center text-xs text-muted-foreground",
className,
)}
{...props}
/>
);
}
export function MessageTyping({
label = "Responding",
className,
...props
}: MessageTypingProps) {
const reduce = useReducedMotion() ?? false;
return (
<span
data-slot="message-typing"
className={cn("inline-flex h-5 items-center gap-1", className)}
{...props}
>
<span className="sr-only">{label}</span>
{[0, 1, 2].map((index) => (
<motion.span
key={index}
aria-hidden="true"
className="size-1 rounded-full bg-current"
animate={
reduce
? { opacity: 0.45 }
: { opacity: [0.28, 0.85, 0.28], y: [0, -2, 0] }
}
transition={{
duration: 1.05,
ease: EASE_OUT,
repeat: Number.POSITIVE_INFINITY,
delay: index * 0.14,
}}
/>
))}
</span>
);
}
"use client";
import { ChevronDown } from "lucide-react";
import {
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
cloneElement,
type ComponentPropsWithRef,
createContext,
type ReactElement,
type ReactNode,
type Ref,
useCallback,
useContext,
useId,
useState,
} from "react";
import {
EASE_OUT,
SPRING_LAYOUT,
SPRING_SWAP,
} from "@/lib/ease";
import { cn } from "@/lib/utils";
import { MessageSideContext } from "@/components/agents/message-context";
export type MessageBubbleVariant =
| "solid"
| "soft"
| "tint"
| "outline"
| "ghost"
| "danger";
export type MessageBubbleAlign = "start" | "end";
interface MessageBubbleContextValue {
align?: MessageBubbleAlign;
animateIn: boolean;
variant: MessageBubbleVariant;
}
const MessageBubbleContext = createContext<MessageBubbleContextValue>({
animateIn: true,
variant: "soft",
});
const MessageBubbleLayoutContext = createContext<() => void>(() => {});
export interface MessageBubbleProps
extends Omit<HTMLMotionProps<"div">, "children"> {
variant?: MessageBubbleVariant;
/** Defaults to the surrounding Message alignment when omitted. */
align?: MessageBubbleAlign;
/** Plays the bubble entrance once when this component mounts. */
animateIn?: boolean;
children?: ReactNode;
}
export interface MessageBubbleContentProps
extends ComponentPropsWithRef<"div"> {
/** Replaces the content element while preserving bubble styling. */
render?: ReactElement;
}
export interface MessageBubbleGroupProps extends ComponentPropsWithRef<"div"> {
spacing?: "compact" | "default";
}
export interface MessageBubbleCollapsibleProps
extends ComponentPropsWithRef<"div"> {
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
collapsedLines?: 2 | 3 | 4 | 5 | 6;
moreLabel?: ReactNode;
lessLabel?: ReactNode;
contentClassName?: string;
triggerClassName?: string;
children?: ReactNode;
}
function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {
return (node: T | null) => {
for (const ref of refs) {
if (typeof ref === "function") ref(node);
else if (ref) ref.current = node;
}
};
}
const BUBBLE_CONTENT_REVEAL = {
duration: 0.12,
ease: EASE_OUT,
delay: 0.04,
} as const;
// Sent bubbles should pop into place quickly with one restrained overshoot.
const BUBBLE_POP = {
type: "spring",
stiffness: 520,
damping: 27,
mass: 0.52,
} as const;
export function MessageBubble({
variant = "soft",
align,
animateIn = false,
className,
children,
initial,
animate,
exit,
transition,
layout,
...props
}: MessageBubbleProps) {
const reduce = useReducedMotion() ?? false;
const messageSide = useContext(MessageSideContext);
const resolvedAlign = align ?? messageSide ?? "start";
return (
<MessageBubbleContext.Provider
value={{ align: resolvedAlign, animateIn, variant }}
>
<motion.div
data-slot="message-bubble"
data-align={resolvedAlign}
data-variant={variant}
layout={layout}
initial={initial ?? false}
animate={animate}
exit={
exit ??
(reduce ? { opacity: 0 } : { opacity: 0, y: -3, scale: 0.99 })
}
transition={transition ?? (reduce ? { duration: 0.12 } : SPRING_LAYOUT)}
className={cn(
"group/bubble flex w-full flex-col",
resolvedAlign === "end" ? "items-end" : "items-start",
className,
)}
{...props}
>
{children}
</motion.div>
</MessageBubbleContext.Provider>
);
}
function bubbleContentClass(
variant: MessageBubbleVariant,
interactive: boolean,
) {
return cn(
"relative z-0 min-w-9 max-w-[82%] rounded-2xl px-3.5 py-2.5 text-sm leading-6 text-foreground",
"[&_a]:font-medium [&_a]:underline [&_a]:underline-offset-4 [&_code]:rounded [&_code]:bg-background/60 [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.9em] [&_ol]:my-2 [&_ol]:list-decimal [&_ol]:pl-5 [&_p+p]:mt-2 [&_pre]:my-2 [&_pre]:overflow-x-auto [&_pre]:rounded-xl [&_pre]:bg-background/60 [&_pre]:p-3 [&_ul]:my-2 [&_ul]:list-disc [&_ul]:pl-5",
variant === "solid" && "text-background",
variant === "ghost" && "w-full max-w-none rounded-none px-0 py-0",
variant === "danger" && "text-destructive",
interactive &&
"cursor-pointer text-left outline-none transition-[background-color,color,transform] duration-150 hover:brightness-[0.98] focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.99]",
);
}
function bubbleSurfaceClass(
variant: MessageBubbleVariant,
align: MessageBubbleAlign,
) {
return cn(
"pointer-events-none absolute inset-0 -z-10 rounded-[inherit]",
align === "end" ? "origin-bottom-right" : "origin-bottom-left",
variant === "solid" && "bg-foreground",
variant === "soft" && "bg-muted",
variant === "tint" && "bg-muted",
variant === "outline" && "border border-border/70 bg-background",
variant === "danger" && "bg-destructive/10",
);
}
export function MessageBubbleContent({
render,
className,
children,
ref,
...props
}: MessageBubbleContentProps) {
const reduce = useReducedMotion() ?? false;
const { align = "start", animateIn, variant } =
useContext(MessageBubbleContext);
const [layoutVersion, setLayoutVersion] = useState(0);
const notifyLayout = useCallback(
() => setLayoutVersion((version) => version + 1),
[],
);
const interactive =
render?.type === "button" || render?.type === "a";
const classes = cn(bubbleContentClass(variant, interactive), className);
const composedChildren = (
<>
{variant !== "ghost" ? (
<motion.span
aria-hidden="true"
layout={reduce ? false : "size"}
layoutDependency={layoutVersion}
initial={
animateIn && !reduce
? {
opacity: 0,
scale: 0.92,
}
: false
}
animate={{ opacity: 1, scale: 1 }}
transition={
reduce
? { duration: 0 }
: {
opacity: { duration: 0.12, ease: EASE_OUT },
scale: BUBBLE_POP,
layout: SPRING_LAYOUT,
}
}
className={bubbleSurfaceClass(variant, align)}
/>
) : null}
<MessageBubbleLayoutContext.Provider value={notifyLayout}>
<motion.div
initial={
animateIn
? reduce
? { opacity: 0 }
: { opacity: 0 }
: false
}
animate={{ opacity: 1 }}
transition={
reduce ? { duration: 0.12, ease: EASE_OUT } : BUBBLE_CONTENT_REVEAL
}
className="relative"
>
{children}
</motion.div>
</MessageBubbleLayoutContext.Provider>
</>
);
if (render) {
const child = render as ReactElement<
Record<string, unknown> & { className?: string; ref?: Ref<HTMLElement> }
>;
return cloneElement(child, {
...props,
ref: mergeRefs(child.props.ref, ref as Ref<HTMLElement> | undefined),
className: cn(classes, child.props.className),
children: composedChildren,
"data-slot": "message-bubble-content",
});
}
return (
<div
ref={ref}
data-slot="message-bubble-content"
className={classes}
{...props}
>
{composedChildren}
</div>
);
}
export function MessageBubbleGroup({
spacing = "compact",
className,
...props
}: MessageBubbleGroupProps) {
return (
<div
data-slot="message-bubble-group"
className={cn(
"flex w-full flex-col",
spacing === "compact" ? "gap-1.5" : "gap-3",
className,
)}
{...props}
/>
);
}
const LINE_CLAMP_CLASS = {
2: "line-clamp-2",
3: "line-clamp-3",
4: "line-clamp-4",
5: "line-clamp-5",
6: "line-clamp-6",
} as const;
export function MessageBubbleCollapsible({
open,
defaultOpen = false,
onOpenChange,
collapsedLines = 4,
moreLabel = "Show more",
lessLabel = "Show less",
contentClassName,
triggerClassName,
className,
children,
...props
}: MessageBubbleCollapsibleProps) {
const reduce = useReducedMotion() ?? false;
const contentId = useId();
const notifyLayout = useContext(MessageBubbleLayoutContext);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const currentOpen = open ?? internalOpen;
const setOpen = useCallback(
(next: boolean) => {
notifyLayout();
if (open === undefined) setInternalOpen(next);
onOpenChange?.(next);
},
[notifyLayout, onOpenChange, open],
);
return (
<div
data-slot="message-bubble-collapsible"
data-state={currentOpen ? "open" : "closed"}
className={cn("w-full", className)}
{...props}
>
<div
id={contentId}
className={cn(
"transition-[mask-image] duration-200",
!currentOpen && LINE_CLAMP_CLASS[collapsedLines],
!currentOpen &&
"[mask-image:linear-gradient(to_bottom,#000_68%,transparent_100%)]",
contentClassName,
)}
>
{children}
</div>
<button
type="button"
aria-expanded={currentOpen}
aria-controls={contentId}
onClick={() => setOpen(!currentOpen)}
className={cn(
"mt-2 inline-flex h-7 items-center gap-1 rounded-full px-2 text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
triggerClassName,
)}
>
<span>{currentOpen ? lessLabel : moreLabel}</span>
<motion.span
aria-hidden="true"
animate={{ rotate: currentOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
>
<ChevronDown className="size-3.5" />
</motion.span>
</button>
</div>
);
}
"use client";
import { ArrowUp, Plus, Square } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
type FormEvent,
type KeyboardEvent,
type ReactNode,
type TextareaHTMLAttributes,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
import { Button } from "@/components/motion/button";
import {
MorphPopover,
MorphPopoverContent,
MorphPopoverTrigger,
} from "@/components/motion/popover-morph";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
} from "@/components/motion/select";
import { SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface PromptModel {
value: string;
label: ReactNode;
icon?: ReactNode;
disabled?: boolean;
}
export interface PromptAction {
value: string;
label: ReactNode;
description?: ReactNode;
icon?: ReactNode;
disabled?: boolean;
}
export interface PromptInputProps extends Omit<
TextareaHTMLAttributes<HTMLTextAreaElement>,
"value" | "defaultValue" | "onChange" | "onSubmit" | "children"
> {
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
models?: PromptModel[];
model?: string;
defaultModel?: string;
onModelChange?: (model: string) => void;
actions?: PromptAction[];
onAction?: (action: string) => void;
onSubmit?: (value: string, model?: string) => void | Promise<void>;
loading?: boolean;
onStop?: () => void;
minRows?: number;
maxRows?: number;
leadingAction?: ReactNode;
className?: string;
}
export function PromptInput({
value,
defaultValue = "",
onValueChange,
models = [],
model,
defaultModel,
onModelChange,
actions = [],
onAction,
onSubmit,
loading = false,
onStop,
minRows = 2,
maxRows = 8,
leadingAction,
className,
disabled,
placeholder = "Ask the agent to do something…",
"aria-label": ariaLabel = "Prompt",
onKeyDown,
...textareaProps
}: PromptInputProps) {
const reduce = useReducedMotion() ?? false;
const textareaRef = useRef<HTMLTextAreaElement>(null);
const measurementRef = useRef<HTMLDivElement>(null);
const [internalValue, setInternalValue] = useState(defaultValue);
const [internalModel, setInternalModel] = useState(
defaultModel ?? models[0]?.value,
);
const [actionsOpen, setActionsOpen] = useState(false);
const currentValue = value ?? internalValue;
const currentModelValue = model ?? internalModel;
const currentModel = models.find(
(option) => option.value === currentModelValue,
);
const canSubmit = Boolean(currentValue.trim()) && !disabled && !loading;
const resizeTextarea = useCallback(() => {
const textarea = textareaRef.current;
const measurement = measurementRef.current;
if (!textarea || !measurement || textarea.value !== currentValue) return;
const lineHeight = 24;
const nextHeight = Math.min(
Math.max(measurement.scrollHeight, minRows * lineHeight),
maxRows * lineHeight,
);
const height = `${nextHeight}px`;
if (textarea.style.height !== height) textarea.style.height = height;
}, [currentValue, maxRows, minRows]);
useLayoutEffect(() => {
resizeTextarea();
}, [resizeTextarea]);
useEffect(() => {
const textarea = textareaRef.current;
if (!textarea || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(resizeTextarea);
observer.observe(textarea);
return () => observer.disconnect();
}, [resizeTextarea]);
const setValue = (next: string) => {
if (value === undefined) setInternalValue(next);
onValueChange?.(next);
};
const setModel = (next: string) => {
if (model === undefined) setInternalModel(next);
onModelChange?.(next);
};
const submit = (event?: FormEvent) => {
event?.preventDefault();
const prompt = currentValue.trim();
if (!prompt || disabled || loading) return;
onSubmit?.(prompt, currentModelValue);
if (value === undefined) setInternalValue("");
textareaRef.current?.focus({ preventScroll: true });
};
const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
onKeyDown?.(event);
if (
event.defaultPrevented ||
event.key !== "Enter" ||
event.shiftKey ||
event.nativeEvent.isComposing
) {
return;
}
event.preventDefault();
submit();
};
return (
<form
onSubmit={submit}
className={cn(
"relative w-full rounded-2xl border border-border/80 bg-background p-2 transition-colors focus-within:border-foreground/25",
disabled && "opacity-60",
className,
)}
>
<div
ref={measurementRef}
aria-hidden="true"
className="pointer-events-none invisible absolute inset-x-2 top-0 whitespace-pre-wrap px-2 text-sm leading-6 [overflow-wrap:break-word]"
>
{`${currentValue}\u200b`}
</div>
<textarea
ref={textareaRef}
value={currentValue}
disabled={disabled}
placeholder={placeholder}
aria-label={ariaLabel}
rows={minRows}
{...textareaProps}
onChange={(event) => setValue(event.target.value)}
onKeyDown={handleKeyDown}
className="scrollbar-hide block w-full resize-none overflow-y-auto bg-transparent px-2 pt-1.5 text-sm leading-6 text-foreground outline-none placeholder:text-muted-foreground/55"
/>
<div className="mt-1 flex min-h-8 items-center gap-1">
{actions.length ? (
<MorphPopover open={actionsOpen} onOpenChange={setActionsOpen}>
<MorphPopoverTrigger>
<Button
type="button"
variant="ghost"
size="icon"
disabled={disabled || loading}
aria-label="Add to prompt"
className="size-8 rounded-full"
>
<motion.span
aria-hidden="true"
animate={{ rotate: actionsOpen ? 45 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
>
<Plus className="size-4" />
</motion.span>
</Button>
</MorphPopoverTrigger>
<MorphPopoverContent
side="top"
align="start"
sideOffset={8}
radius={12}
className="w-56 p-1.5"
>
{actions.map((action) => (
<button
key={action.value}
type="button"
disabled={action.disabled}
onClick={() => {
onAction?.(action.value);
setActionsOpen(false);
}}
className="flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left outline-none transition-colors hover:bg-muted focus-visible:bg-muted disabled:pointer-events-none disabled:opacity-50"
>
{action.icon ? (
<span className="mt-0.5 grid size-5 shrink-0 place-items-center text-muted-foreground [&_svg]:size-4">
{action.icon}
</span>
) : null}
<span className="min-w-0">
<span className="block text-sm text-foreground">
{action.label}
</span>
{action.description ? (
<span className="mt-0.5 block text-xs leading-4 text-muted-foreground">
{action.description}
</span>
) : null}
</span>
</button>
))}
</MorphPopoverContent>
</MorphPopover>
) : null}
{leadingAction}
{models.length ? (
<Select
value={currentModelValue}
onValueChange={setModel}
disabled={disabled || loading}
className="min-w-0"
>
<SelectTrigger className="h-8 w-auto max-w-52 rounded-xl border-0 bg-transparent px-2 py-0 text-xs hover:bg-muted focus-visible:ring-2">
<span className="flex min-w-0 items-center gap-1.5">
{currentModel?.icon ? (
<span className="grid size-4 shrink-0 place-items-center text-muted-foreground [&_svg]:size-3.5">
{currentModel.icon}
</span>
) : null}
<span className="truncate text-muted-foreground">
{currentModel?.label ?? "Choose model"}
</span>
</span>
</SelectTrigger>
<SelectContent className="right-auto w-52 shadow-none">
{models.map((option) => (
<SelectItem
key={option.value}
value={option.value}
disabled={option.disabled}
className="py-2"
>
<span className="flex min-w-0 items-center gap-2">
{option.icon ? (
<span className="grid size-5 shrink-0 place-items-center text-muted-foreground [&_svg]:size-4">
{option.icon}
</span>
) : null}
<span className="min-w-0 truncate text-sm text-foreground">
{option.label}
</span>
</span>
</SelectItem>
))}
</SelectContent>
</Select>
) : null}
<Button
type={loading ? "button" : "submit"}
size="icon"
disabled={loading ? !onStop : !canSubmit}
aria-label={loading ? "Stop generating" : "Send prompt"}
onClick={loading ? onStop : undefined}
className="ml-auto size-8 rounded-full"
>
<AnimatePresence initial={false} mode="popLayout">
<motion.span
key={loading ? "stop" : "send"}
initial={reduce ? { opacity: 1 } : { opacity: 0, y: 3, scale: 0.8 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3, scale: 0.8 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="grid place-items-center"
>
{loading ? (
<Square className="size-3 fill-current" />
) : (
<ArrowUp className="size-4" />
)}
</motion.span>
</AnimatePresence>
</Button>
</div>
</form>
);
}
"use client";
import {
Check,
ChevronDown,
Copy,
RotateCcw,
ThumbsDown,
ThumbsUp,
} from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
type ReactNode,
useCallback,
useEffect,
useId,
useRef,
useState,
} from "react";
import {
type CitationItem,
CitationList,
CitationStack,
} from "@/components/agents/citations";
import { AgentDisclosure } from "@/components/agents/agent-disclosure";
import { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type StreamingResponseStatus = "streaming" | "complete" | "error";
export type StreamingResponseFeedback = "up" | "down" | null;
export interface StreamingResponseProps {
/** Rendered response content. Pass plain text or the output of a Markdown renderer. */
children: ReactNode;
status?: StreamingResponseStatus;
/** Plain-text value copied by the built-in copy action. */
copyText?: string;
/** Overrides the built-in clipboard action. */
onCopy?: () => void | Promise<void>;
onRetry?: () => void;
/** Optional sources shown as a compact footer disclosure after streaming. */
sources?: CitationItem[];
sourcesOpen?: boolean;
defaultSourcesOpen?: boolean;
onSourcesOpenChange?: (open: boolean) => void;
sourceIdPrefix?: string;
feedback?: StreamingResponseFeedback;
defaultFeedback?: StreamingResponseFeedback;
onFeedbackChange?: (feedback: StreamingResponseFeedback) => void;
/** Set false when a surrounding conversation log announces streamed text. */
announce?: boolean;
/** Hides the built-in completion actions without changing response status. */
showActions?: boolean;
className?: string;
contentClassName?: string;
actionsClassName?: string;
}
function ResponseAction({
label,
active = false,
onClick,
children,
}: {
label: string;
active?: boolean;
onClick: () => void;
children: ReactNode;
}) {
const reduce = useReducedMotion() ?? false;
return (
<motion.button
type="button"
aria-label={label}
title={label}
aria-pressed={label === "Helpful" || label === "Not helpful" ? active : undefined}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.9 }}
transition={SPRING_PRESS}
className={cn(
"grid size-7 place-items-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
active && "bg-muted text-foreground",
)}
>
{children}
</motion.button>
);
}
export function StreamingResponse({
children,
status = "streaming",
copyText,
onCopy,
onRetry,
sources = [],
sourcesOpen,
defaultSourcesOpen = false,
onSourcesOpenChange,
sourceIdPrefix,
feedback,
defaultFeedback = null,
onFeedbackChange,
announce = true,
showActions = true,
className,
contentClassName,
actionsClassName,
}: StreamingResponseProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const [copied, setCopied] = useState(false);
const [internalFeedback, setInternalFeedback] =
useState<StreamingResponseFeedback>(defaultFeedback);
const [internalSourcesOpen, setInternalSourcesOpen] =
useState(defaultSourcesOpen);
const copyTimer = useRef<number | undefined>(undefined);
const currentFeedback = feedback ?? internalFeedback;
const currentSourcesOpen = sourcesOpen ?? internalSourcesOpen;
const streaming = status === "streaming";
const complete = status === "complete";
const canCopy = Boolean(copyText || onCopy);
const hasSources = sources.length > 0;
const shouldShowActions =
showActions && !streaming && (canCopy || onRetry || complete || hasSources);
const sourcesContentId = `${baseId}-sources`;
const resolvedSourcePrefix =
sourceIdPrefix ?? `response-source-${baseId.replace(/:/g, "")}`;
useEffect(
() => () => {
if (copyTimer.current) window.clearTimeout(copyTimer.current);
},
[],
);
const handleCopy = useCallback(async () => {
if (onCopy) await onCopy();
else if (copyText) await navigator.clipboard?.writeText(copyText);
setCopied(true);
if (copyTimer.current) window.clearTimeout(copyTimer.current);
copyTimer.current = window.setTimeout(() => setCopied(false), 1600);
}, [copyText, onCopy]);
const setFeedback = (next: Exclude<StreamingResponseFeedback, null>) => {
const value = currentFeedback === next ? null : next;
if (feedback === undefined) setInternalFeedback(value);
onFeedbackChange?.(value);
};
const setSourcesOpen = useCallback(
(next: boolean) => {
if (sourcesOpen === undefined) setInternalSourcesOpen(next);
onSourcesOpenChange?.(next);
},
[onSourcesOpenChange, sourcesOpen],
);
return (
<div
data-state={status}
aria-busy={streaming}
className={cn("w-full", className)}
>
<div
aria-live={announce ? "polite" : "off"}
className={cn(
"text-sm leading-6 text-foreground/90 [&_a]:font-medium [&_a]:underline [&_a]:underline-offset-4 [&_code]:rounded [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.9em] [&_ol]:my-3 [&_ol]:list-decimal [&_ol]:space-y-1 [&_ol]:pl-5 [&_p+p]:mt-3 [&_pre]:my-3 [&_pre]:overflow-x-auto [&_pre]:rounded-xl [&_pre]:border [&_pre]:border-border [&_pre]:bg-muted/45 [&_pre]:p-3 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_ul]:my-3 [&_ul]:list-disc [&_ul]:space-y-1 [&_ul]:pl-5",
contentClassName,
)}
>
{children}
</div>
<AnimatePresence initial={false}>
{shouldShowActions ? (
<motion.div
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: reduce ? 0.12 : 0.22, ease: EASE_OUT }}
className="mt-3"
>
<div className={cn("flex items-center gap-0.5", actionsClassName)}>
{canCopy ? (
<ResponseAction
label={copied ? "Copied" : "Copy response"}
onClick={handleCopy}
>
{copied ? (
<Check className="size-3.5" />
) : (
<Copy className="size-3.5" />
)}
</ResponseAction>
) : null}
{onRetry ? (
<ResponseAction label="Retry response" onClick={onRetry}>
<RotateCcw className="size-3.5" />
</ResponseAction>
) : null}
{complete ? (
<>
<ResponseAction
label="Helpful"
active={currentFeedback === "up"}
onClick={() => setFeedback("up")}
>
<ThumbsUp className="size-3.5" />
</ResponseAction>
<ResponseAction
label="Not helpful"
active={currentFeedback === "down"}
onClick={() => setFeedback("down")}
>
<ThumbsDown className="size-3.5" />
</ResponseAction>
</>
) : null}
{hasSources ? (
<button
type="button"
aria-expanded={currentSourcesOpen}
aria-controls={sourcesContentId}
onClick={() => setSourcesOpen(!currentSourcesOpen)}
className="group ml-1 inline-flex min-h-7 items-center gap-2 rounded-md px-1.5 text-xs text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<CitationStack citations={sources} />
<span className="tabular-nums">
{sources.length} {sources.length === 1 ? "source" : "sources"}
</span>
<motion.span
aria-hidden="true"
animate={{ rotate: currentSourcesOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="text-muted-foreground/50 group-hover:text-muted-foreground"
>
<ChevronDown className="size-3" />
</motion.span>
</button>
) : null}
</div>
{hasSources ? (
<AgentDisclosure
id={sourcesContentId}
open={currentSourcesOpen}
>
<CitationList
citations={sources}
idPrefix={resolvedSourcePrefix}
className="mt-2 rounded-xl bg-muted p-2"
/>
</AgentDisclosure>
) : null}
</motion.div>
) : null}
</AnimatePresence>
</div>
);
}
"use client";
import { createContext } from "react";
export type MessageSide = "start" | "end";
export const MessageSideContext = createContext<MessageSide | undefined>(
undefined,
);
export type {
ButtonLinkProps,
ButtonProps,
ButtonSize,
ButtonVariant,
} from "./base";
export { Button, ButtonLink } from "./base";
export type { MagneticButtonProps } from "./magnetic";
export { MagneticButton } from "./magnetic";
export type { MetallicButtonProps } from "./metallic";
export { MetallicButton } from "./metallic";
export type { ButtonState, StatefulButtonProps } from "./stateful";
export { StatefulButton } from "./stateful";
"use client";
import {
AnimatePresence,
animate,
motion,
useMotionValue,
usePresence,
useReducedMotion,
useTransform,
} from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
type ReactElement,
type ReactNode,
type Ref,
type RefObject,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { usePopoverPortalPosition } from "@/components/motion/popover-position";
import { EASE_OUT } from "@/lib/ease";
import { FOCUSABLE_SELECTOR } from "@/lib/focusable";
import { cn } from "@/lib/utils";
type Side = "top" | "bottom";
type Align = "start" | "end";
type MorphContextValue = {
open: boolean;
setOpen: (open: boolean) => void;
toggle: () => void;
triggerId: string;
contentId: string;
/** The element the panel measures against — see `registerTrigger`. */
triggerRef: React.MutableRefObject<HTMLElement | null>;
registerTrigger: (node: HTMLElement | null) => void;
contentRef: React.MutableRefObject<HTMLDivElement | null>;
/** Arms or disarms moving focus into the panel as it next appears. */
armFocusOnOpen: (armed: boolean) => void;
/** Reads and disarms the flag set by `armFocusOnOpen`. */
takeFocusOnOpen: () => boolean;
};
const MorphContext = createContext<MorphContextValue | null>(null);
function useMorphContext(component: string) {
const ctx = useContext(MorphContext);
if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);
return ctx;
}
export interface MorphPopoverProps {
children: ReactNode;
/** Controlled open state. */
open?: boolean;
/** Uncontrolled initial open state. */
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
className?: string;
}
/**
* A popover whose full-size panel reveals from the corner nearest the trigger
* on one spring, then retraces the same clip on close. Content and surface
* edges keep their size throughout. Closes on outside pointer / Escape.
* Controlled or uncontrolled.
*/
export function MorphPopover({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
className,
}: MorphPopoverProps) {
const baseId = useId();
const [root, setRoot] = useState<HTMLDivElement | null>(null);
const [trigger, setTrigger] = useState<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const controlled = controlledOpen !== undefined;
const open = controlled ? controlledOpen : internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const toggle = useCallback(() => setOpen(!open), [setOpen, open]);
// A keyboard open arms focus for the panel to take as it appears. Any later
// key or pointer press disarms it, so an open the parent declined cannot
// leave it armed for a later open that nobody asked to focus.
const focusOnOpenRef = useRef(false);
const disarmRef = useRef<AbortController | null>(null);
const armFocusOnOpen = useCallback((armed: boolean) => {
disarmRef.current?.abort();
disarmRef.current = null;
focusOnOpenRef.current = armed;
if (!armed) return;
const controller = new AbortController();
const disarm = () => {
focusOnOpenRef.current = false;
controller.abort();
};
const options = { capture: true, signal: controller.signal };
document.addEventListener("keydown", disarm, options);
document.addEventListener("pointerdown", disarm, options);
disarmRef.current = controller;
}, []);
const takeFocusOnOpen = useCallback(() => {
const armed = focusOnOpenRef.current;
armFocusOnOpen(false);
return armed;
}, [armFocusOnOpen]);
useEffect(() => () => disarmRef.current?.abort(), []);
// A trigger normally registers itself through MorphPopoverTrigger. It can't
// when something else already clones the element — a Tooltip wrapping the
// button, say — and an unregistered trigger leaves the panel with nothing to
// measure against, so it renders permanently invisible. The root boxes the
// trigger exactly (the content portals out of it), so it stands in until a
// real trigger registers, and stands in again if that one unmounts. Both are
// state, so a trigger arriving while the panel is open re-anchors it.
const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(
() => ({ current: trigger ?? root }),
[root, trigger],
);
// The panel is a `role="dialog"` and goes inert the moment it closes, so
// focus cannot be left sitting inside it: a dismissal hands it back to the
// trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes
// the focus onward itself when it lands on something focusable — this only
// catches the case where it would otherwise be stranded. When no trigger has
// registered, the root anchor stands in only if it can actually hold focus;
// there is nowhere better than where the keyboard already is, so leave it.
const close = useCallback(() => {
setOpen(false);
const focused = document.activeElement;
const inPanel =
focused instanceof HTMLElement && contentRef.current?.contains(focused);
if (!inPanel) return;
const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);
restore?.focus();
}, [root, setOpen, trigger]);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && close();
const onPointer = (e: PointerEvent) => {
const target = e.target as Node;
if (
root &&
!root.contains(target) &&
!contentRef.current?.contains(target)
)
close();
};
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer);
};
}, [open, root, close]);
const ctx = useMemo<MorphContextValue>(
() => ({
open,
setOpen,
toggle,
triggerId: `${baseId}-trigger`,
contentId: `${baseId}-content`,
triggerRef: anchorRef,
registerTrigger: setTrigger,
contentRef,
armFocusOnOpen,
takeFocusOnOpen,
}),
[open, setOpen, toggle, baseId, anchorRef, armFocusOnOpen, takeFocusOnOpen],
);
return (
<MorphContext.Provider value={ctx}>
<div ref={setRoot} className={cn("relative inline-flex", className)}>
{children}
</div>
</MorphContext.Provider>
);
}
export interface MorphPopoverTriggerProps {
children: ReactElement;
}
function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {
return (node: T | null) => {
for (const ref of refs) {
if (typeof ref === "function") ref(node);
else if (ref && typeof ref === "object")
(ref as React.MutableRefObject<T | null>).current = node;
}
};
}
/** Wraps a single element, toggling the popover on click. */
export function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {
const ctx = useMorphContext("MorphPopoverTrigger");
const child = children as ReactElement<Record<string, unknown>>;
const childOnClick = child?.props?.onClick as
| ((e: unknown) => void)
| undefined;
const childOnKeyDown = child?.props?.onKeyDown as
| ((e: unknown) => void)
| undefined;
const childOnPointerDown = child?.props?.onPointerDown as
| ((e: unknown) => void)
| undefined;
// Set by an Enter or Space keydown on the trigger, cleared by a pointer
// press, read by the click that follows.
const keyboardRef = useRef(false);
const childRef = (child?.props as { ref?: Ref<HTMLElement> } | undefined)
?.ref;
// Register once per actual ref change, not once per open-state render.
const mergedRef = useMemo(
() => mergeRefs(childRef, ctx.registerTrigger),
[childRef, ctx.registerTrigger],
);
if (!isValidElement(children)) return children;
return cloneElement(child, {
id: ctx.triggerId,
ref: mergedRef,
onKeyDown: (e: unknown) => {
childOnKeyDown?.(e);
const key = (e as { key?: string } | undefined)?.key;
keyboardRef.current = key === "Enter" || key === " ";
},
onPointerDown: (e: unknown) => {
childOnPointerDown?.(e);
keyboardRef.current = false;
},
onClick: (e: unknown) => {
childOnClick?.(e);
// Enter and Space reach here as a click with `detail` 0 after their
// keydown on this element. A pointer click counts at least 1, and a
// scripted click() has no keydown before it. Only a keyboard open
// moves focus into the panel.
const keyboard =
keyboardRef.current &&
(e as { detail?: number } | undefined)?.detail === 0;
keyboardRef.current = false;
ctx.armFocusOnOpen(!ctx.open && keyboard);
ctx.toggle();
},
"aria-haspopup": "dialog",
"aria-expanded": ctx.open,
"aria-controls": ctx.open ? ctx.contentId : undefined,
});
}
// Full-distance clip travel needs a shorter curve than SPRING_PANEL's slow
// overdamped tail. A non-bouncing spring reaches its rest within 260 ms.
const MORPH_ENTER = { type: "spring", duration: 0.26, bounce: 0 } as const;
const MORPH_EXIT = { duration: 0.2, ease: EASE_OUT } as const;
// Keep the panel and content at their final size. An inset clip reveals the
// nearest corner without scaling borders, shadows or keyboard-focus geometry.
// A full-size clip keeps content at its final coordinates without box-to-box
// scale correction. One progress value keeps clip and opacity synchronized;
// clip-path and the shadow may paint, so this is not a compositor-only morph.
function clipAt(side: Side, align: Align, radius: number, inset: number) {
return `inset(${side === "top" ? inset : 0}% ${align === "start" ? inset : 0}% ${side === "bottom" ? inset : 0}% ${align === "end" ? inset : 0}% round ${radius}px)`;
}
export interface MorphPopoverContentProps {
children: ReactNode;
side?: Side;
align?: Align;
/** Gap between trigger and panel, in px. Default 8. */
sideOffset?: number;
/** Panel corner radius, in px. Default 16. */
radius?: number;
/** Draw the surface shadow. Default true. */
shadow?: boolean;
/**
* Runs after the portalled surface is positioned and visible. Passing it
* hands focus to the caller: the panel then moves no focus on its own.
*/
onOpenAutoFocus?: (content: HTMLDivElement) => void;
/**
* Element to focus when the trigger opens the panel by keyboard. Defaults
* to the first focusable element in the panel, or the panel itself. A
* pointer open does not move focus. Ignored with `onOpenAutoFocus`.
*/
initialFocus?: RefObject<HTMLElement | null>;
className?: string;
}
export function MorphPopoverContent(props: MorphPopoverContentProps) {
const ctx = useMorphContext("MorphPopoverContent");
const [portalReady, setPortalReady] = useState(false);
useEffect(() => setPortalReady(true), []);
if (!portalReady) return null;
return createPortal(
<AnimatePresence>
{ctx.open && <MorphPopoverSurface {...props} />}
</AnimatePresence>,
document.body,
);
}
// Measurement belongs to the mounted portal session: reopening must not start
// an entrance at the previous session's coordinates before measuring this one.
function MorphPopoverSurface({
children,
side = "bottom",
align = "end",
sideOffset = 8,
radius = 16,
shadow = true,
onOpenAutoFocus,
initialFocus,
className,
}: MorphPopoverContentProps) {
const ctx = useMorphContext("MorphPopoverContent");
const reduce = useReducedMotion() ?? false;
const [isPresent, safeToRemove] = usePresence();
const layout = usePopoverPortalPosition(
ctx.triggerRef,
ctx.contentRef,
isPresent,
);
const preferredLeft = layout
? align === "end"
? layout.trigger.left + layout.trigger.width - layout.content.width
: layout.trigger.left
: 0;
// Keep larger compositions, such as calendars, inside the viewport. Prefer
// the requested side, then use the roomier side when it cannot fit there.
const gutter = 12;
const below = layout
? Math.max(
0,
window.innerHeight -
layout.trigger.top -
layout.trigger.height -
sideOffset -
gutter,
)
: 0;
const above = layout
? Math.max(0, layout.trigger.top - sideOffset - gutter)
: 0;
const requestedSpace = side === "bottom" ? below : above;
const otherSpace = side === "bottom" ? above : below;
const resolvedSide =
layout &&
layout.content.height > requestedSpace &&
otherSpace > requestedSpace
? side === "bottom"
? "top"
: "bottom"
: side;
const availableHeight = resolvedSide === "bottom" ? below : above;
const left = layout
? Math.max(
gutter,
Math.min(
preferredLeft,
window.innerWidth - layout.content.width - gutter,
),
)
: 0;
const top = layout
? resolvedSide === "bottom"
? layout.trigger.top + layout.trigger.height + sideOffset
: Math.max(
gutter,
layout.trigger.top - layout.content.height - sideOffset,
)
: 0;
const progress = useMotionValue(0);
const clipPath = useTransform(progress, (p) =>
clipAt(resolvedSide, align, radius, 92 * (1 - p)),
);
const surfaceOpacity = useTransform(progress, [0, 0.15], [0, 1]);
// Reduced motion has no travel, so a short fade carries the whole entrance
// and exit on its own.
const fade = useMotionValue(reduce ? 0 : 1);
const ready = layout !== null;
const focusedOnOpen = useRef(false);
useEffect(() => {
if (
!ready ||
!isPresent ||
focusedOnOpen.current ||
!ctx.contentRef.current
)
return;
focusedOnOpen.current = true;
onOpenAutoFocus?.(ctx.contentRef.current);
}, [ready, isPresent, ctx.contentRef, onOpenAutoFocus]);
// `safeToRemove` is a new function on every render: AnimatePresence
// rebuilds its context each time its parent renders. Read it through a ref
// so a render during the exit (a consumer's state change, a list streaming
// in) does not restart the exit from where it got to — restarted every
// render, it would close in ever smaller steps and never report completion,
// leaving an inert, invisible panel mounted for good.
const safeToRemoveRef = useRef(safeToRemove);
useLayoutEffect(() => {
safeToRemoveRef.current = safeToRemove;
});
useEffect(() => {
if (!ready) {
if (!isPresent) safeToRemoveRef.current?.();
return;
}
const settle = () => {
if (!isPresent) safeToRemoveRef.current?.();
};
if (reduce) {
progress.jump(1);
const animation = animate(fade, isPresent ? 1 : 0, {
duration: 0.12,
onComplete: settle,
});
return () => animation.stop();
}
const animation = animate(progress, isPresent ? 1 : 0, {
...(isPresent ? MORPH_ENTER : MORPH_EXIT),
onComplete: settle,
});
return () => animation.stop();
}, [fade, progress, ready, isPresent, reduce]);
// The wrapper stays `visibility: hidden` until the first measurement, and
// focus() inside a hidden subtree is silently ignored. So move focus in the
// commit that makes the panel visible, not when it mounts. A CSS transition
// on `visibility` can still hold the controls hidden for a moment after
// that commit (a reduced-motion reset that gives every element a short
// transition-duration does), so while focus rests on the panel or has not
// moved, each such transition that ends tries the candidates again, until
// the user presses a key or pointer. The effect runs once per open, so it
// reads the caller's props through refs: a new ref or callback passed
// mid-open must not tear down a pending retry.
const initialFocusRef = useRef(initialFocus);
const callerFocusesRef = useRef(onOpenAutoFocus !== undefined);
useLayoutEffect(() => {
initialFocusRef.current = initialFocus;
callerFocusesRef.current = onOpenAutoFocus !== undefined;
});
const { contentRef, takeFocusOnOpen } = ctx;
useLayoutEffect(() => {
if (!ready || !isPresent) return;
if (!takeFocusOnOpen() || callerFocusesRef.current) return;
const panel = contentRef.current;
const wrapper = panel?.parentElement;
if (!panel || !wrapper) return;
const from = document.activeElement;
const unmoved = () =>
document.activeElement === from || document.activeElement === panel;
// The selector also matches elements focus() refuses: a hidden input, a
// disabled button that carries a tabindex, anything under display: none.
// Keep the first candidate that takes focus, else hold it on the panel.
const focusFirst = () => {
const candidates = [
initialFocusRef.current?.current,
...panel.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
];
for (const candidate of candidates) {
if (!candidate) continue;
candidate.focus({ preventScroll: true });
if (unmoved()) continue;
// preventScroll keeps the page still, but it also stops the panel's
// own scroll area from bringing a row below the fold into view.
candidate.scrollIntoView?.({ block: "nearest" });
return true;
}
panel.focus({ preventScroll: true });
return false;
};
if (focusFirst()) return;
const retry = (event: TransitionEvent) => {
if (event.propertyName !== "visibility") return;
if (!unmoved() || focusFirst()) stop();
};
const stop = () => {
wrapper.removeEventListener("transitionend", retry);
document.removeEventListener("keydown", stop, true);
document.removeEventListener("pointerdown", stop, true);
};
wrapper.addEventListener("transitionend", retry);
document.addEventListener("keydown", stop, true);
document.addEventListener("pointerdown", stop, true);
return stop;
}, [ready, isPresent, contentRef, takeFocusOnOpen]);
return (
<motion.div
data-morph-popover-portal=""
inert={!isPresent}
style={{
left,
top,
opacity: reduce ? fade : surfaceOpacity,
pointerEvents: isPresent ? "auto" : "none",
visibility: layout ? "visible" : "hidden",
}}
// A drop-shadow follows the clipped surface; box-shadow would be cut
// off by its own clip. Caller surface classes retain their old target.
className={cn(
"fixed z-[9999]",
shadow && "[filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]",
)}
>
<motion.div
ref={ctx.contentRef}
id={ctx.contentId}
role="dialog"
aria-labelledby={ctx.triggerId}
tabIndex={-1}
style={{
clipPath: reduce ? undefined : clipPath,
borderRadius: radius,
maxHeight: layout ? availableHeight : undefined,
overflowX: "hidden",
overflowY: "auto",
}}
className={cn(
// The panel holds focus when nothing inside it can. An inset ring
// stays inside the clip that would cut off an outline.
"overflow-hidden border border-border bg-background outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
className,
)}
>
{children}
</motion.div>
</motion.div>
);
}
"use client";
import { Check, ChevronDown } from "lucide-react";
import {
animate,
type MotionValue,
motion,
useMotionValue,
useMotionValueEvent,
useReducedMotion,
useTransform,
type Variants,
} from "motion/react";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { type ListboxRow, useListbox } from "@/lib/hooks/use-listbox";
import { cn } from "@/lib/utils";
// One progress value drives the surface, gap, corners and chevron. This short
// spring suits the full reveal distance; each reader clamps its small internal
// overshoot, so all visible endpoints settle together. Rows share a short
// reveal so long lists have no late entries.
const UNFOLD_SPRING = {
type: "spring",
visualDuration: 0.2,
bounce: 0.12,
} as const;
// Exits are faster than entrances: the panel folds back on a short ease.
const UNFOLD_EXIT = { duration: 0.2, ease: EASE_OUT } as const;
const RADIUS = 12;
// How far the open panel sits from the trigger once it has pulled away.
const GAP = 8;
// The surface starts as a thin lip flush against the trigger's edge.
const LIP = 8;
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
const ITEM_VARIANTS: Variants = {
// A shared short reveal keeps late rows in long, scrolled lists ready with
// the surface. Per-index staggering can delay visible rows by over a second.
hidden: { opacity: 0, y: -4, transition: { duration: 0.08, ease: EASE_OUT } },
show: { opacity: 1, y: 0, transition: { duration: 0.12, ease: EASE_OUT } },
};
type Placement = "bottom" | "top";
interface SelectContextValue {
value: string | undefined;
open: boolean;
setOpen: (open: boolean) => void;
select: (value: string) => void;
register: (value: string, label: string, disabled: boolean) => void;
unregister: (value: string) => void;
labelFor: (value: string | undefined) => string | undefined;
rows: ListboxRow[];
/** Closes the panel; focus inside it returns to the trigger. */
close: () => void;
reduce: boolean;
progress: MotionValue<number>;
triggerId: string;
listId: string;
disabled: boolean;
placement: Placement;
setPlacement: (p: Placement) => void;
}
const SelectContext = createContext<SelectContextValue | null>(null);
// The option keyboard focus is on, resolved during render by the content.
const ActiveOptionContext = createContext<string | undefined>(undefined);
function useSelectContext(component: string) {
const ctx = useContext(SelectContext);
if (!ctx) throw new Error(`${component} must be used within <Select>`);
return ctx;
}
export interface SelectProps {
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/**
* Controlled open state of the panel. A layout that stacks selects can hold
* this to keep exactly one panel open — the panel is absolutely positioned
* inside its field, so two open at once paint over each other's options.
*/
open?: boolean;
/** Uncontrolled initial open state. Default false. */
defaultOpen?: boolean;
/**
* Fires whenever the panel opens or closes. The panel is absolutely
* positioned inside the field, so a layout that stacks selects has to know
* which one is open to paint it above its neighbours.
*/
onOpenChange?: (open: boolean) => void;
disabled?: boolean;
className?: string;
children: ReactNode;
}
export function Select({
value,
defaultValue,
onValueChange,
open: openProp,
defaultOpen = false,
onOpenChange,
disabled = false,
className,
children,
}: SelectProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const [internal, setInternal] = useState(defaultValue);
const [labels, setLabels] = useState<
Map<string, { label: string; disabled: boolean }>
>(new Map());
const [placement, setPlacement] = useState<Placement>("bottom");
const controlled = value !== undefined;
const current = controlled ? value : internal;
const openControlled = openProp !== undefined;
const open = openControlled ? openProp : internalOpen;
const progress = useMotionValue(open ? 1 : 0);
const setOpen = useCallback(
(next: boolean) => {
if (!openControlled) setInternalOpen(next);
onOpenChange?.(next);
},
[onOpenChange, openControlled],
);
// The panel turns inert as it closes, which would drop focus held inside it
// on the page body. Hand it back to the trigger before that happens.
const close = useCallback(() => {
const trigger = document.getElementById(`${baseId}-trigger`);
if (
rootRef.current?.contains(document.activeElement) &&
document.activeElement !== trigger
)
trigger?.focus();
setOpen(false);
}, [baseId, setOpen]);
const select = useCallback(
(next: string) => {
if (!controlled) setInternal(next);
onValueChange?.(next);
close();
},
[controlled, onValueChange, close],
);
const register = useCallback((v: string, label: string, disabled: boolean) => {
setLabels((m) => {
const entry = m.get(v);
if (entry?.label === label && entry.disabled === disabled) return m;
return new Map(m).set(v, { label, disabled });
});
}, []);
const unregister = useCallback((v: string) => {
setLabels((m) => {
if (!m.has(v)) return m;
const next = new Map(m);
next.delete(v);
return next;
});
}, []);
// Reduced motion has no travel, so the progress only carries a short fade.
useEffect(() => {
const animation = animate(
progress,
open ? 1 : 0,
reduce ? { duration: 0.12 } : open ? UNFOLD_SPRING : UNFOLD_EXIT,
);
return () => animation.stop();
}, [open, progress, reduce]);
// close on outside pointer / escape
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && close();
const onPointer = (e: PointerEvent) => {
if (rootRef.current && !rootRef.current.contains(e.target as Node))
setOpen(false);
};
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer);
};
}, [open, setOpen, close]);
const rows = useMemo(
() =>
Array.from(labels, ([id, entry]) => ({
id,
label: entry.label,
disabled: entry.disabled,
})),
[labels],
);
const ctx = useMemo<SelectContextValue>(
() => ({
value: current,
open,
setOpen,
select,
register,
unregister,
labelFor: (v) => (v === undefined ? undefined : labels.get(v)?.label),
rows,
close,
reduce,
progress,
triggerId: `${baseId}-trigger`,
listId: `${baseId}-list`,
disabled,
placement,
setPlacement,
}),
[
current,
open,
setOpen,
select,
register,
unregister,
labels,
rows,
close,
reduce,
progress,
baseId,
disabled,
placement,
],
);
return (
<SelectContext.Provider value={ctx}>
<div ref={rootRef} className={cn("relative", className)}>
{children}
</div>
</SelectContext.Provider>
);
}
export interface SelectTriggerProps {
className?: string;
children: ReactNode;
}
export function SelectTrigger({ className, children }: SelectTriggerProps) {
const ctx = useSelectContext("SelectTrigger");
const isTop = ctx.placement === "top";
// The edge facing the panel flattens while the panel is attached to it and
// rounds back as the panel pulls away — the two pinch apart — on the same
// curve the panel moves on. The far edge stays rounded.
const nearRadius = useTransform(
ctx.progress,
[0, 0.2, 0.4, 1],
[RADIUS, 0, 0, RADIUS],
);
const rotate = useTransform(ctx.progress, (p) =>
ctx.reduce ? (ctx.open ? 180 : 0) : Math.min(1, Math.max(0, p)) * 180,
);
return (
<motion.button
type="button"
id={ctx.triggerId}
disabled={ctx.disabled}
aria-haspopup="listbox"
aria-expanded={ctx.open}
aria-controls={ctx.listId}
onClick={() => ctx.setOpen(!ctx.open)}
onKeyDown={(event) => {
if (
!ctx.open &&
(event.key === "ArrowDown" || event.key === "ArrowUp")
) {
event.preventDefault();
ctx.setOpen(true);
}
}}
style={{
borderTopLeftRadius: ctx.reduce || !isTop ? RADIUS : nearRadius,
borderTopRightRadius: ctx.reduce || !isTop ? RADIUS : nearRadius,
borderBottomLeftRadius: ctx.reduce || isTop ? RADIUS : nearRadius,
borderBottomRightRadius: ctx.reduce || isTop ? RADIUS : nearRadius,
}}
className={cn(
"relative z-10 flex w-full items-center justify-between gap-2 border border-border bg-background px-3 py-2 text-sm text-foreground outline-none transition-colors",
"hover:border-(--color-border-strong) focus-visible:ring-2 focus-visible:ring-foreground/20",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
{children}
<motion.span
aria-hidden
style={{ rotate }}
className="text-muted-foreground"
>
<ChevronDown className="h-4 w-4" />
</motion.span>
</motion.button>
);
}
export interface SelectValueProps {
placeholder?: string;
className?: string;
}
export function SelectValue({ placeholder, className }: SelectValueProps) {
const ctx = useSelectContext("SelectValue");
const label = ctx.labelFor(ctx.value);
return (
<span
className={cn(label ? "text-foreground" : "text-muted-foreground", className)}
>
{label ?? placeholder ?? "Select"}
</span>
);
}
export interface SelectContentProps {
className?: string;
children: ReactNode;
}
export function SelectContent({ className, children }: SelectContentProps) {
const ctx = useSelectContext("SelectContent");
const panelRef = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(0);
const { open, progress, reduce, setPlacement } = ctx;
const { activeId, onKeyDown } = useListbox({
open,
rows: ctx.rows,
selected: ctx.value,
list: panelRef,
});
// Keep descendants laid out while hidden: display:none resets nested
// scrollers in Chromium. Collapse only the hidden outer footprint after
// exit so it cannot extend page scrolling. Opening restores the full box
// before measurement or focus; neither layout change is animated.
const [exiting, setExiting] = useState(false);
const [wasOpen, setWasOpen] = useState(open);
if (open !== wasOpen) {
setWasOpen(open);
if (!open) setExiting(true);
}
const present = open || exiting;
useMotionValueEvent(progress, "animationComplete", () => {
if (progress.get() === 0) setExiting(false);
});
useLayoutEffect(() => {
const node = panelRef.current;
if (!node || !present) return;
const measure = () => setHeight(node.offsetHeight);
measure();
const observer = new ResizeObserver(measure);
observer.observe(node);
return () => observer.disconnect();
}, [present]);
// On open, flip upward when there isn't room below and there's more above.
useLayoutEffect(() => {
if (!open) return;
const trigger = document.getElementById(ctx.triggerId);
const node = panelRef.current;
if (!trigger || !node) return;
const rect = trigger.getBoundingClientRect();
const h = node.offsetHeight;
const below = window.innerHeight - rect.bottom;
const above = rect.top;
setPlacement(below < h + 16 && above > below ? "top" : "bottom");
}, [open, ctx.triggerId, setPlacement]);
const isTop = ctx.placement === "top";
// Reveal a full-size panel from its near edge. No ancestor scales the list,
// so rows, borders and shadow keep their natural thickness. The clip and
// corner writes can paint; only the gap uses a transform. All read one
// progress value, with no animated layout properties.
const ready = height > 0 && !reduce;
const fromY = ready ? (isTop ? GAP : -GAP) : 0;
const detach = useTransform(progress, [0.4, 1], [0, 1]);
const y = useTransform(detach, (d) => lerp(fromY, 0, d));
const nearRadius = useTransform(detach, (d) => (ready ? RADIUS * d : RADIUS));
const borderRadius = useTransform(nearRadius, (near) =>
isTop
? `${RADIUS}px ${RADIUS}px ${near}px ${near}px`
: `${near}px ${near}px ${RADIUS}px ${RADIUS}px`,
);
const clipPath = useTransform([progress, nearRadius], ([p, near]: number[]) => {
if (!ready) return "none";
// Clamp overshoot so the clip never extends into the trigger or exposes
// overflowing children. At rest remove it so the native shadow is whole.
const reveal = Math.min(1, Math.max(0, p));
if (reveal === 1) return "none";
const hidden = Math.max(0, (height - LIP) * (1 - reveal));
const inset = isTop ? `${hidden}px 0 0 0` : `0 0 ${hidden}px 0`;
const corners = isTop
? `${RADIUS}px ${RADIUS}px ${near}px ${near}px`
: `${near}px ${near}px ${RADIUS}px ${RADIUS}px`;
return `inset(${inset} round ${corners})`;
});
// The surface materialises over its first frames rather than popping in as
// a lip; with reduced motion the fade is the whole entrance.
const opacity = useTransform(progress, reduce ? [0, 1] : [0, 0.12], [0, 1]);
return (
<motion.div
ref={panelRef}
id={ctx.listId}
role="listbox"
aria-labelledby={ctx.triggerId}
aria-hidden={!open}
inert={!open}
onKeyDown={(event) => {
// Tab leaves the list from the trigger, so focus moves on to the
// control after the select rather than into the closing panel.
if (event.key === "Tab") ctx.close();
else onKeyDown(event);
}}
style={{
visibility: present ? undefined : "hidden",
maxHeight: present ? undefined : 0,
borderWidth: present ? undefined : 0,
y,
clipPath,
borderRadius,
opacity,
pointerEvents: open ? "auto" : "none",
marginTop: isTop ? 0 : GAP,
marginBottom: isTop ? GAP : 0,
}}
// flush against the trigger, then separates into its own rounded pill;
// sits above or below depending on available space
className={cn(
"absolute left-0 right-0 z-20 overflow-hidden border border-border bg-background shadow-lg",
isTop ? "bottom-full" : "top-full",
className,
)}
>
<ActiveOptionContext.Provider value={activeId}>
<motion.div
initial={false}
animate={open ? "show" : "hidden"}
className="p-1"
>
{children}
</motion.div>
</ActiveOptionContext.Provider>
</motion.div>
);
}
export interface SelectItemProps {
value: string;
disabled?: boolean;
className?: string;
children: ReactNode;
}
export function SelectItem({
value,
disabled = false,
className,
children,
}: SelectItemProps) {
const ctx = useSelectContext("SelectItem");
const activeId = useContext(ActiveOptionContext);
const selected = ctx.value === value;
const label = typeof children === "string" ? children : value;
useLayoutEffect(() => {
ctx.register(value, label, disabled);
}, [ctx.register, value, label, disabled]);
useLayoutEffect(() => () => ctx.unregister(value), [ctx.unregister, value]);
return (
<motion.div variants={ctx.reduce ? undefined : ITEM_VARIANTS}>
<button
type="button"
role="option"
aria-selected={selected}
disabled={disabled}
// One tab stop: the active option, which focus follows while open.
tabIndex={activeId === value ? 0 : -1}
data-listbox-id={value}
onClick={() => ctx.select(value)}
className={cn(
"flex w-full items-center justify-between gap-2 rounded-lg px-2.5 py-1.5 text-left text-sm outline-none transition-colors",
selected
? "bg-muted text-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:bg-muted",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
{children}
{selected ? <Check className="h-3.5 w-3.5 shrink-0" /> : null}
</button>
</motion.div>
);
}
"use client";
import { motion, type HTMLMotionProps, useReducedMotion } from "motion/react";
import type { CSSProperties } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface AgentDisclosureProps
extends Omit<HTMLMotionProps<"div">, "animate" | "initial"> {
open: boolean;
openHeight?: CSSProperties["height"];
}
/** Shared transform-only reveal for collapsible agent content. */
export function AgentDisclosure({
open,
openHeight = "auto",
className,
style,
transition,
...props
}: AgentDisclosureProps) {
const reduce = useReducedMotion() ?? false;
return (
<motion.div
{...props}
aria-hidden={!open}
inert={!open}
initial={false}
animate={
reduce
? { opacity: open ? 1 : 0 }
: {
opacity: open ? 1 : 0,
clipPath: open ? "inset(0 0 0% 0)" : "inset(0 0 100% 0)",
y: open ? 0 : -4,
}
}
transition={
transition ?? {
duration: reduce ? 0 : open ? 0.22 : 0.14,
ease: EASE_OUT,
}
}
className={cn("overflow-hidden", className)}
style={{
...style,
height: open ? openHeight : 0,
pointerEvents: open ? undefined : "none",
transformOrigin: "top",
}}
/>
);
}
"use client";
import { BookOpenText, ChevronDown, ExternalLink, Globe2 } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
type ReactNode,
useCallback,
useId,
useState,
} from "react";
import { AgentDisclosure } from "@/components/agents/agent-disclosure";
import { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from "@/lib/ease";
import { useFavicon } from "@/lib/hooks/use-favicon";
import { cn } from "@/lib/utils";
export interface CitationItem {
id: string;
title: ReactNode;
domain?: ReactNode;
url?: string;
/**
* Replaces the URL favicon, e.g. a document icon for non-web sources. An svg
* child is sized to match the favicon; falsy values fall back to the favicon.
*/
icon?: ReactNode;
}
export interface CitationsProps {
citations: CitationItem[];
title?: ReactNode;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
idPrefix?: string;
className?: string;
}
export interface CitationProps {
citationId: string;
index: number;
/** Must match the related Citations idPrefix. */
idPrefix: string;
/**
* Accessible name for the marker. Defaults to `View citation {index}`. Include
* the index so voice control users can say the number they see.
*/
label?: string;
className?: string;
}
export interface CitationListProps {
citations: CitationItem[];
idPrefix?: string;
className?: string;
}
export interface CitationStackProps {
citations: CitationItem[];
limit?: number;
className?: string;
}
function citationTargetId(prefix: string, citationId: string) {
return `${prefix}-${citationId.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
}
export function Citation({
citationId,
index,
idPrefix,
label,
className,
}: CitationProps) {
return (
<a
href={`#${citationTargetId(idPrefix, citationId)}`}
aria-label={label ?? `View citation ${index}`}
className={cn(
"mx-0.5 inline-flex min-w-4 -translate-y-0.5 items-center justify-center rounded-md bg-muted/60 px-1 py-0.5 text-[10px] font-semibold leading-none text-muted-foreground no-underline outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
className,
)}
>
{index}
</a>
);
}
export function CitationFavicon({
url,
icon,
className,
}: {
url?: string;
/** Drawn instead of the favicon when truthy. */
icon?: ReactNode;
className?: string;
}) {
const favicon = useFavicon(icon ? undefined : url);
return (
<span
aria-hidden="true"
className={cn(
"grid size-5 shrink-0 place-items-center text-muted-foreground [&>svg]:size-3.5",
className,
)}
>
{icon ? (
icon
) : favicon.src ? (
// biome-ignore lint/performance/noImgElement: Dynamic cross-site favicons keep this framework-agnostic registry component portable.
<img
ref={favicon.ref}
src={favicon.src}
alt=""
width={16}
height={16}
referrerPolicy="no-referrer"
className="size-4 rounded-sm object-contain"
/>
) : (
<Globe2 className="size-3.5" />
)}
</span>
);
}
export function CitationStack({
citations,
limit = 3,
className,
}: CitationStackProps) {
return (
<span
aria-hidden="true"
className={cn("flex -space-x-1.5", className)}
>
{citations.slice(0, limit).map((citation) => (
<CitationFavicon
key={citation.id}
url={citation.url}
icon={citation.icon}
className="size-6 rounded-full bg-background ring-2 ring-background"
/>
))}
</span>
);
}
function CitationRow({
citation,
index,
idPrefix,
}: {
citation: CitationItem;
index: number;
idPrefix: string;
}) {
const content = (
<>
<CitationFavicon url={citation.url} icon={citation.icon} />
<span className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5">
<span className="truncate text-sm font-medium text-foreground/80 transition-colors group-hover/citation:text-foreground">
{citation.title}
</span>
{citation.domain ? (
<span className="min-w-0 truncate text-xs text-muted-foreground/60">
{citation.domain}
</span>
) : null}
</span>
<span className="flex shrink-0 items-center gap-1.5">
<span className="grid size-5 place-items-center rounded-md bg-foreground/[0.05] text-[10px] font-semibold tabular-nums text-muted-foreground">
{index}
</span>
{citation.url ? (
<ExternalLink className="size-3.5 text-muted-foreground/40 transition-colors group-hover/citation:text-muted-foreground" />
) : null}
</span>
</>
);
const className =
"group/citation flex items-center gap-2 rounded-md px-1.5 py-1 outline-none focus-visible:ring-2 focus-visible:ring-ring";
const id = citationTargetId(idPrefix, citation.id);
return citation.url ? (
<a
id={id}
href={citation.url}
target="_blank"
rel="noreferrer noopener"
className={className}
>
{content}
</a>
) : (
<div id={id} className={className}>
{content}
</div>
);
}
export function CitationList({
citations,
idPrefix,
className,
}: CitationListProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const resolvedPrefix =
idPrefix ?? `citation-list-${baseId.replace(/:/g, "")}`;
return (
<div className={cn("grid gap-0.5", className)}>
<AnimatePresence mode="popLayout">
{citations.map((citation, index) => (
<motion.div
layout="position"
key={citation.id}
initial={reduce ? { opacity: 1 } : { opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3 }}
transition={
reduce
? { duration: 0 }
: {
opacity: { duration: 0.18, ease: EASE_OUT },
y: SPRING_LAYOUT,
layout: SPRING_LAYOUT,
}
}
>
<CitationRow
citation={citation}
index={index + 1}
idPrefix={resolvedPrefix}
/>
</motion.div>
))}
</AnimatePresence>
</div>
);
}
export function Citations({
citations,
title = "Sources",
open,
defaultOpen = false,
onOpenChange,
idPrefix,
className,
}: CitationsProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const contentId = `${baseId}-content`;
const resolvedPrefix =
idPrefix ?? `citation-${baseId.replace(/:/g, "")}`;
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const currentOpen = open ?? internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (open === undefined) setInternalOpen(next);
onOpenChange?.(next);
},
[onOpenChange, open],
);
return (
<div className={cn("w-full text-sm", className)}>
<button
type="button"
aria-expanded={currentOpen}
aria-controls={contentId}
onClick={() => setOpen(!currentOpen)}
className="group -ml-1 flex min-h-8 items-center gap-2 rounded-lg px-1 text-left text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<BookOpenText className="size-4" />
<span className="font-medium">{title}</span>
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-semibold tabular-nums">
{citations.length}
</span>
<motion.span
aria-hidden="true"
animate={{ rotate: currentOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="text-muted-foreground/60"
>
<ChevronDown className="size-3.5" />
</motion.span>
</button>
<AgentDisclosure
id={contentId}
open={currentOpen}
>
<CitationList
citations={citations}
idPrefix={resolvedPrefix}
className="mt-1"
/>
</AgentDisclosure>
</div>
);
}
"use client";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
type PointerEvent,
type ReactNode,
useCallback,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { cn } from "@/lib/utils";
export type ButtonVariant = "primary" | "secondary" | "ghost" | "outline";
export type ButtonSize = "sm" | "md" | "lg" | "icon";
export interface ButtonProps extends Omit<
HTMLMotionProps<"button">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
/** Spawn a Material-style ripple from the press point. Off by default. */
ripple?: boolean;
children?: ReactNode;
}
export interface ButtonLinkProps extends Omit<
HTMLMotionProps<"a">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
children?: ReactNode;
}
type Ripple = { id: number; x: number; y: number; size: number };
const VARIANT_CLASS: Record<ButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
ghost: "text-muted-foreground hover:text-foreground hover:bg-muted/60",
outline:
"border border-border bg-transparent text-foreground hover:bg-muted/60",
};
const SIZE_CLASS: Record<ButtonSize, string> = {
sm: "h-8 px-3 text-xs gap-1.5 rounded-full",
md: "h-10 px-5 text-sm gap-2 rounded-full",
lg: "h-12 px-6 text-base gap-2 rounded-full",
icon: "h-8 w-8 rounded-lg",
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
function Button(
{
variant = "primary",
size = "md",
pressScale = 0.93,
ripple = false,
className,
children,
onPointerDown,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
const [ripples, setRipples] = useState<Ripple[]>([]);
const nextId = useRef(0);
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLButtonElement>) => {
if (ripple && !reduce) {
const rect = event.currentTarget.getBoundingClientRect();
const size = Math.max(rect.width, rect.height) * 2;
const id = nextId.current++;
setRipples((prev) => [
...prev,
{
id,
x: event.clientX - rect.left,
y: event.clientY - rect.top,
size,
},
]);
}
onPointerDown?.(event);
},
[ripple, reduce, onPointerDown],
);
return (
<motion.button
ref={ref}
type="button"
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
onPointerDown={handlePointerDown}
className={cn(
"inline-flex items-center justify-center font-medium select-none",
"transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
ripple && "relative overflow-hidden",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{ripple && !reduce ? (
<span className="pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]">
<AnimatePresence>
{ripples.map((r) => (
<motion.span
key={r.id}
className="absolute rounded-full bg-current"
style={{
left: r.x,
top: r.y,
width: r.size,
height: r.size,
x: "-50%",
y: "-50%",
}}
initial={{ scale: 0.05, opacity: 0.3 }}
animate={{ scale: 1, opacity: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: 1.6, ease: EASE_OUT }}
onAnimationComplete={() =>
setRipples((prev) => prev.filter((x) => x.id !== r.id))
}
/>
))}
</AnimatePresence>
</span>
) : null}
{children}
</motion.button>
);
},
);
export const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(
function ButtonLink(
{
variant = "primary",
size = "md",
pressScale = 0.93,
className,
children,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
return (
<motion.a
ref={ref}
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
className={cn(
"inline-flex items-center justify-center font-medium select-none",
"transition-colors",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{children}
</motion.a>
);
},
);
"use client";
import { forwardRef } from "react";
import { Magnetic } from "../magnetic";
import { Button, type ButtonProps } from "./base";
export interface MagneticButtonProps extends ButtonProps {
/** Magnetic pull strength. Default 0.25. */
strength?: number;
/** Class applied to the magnetic wrapper. */
magneticClassName?: string;
}
export const MagneticButton = forwardRef<HTMLButtonElement, MagneticButtonProps>(function MagneticButton(
{ strength = 0.25, magneticClassName, children, ...rest },
ref,
) {
return (
<Magnetic strength={strength} className={magneticClassName}>
<Button ref={ref} {...rest}>
{children}
</Button>
</Magnetic>
);
});
"use client";
import { motion, useReducedMotion } from "motion/react";
import { forwardRef, useState } from "react";
import { EASE_IN_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { Button, type ButtonProps } from "./base";
export interface MetallicButtonProps extends Omit<
ButtonProps,
"ripple" | "variant"
> {
/** Stops the traveling reflection while preserving the chrome rim. */
paused?: boolean;
}
// The rim and highlight drift separately so the material stays quiet and reflective.
const SILVER_DRIFT = {
duration: 8,
ease: EASE_IN_OUT,
repeat: Infinity,
};
const CHROME_SHIMMER = {
duration: 2.4,
ease: EASE_IN_OUT,
};
export const MetallicButton = forwardRef<
HTMLButtonElement,
MetallicButtonProps
>(function MetallicButton(
{
size = "md",
paused = false,
className,
children,
onHoverStart,
onHoverEnd,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const still = paused || Boolean(reduce);
const [hovered, setHovered] = useState(false);
return (
<Button
ref={ref}
variant="ghost"
size={size}
onHoverStart={(event, info) => {
setHovered(true);
onHoverStart?.(event, info);
}}
onHoverEnd={(event, info) => {
setHovered(false);
onHoverEnd?.(event, info);
}}
className={cn(
"group relative isolate overflow-hidden border-0 bg-transparent text-foreground",
"hover:bg-transparent hover:text-foreground",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
"shadow-[0_8px_22px_rgba(0,0,0,0.16)]",
size === "icon" && "rounded-full",
className,
)}
{...rest}
>
<motion.span
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 left-[-18%] z-0 w-[136%] rounded-[inherit] bg-[linear-gradient(105deg,#111_0%,#737373_14%,#fafafa_26%,#525252_38%,#0a0a0a_50%,#a3a3a3_64%,#fff_75%,#404040_87%,#111_100%)]"
animate={still ? undefined : { x: ["0%", "13%", "0%"] }}
transition={still ? undefined : SILVER_DRIFT}
/>
<motion.span
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 left-[-58%] z-[1] w-[52%] -skew-x-12 bg-[linear-gradient(90deg,transparent,rgba(255,255,255,0.5)_48%,transparent)] opacity-50 blur-[3px] mix-blend-screen"
animate={still ? undefined : { x: hovered ? "310%" : "0%" }}
transition={still ? undefined : CHROME_SHIMMER}
/>
<span
aria-hidden="true"
className="pointer-events-none absolute inset-[2px] z-[2] rounded-[inherit] bg-background transition-colors group-hover:bg-muted/40"
/>
<span
aria-hidden="true"
className="pointer-events-none absolute inset-[2px] z-[3] rounded-[inherit] shadow-[inset_0_1px_0_rgba(255,255,255,0.28),inset_0_-1px_0_rgba(0,0,0,0.16)]"
/>
<span className="relative z-10 inline-flex items-center justify-center gap-2">
{children}
</span>
</Button>
);
});
"use client";
import { Check, Loader2, X } from "lucide-react";
import {
AnimatePresence,
motion,
useReducedMotion,
type Variants,
} from "motion/react";
import {
forwardRef,
type ReactNode,
useLayoutEffect,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { Button, type ButtonProps } from "./base";
export type ButtonState = "idle" | "loading" | "success" | "error";
export interface StatefulButtonProps extends Omit<ButtonProps, "children"> {
state?: ButtonState;
children: ReactNode;
loadingText?: ReactNode;
successText?: ReactNode;
errorText?: ReactNode;
icon?: ReactNode;
}
const CASCADE_STAGGER = 0.025;
const ROLL_BLUR = "blur(6px)";
const CASCADE_LETTER_VARIANTS: Variants = {
initial: { opacity: 0, y: "105%", filter: ROLL_BLUR },
animate: (delay: number = 0) => ({
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: { ...SPRING_SWAP, delay },
}),
exit: (delay: number = 0) => ({
opacity: 0,
y: "-105%",
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },
}),
};
const ICON_VARIANTS: Variants = {
// Width collapses too, so the icon adds/removes its own space smoothly
// instead of popping the row width in a single frame.
initial: { opacity: 0, width: 0, scale: 0.7, filter: ROLL_BLUR },
animate: {
opacity: 1,
width: "1.5rem",
scale: 1,
filter: "blur(0px)",
transition: SPRING_SWAP,
},
exit: {
opacity: 0,
width: 0,
scale: 0.7,
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT },
},
};
function IconSlot({ keyId, children }: { keyId: string; children: ReactNode }) {
const reduce = useReducedMotion();
return (
<motion.span
key={keyId}
variants={ICON_VARIANTS}
initial={reduce ? { opacity: 0 } : "initial"}
animate={reduce ? { opacity: 1 } : "animate"}
exit={reduce ? { opacity: 0 } : "exit"}
transition={reduce ? { duration: 0.15 } : undefined}
className="inline-grid shrink-0 place-items-center overflow-hidden"
>
{children}
</motion.span>
);
}
function TextSlot({
value,
children,
}: {
value: string;
children: ReactNode;
}) {
const reduce = useReducedMotion();
const measureRef = useRef<HTMLSpanElement>(null);
const [width, setWidth] = useState<number>();
const label = typeof children === "string" ? children : null;
const cascade = label !== null && !reduce;
// Measure strings with the same per-letter layout as the cascade. Measuring
// the whole string preserves kerning, which can make it narrower than the
// inline-block letters and clip the final glyph during the width animation.
useLayoutEffect(() => {
const nextWidth = measureRef.current?.offsetWidth;
if (!nextWidth) return;
setWidth((current) => (current === nextWidth ? current : nextWidth));
});
return (
<motion.span
initial={false}
animate={{ width }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="relative inline-block overflow-hidden whitespace-nowrap align-bottom"
>
<span
ref={measureRef}
aria-hidden
className="invisible inline-block whitespace-nowrap"
>
{cascade
? label.split("").map((char, index) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
className="inline-block whitespace-pre"
>
{char}
</span>
))
: children}
</span>
{cascade ? (
<>
<span className="sr-only">{label}</span>
<AnimatePresence initial={false}>
<motion.span
key={`cascade-${value}`}
aria-hidden
initial="initial"
animate="animate"
exit="exit"
className="absolute left-0 top-0 inline-block whitespace-pre"
>
{label.split("").map((char, index) => (
<motion.span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
custom={index * CASCADE_STAGGER}
variants={CASCADE_LETTER_VARIANTS}
// Own states: a label that swaps away and straight back
// re-enters mid-exit, and only owned targets are restored.
initial="initial"
animate="animate"
exit="exit"
className="inline-block whitespace-pre will-change-[opacity,filter,transform]"
>
{char}
</motion.span>
))}
</motion.span>
</AnimatePresence>
</>
) : (
<AnimatePresence initial={false}>
<motion.span
key={`text-${value}`}
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: ROLL_BLUR }}
animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: "blur(0px)" }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: ROLL_BLUR }}
transition={reduce ? { duration: 0.15 } : SPRING_SWAP}
className="absolute left-0 top-0 inline-block will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
)}
</motion.span>
);
}
export const StatefulButton = forwardRef<HTMLButtonElement, StatefulButtonProps>(function StatefulButton(
{
state = "idle",
children,
loadingText = "Loading",
successText = "Done",
errorText = "Try again",
icon,
disabled,
...rest
},
ref,
) {
const isBusy = state === "loading";
const stateText =
state === "loading"
? loadingText
: state === "success"
? successText
: state === "error"
? errorText
: children;
const textKey =
typeof stateText === "string" ? `${state}-${stateText}` : state;
return (
<Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} whileHover={undefined} {...rest}>
<span
aria-live="polite"
className="relative inline-flex items-center justify-center overflow-hidden"
>
<AnimatePresence initial={false}>
{state === "loading" ? (
<IconSlot keyId="loading-icon">
<Loader2 className="h-4 w-4 animate-spin" />
</IconSlot>
) : null}
{state === "success" ? (
<IconSlot keyId="success-icon">
<Check className="h-4 w-4" />
</IconSlot>
) : null}
{state === "error" ? (
<IconSlot keyId="error-icon">
<X className="h-4 w-4" />
</IconSlot>
) : null}
</AnimatePresence>
<TextSlot value={textKey}>{stateText}</TextSlot>
<AnimatePresence initial={false}>
{state === "idle" && icon ? (
<IconSlot keyId="idle-icon">{icon}</IconSlot>
) : null}
</AnimatePresence>
</span>
</Button>
);
});
"use client";
import {
type MutableRefObject,
useCallback,
useLayoutEffect,
useState,
} from "react";
export type PortalLayout = {
trigger: {
left: number;
top: number;
width: number;
height: number;
};
content: {
width: number;
height: number;
};
};
function sameLayout(a: PortalLayout | null, b: PortalLayout) {
return (
a?.trigger.left === b.trigger.left &&
a.trigger.top === b.trigger.top &&
a.trigger.width === b.trigger.width &&
a.trigger.height === b.trigger.height &&
a.content.width === b.content.width &&
a.content.height === b.content.height
);
}
/** Measures a trigger and portalled panel in viewport coordinates. */
export function usePopoverPortalPosition<
TriggerElement extends HTMLElement,
ContentElement extends HTMLElement,
>(
triggerRef: MutableRefObject<TriggerElement | null>,
contentRef: MutableRefObject<ContentElement | null>,
active: boolean,
) {
const [layout, setLayout] = useState<PortalLayout | null>(null);
const update = useCallback(() => {
const trigger = triggerRef.current;
const content = contentRef.current;
if (!trigger || !content) return;
const rect = trigger.getBoundingClientRect();
const next: PortalLayout = {
trigger: {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
},
content: {
width: content.offsetWidth,
height: content.offsetHeight,
},
};
setLayout((current) => (sameLayout(current, next) ? current : next));
}, [contentRef, triggerRef]);
useLayoutEffect(() => {
update();
if (!active) return;
const trigger = triggerRef.current;
const content = contentRef.current;
const observer = new ResizeObserver(update);
if (trigger) observer.observe(trigger);
if (content) observer.observe(content);
window.addEventListener("scroll", update, true);
window.addEventListener("resize", update);
return () => {
observer.disconnect();
window.removeEventListener("scroll", update, true);
window.removeEventListener("resize", update);
};
}, [active, contentRef, triggerRef, update]);
return layout;
}
"use client";
import { motion, useMotionValue, useReducedMotion, useSpring } from "motion/react";
import { useRef, type ReactNode } from "react";
import { SPRING_MOUSE } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { cn } from "@/lib/utils";
export interface MagneticProps {
children: ReactNode;
strength?: number;
className?: string;
}
export function Magnetic({ children, strength = 0.35, className }: MagneticProps) {
const ref = useRef<HTMLDivElement>(null);
const reduce = useReducedMotion();
const canHover = useHoverCapable();
// Decorative cursor-follow: skip on touch (phantom hover) and reduced motion.
const enabled = !reduce && canHover;
const x = useMotionValue(0);
const y = useMotionValue(0);
const sx = useSpring(x, SPRING_MOUSE);
const sy = useSpring(y, SPRING_MOUSE);
const onMove = (e: React.MouseEvent<HTMLDivElement>) => {
const el = ref.current;
if (!el || !enabled) return;
const rect = el.getBoundingClientRect();
x.set((e.clientX - rect.left - rect.width / 2) * strength);
y.set((e.clientY - rect.top - rect.height / 2) * strength);
};
const onLeave = () => {
x.set(0);
y.set(0);
};
return (
<motion.div
ref={ref}
onMouseMove={onMove}
onMouseLeave={onLeave}
style={{ x: sx, y: sy }}
className={cn("inline-block", className)}
>
{children}
</motion.div>
);
}
API Reference
followOutput?booleanKeep streamed output pinned while the reader remains near the end.
truefollowThreshold?numberDistance from the end that still counts as following the output.
56smooth?booleanSmoothly follow growing content.
trueonFollowChange?((following: boolean) => void)Reports when the reader leaves or returns to the live edge.
—label?stringAccessible label for the scrollable transcript.
Conversationbusy?booleanMarks the transcript as waiting for more streamed content.
—navigation?"rail"Adds a compact rail for navigating between rendered Message rows.
—navigationLabel?stringAccessible label for the optional message navigation rail.
Message navigationviewportClassName?string—contentClassName?string—railClassName?string—viewportRef?Ref<HTMLElement>—viewportProps?Omit<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "children" | "ref" | "className">—contentProps?Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "children" | "ref" | "className">—className?string—Composition
Keep the scrolling viewport outside the message primitives it follows.
MessageScroller
└── MessageGroup
└── Message
└── MessageContentNote: Message provides stable, semantic rows for the transcript. Prompt Input starts new turns without owning transcript movement. Streaming Response supplies the growing content the viewport follows.
How it works
A streaming transcript is not ordinary overflow. It must follow new output while the reader stays at the live edge, then stop moving the moment they choose to inspect earlier work.
Related components
Message
Composable conversation primitives for message rows, grouped bubbles, avatars, metadata, live markers, and a mount-only trailing-edge pop-up for newly sent rows.
Chat App
A complete agent conversation workspace composing navigation, messages, streaming, planning, approvals, tools, code, diffs, generated media, sources, and prompt input.
Tool Result
A lightweight execution disclosure for syntax-highlighted terminal output and request responses that collapses into a compact completed state.
Updated