Preview
"use client";
import {
Message,
MessageAvatar,
MessageContent,
MessageFooter,
MessageGroup,
MessageHeader,
} from "@/components/agents/message";
import {
MessageBubble,
MessageBubbleContent,
} from "@/components/agents/message-bubble";
export function MessageUsage() {
return (
<MessageGroup spacing="default">
<Message from="user" animateIn>
<MessageAvatar>Y</MessageAvatar>
<MessageContent>
<MessageHeader>
<span>You</span>
<span>Now</span>
</MessageHeader>
<MessageBubble variant="solid">
<MessageBubbleContent>
Can you summarize the release notes?
</MessageBubbleContent>
</MessageBubble>
<MessageFooter>Delivered</MessageFooter>
</MessageContent>
</Message>
<Message from="assistant">
<MessageAvatar>AI</MessageAvatar>
<MessageContent>
<MessageHeader>
<span>Assistant</span>
<span>Just now</span>
</MessageHeader>
<MessageBubble variant="soft">
<MessageBubbleContent>
The release improves streaming, navigation, and recovery states.
</MessageBubbleContent>
</MessageBubble>
</MessageContent>
</Message>
</MessageGroup>
);
}
"use client";
// beui.dev/components/agents/message
import { motion, useReducedMotion } from "motion/react";
import {
type ComponentPropsWithRef,
createContext,
type ReactNode,
useContext,
} from "react";
import { MessageSideContext } from "@/components/agents/message-context";
import { EASE_OUT } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export {
MessageBubble,
MessageBubbleCollapsible,
MessageBubbleContent,
MessageBubbleGroup,
} from "@/components/agents/message-bubble";
export type { MessageScrollerProps } from "@/components/agents/message-scroller";
export { MessageScroller } from "@/components/agents/message-scroller";
export type MessageFrom = "user" | "assistant";
export const messageMessages = {
user: "user message",
assistant: "assistant message",
typing: "Responding",
};
export type MessageMessages = typeof messageMessages;
interface MessageContextValue {
from: MessageFrom;
}
const MessageContext = createContext<MessageContextValue>({
from: "assistant",
});
export interface MessageProps
extends Omit<ComponentPropsWithRef<typeof motion.article>, "children"> {
/** Who sent it; "user" rows align to the end, "assistant" rows to the start. */
from: MessageFrom;
/** Plays a trailing-edge pop-up once when this message row mounts. */
animateIn?: boolean;
children: ReactNode;
/** Override any built-in string. */
labels?: Partial<MessageMessages>;
}
export interface MessageGroupProps extends ComponentPropsWithRef<"div"> {
/** Gap between messages: 6 px for "compact", 16 px for "default". Default: "compact" */
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"> {
/** Screen reader text for the typing dots. Default: "Responding" */
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,
labels,
...props
}: MessageProps) {
const reduce = useReducedMotion() ?? false;
const t = useMessages("message", messageMessages, labels);
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"] ?? t(from)}
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",
// A message that follows one from the same speaker tightens its
// bubble's top corner on that side, so the run reads as one turn.
"[&>[data-from=user]+[data-from=user]_[data-slot=message-bubble-content]]:rounded-se-md",
"[&>[data-from=assistant]+[data-from=assistant]_[data-slot=message-bubble-content]]:rounded-ss-md",
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(
// No inset: the label lines up with the edge of the bubble or text
// below it, whichever variant is used.
"flex items-center gap-1.5 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 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,
className,
...props
}: MessageTypingProps) {
const reduce = useReducedMotion() ?? false;
const t = useMessages("message", messageMessages);
return (
<span
data-slot="message-typing"
className={cn("inline-flex h-5 items-center gap-1", className)}
{...props}
>
<span className="sr-only">{label ?? t("typing")}</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>
);
}
Add it with the shadcn CLI, or copy the source manually.
npx shadcn add https://beui.dev/r/theme.json. Theme setupInstall dependencies
npm i @floating-ui/dom clsx lucide-react motion tailwind-mergeAdd util files
// 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;
/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */
export const EASE_IN = [0.55, 0, 1, 0.45] 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;
/** Shared-surface morphs: a trigger growing into its panel and back on one
* weighted spring, so opening and closing travel the same path. */
export const SPRING_MORPH = {
type: "spring",
duration: 0.5,
bounce: 0.22,
} as const;
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useMemo,
} from "react";
/**
* A component's messages. Plain strings with `{name}` placeholders, so a
* dictionary stays JSON-serializable and can be passed from a server layout.
* There are no plural forms: write messages that read correctly for any count.
*/
export type Messages = Record<string, string>;
/** A language file: component namespace → any subset of that component's messages. */
export type LocaleMessages = Record<string, Partial<Messages>>;
type LocaleContextValue = {
locale?: string;
messages: LocaleMessages;
};
const NO_MESSAGES: LocaleMessages = {};
const LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });
/** Without a locale, digits stay plain so server and client render the same text. */
export function formatNumber(value: number, locale?: string) {
return locale ? new Intl.NumberFormat(locale).format(value) : String(value);
}
export interface LocaleProviderProps {
/** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */
locale: string;
/**
* Component namespace → translated strings. Missing keys fall back to English.
* Pass a stable object (a module constant, imported JSON or a memoized value):
* a new object each render gives every translated component a new `t`.
*/
messages?: LocaleMessages;
children: ReactNode;
}
export function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {
const value = useMemo(() => ({ locale, messages }), [locale, messages]);
return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;
}
export function useLocale(): { locale?: string } {
return { locale: useContext(LocaleContext).locale };
}
/**
* Resolves a component's strings: `labels` prop, then the provider's
* messages for `namespace`, then the component's English `defaults`.
* Numbers passed as values are formatted for the provider's locale.
*/
export function useMessages<T extends Messages>(
namespace: string,
defaults: T,
labels?: Partial<T>,
) {
const { locale, messages } = useContext(LocaleContext);
const provided = messages[namespace];
// Inline `labels={{ … }}` is a new object every render. Keying it by content
// keeps `t` one identity until a label changes, so effects and memos that
// depend on `t` don't re-run per render, and render-time reads never lag.
const labelsKey = labels ? JSON.stringify(labels) : "";
const stableLabels = useMemo(
() => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),
[labelsKey],
);
return useCallback(
(key: keyof T & string, values?: Record<string, string | number>) => {
const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];
if (!values) return template;
return template.replace(/\{(\w+)\}/g, (match, name: string) => {
const value = values[name];
if (value === undefined) return match;
return typeof value === "number" ? formatNumber(value, locale) : value;
});
},
[defaults, stableLabels, locale, provided],
);
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
import type { Ref } from "react";
/** Points a callback or object ref at `value`. */
export function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
if (typeof ref === "function") ref(value);
else if (ref) ref.current = value;
}
/** One callback ref that sets every ref it is given. */
export function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {
return (node: T | null) => {
for (const ref of refs) assignRef(ref, node);
};
}
"use client";
import { type RefObject, useEffect, useLayoutEffect, useRef } from "react";
import { inOtherLayer, type Layer, openLayer, ownsEscape } from "@/lib/layers";
/**
* 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";
/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */
export type DismissReason = "escape" | "pointer" | "focus";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */
focusOutside?: boolean;
/**
* Dismiss on a pointerdown outside. Default true. Turn it off for an overlay
* whose own backdrop handles presses and only needs Escape and layering.
*/
outsidePress?: boolean;
/** Return true for an outside target that should *not* dismiss. */
ignore?: (target: Element) => boolean;
}
// 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.
*
* Each open dismissal is a layer in `lib/layers.ts`, so only the innermost
* open overlay answers Escape (a menu inside a drawer closes, the drawer
* stays), and a drawer's focus trap leaves focus in a menu it portaled out.
*/
export function useDismiss(
open: boolean,
onDismiss: (reason: DismissReason) => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
focusOutside = false,
outsidePress = true,
ignore,
}: DismissOptions = {},
) {
// Read through refs, so a callback rebuilt each render neither re-binds the
// listeners nor moves this layer to the top of the stack.
const dismissRef = useRef(onDismiss);
const ignoreRef = useRef(ignore);
useLayoutEffect(() => {
dismissRef.current = onDismiss;
ignoreRef.current = ignore;
});
useEffect(() => {
if (!open) return;
const inside = (target: Node) =>
Boolean(ref?.current?.contains(target)) ||
(target instanceof Element && Boolean(ignoreRef.current?.(target)));
const layer: Layer = { contains: inside, escape: dismissOnEscape };
const closeLayer = openLayer(layer);
const onKey = (event: KeyboardEvent) => {
if (!dismissOnEscape || event.key !== "Escape" || !ownsEscape(layer, event)) return;
event.preventDefault();
dismissRef.current("escape");
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside another open one: 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" && !inOtherLayer(layer, target, { traps: false })) {
consumeActivation(event);
}
dismissRef.current("pointer");
};
const onFocus = (event: FocusEvent) => {
const target = event.target;
if (target instanceof Node && !inside(target)) dismissRef.current("focus");
};
window.addEventListener("keydown", onKey);
if (outsidePress) window.addEventListener("pointerdown", onPointer, true);
if (focusOutside) window.addEventListener("focusin", onFocus);
return () => {
closeLayer();
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
window.removeEventListener("focusin", onFocus);
};
}, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);
}
"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;
},
}),
[],
);
}
/**
* Every open overlay on the page, innermost last: focus traps, modal scopes
* and dismissable menus all register here. Overlays have no shared z-order to
* consult, and a menu inside a drawer portals out of it, so this stack is how
* they agree on who answers Escape and where focus may go.
*/
export interface Layer {
/** Whether `target` belongs to this layer (its panel, portals, trigger). */
contains: (target: Node) => boolean;
/** True for focus traps and modal scopes, which pull stray focus back. */
traps?: boolean;
/** False for a layer that ignores Escape, so the key reaches the one below. */
escape?: boolean;
}
const stack: Layer[] = [];
// The innermost layer when each Escape began, read before any handler runs,
// so a layer that closes itself mid-event can't hand the key to the one below.
const escapeOwners = new WeakMap<Event, Layer | undefined>();
let listening = false;
function innermostEscapeLayer() {
for (let index = stack.length - 1; index >= 0; index--) {
if (stack[index].escape !== false) return stack[index];
}
return undefined;
}
function recordEscapeOwner(event: KeyboardEvent) {
if (event.key === "Escape") escapeOwners.set(event, innermostEscapeLayer());
}
/** Registers an open layer. Call the returned function when it closes. */
export function openLayer(layer: Layer) {
if (!listening) {
document.addEventListener("keydown", recordEscapeOwner, true);
listening = true;
}
stack.push(layer);
return () => {
const index = stack.indexOf(layer);
if (index !== -1) stack.splice(index, 1);
};
}
/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */
export function ownsEscape(layer: Layer, event: KeyboardEvent) {
if (event.defaultPrevented) return false;
const owner = escapeOwners.has(event)
? escapeOwners.get(event)
: innermostEscapeLayer();
return owner === layer;
}
/** Whether `target` sits in a layer opened on top of `layer`. */
export function inLayerAbove(layer: Layer, target: Node) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.contains(target));
}
/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */
export function trapAbove(layer: Layer) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.traps);
}
/**
* Whether `target` belongs to any open layer other than `layer`. Pass
* `traps: false` to count only dismissable overlays, not the traps under them.
*/
export function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {
return stack.some(
(other) => other !== layer && (traps || !other.traps) && other.contains(target),
);
}
// 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;
"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 };
}
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
/** How long the copied state holds after a copy, in ms. */
const COPIED_MS = 1600;
/**
* A copy action and a `copied` flag that holds for a moment after it works.
*
* `copy` runs `onCopy` when given, else writes `text` to the clipboard. The
* flag turns on only once that succeeded: no clipboard (an insecure origin),
* a refused write or a throwing `onCopy` leave it off rather than claiming a
* copy that never happened.
*/
export function useCopy({
text,
onCopy,
}: {
text?: string;
onCopy?: () => void | Promise<void>;
}) {
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
const copy = useCallback(async () => {
try {
if (onCopy) await onCopy();
else if (text !== undefined && navigator.clipboard) {
await navigator.clipboard.writeText(text);
} else return;
} catch {
return;
}
setCopied(true);
clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(false), COPIED_MS);
}, [onCopy, text]);
return { copied, copy };
}
"use client";
import { useIsPresent } from "motion/react";
import type { ReactNode } from "react";
export interface PresenceGateRenderProps {
/**
* False from the render that starts the exit animation onward. An overlay
* kept in the tree by `AnimatePresence` is still the topmost thing on the
* page, so anything it decides from `open` alone stays true for the whole
* exit - this is the boolean that already knows the overlay is leaving.
*/
isPresent: boolean;
/**
* Spread onto every layer that takes pointer events while the overlay is
* open. Interaction releases in the same commit that starts the exit while
* the visual exit keeps playing: pointer events stop landing, and `inert`
* drops the subtree from focus order, from tab order and from the
* accessibility tree - an exiting dialog is not a dialog you can still type
* into. A layer that never takes pointer events (a wrapper that only centres
* the panel) takes `inert={!isPresent}` alone, so its own
* `pointer-events-none` is not overwritten.
*/
gate: {
inert: boolean;
style: { pointerEvents: "auto" | "none" };
};
}
export interface PresenceGateProps {
children: (props: PresenceGateRenderProps) => ReactNode;
}
/**
* Reads the presence of the subtree it renders and hands it down.
*
* `useIsPresent` only answers inside the `AnimatePresence` subtree, and the
* components that own an overlay render the `AnimatePresence` themselves, so
* the boolean has to be read one component further down: this is that
* component, and the render prop is how it reaches the layers.
*/
export function PresenceGate({ children }: PresenceGateProps) {
const isPresent = useIsPresent();
return children({
isPresent,
gate: {
inert: !isPresent,
style: { pointerEvents: isPresent ? "auto" : "none" },
},
});
}
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
} from "react";
import {
registerSoundSettings,
retainAudioContext,
type SoundSettingsEntry,
} from "@/lib/audio-context";
import type { PlayOptions, Sound } from "@/lib/sounds/engine";
export interface SoundSettings {
/** False mutes every beUI sound under the provider. */
enabled: boolean;
/** 0 to 1, scales every beUI sound. */
volume: number;
}
const SoundContext = createContext<SoundSettings & { depth: number }>({
enabled: true,
volume: 1,
depth: 0,
});
/**
* App-wide sound settings. `enabled={false}` mutes every beUI sound, from
* component `sound` props and `useSound` to the games, Wheel Picker and
* Bookshelf, and `volume` scales them all. Without a provider, sounds play at
* full volume. A nested provider overrides the one around it.
*/
export function SoundProvider({
enabled = true,
volume = 1,
children,
}: Partial<SoundSettings> & { children: ReactNode }) {
const depth = useContext(SoundContext).depth + 1;
const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);
// Module-level as well (lib/audio-context.ts), so players outside React
// and `sound.play()` obey it too.
const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });
const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);
useEffect(() => {
registration.current = registerSoundSettings(entry.current);
return () => {
registration.current?.release();
registration.current = null;
};
}, []);
useEffect(() => {
Object.assign(entry.current, { depth, enabled, volume });
registration.current?.update();
}, [depth, enabled, volume]);
return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;
}
export function useSoundSettings(): SoundSettings {
return useContext(SoundContext);
}
export interface UseSoundOptions {
/** False makes `play` do nothing, for a component's `sound` prop. */
enabled?: boolean;
/** 0 to 1 for this sound, on top of the provider volume. */
volume?: number;
}
/**
* A stable `play()` for one sound. It does nothing while disabled or muted,
* and keeps the shared audio context warm only while it can play.
*/
export function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {
const settings = useSoundSettings();
const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;
// Read by the stable callback, so a caller's effects don't re-run when
// the settings change.
const latest = useRef({ on, volume, sound });
useLayoutEffect(() => {
latest.current = { on, volume, sound };
});
useEffect(() => {
if (!on) return;
return retainAudioContext();
}, [on]);
return useCallback((options?: PlayOptions) => {
const current = latest.current;
if (!current.on) return;
current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });
}, []);
}
import { defineSound } from "./engine";
/** The open whoosh falling and a little quicker, settling with a soft low tap, for things closing. */
export const closeSound = defineSound({
name: "Close",
duration: 0.16,
room: 0.18,
build: (v) => {
v.noise({ freq: 2600, to: 700, q: 1.2, attack: 0.012, decay: 0.09, gain: 0.7 });
v.click({ freq: 1400, q: 1.2, at: 0.05, decay: 0.006, gain: 0.2 });
v.strike({ freq: 260, material: "wood", bend: 1.2, at: 0.05, decay: 0.045, gain: 0.3 });
},
});
import { defineSound } from "./engine";
/** A soft rising whoosh that lands with a light glass touch, for menus, popovers and dialogs opening. */
export const openSound = defineSound({
name: "Open",
duration: 0.2,
room: 0.2,
build: (v) => {
v.noise({ freq: 600, to: 2600, q: 1.2, attack: 0.035, decay: 0.11, gain: 0.75 });
v.noise({ freq: 4500, to: 6000, q: 1, attack: 0.03, decay: 0.07, gain: 0.05 });
v.strike({ freq: 1320, material: "glass", at: 0.05, decay: 0.07, gain: 0.12 });
},
});
import { defineSound } from "./engine";
/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */
export const selectSound = defineSound({
name: "Select",
duration: 0.05,
room: 0.08,
build: (v) => {
v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });
v.strike({ freq: 1700, material: "metal", decay: 0.028, gain: 0.3 });
v.strike({ freq: 520, material: "wood", bend: 1.15, decay: 0.012, gain: 0.25 });
},
});
"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 };
}
import { defineSound } from "./engine";
/** A physical button: a switch click that settles twice over a soft thump and a little casing ring. */
export const pressSound = defineSound({
name: "Press",
duration: 0.1,
vary: 0.03,
room: 0.1,
build: (v) => {
v.click({ freq: 2800, q: 1.8, decay: 0.005, gain: 0.5 });
v.click({ freq: 4200, q: 2.5, at: 0.011, decay: 0.003, gain: 0.16 });
v.strike({ freq: 150, material: "wood", bend: 1.5, decay: 0.07, gain: 0.75 });
v.strike({ freq: 1250, material: "plastic", decay: 0.022, gain: 0.14 });
},
});
// One AudioContext for every synthesized sound on the page: the sounds
// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino
// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap
// concurrent contexts, and a page can show a date made of several WheelPickers
// next to a game, so they all share this one. It is created on first use and
// closed once every player is disposed.
//
// Every player connects to `audioOutput()` rather than the context's
// destination, so the page-wide volume and mute from `SoundProvider`
// (lib/sound.tsx) reach all of them in one place.
type AudioContextCtor = typeof AudioContext;
let context: AudioContext | null = null;
let master: GainNode | null = null;
let users = 0;
/** Settings one mounted `SoundProvider` asks for. */
export interface SoundSettingsEntry {
/** Nesting depth: the deepest provider decides. */
depth: number;
enabled: boolean;
volume: number;
}
// Mounted providers in mount order. Module state, so `sound.play()` called
// outside React obeys them too. The deepest provider wins; among equals, the
// one mounted last. Effects run child first, so this can't be "whoever ran
// last".
const providers = new Set<SoundSettingsEntry>();
let allowed = true;
let volume = 1;
function applySettings() {
let chosen: SoundSettingsEntry | undefined;
for (const entry of providers) {
if (!chosen || entry.depth >= chosen.depth) chosen = entry;
}
allowed = chosen?.enabled ?? true;
volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));
if (master) master.gain.value = volume;
}
/**
* Registers a provider's settings; call `update` after changing the entry and
* the returned release function when the provider unmounts.
*/
export function registerSoundSettings(entry: SoundSettingsEntry) {
providers.add(entry);
applySettings();
return {
update: applySettings,
release() {
providers.delete(entry);
applySettings();
},
};
}
/**
* Registers a sound player. Call the returned function when the player is
* disposed; the context closes after the last one.
*/
export function retainAudioContext() {
users++;
let released = false;
return () => {
if (released) return;
released = true;
users--;
if (users === 0 && context) {
void context.close();
context = null;
master = null;
}
};
}
/**
* The shared context, created on first call and resumed if suspended. Null
* during SSR, in browsers without Web Audio, and while sounds are muted or at
* zero volume.
*/
export function getAudioContext(): AudioContext | null {
if (!allowed || volume <= 0) return null;
if (!context) {
if (typeof window === "undefined") return null;
const Ctor =
window.AudioContext ??
(window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;
if (!Ctor) return null;
context = new Ctor();
}
// Browsers may refuse outside a user gesture. Players call this from
// pointer and key handlers first, so a later call finds it running.
if (context.state === "suspended") void context.resume().catch(() => undefined);
return context;
}
/** The node every player connects to: the page-wide volume, then the speakers. */
export function audioOutput(ctx: AudioContext): AudioNode {
if (master?.context !== ctx) {
master = ctx.createGain();
master.gain.value = volume;
master.connect(ctx.destination);
}
return master;
}
const gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();
/**
* A player's own level, made once per context and routed into `audioOutput`.
* Players keep their mix this way without rebuilding nodes on every play, and
* a context closed and recreated gets fresh ones.
*/
export function playerGain(ctx: AudioContext, key: string, level: number): GainNode {
let byKey = gains.get(ctx);
if (!byKey) {
byKey = new Map();
gains.set(ctx, byKey);
}
let gain = byKey.get(key);
if (!gain) {
gain = ctx.createGain();
gain.gain.value = level;
gain.connect(audioOutput(ctx));
byKey.set(key, gain);
}
return gain;
}
import { audioOutput, getAudioContext } from "@/lib/audio-context";
// Every beUI sound is a short recipe played with Web Audio the moment it is
// asked for. Nothing is downloaded. Recipes are built the way a real tap
// sounds: a contact click (a millisecond of filtered noise), a body that
// rings at a few inharmonic partials of a material and settles in pitch, and
// a little of a small room behind it.
/** Options for one play of a sound. */
export interface PlayOptions {
/** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */
volume?: number;
/** Pitch multiplier; 1 is the designed pitch. */
pitch?: number;
}
/** Where a sound renders: the live context, or an offline one for drawing. */
export interface SoundTarget {
context: BaseAudioContext;
destination: AudioNode;
/** Start time on the context clock, in seconds. */
when: number;
volume: number;
pitch: number;
}
/** A plain oscillator with an attack, a decay and an optional glide. */
export interface ToneSpec {
type?: OscillatorType;
/** Start frequency in Hz. */
freq: number;
/** End frequency in Hz; glides from `freq` over `glide`. */
to?: number;
/** Glide time in seconds; defaults to the attack plus decay. */
glide?: number;
/** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */
bend?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Fade-in time in seconds. */
attack?: number;
/** Time to fade to silence after the attack, in seconds. */
decay: number;
gain: number;
}
/** A burst of filtered white noise. */
export interface NoiseSpec {
filter?: BiquadFilterType;
/** Filter frequency in Hz. */
freq: number;
/** End filter frequency in Hz; sweeps from `freq` over the decay. */
to?: number;
q?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Fade-in time in seconds. */
attack?: number;
/** Time to fade to silence after the attack, in seconds. */
decay: number;
gain: number;
}
/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */
export interface ClickSpec {
/** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */
freq: number;
/** Band width; higher is narrower and more tonal. */
q?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Time to fade to silence, in seconds. */
decay?: number;
gain: number;
}
/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */
export interface Material {
partials: readonly (readonly [ratio: number, level: number])[];
/** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */
damping: number;
}
// Partial ratios follow the modes of small struck objects: a free bar for
// wood and metal, a cup for glass, a tuned bar for the mallet.
export const MATERIALS = {
wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },
plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },
glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },
metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },
mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },
bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },
} satisfies Record<string, Material>;
/** A struck object: one partial per mode of its material, each with its own decay. */
export interface StrikeSpec {
/** Fundamental in Hz. */
freq: number;
/** A name from `MATERIALS` or your own partials. Default: "plastic". */
material?: keyof typeof MATERIALS | Material;
/** Starts this many times higher and settles in about 15 ms. Default: 1.01. */
bend?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Time for the fundamental to fade to silence, in seconds. */
decay: number;
gain: number;
}
export interface Voice {
tone(spec: ToneSpec): void;
noise(spec: NoiseSpec): void;
click(spec: ClickSpec): void;
strike(spec: StrikeSpec): void;
}
export interface Sound {
/** Display name, like "Tap". */
name: string;
/** Length in seconds; the room tail rings a little past it. */
duration: number;
/** Plays the sound now. Silent during SSR and while sounds are muted. */
play(options?: PlayOptions): void;
/** Schedules the sound on any context; `play` uses the live one. */
render(target: SoundTarget): void;
}
export interface SoundRecipe {
/** Display name, like "Tap". */
name: string;
/** Length in seconds; the room tail rings a little past it. */
duration: number;
/** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */
vary?: number;
/** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */
room?: number;
/** Adds the sound's layers to the voice on each play. */
build: (voice: Voice) => void;
}
// Keeps a sum of voices well under clipping at volume 1.
const MASTER_GAIN = 0.16;
const SILENT = 0.0001;
// Time a strike or bend takes to settle onto its pitch.
const SETTLE = 0.015;
const noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();
/** One second of white noise per context, shared by every noise voice. */
export function noiseBuffer(context: BaseAudioContext) {
let buffer = noiseBuffers.get(context);
if (!buffer) {
buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
noiseBuffers.set(context, buffer);
}
return buffer;
}
// A small, soft room: 8 early reflections, then a diffuse tail that falls
// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls
// absorb highs first. Generated once per context.
const ROOM_LENGTH = 0.3;
// The convolver's equal-power normalization leaves the room about 15 dB
// under the dry sound; this brings `room: 0.12` to a tail heard only as space.
const ROOM_GAIN = 6;
const roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();
function roomBuffer(context: BaseAudioContext) {
let buffer = roomBuffers.get(context);
if (!buffer) {
const rate = context.sampleRate;
const length = Math.ceil(ROOM_LENGTH * rate);
buffer = context.createBuffer(2, length, rate);
for (let channel = 0; channel < 2; channel++) {
const data = buffer.getChannelData(channel);
let smooth = 0;
for (let i = Math.floor(0.004 * rate); i < length; i++) {
const t = i / rate;
// One-pole low-pass whose cutoff closes over the tail.
const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;
smooth += brightness * (Math.random() * 2 - 1 - smooth);
data[i] = smooth * Math.exp(-t / 0.043);
}
for (let r = 0; r < 8; r++) {
const at = Math.floor((0.005 + Math.random() * 0.022) * rate);
data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);
}
}
roomBuffers.set(context, buffer);
}
return buffer;
}
// One convolver per output node, shared by every play: building one is the
// expensive part, sending to it is cheap.
const rooms = new WeakMap<AudioNode, ConvolverNode>();
function roomFor(context: BaseAudioContext, destination: AudioNode) {
let room = rooms.get(destination);
if (!room) {
room = context.createConvolver();
room.buffer = roomBuffer(context);
room.connect(destination);
rooms.set(destination, room);
}
return room;
}
/** A linear attack to `peak`, then an exponential fall to silence. */
function envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {
param.setValueAtTime(0, start);
param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);
param.exponentialRampToValueAtTime(SILENT, start + attack + decay);
}
function voiceFor(target: SoundTarget, output: AudioNode): Voice {
const { context, when, pitch } = target;
// Partials above this only add hiss on small speakers, or alias near Nyquist.
const ceiling = Math.min(12000, context.sampleRate * 0.45);
const tone: Voice["tone"] = ({ type = "sine", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {
const start = when + at;
const osc = context.createOscillator();
const amp = context.createGain();
osc.type = type;
const base = freq * pitch;
osc.frequency.setValueAtTime(base * (bend ?? 1), start);
if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);
if (to !== undefined) {
osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));
}
envelope(amp.gain, start, attack, decay, gain);
osc.connect(amp).connect(output);
osc.start(start);
osc.stop(start + attack + decay + 0.02);
};
const noise: Voice["noise"] = ({ filter = "bandpass", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {
const start = when + at;
const source = context.createBufferSource();
const shape = context.createBiquadFilter();
const amp = context.createGain();
source.buffer = noiseBuffer(context);
shape.type = filter;
shape.Q.value = q;
shape.frequency.setValueAtTime(freq * pitch, start);
if (to !== undefined) {
shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);
}
envelope(amp.gain, start, attack, decay, gain);
source.connect(shape).connect(amp).connect(output);
// A random offset into the buffer keeps each burst a little different.
source.start(start, Math.random() * 0.5);
source.stop(start + attack + decay + 0.02);
};
return {
tone,
noise,
click({ freq, q = 2, at = 0, decay = 0.005, gain }) {
// A little spread on the band, so no two contacts are identical.
noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });
},
strike({ freq, material = "plastic", bend = 1.01, at = 0, decay, gain }) {
const { partials, damping } = typeof material === "string" ? MATERIALS[material] : material;
for (const [ratio, level] of partials) {
if (freq * ratio * pitch * bend > ceiling) continue;
tone({
// Real objects are never perfectly tuned; a hair of detune per partial.
freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),
bend,
at,
attack: 0.001,
decay: decay / ratio ** damping,
gain: gain * level,
});
}
},
};
}
/** Turns a recipe into a playable sound. */
export function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {
const render = (target: SoundTarget) => {
const { context, destination } = target;
const output = context.createGain();
output.gain.value = MASTER_GAIN * target.volume;
output.connect(destination);
if (room > 0) {
const send = context.createGain();
send.gain.value = room * ROOM_GAIN;
output.connect(send).connect(roomFor(context, destination));
}
build(voiceFor(target, output));
};
return {
name,
duration,
render,
play({ volume = 1, pitch = 1 } = {}) {
const context = getAudioContext();
if (!context || volume <= 0) return;
const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;
render({
context,
// The page-wide volume is applied there.
destination: audioOutput(context),
when: context.currentTime + 0.005,
volume,
pitch: pitch * spread,
});
},
};
}
/** 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;
}
}
"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;
}
Copy the source code
"use client";
// beui.dev/components/agents/message
import { motion, useReducedMotion } from "motion/react";
import {
type ComponentPropsWithRef,
createContext,
type ReactNode,
useContext,
} from "react";
import { MessageSideContext } from "@/components/agents/message-context";
import { EASE_OUT } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export {
MessageBubble,
MessageBubbleCollapsible,
MessageBubbleContent,
MessageBubbleGroup,
} from "@/components/agents/message-bubble";
export type { MessageScrollerProps } from "@/components/agents/message-scroller";
export { MessageScroller } from "@/components/agents/message-scroller";
export type MessageFrom = "user" | "assistant";
export const messageMessages = {
user: "user message",
assistant: "assistant message",
typing: "Responding",
};
export type MessageMessages = typeof messageMessages;
interface MessageContextValue {
from: MessageFrom;
}
const MessageContext = createContext<MessageContextValue>({
from: "assistant",
});
export interface MessageProps
extends Omit<ComponentPropsWithRef<typeof motion.article>, "children"> {
/** Who sent it; "user" rows align to the end, "assistant" rows to the start. */
from: MessageFrom;
/** Plays a trailing-edge pop-up once when this message row mounts. */
animateIn?: boolean;
children: ReactNode;
/** Override any built-in string. */
labels?: Partial<MessageMessages>;
}
export interface MessageGroupProps extends ComponentPropsWithRef<"div"> {
/** Gap between messages: 6 px for "compact", 16 px for "default". Default: "compact" */
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"> {
/** Screen reader text for the typing dots. Default: "Responding" */
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,
labels,
...props
}: MessageProps) {
const reduce = useReducedMotion() ?? false;
const t = useMessages("message", messageMessages, labels);
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"] ?? t(from)}
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",
// A message that follows one from the same speaker tightens its
// bubble's top corner on that side, so the run reads as one turn.
"[&>[data-from=user]+[data-from=user]_[data-slot=message-bubble-content]]:rounded-se-md",
"[&>[data-from=assistant]+[data-from=assistant]_[data-slot=message-bubble-content]]:rounded-ss-md",
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(
// No inset: the label lines up with the edge of the bubble or text
// below it, whichever variant is used.
"flex items-center gap-1.5 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 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,
className,
...props
}: MessageTypingProps) {
const reduce = useReducedMotion() ?? false;
const t = useMessages("message", messageMessages);
return (
<span
data-slot="message-typing"
className={cn("inline-flex h-5 items-center gap-1", className)}
{...props}
>
<span className="sr-only">{label ?? t("typing")}</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 {
animate,
type HTMLMotionProps,
motion,
useMotionTemplate,
useMotionValue,
useReducedMotion,
} from "motion/react";
import {
type ComponentPropsWithRef,
cloneElement,
createContext,
type ReactElement,
type ReactNode,
type Ref,
useCallback,
useContext,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
import { MessageSideContext } from "@/components/agents/message-context";
import { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { mergeRefs } from "@/lib/merge-refs";
import { cn } from "@/lib/utils";
export type MessageBubbleVariant =
| "solid"
| "soft"
| "tint"
| "outline"
| "ghost"
| "danger";
export type MessageBubbleAlign = "start" | "end";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const messageBubbleMessages = {
showMore: "Show more",
showLess: "Show less",
};
export type MessageBubbleMessages = typeof messageBubbleMessages;
interface MessageBubbleContextValue {
align?: MessageBubbleAlign;
animateIn: boolean;
variant: MessageBubbleVariant;
labels?: Partial<MessageBubbleMessages>;
}
const MessageBubbleContext = createContext<MessageBubbleContextValue>({
animateIn: true,
variant: "soft",
});
export interface MessageBubbleProps
extends Omit<HTMLMotionProps<"div">, "children"> {
/** Fill and border style of the bubble. Default: "soft" */
variant?: MessageBubbleVariant;
/** Defaults to the surrounding Message alignment when omitted. */
align?: MessageBubbleAlign;
/** Plays the bubble entrance once when this component mounts. */
animateIn?: boolean;
/** Override any built-in string. */
labels?: Partial<MessageBubbleMessages>;
children?: ReactNode;
}
export interface MessageBubbleContentProps
extends ComponentPropsWithRef<"div"> {
/** Replaces the content element while preserving bubble styling. */
render?: ReactElement;
}
export interface MessageBubbleGroupProps extends ComponentPropsWithRef<"div"> {
/** Gap between bubbles. Default: "compact" */
spacing?: "compact" | "default";
}
export interface MessageBubbleCollapsibleProps
extends ComponentPropsWithRef<"div"> {
/** Whether the full text shows, for controlled use. */
open?: boolean;
/** Whether the full text shows at first when uncontrolled. Default: false */
defaultOpen?: boolean;
/** Called with the new state when the text expands or collapses. */
onOpenChange?: (open: boolean) => void;
/** Lines shown while collapsed. Default: 4 */
collapsedLines?: 2 | 3 | 4 | 5 | 6;
/** Text of the expand button. Default: "Show more" */
moreLabel?: ReactNode;
/** Text of the collapse button. Default: "Show less" */
lessLabel?: ReactNode;
/** Classes merged onto the clamped text wrapper. */
contentClassName?: string;
/** Classes merged onto the show more button. */
triggerClassName?: string;
children?: ReactNode;
}
const BUBBLE_CONTENT_REVEAL = {
duration: 0.12,
ease: EASE_OUT,
delay: 0.04,
} as const;
// Expanded text wipes in top to bottom, quick enough to read straight on.
const REVEAL = { duration: 0.32, ease: EASE_OUT } as const;
// Clamped text stays solid to here (%), then fades out by the bottom.
const CLAMP_SOLID = 68;
// How soft the moving edge of the wipe is, in % of the text's height.
const WIPE_EDGE = 12;
// 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,
labels,
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, labels }}
>
<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,
align: MessageBubbleAlign,
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",
// The corner by the speaker is tighter, so a bubble points at who said it.
align === "end" ? "rounded-ee-md" : "rounded-es-md",
"[&_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-primary-foreground [&_code]:bg-primary-foreground/15 [&_pre]:bg-primary-foreground/15",
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-primary",
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 interactive =
render?.type === "button" || render?.type === "a";
const classes = cn(
bubbleContentClass(variant, align, interactive),
className,
);
const composedChildren = (
<>
{/* The surface pops in once, then always matches its text: a surface
that springs after its content leaves streamed lines and expanded
text hanging outside the bubble. */}
{variant !== "ghost" ? (
<motion.span
aria-hidden="true"
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,
}
}
className={bubbleSurfaceClass(variant, align)}
/>
) : null}
<motion.div
initial={animateIn ? { opacity: 0 } : false}
animate={{ opacity: 1 }}
transition={
reduce ? { duration: 0.12, ease: EASE_OUT } : BUBBLE_CONTENT_REVEAL
}
className="relative"
>
{children}
</motion.div>
</>
);
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",
// A bubble that follows one from the same speaker tightens its top
// corner on that side too, so the run reads as one turn.
"[&>[data-align=end]+[data-align=end]_[data-slot=message-bubble-content]]:rounded-se-md",
"[&>[data-align=start]+[data-align=start]_[data-slot=message-bubble-content]]:rounded-ss-md",
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,
lessLabel,
contentClassName,
triggerClassName,
className,
children,
...props
}: MessageBubbleCollapsibleProps) {
const reduce = useReducedMotion() ?? false;
const contentId = useId();
const t = useMessages(
"messageBubble",
messageBubbleMessages,
useContext(MessageBubbleContext).labels,
);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const currentOpen = open ?? internalOpen;
const contentRef = useRef<HTMLDivElement>(null);
// Where the clamped text ended, as a share of the full text: the reveal
// starts there, so the lines already on screen never blink.
const clampedHeight = useRef(0);
// The fade mask, from solid (`solid`%) to clear (`clear`%). Clamped, it
// softens the last lines; open, it wipes down until the text is all solid.
const solid = useMotionValue(currentOpen ? 100 : CLAMP_SOLID);
const clear = useMotionValue(currentOpen ? 100 + WIPE_EDGE : 100);
const mask = useMotionTemplate`linear-gradient(to bottom, #000 ${solid}%, transparent ${clear}%)`;
const setOpen = useCallback(
(next: boolean) => {
if (next) clampedHeight.current = contentRef.current?.offsetHeight ?? 0;
if (open === undefined) setInternalOpen(next);
onOpenChange?.(next);
},
[onOpenChange, open],
);
// Opening shows the whole text at once (no height animation) and wipes the
// new lines in from the top; closing clamps straight back.
useLayoutEffect(() => {
if (!currentOpen) {
solid.set(CLAMP_SOLID);
clear.set(100);
return;
}
const full = contentRef.current?.offsetHeight ?? 0;
const start =
reduce || !full || !clampedHeight.current
? 100
: Math.min(100, (clampedHeight.current / full) * 100 - WIPE_EDGE);
solid.set(start);
clear.set(start + WIPE_EDGE);
if (start >= 100) return;
const toSolid = animate(solid, 100, REVEAL);
const toClear = animate(clear, 100 + WIPE_EDGE, REVEAL);
return () => {
toSolid.stop();
toClear.stop();
};
}, [currentOpen, reduce, solid, clear]);
return (
<div
data-slot="message-bubble-collapsible"
data-state={currentOpen ? "open" : "closed"}
className={cn("w-full", className)}
{...props}
>
<motion.div
ref={contentRef}
id={contentId}
style={{ maskImage: mask, WebkitMaskImage: mask }}
className={cn(
!currentOpen && LINE_CLAMP_CLASS[collapsedLines],
contentClassName,
)}
>
{children}
</motion.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 ?? t("showLess"))
: (moreLabel ?? t("showMore"))}</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 { createContext } from "react";
export type MessageSide = "start" | "end";
export const MessageSideContext = createContext<MessageSide | undefined>(
undefined,
);
"use client";
import { ArrowDown } from "lucide-react";
import { AnimatePresence, motion, 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 { Tooltip } from "@/components/motion/tooltip";
import { EASE_OUT } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
// The jump button rises in from the bottom edge and drops back out, faster.
const JUMP_IN = { duration: 0.2, ease: EASE_OUT } as const;
const JUMP_OUT = { duration: 0.14, ease: EASE_OUT } as const;
export const messageScrollerMessages = {
label: "Conversation",
jumpToLatest: "Jump to latest",
navigationLabel: "Message navigation",
preview: "Message",
goToUser: "Go to user message {index} of {total}",
goToAssistant: "Go to assistant message {index} of {total}",
goToMessage: "Go to conversation message {index} of {total}",
};
export type MessageScrollerMessages = typeof messageScrollerMessages;
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,
emptyLabel: string,
assistantResponse?: HTMLElement,
) {
const text = getMessageText(message);
if (!text) {
return { label: emptyLabel, 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";
/** Shows a button back to the latest message once the reader scrolls up. Default true. */
jumpButton?: boolean;
/** Accessible label for the optional message navigation rail. */
navigationLabel?: string;
/** Classes merged onto the scrolling viewport. */
viewportClassName?: string;
/** Classes merged onto the log element that wraps the messages. */
contentClassName?: string;
/** Classes merged onto the navigation rail, used with `navigation="rail"`. */
railClassName?: string;
/** Ref to the scrolling viewport element. */
viewportRef?: Ref<HTMLElement>;
/** Extra props for the scrolling viewport. Its event handlers still run. */
viewportProps?: Omit<
ComponentPropsWithRef<"section">,
"children" | "className" | "ref"
>;
/** Extra props for the log element that wraps the messages. */
contentProps?: Omit<
ComponentPropsWithRef<"div">,
"children" | "className" | "ref"
>;
/** Override any built-in string. */
labels?: Partial<MessageScrollerMessages>;
}
export function MessageScroller({
followOutput = true,
followThreshold = 56,
smooth = true,
onFollowChange,
label,
busy,
navigation,
jumpButton = true,
navigationLabel,
viewportClassName,
contentClassName,
railClassName,
viewportRef: externalViewportRef,
viewportProps,
contentProps,
className,
children,
labels,
...props
}: MessageScrollerProps) {
const reduce = useReducedMotion() ?? false;
const t = useMessages("messageScroller", messageScrollerMessages, labels);
// Read by the stable rail sync so inline `labels` don't rebuild it each render.
const tRef = useRef(t);
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);
// Mirrors followingRef for rendering: the jump button shows while false.
const [atLiveEdge, setAtLiveEdge] = useState(true);
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;
setAtLiveEdge(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,
tRef.current("preview"),
assistantResponse,
);
return {
id,
label: preview.label,
description: preview.description,
ariaLabel: tRef.current(
sender === "user"
? "goToUser"
: sender === "assistant"
? "goToAssistant"
: "goToMessage",
{ index: index + 1, total: 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]);
useLayoutEffect(() => {
tRef.current = t;
scheduleRailSync();
}, [t, scheduleRailSync]);
// A scroll this component started must not read as the reader scrolling
// away. A smooth scroll can outlast any fixed guess, so the flag clears on
// `scrollend`; the timer is the fallback where that event doesn't exist.
const releaseAfterScroll = useCallback(
(viewport: HTMLElement, behavior: ScrollBehavior) => {
if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);
const release = () => {
programmaticScrollRef.current = false;
viewport.removeEventListener("scrollend", release);
if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);
};
if (behavior !== "smooth") {
scrollTimerRef.current = window.setTimeout(release, 0);
return;
}
const hasScrollEnd = "onscrollend" in window;
if (hasScrollEnd) viewport.addEventListener("scrollend", release);
scrollTimerRef.current = window.setTimeout(release, hasScrollEnd ? 1200 : 320);
},
[],
);
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;
}
releaseAfterScroll(viewport, behavior);
},
[releaseAfterScroll],
);
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;
}
releaseAfterScroll(viewport, behavior);
},
[railItems, reduce, releaseAfterScroll, scrollToEnd, setFollowing, smooth],
);
const viewport = (
<section
ref={setViewportRef}
aria-label={label ?? t("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>
);
const jumpToLatest = () => {
setFollowing(true);
scrollToEnd(reduce || !smooth ? "auto" : "smooth");
};
const showJump = jumpButton && followOutput && !atLiveEdge;
return (
<div
data-slot="message-scroller"
className={cn("relative min-h-0", className)}
{...props}
>
{navigation === "rail" ? (
<PreviewRail
items={railOverflowing ? railItems : []}
label={navigationLabel ?? t("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
)}
{/* Back to the live edge, once the reader has scrolled away from it. */}
<AnimatePresence>
{showJump ? (
<motion.div
key="jump"
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 8, scale: 0.95 }}
animate={{ opacity: 1, y: 0, scale: 1, transition: JUMP_IN }}
exit={reduce ? { opacity: 0, transition: JUMP_OUT } : { opacity: 0, y: 8, scale: 0.95, transition: JUMP_OUT }}
className="pointer-events-none absolute inset-x-0 bottom-3 flex justify-center"
>
<Tooltip content={t("jumpToLatest")} side="top">
<button
type="button"
onClick={jumpToLatest}
aria-label={t("jumpToLatest")}
// Card fill and the strong border: it floats over messages
// that share the background, and must read as a control.
className="pointer-events-auto inline-flex size-8 items-center justify-center rounded-full border border-(--color-border-strong) bg-card text-muted-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)] outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.97]"
>
<ArrowDown aria-hidden="true" className="size-4" />
</button>
</Tooltip>
</motion.div>
) : null}
</AnimatePresence>
</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 { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const previewRailMessages = {
label: "Section navigation",
};
export type PreviewRailMessages = typeof previewRailMessages;
export interface PreviewRailItem {
/** Unique key, used for the active item and passed to `onActiveChange`. */
id: string;
/** Title of the preview card and the tick's accessible name. */
label: string;
/** Accessible name for the tick when it should differ from `label`. */
ariaLabel?: string;
/** Muted text under the title in the preview card. */
description?: ReactNode;
/** Makes the tick a link; on touch, the first tap shows the preview. */
href?: string;
/** Link target for `href`. */
target?: "_blank" | "_self" | "_parent" | "_top";
/** Link `rel`. Default: "noreferrer noopener" when `target` is "_blank" */
rel?: string;
}
export interface PreviewRailProps {
/** Rail entries, each a tick with a preview card and an optional link. */
items: PreviewRailItem[];
/** Accessible name for the rail's nav element. Default: "Section navigation" */
label?: string;
/** Lay the ticks out in a column or a row. Default: "vertical" */
orientation?: "vertical" | "horizontal";
/** The selected item id, for controlled use. */
activeId?: string;
/** The initial selected item id when uncontrolled. Default: the first item. */
defaultActiveId?: string;
/** Called with the item id when an item is selected. */
onActiveChange?: (id: string) => void;
/** Called with the item when it is clicked or tapped. */
onItemSelect?: (item: PreviewRailItem) => void;
/** Custom content for the hover card. Default: the item's label and description. */
renderPreview?: (item: PreviewRailItem) => ReactNode;
/** Show a preview card beside the hovered or focused tick. Default: true */
showPreview?: boolean;
/** Which side of the rail the vertical preview card sits on. Default: "after" */
previewSide?: "before" | "after";
/** Keep the selected tick lit when nothing is hovered or focused. Default: false */
highlightActive?: boolean;
/** Length of each tick's slot along the rail (px). Default: 24 */
itemSize?: number;
children?: ReactNode;
/** Classes merged onto the root element. */
className?: string;
/** Classes merged onto the nav element that holds the ticks. */
railClassName?: string;
/** Classes merged onto the layer that positions the preview cards. */
previewContainerClassName?: string;
/** Classes merged onto the wrapper around the shown preview card. */
previewClassName?: string;
/** Override any built-in string. */
labels?: Partial<PreviewRailMessages>;
}
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: labelProp,
orientation = "vertical",
activeId,
defaultActiveId,
onActiveChange,
onItemSelect,
renderPreview,
showPreview = true,
previewSide = "after",
highlightActive = false,
itemSize = 24,
children,
className,
railClassName,
previewContainerClassName,
previewClassName,
labels,
}: PreviewRailProps) {
const t = useMessages("previewRail", previewRailMessages, labels);
const label = labelProp ?? t("label");
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 { AnimatePresence } from "motion/react";
import {
type ComponentProps,
type PointerEvent as ReactPointerEvent,
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 { TooltipSurface } from "@/components/motion/tooltip-surface";
import { type DismissReason, useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { assignRef } from "@/lib/merge-refs";
import { cn } from "@/lib/utils";
import { focusFromKeyboard, graceArea, inBox, inPolygon, watchModality } from "./tooltip/grace";
import { TooltipArrow, TooltipPositioner } from "./tooltip/positioner";
import {
type TooltipAlign,
type TooltipAnchor,
type TooltipPoint,
type TooltipSide,
useTooltipPointer,
} from "./tooltip/use-position";
export type { TooltipAlign, TooltipSide };
/* -------------------------------------------------------------------------- */
/* Provider */
/* -------------------------------------------------------------------------- */
interface TooltipTiming {
/** Delay before a hover opens a tooltip (ms). */
delay: number;
/** Delay before a tooltip closes once the pointer has left it (ms). */
closeDelay: number;
/** After one tooltip closes, others open instantly for this long (ms). */
skipDelay: number;
}
const TimingContext = createContext<TooltipTiming>({ delay: 120, closeDelay: 0, skipDelay: 300 });
export interface TooltipProviderProps extends Partial<TooltipTiming> {
children: ReactNode;
}
/** Shared timing for every tooltip inside it. Optional: tooltips work without one. */
export function TooltipProvider({ children, ...timing }: TooltipProviderProps) {
const parent = useContext(TimingContext);
const { delay = parent.delay, closeDelay = parent.closeDelay, skipDelay = parent.skipDelay } =
timing;
const value = useMemo(() => ({ delay, closeDelay, skipDelay }), [delay, closeDelay, skipDelay]);
return <TimingContext.Provider value={value}>{children}</TimingContext.Provider>;
}
/* -------------------------------------------------------------------------- */
/* Root */
/* -------------------------------------------------------------------------- */
// Moving along a toolbar should feel instant after the first label, and only
// one label may show at a time: a keyboard-focused control and a hovered one
// would otherwise both claim the screen.
let lastClosedAt = 0;
let current: { close: () => void } | null = null;
function isEmpty(content: ReactNode) {
return content == null || content === false || content === "";
}
interface TooltipContextValue {
open: boolean;
/** Show and hide without animating (keyboard focus, a warm toolbar, a replaced label). */
instant: boolean;
contentId: string;
labelId: string;
asLabel: boolean;
empty: boolean;
followCursor: boolean;
anchor: TooltipAnchor | null;
/** True when a TooltipTrigger owns the anchor; false for an external `anchorRef`. */
triggered: boolean;
floatingRef: RefObject<HTMLSpanElement | null>;
pointer: ReturnType<typeof useTooltipPointer>;
setTrigger: (element: TooltipAnchor | null) => void;
setEmpty: (empty: boolean) => void;
close: () => void;
onContentEnter: () => void;
onContentLeave: (event: ReactPointerEvent) => void;
}
const TooltipContext = createContext<TooltipContextValue | null>(null);
function useTooltipContext(part: string) {
const context = useContext(TooltipContext);
if (!context) throw new Error(`${part} must be used inside <Tooltip>`);
return context;
}
export interface TooltipRootProps {
children?: ReactNode;
/** Whether the tooltip is shown, for controlled use. */
open?: boolean;
/** Whether the tooltip starts shown when uncontrolled. Default: false */
defaultOpen?: boolean;
/** Called with the new state when the tooltip shows or hides. */
onOpenChange?: (open: boolean) => void;
/** Delay before showing on hover (ms). Keyboard focus shows immediately. */
delay?: number;
/** Delay before hiding once the pointer has left (ms). */
closeDelay?: number;
/** Never show, e.g. while the label it carries is already visible. */
disabled?: boolean;
/**
* Use the tooltip as the trigger's accessible name rather than its
* description. For icon-only controls whose only label is the tooltip.
*/
asLabel?: boolean;
/** Follow real pointer coordinates; keyboard focus still uses the anchor. */
followCursor?: boolean;
/** Existing anchor for controlled integrations such as chart cells. */
anchorRef?: RefObject<TooltipAnchor | null>;
/** Id of the tooltip surface, for anchors that reference it themselves. */
id?: string;
}
function TooltipRoot({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
delay: delayProp,
closeDelay: closeDelayProp,
disabled = false,
asLabel = false,
followCursor = false,
anchorRef,
id,
initialEmpty = false,
}: TooltipRootProps & { initialEmpty?: boolean }) {
const timing = useContext(TimingContext);
const delay = delayProp ?? timing.delay;
const closeDelay = closeDelayProp ?? timing.closeDelay;
const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
const open = controlledOpen ?? uncontrolledOpen;
// Keyboard focus and a warm toolbar show the label at once; animating
// something seen this often only makes it feel slow.
const [instant, setInstant] = useState(false);
const [empty, setEmpty] = useState(initialEmpty);
const [trigger, setTrigger] = useState<TooltipAnchor | null>(null);
const [external, setExternal] = useState<TooltipAnchor | null>(null);
const anchor = anchorRef ? external : trigger;
const generatedId = useId();
const contentId = id ?? `${generatedId}-content`;
const labelId = `${generatedId}-label`;
const floatingRef = useRef<HTMLSpanElement | null>(null);
const anchorObject = useRef<TooltipAnchor | null>(null);
const pointer = useTooltipPointer(anchor, followCursor);
// An external ref can attach after this component renders; read it once it has.
useLayoutEffect(() => {
if (!anchorRef) return;
const element = anchorRef.current ?? null;
if (element !== external) setExternal(element);
});
// Everything the event listeners read, current without re-binding them.
const latest = useRef({ open, delay, closeDelay, disabled, empty, onOpenChange, controlled: false });
useLayoutEffect(() => {
anchorObject.current = anchor;
latest.current = {
open,
delay,
closeDelay,
disabled,
empty,
onOpenChange,
controlled: controlledOpen !== undefined,
};
});
const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const grace = useRef<(() => void) | null>(null);
const self = useRef<{ close: () => void }>({ close: () => {} });
const clearTimers = useCallback(() => {
if (openTimer.current) clearTimeout(openTimer.current);
if (closeTimer.current) clearTimeout(closeTimer.current);
openTimer.current = null;
closeTimer.current = null;
}, []);
const stopGrace = useCallback(() => {
grace.current?.();
grace.current = null;
}, []);
// Only a real change reaches the consumer: a pointer leaving a closed
// tooltip is not news.
const commit = useCallback((next: boolean) => {
if (latest.current.open === next) return;
if (!latest.current.controlled) setUncontrolledOpen(next);
latest.current.onOpenChange?.(next);
}, []);
const openNow = useCallback(
(now = false) => {
clearTimers();
stopGrace();
if (latest.current.disabled || latest.current.empty) return;
// The label being replaced leaves at once, so two never show together.
if (current && current !== self.current) current.close();
current = self.current;
setInstant(now);
commit(true);
},
[clearTimers, stopGrace, commit],
);
const finish = useCallback(
(now: boolean) => {
clearTimers();
stopGrace();
if (latest.current.open) lastClosedAt = Date.now();
if (current === self.current) current = null;
if (latest.current.open) setInstant(now);
commit(false);
},
[clearTimers, stopGrace, commit],
);
// Also a listener (window blur, outside press), so it takes no arguments.
const close = useCallback(() => finish(false), [finish]);
useLayoutEffect(() => {
self.current.close = () => finish(true);
}, [finish]);
const requestOpen = useCallback(() => {
clearTimers();
if (latest.current.open || latest.current.disabled || latest.current.empty) return;
// Warm: another label is still showing (the pointer is crossing to this
// one), or one closed a moment ago. Either way, skip the delay and the fade.
const warm =
(current !== null && current !== self.current) ||
Date.now() - lastClosedAt < timing.skipDelay;
if (warm) openNow(true);
else if (latest.current.delay <= 0) openNow();
else openTimer.current = setTimeout(() => openNow(), latest.current.delay);
}, [clearTimers, openNow, timing.skipDelay]);
const requestClose = useCallback(() => {
clearTimers();
if (latest.current.closeDelay > 0) {
closeTimer.current = setTimeout(close, latest.current.closeDelay);
} else close();
}, [clearTimers, close]);
// Hold the label open while the pointer crosses from one box toward the other.
const startGrace = useCallback(
(exit: TooltipPoint, from: Element, to: Element | null) => {
stopGrace();
if (!to) return requestClose();
const target = to.getBoundingClientRect();
const origin = from.getBoundingClientRect();
const corridor = graceArea(exit, target);
const onMove = (event: PointerEvent) => {
const point = { x: event.clientX, y: event.clientY };
if (inBox(point, target) || inBox(point, origin)) return;
if (!inPolygon(point, corridor)) requestClose();
};
document.addEventListener("pointermove", onMove);
grace.current = () => document.removeEventListener("pointermove", onMove);
},
[stopGrace, requestClose],
);
const hover = useHoverGesture();
const tap = useTapGesture<boolean>();
// Listeners go on the trigger itself rather than on cloned props, so a
// component that owns its own handlers keeps them, and no wrapper element
// sits between the control and its layout.
useEffect(() => {
if (anchorRef || !trigger) return;
watchModality();
// A mouse press dismisses the label and keeps it away until the pointer
// leaves; hovering a control you just clicked should not bring it back.
let suppressed = false;
// Focus that came from the keyboard holds the label open on its own.
let keyboardFocus = false;
const onEnter = (event: PointerEvent) => {
if (!hover.enter(event)) return;
stopGrace();
if (closeTimer.current) clearTimeout(closeTimer.current);
if (!suppressed) requestOpen();
};
const onLeave = (event: PointerEvent) => {
if (!hover.leave(event)) return;
suppressed = false;
if (keyboardFocus) return;
if (openTimer.current) {
clearTimers();
return;
}
if (latest.current.open && !followCursor) {
startGrace({ x: event.clientX, y: event.clientY }, trigger, floatingRef.current);
} else requestClose();
};
const onDown = (event: PointerEvent) => {
tap.start(event, latest.current.open);
if (event.pointerType === "mouse") {
suppressed = true;
close();
}
};
// A finger never hovers, and Safari does not focus a button on tap either,
// so the label is only reachable if the tap itself toggles it. The click
// carries no pointerType; the pointerdown before it says whether it was a
// tap, and keyboard activation has none at all.
const onClick = () => {
const gesture = tap.take();
if (!gesture || gesture.pointerType === "mouse") return;
if (gesture.state) close();
else openNow();
};
const onKey = () => tap.drop();
const onFocusIn = () => {
if (!focusFromKeyboard()) return;
keyboardFocus = true;
openNow(true);
};
const onFocusOut = (event: FocusEvent) => {
if (trigger.contains(event.relatedTarget as Node | null)) return;
const fromKeyboard = keyboardFocus;
keyboardFocus = false;
finish(fromKeyboard);
};
// Both element kinds dispatch the same events; one type keeps the listeners typed.
const el = trigger as HTMLElement;
el.addEventListener("pointerenter", onEnter);
el.addEventListener("pointerleave", onLeave);
el.addEventListener("pointerdown", onDown);
el.addEventListener("pointercancel", tap.drop);
el.addEventListener("click", onClick);
el.addEventListener("keydown", onKey);
el.addEventListener("focusin", onFocusIn);
el.addEventListener("focusout", onFocusOut);
return () => {
el.removeEventListener("pointerenter", onEnter);
el.removeEventListener("pointerleave", onLeave);
el.removeEventListener("pointerdown", onDown);
el.removeEventListener("pointercancel", tap.drop);
el.removeEventListener("click", onClick);
el.removeEventListener("keydown", onKey);
el.removeEventListener("focusin", onFocusIn);
el.removeEventListener("focusout", onFocusOut);
};
}, [
anchorRef,
trigger,
followCursor,
hover,
tap,
requestOpen,
requestClose,
openNow,
close,
finish,
clearTimers,
stopGrace,
startGrace,
]);
// While open, a trigger that turns disabled loses focus without a blur event,
// and a window that loses focus never reports the pointer leaving.
useEffect(() => {
if (!open || anchorRef || !trigger) return;
const observer = new MutationObserver(() => {
if (trigger.matches(":disabled, [aria-disabled='true']")) close();
});
observer.observe(trigger, { attributes: true, attributeFilter: ["disabled", "aria-disabled"] });
window.addEventListener("blur", close);
return () => {
observer.disconnect();
window.removeEventListener("blur", close);
};
}, [open, anchorRef, trigger, close]);
// A chart drives its own open state and swaps content as it goes; only a
// trigger-owned label closes itself for having nothing to say.
useEffect(() => {
if (disabled || (empty && !anchorRef)) close();
}, [disabled, empty, anchorRef, close]);
useEffect(
() => () => {
clearTimers();
stopGrace();
if (current === self.current) current = null;
},
[clearTimers, stopGrace],
);
const insideTooltip = useCallback(
(target: Element) => Boolean(floatingRef.current?.contains(target)),
[],
);
// ...and closed by the next tap that lands somewhere else, or Escape. The
// label covers nothing interactive, so that tap passes through to what it hit.
// Escape is a key press, so the label goes at once.
const dismiss = useCallback((reason: DismissReason) => finish(reason === "escape"), [finish]);
useDismiss(open, dismiss, anchorObject, { ignore: insideTooltip });
const onContentEnter = useCallback(() => {
stopGrace();
clearTimers();
}, [stopGrace, clearTimers]);
const onContentLeave = useCallback(
(event: ReactPointerEvent) => {
const floating = floatingRef.current;
if (!floating) return;
if (anchorRef) {
// Bridge the small gap back onto a chart; it reopens on its own terms.
clearTimers();
closeTimer.current = setTimeout(close, 100);
return;
}
startGrace({ x: event.clientX, y: event.clientY }, floating, anchorObject.current);
},
[anchorRef, clearTimers, close, startGrace],
);
const value = useMemo<TooltipContextValue>(
() => ({
open,
instant,
contentId,
labelId,
asLabel,
empty,
followCursor,
anchor,
triggered: !anchorRef,
floatingRef,
pointer,
setTrigger,
setEmpty,
close,
onContentEnter,
onContentLeave,
}),
[
open,
instant,
contentId,
labelId,
asLabel,
empty,
followCursor,
anchor,
anchorRef,
pointer,
close,
onContentEnter,
onContentLeave,
],
);
return <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>;
}
/* -------------------------------------------------------------------------- */
/* Trigger */
/* -------------------------------------------------------------------------- */
function mergeIds(...ids: unknown[]) {
return ids.filter((value) => typeof value === "string" && value).join(" ") || undefined;
}
export interface TooltipTriggerProps extends ComponentProps<"button"> {
/** Use the single child element as the trigger instead of rendering a button. */
asChild?: boolean;
}
export function TooltipTrigger({ asChild = false, children, ref, ...props }: TooltipTriggerProps) {
const { open, contentId, labelId, asLabel, empty, setTrigger } =
useTooltipContext("TooltipTrigger");
const child = asChild && isValidElement(children) ? children : null;
const childProps = (child?.props ?? props) as Record<string, unknown>;
const childRef = child ? (childProps.ref as Ref<TooltipAnchor> | undefined) : undefined;
const attached = useRef<TooltipAnchor | null>(null);
const setRef = useCallback(
(element: TooltipAnchor | null) => {
attached.current = element;
setTrigger(element);
assignRef(childRef ?? (ref as Ref<TooltipAnchor> | undefined), element);
},
[setTrigger, childRef, ref],
);
useEffect(() => {
if (process.env.NODE_ENV !== "production" && child && !attached.current) {
console.warn(
"TooltipTrigger: the child did not attach a ref, so the tooltip has nothing to listen to. Render a DOM element or a component that passes `ref` through.",
);
}
}, [child]);
const aria = asLabel
? {
"aria-labelledby": empty
? (childProps["aria-labelledby"] as string | undefined)
: labelId,
}
: {
"aria-describedby": mergeIds(
childProps["aria-describedby"],
open && !empty ? contentId : undefined,
),
};
if (asChild) {
if (!child) return children;
return cloneElement(child as ReactElement<Record<string, unknown>>, { ref: setRef, ...aria });
}
return (
<button
type="button"
data-state={open ? "open" : "closed"}
{...props}
ref={setRef as Ref<HTMLButtonElement>}
{...aria}
>
{children}
</button>
);
}
/* -------------------------------------------------------------------------- */
/* Content */
/* -------------------------------------------------------------------------- */
export interface TooltipContentProps {
children?: ReactNode;
/** Preferred side of the anchor. Flips when there is no room. Default: "top" */
side?: TooltipSide;
/** Alignment along the chosen side. Default: "center" */
align?: TooltipAlign;
/** Gap between anchor and tooltip (px). */
sideOffset?: number;
/** Draw an arrow pointing at the anchor. */
arrow?: boolean;
/** Point within the anchor, as fractions of its rendered width and height. */
anchorPoint?: TooltipPoint;
/** Classes merged onto the tooltip surface. */
className?: string;
}
export function TooltipContent({
children,
side = "top",
align = "center",
sideOffset,
arrow = false,
anchorPoint,
className,
}: TooltipContentProps) {
const {
open,
instant,
contentId,
labelId,
asLabel,
followCursor,
anchor,
floatingRef,
pointer,
setEmpty,
close,
onContentEnter,
onContentLeave,
} = useTooltipContext("TooltipContent");
const empty = isEmpty(children);
const arrowRef = useRef<SVGSVGElement | null>(null);
useLayoutEffect(() => {
setEmpty(empty);
}, [empty, setEmpty]);
if (typeof document === "undefined") return null;
return createPortal(
<>
{/* The name has to exist while the label is closed, so it lives apart from the surface. */}
{asLabel && !empty ? (
<span id={labelId} hidden>
{children}
</span>
) : null}
{/* `custom` reaches a surface that is already exiting, so a label closed
from the keyboard or replaced by a neighbour leaves without animating. */}
<AnimatePresence custom={instant}>
{open && !empty ? (
<TooltipPositioner
key="tooltip"
anchor={anchor}
floatingRef={floatingRef}
arrowRef={arrow ? arrowRef : undefined}
anchorPoint={anchorPoint}
followCursor={followCursor}
side={side}
align={align}
sideOffset={sideOffset}
onDismiss={close}
pointer={pointer}
>
{(positioned, isPresent, placedSide) => (
<TooltipSurface
id={asLabel ? undefined : contentId}
aria-hidden={asLabel || undefined}
ready={positioned}
instant={instant}
onPointerEnter={onContentEnter}
onPointerLeave={onContentLeave}
style={{ pointerEvents: isPresent && !followCursor ? "auto" : "none" }}
className={cn(
"max-w-[min(20rem,calc(100vw-16px))] whitespace-normal break-words",
arrow && "relative",
className,
)}
>
{children}
{arrow ? <TooltipArrow ref={arrowRef} side={placedSide} /> : null}
</TooltipSurface>
)}
</TooltipPositioner>
) : null}
</AnimatePresence>
</>,
document.body,
);
}
/* -------------------------------------------------------------------------- */
/* Tooltip (root, or one-line shorthand when given `content`) */
/* -------------------------------------------------------------------------- */
export interface TooltipProps
extends TooltipRootProps,
Omit<TooltipContentProps, "children" | "className"> {
/**
* Shorthand: the tooltip's content. With it, `children` is the trigger
* element; without it, compose `TooltipTrigger` and `TooltipContent`.
*/
content?: ReactNode;
/** Shorthand only: classes for the tooltip surface. */
className?: string;
}
export function Tooltip(props: TooltipProps) {
if (!("content" in props)) return <TooltipRoot {...props} />;
const {
content,
children,
side,
align,
sideOffset,
arrow,
anchorPoint,
className,
...root
} = props;
if (!root.anchorRef && !isValidElement(children)) return children ?? null;
return (
<TooltipRoot {...root} initialEmpty={isEmpty(content)}>
{isValidElement(children) ? <TooltipTrigger asChild>{children}</TooltipTrigger> : null}
<TooltipContent
side={side}
align={align}
sideOffset={sideOffset}
arrow={arrow}
anchorPoint={anchorPoint}
className={className}
>
{content}
</TooltipContent>
</TooltipRoot>
);
}
type Point = { x: number; y: number };
type Box = { left: number; top: number; right: number; bottom: number };
/**
* The corridor a pointer may cross between the trigger and the open tooltip
* without closing it: the convex hull of where it left and the box it is
* heading for. A fixed timeout either cuts a slow diagonal move short or keeps
* the label alive after the pointer has plainly gone elsewhere; this follows
* the path itself.
*/
export function graceArea(exit: Point, target: Box): Point[] {
// A few pixels either side of the exit point give the corridor some width at
// its narrow end, so a hand that drifts sideways while it moves stays inside.
const pad = 5;
return hull([
{ x: exit.x - pad, y: exit.y - pad },
{ x: exit.x + pad, y: exit.y - pad },
{ x: exit.x - pad, y: exit.y + pad },
{ x: exit.x + pad, y: exit.y + pad },
{ x: target.left, y: target.top },
{ x: target.right, y: target.top },
{ x: target.right, y: target.bottom },
{ x: target.left, y: target.bottom },
]);
}
export function inBox(point: Point, box: Box) {
return (
point.x >= box.left && point.x <= box.right && point.y >= box.top && point.y <= box.bottom
);
}
export function inPolygon(point: Point, polygon: Point[]) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const a = polygon[i];
const b = polygon[j];
if (
a.y > point.y !== b.y > point.y &&
point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x
) {
inside = !inside;
}
}
return inside;
}
// Monotone chain; the corridor is always convex, so a hull is all it needs.
function hull(points: Point[]) {
const sorted = [...points].sort((a, b) => a.x - b.x || a.y - b.y);
const cross = (o: Point, a: Point, b: Point) =>
(a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
const lower: Point[] = [];
for (const p of sorted) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {
lower.pop();
}
lower.push(p);
}
const upper: Point[] = [];
for (let i = sorted.length - 1; i >= 0; i--) {
const p = sorted[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {
upper.pop();
}
upper.push(p);
}
lower.pop();
upper.pop();
return lower.concat(upper);
}
/**
* How the user last reached for the page. A focus that a mouse press caused is
* not a request to read the label: the pointer is already on the control and
* hovering showed it. A focus that followed a key - Tab, or a roving arrow key
* moving focus in script - is the only way a keyboard user sees it at all.
*/
let modality: "keyboard" | "pointer" = "keyboard";
let listening = false;
export function watchModality() {
if (listening || typeof window === "undefined") return;
listening = true;
window.addEventListener("keydown", () => (modality = "keyboard"), true);
window.addEventListener("pointerdown", () => (modality = "pointer"), true);
}
export function focusFromKeyboard() {
return modality === "keyboard";
}
"use client";
import { useIsPresent } from "motion/react";
import { type CSSProperties, type ReactNode, type Ref, useCallback, useState } from "react";
import { type TooltipSide, useTooltipPosition } from "./use-position";
type PositionProps = Parameters<typeof useTooltipPosition>[0];
/** Readiness lives with the mounted overlay, not a trigger ref's attach/detach cycle. */
export function TooltipPositioner({
children,
...position
}: Omit<PositionProps, "open" | "onPosition"> & {
children: (ready: boolean, present: boolean, side: TooltipSide) => ReactNode;
}) {
const present = useIsPresent();
const [ready, setReady] = useState(false);
const [side, setSide] = useState<TooltipSide>(position.side);
const onPosition = useCallback((placed: TooltipSide) => {
setReady(true);
setSide(placed);
}, []);
useTooltipPosition({ ...position, open: present, onPosition });
return (
<span
ref={position.floatingRef}
inert={!present}
aria-hidden={!present || undefined}
className="pointer-events-none fixed left-0 top-0 z-[9999] w-max"
style={{ visibility: "hidden", maxWidth: "calc(100vw - 16px)" }}
>
{children(ready, present, side)}
</span>
);
}
// Each arrow is a 12px box whose base sits on the surface's inner border edge,
// so its fill covers the border beneath it and only the two outer edges stroke.
const ARROW: Record<TooltipSide, { path: string; style: CSSProperties }> = {
top: { path: "M0 6L6 12L12 6", style: { top: "calc(100% - 6px)" } },
bottom: { path: "M0 6L6 0L12 6", style: { bottom: "calc(100% - 6px)" } },
left: { path: "M6 0L12 6L6 12", style: { left: "calc(100% - 6px)" } },
right: { path: "M6 0L0 6L6 12", style: { right: "calc(100% - 6px)" } },
};
export function TooltipArrow({ side, ref }: { side: TooltipSide; ref: Ref<SVGSVGElement> }) {
const { path, style } = ARROW[side];
return (
<svg
ref={ref}
aria-hidden="true"
width="12"
height="12"
viewBox="0 0 12 12"
className="pointer-events-none absolute overflow-visible"
style={style}
>
{/* Redrawn to fit the surface's edge once placed (see arrowShape). */}
<path data-arrow-fill="" d={`${path}Z`} style={{ fill: "var(--tooltip-arrow-fill, transparent)" }} />
<path
data-arrow-stroke=""
d={path}
fill="none"
strokeWidth="1"
style={{ stroke: "var(--tooltip-arrow-stroke, transparent)" }}
/>
</svg>
);
}
"use client";
import {
arrow as arrowMiddleware,
autoUpdate,
computePosition,
flip,
hide,
offset,
type Placement,
shift,
type VirtualElement,
} from "@floating-ui/dom";
import { type RefObject, useCallback, useLayoutEffect, useMemo, useRef } from "react";
export type TooltipSide = "top" | "right" | "bottom" | "left";
export type TooltipAlign = "start" | "center" | "end";
export type TooltipPoint = {
/** Horizontal position; for `anchorPoint`, a 0 to 1 fraction of the anchor's width. */
x: number;
/** Vertical position; for `anchorPoint`, a 0 to 1 fraction of the anchor's height. */
y: number;
};
export type TooltipAnchor = HTMLElement | SVGElement;
const ORIGIN: Record<TooltipSide, string> = {
top: "center bottom",
bottom: "center top",
left: "right center",
right: "left center",
};
/** `top` painted over `bottom`, as one opaque colour. Falls back to `top`. */
function blend(top: string, bottom: string) {
const context = document.createElement("canvas").getContext("2d", { willReadFrequently: true });
if (!context) return top;
context.fillStyle = bottom;
context.fillRect(0, 0, 1, 1);
context.fillStyle = top;
context.fillRect(0, 0, 1, 1);
const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data;
// A see-through background has nothing solid to blend onto.
return a === 255 ? `rgb(${r}, ${g}, ${b})` : top;
}
/** The arrow element's box, which the arrow middleware centres along the edge. */
const ARROW_SIZE = 12;
/** How far the tip reaches past the border's inner edge. */
const ARROW_REACH = 6;
/**
* How far a rounded edge has curved in from its straight line at `position`
* along an edge of `length`, with corners of `radius`. Zero on the straight
* stretch between the corners.
*/
function curveDepth(position: number, length: number, radius: number) {
const offset =
position < radius ? radius - position : position > length - radius ? position - (length - radius) : 0;
if (offset <= 0) return 0;
return radius - Math.sqrt(Math.max(radius * radius - offset * offset, 0));
}
/**
* The arrow's two paths, in the surface's border-box coordinates. Each 45°
* side runs from the tip until it meets the middle of the surface's border,
* wherever that is: on a straight stretch, or partway round a pill's curved
* end. The stroke covers only those two sides, so the border flows straight
* into them. The fill closes a little inside the surface, hiding the stretch
* of border the arrow sits on.
*/
function arrowShape({
side,
center,
width,
height,
radius,
border,
}: {
side: TooltipSide;
center: number;
width: number;
height: number;
radius: number;
border: number;
}) {
const vertical = side === "top" || side === "bottom";
const length = vertical ? width : height;
// Work on one edge: `depth` runs inward from the edge's outer line, `along` runs down it.
const tip = { depth: border - ARROW_REACH, along: center };
// The border's centre line: the stroke meets it there, so the two line up.
const line = border / 2;
// Both sides follow the same rule, so an arrow a pixel off-centre stays symmetric.
const curved =
curveDepth(center - ARROW_SIZE / 2, length, radius) > 0 ||
curveDepth(center + ARROW_SIZE / 2, length, radius) > 0;
const meet = (direction: -1 | 1) => {
// On a straight stretch the 45° side meets the border directly.
if (!curved) {
for (let t = 0; t <= ARROW_SIZE; t += 0.05) {
const along = center + direction * t;
const depth = tip.depth + t;
if (depth >= line) return { depth, along };
}
}
// On a pill's round end a 45° side passes outside the curve, or meets it
// at a kink. Run the side tangent to the curve instead, so the border
// flows into it without a corner.
const curve = radius - line;
const centre = { depth: radius, along: direction < 0 ? radius : length - radius };
const dx = tip.depth - centre.depth;
const dy = tip.along - centre.along;
const distance = Math.hypot(dx, dy);
if (distance <= curve) return { depth: line, along: center + direction * ARROW_REACH };
const base = Math.atan2(dy, dx);
const spread = Math.acos(curve / distance);
const candidates = [base + spread, base - spread].map((angle) => ({
depth: centre.depth + curve * Math.cos(angle),
along: centre.along + curve * Math.sin(angle),
}));
// The tangent on this side of the tip.
return direction < 0
? candidates[0].along < candidates[1].along
? candidates[0]
: candidates[1]
: candidates[0].along > candidates[1].along
? candidates[0]
: candidates[1];
};
const start = meet(-1);
const end = meet(1);
const inside = Math.max(start.depth, end.depth) + border + 1;
const point = ({ depth, along }: { depth: number; along: number }) => {
const [x, y] =
side === "right"
? [depth, along]
: side === "left"
? [width - depth, along]
: side === "bottom"
? [along, depth]
: [along, height - depth];
return `${x.toFixed(2)} ${y.toFixed(2)}`;
};
return {
fill: `M${point(tip)}L${point(start)}L${point({ depth: inside, along: start.along })}L${point({ depth: inside, along: end.along })}L${point(end)}Z`,
stroke: `M${point(start)}L${point(tip)}L${point(end)}`,
};
}
/** Position is geometry, not animation. One write per frame, never a spring chasing a pointer. */
export function useTooltipPosition({
open,
anchor,
floatingRef,
arrowRef,
anchorPoint,
followCursor,
side,
align,
sideOffset,
onDismiss,
onPosition,
pointer,
}: {
open: boolean;
anchor: TooltipAnchor | null;
floatingRef: RefObject<HTMLSpanElement | null>;
arrowRef?: RefObject<SVGSVGElement | null>;
anchorPoint?: TooltipPoint;
followCursor: boolean;
side: TooltipSide;
align: TooltipAlign;
sideOffset?: number;
onDismiss: () => void;
onPosition: (side: TooltipSide) => void;
pointer: ReturnType<typeof useTooltipPointer>;
}) {
const { cursor, onMove } = pointer;
const preferred: Placement = align === "center" ? side : `${side}-${align}`;
const cursorSide = useRef<Placement | null>(null);
useLayoutEffect(() => {
cursorSide.current = open ? preferred : null;
}, [open, preferred]);
const frame = useRef<number | null>(null);
const version = useRef(0);
const update = useRef<() => void>(() => {});
const schedule = useCallback(() => {
// Invalidate older async calculations as soon as new geometry is requested.
version.current++;
if (frame.current !== null) return;
frame.current = requestAnimationFrame(() => {
frame.current = null;
update.current();
});
}, []);
useLayoutEffect(() => {
onMove.current = schedule;
return () => {
onMove.current = null;
};
}, [onMove, schedule]);
const pointX = anchorPoint?.x;
const pointY = anchorPoint?.y;
// Latest committed inputs are read without recreating observers for every period/content update.
useLayoutEffect(() => {
update.current = () => {
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const revision = ++version.current;
const currentCursor = followCursor ? cursor.current : null;
const virtual = Boolean(currentCursor) || pointX !== undefined || pointY !== undefined;
const reference: Element | VirtualElement = virtual
? {
contextElement: anchor,
getBoundingClientRect: () => {
const rect = anchor.getBoundingClientRect();
const x = currentCursor?.x ?? rect.left + rect.width * (pointX ?? 0.5);
const y = currentCursor?.y ?? rect.top + rect.height * (pointY ?? 0.5);
return { x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 };
},
}
: anchor;
const arrowElement = arrowRef?.current ?? null;
void computePosition(reference, floating, {
strategy: "fixed",
placement: currentCursor ? (cursorSide.current ?? preferred) : preferred,
middleware: [
offset(sideOffset ?? (currentCursor ? 12 : 8)),
flip({ padding: 8 }),
shift({ padding: 8 }),
...(arrowElement ? [arrowMiddleware({ element: arrowElement, padding: 10 })] : []),
// A label left floating over whatever scrolled into its trigger's place
// describes nothing there. Points inside a chart move with the chart.
...(virtual ? [] : [hide({ strategy: "referenceHidden" })]),
],
}).then(({ x, y, placement, middlewareData }) => {
if (version.current !== revision || !floating.isConnected) return;
// Hold the chosen side for this hover session. Crossing a flip threshold
// repeatedly must not bounce the surface above and below the pointer.
if (currentCursor) cursorSide.current = placement;
else cursorSide.current = null;
const placedSide = placement.split("-")[0] as TooltipSide;
const dpr = window.devicePixelRatio || 1;
floating.style.transform = `translate3d(${Math.round(x * dpr) / dpr}px, ${Math.round(y * dpr) / dpr}px, 0)`;
floating.style.setProperty("--tooltip-origin", ORIGIN[placedSide]);
// A box with no size has no clipped state to report, only a missing layout.
const box = anchor.getBoundingClientRect();
const clipped =
Boolean(middlewareData.hide?.referenceHidden) && (box.width > 0 || box.height > 0);
floating.style.visibility = clipped ? "hidden" : "visible";
floating.dataset.placement = placement;
const surface = arrowElement?.parentElement;
if (arrowElement && surface) {
// The middleware centres the 12px arrow box along the edge; its
// centre is where the tip points. The paths are drawn in the
// surface's border-box coordinates, so the svg sits at its corner.
const { x: ax, y: ay } = middlewareData.arrow ?? {};
const vertical = placedSide === "top" || placedSide === "bottom";
const width = surface.offsetWidth;
const height = surface.offsetHeight;
const along = (vertical ? ax : ay) ?? ((vertical ? width : height) - ARROW_SIZE) / 2;
const style = getComputedStyle(surface);
const shape = arrowShape({
side: placedSide,
center: along + ARROW_SIZE / 2,
width,
height,
// `rounded-full` resolves to a huge radius; the box clamps it to half its short side.
radius: Math.min(Number.parseFloat(style.borderTopLeftRadius) || 0, width / 2, height / 2),
border: surface.clientLeft,
});
Object.assign(arrowElement.style, {
left: `${-surface.clientLeft}px`,
top: `${-surface.clientTop}px`,
right: "auto",
bottom: "auto",
});
arrowElement.querySelector("[data-arrow-fill]")?.setAttribute("d", shape.fill);
arrowElement.querySelector("[data-arrow-stroke]")?.setAttribute("d", shape.stroke);
// Paint with whatever the surface resolved to, so a restyled tooltip
// keeps a matching arrow without a second set of classes. A
// see-through border is drawn over the surface's own background, so
// the stroke takes that blended colour: half of it sits over the
// page, and it overlaps the border where the two meet.
arrowElement.style.setProperty("--tooltip-arrow-fill", style.backgroundColor);
arrowElement.style.setProperty(
"--tooltip-arrow-stroke",
blend(style.borderTopColor, style.backgroundColor),
);
}
onPosition(placedSide);
});
};
if (open) schedule();
}, [
open,
anchor,
floatingRef,
arrowRef,
followCursor,
pointX,
pointY,
preferred,
sideOffset,
schedule,
onPosition,
cursor,
]);
useLayoutEffect(() => {
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const stop = autoUpdate(anchor, floating, schedule);
const onScroll = () => {
// A stationary pointer no longer describes the same chart point after scrolling.
if (followCursor && cursor.current) onDismiss();
};
window.addEventListener("scroll", onScroll, true);
return () => {
stop();
window.removeEventListener("scroll", onScroll, true);
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
frame.current = null;
};
}, [open, anchor, floatingRef, followCursor, onDismiss, schedule, cursor]);
useLayoutEffect(
() => () => {
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
},
[],
);
}
/** Pointer lifetime belongs to the anchor, including the opening delay. */
export function useTooltipPointer(anchor: TooltipAnchor | null, followCursor: boolean) {
const cursor = useRef<TooltipPoint | null>(null);
const onMove = useRef<(() => void) | null>(null);
const pointerFocus = useRef(false);
useLayoutEffect(() => {
if (!anchor || !followCursor) return;
const point = (event: PointerEvent) => {
if (event.type === "pointermove" && event.pointerType === "touch" && !event.buttons) return;
cursor.current = { x: event.clientX, y: event.clientY };
if (event.type === "pointerdown") pointerFocus.current = true;
onMove.current?.();
};
const keyboard = () => {
cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const focus = () => {
if (!pointerFocus.current) cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const leave = () => {
cursor.current = null;
};
anchor.addEventListener("pointerenter", point as EventListener, { passive: true });
anchor.addEventListener("pointermove", point as EventListener, { passive: true });
anchor.addEventListener("pointerdown", point as EventListener, { passive: true });
anchor.addEventListener("pointerleave", leave);
anchor.addEventListener("pointercancel", leave);
anchor.addEventListener("keydown", keyboard);
anchor.addEventListener("focusin", focus);
return () => {
cursor.current = null;
anchor.removeEventListener("pointerenter", point as EventListener);
anchor.removeEventListener("pointermove", point as EventListener);
anchor.removeEventListener("pointerdown", point as EventListener);
anchor.removeEventListener("pointerleave", leave);
anchor.removeEventListener("pointercancel", leave);
anchor.removeEventListener("keydown", keyboard);
anchor.removeEventListener("focusin", focus);
};
}, [anchor, followCursor]);
return useMemo(() => ({ cursor, onMove }), []);
}
"use client";
import { motion, useReducedMotion, type Variants } from "motion/react";
import type { ComponentProps, ReactNode, Ref } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
const ENTER = { duration: 0.18, ease: EASE_OUT };
const EXIT = { duration: 0.12, ease: EASE_OUT };
const INSTANT = { duration: 0 };
/**
* `custom` is the `instant` flag. An exiting surface reads it from its
* `AnimatePresence`, so a tooltip replaced by a neighbour vanishes at once
* even though it has already left the React tree.
*/
const variants = (reduce: boolean): Variants => ({
closed: (instant = false) => ({
opacity: 0,
scale: reduce ? 1 : 0.97,
transition: instant ? INSTANT : EXIT,
}),
open: (instant = false) => ({
opacity: 1,
scale: 1,
transition: instant ? INSTANT : ENTER,
}),
});
/** Presentation only: the unanimated parent owns measurement and positioning. */
export function TooltipSurface({
children,
className,
ref,
ready = true,
instant = false,
style,
...props
}: Omit<ComponentProps<typeof motion.span>, "children"> & {
children?: ReactNode;
/** Start the entrance only after the positioning layer has been measured. */
ready?: boolean;
/**
* Appear and disappear without animating: a label opened from the keyboard,
* or one of a row of tooltips the pointer is moving along.
*/
instant?: boolean;
ref?: Ref<HTMLSpanElement>;
}) {
const reduce = useReducedMotion() ?? false;
return (
<motion.span
ref={ref}
role="tooltip"
custom={instant}
variants={variants(reduce)}
initial="closed"
animate={ready ? "open" : "closed"}
exit="closed"
style={{ transformOrigin: "var(--tooltip-origin, center)", ...style }}
className={cn(
"block whitespace-nowrap rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)]",
className,
)}
{...props}
>
{children}
</motion.span>
);
}
"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;
// The reply's bubble opens with the typing dots in it and streams into
// the same bubble, so nothing swaps when the first words arrive.
setMessages((current) => [
...current,
{ id: userId, from: "user", content: prompt, animateIn: true },
{
id: assistantId,
from: "assistant",
content: "",
animateIn: true,
streaming: true,
},
]);
setPending(true);
replyTimer.current = window.setTimeout(() => {
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);
// A reply stopped before its first word leaves no empty bubble behind.
setMessages((current) =>
current
.filter((message) => !(message.streaming && !message.content))
.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
}
// The reply's bubble pops from its corner; a sent row
// already rises as a whole.
animateIn={message.from === "assistant" && message.animateIn}
>
<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>
))}
</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 { ArrowUp, ChevronDown, Plus, Square } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
type ComponentProps,
type FormEvent,
type KeyboardEvent,
type ReactNode,
type TextareaHTMLAttributes,
useCallback,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
import { ClipResizeFrame } from "@/components/agents/clip-resize-frame";
import { Button } from "@/components/motion/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/components/motion/dropdown-menu";
import { MENU_ITEM_CLASS, MenuItemHighlight } from "@/components/motion/menu/menu-item-highlight";
import { Tooltip } from "@/components/motion/tooltip";
import { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from "@/lib/ease";
import { useRowCursor } from "@/lib/hooks/use-row-cursor";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
/** One identity for the default, so the filtered list stays stable. */
const NO_COMMANDS: PromptCommand[] = [];
// The slash list rises in and drops away faster; rows fade in and out as the
// filter changes, and the rest slide into place.
const LIST_IN = { duration: 0.18, ease: EASE_OUT } as const;
const LIST_OUT = { duration: 0.12, ease: EASE_OUT } as const;
const ROW_OUT = { duration: 0.1, ease: EASE_OUT } as const;
const ROW_MOVE = { layout: SPRING_LAYOUT, opacity: { duration: 0.16, ease: EASE_OUT } } as const;
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const promptInputMessages = {
placeholder: "Ask the agent to do something…",
label: "Prompt",
addToPrompt: "Add to prompt",
chooseModel: "Choose model",
send: "Send prompt",
stop: "Stop generating",
commands: "Commands",
};
export type PromptInputMessages = typeof promptInputMessages;
export interface PromptModel {
/** Unique key, passed to `onModelChange` and `onSubmit`. */
value: string;
/** Name shown in the model menu and on its trigger when selected. */
label: ReactNode;
/** Icon before the label in the menu and on the trigger. */
icon?: ReactNode;
/** Stops the model from being picked. */
disabled?: boolean;
}
export interface PromptAction {
/** Unique key, passed to `onAction` when the item is chosen. */
value: string;
/** Item text in the add menu. */
label: ReactNode;
/** Muted line under the label. */
description?: ReactNode;
/** Icon before the label. */
icon?: ReactNode;
/** Stops the item from being chosen. */
disabled?: boolean;
}
export interface PromptCommand {
/** What follows the slash: typing `/value` finds it, and picking it writes `/value ` into the prompt. */
value: string;
/** Name shown in the command list. Also matched while typing. */
label: string;
/** Muted line beside the label. */
description?: ReactNode;
/** Icon before the label. */
icon?: ReactNode;
}
export interface PromptInputProps extends Omit<
TextareaHTMLAttributes<HTMLTextAreaElement>,
"value" | "defaultValue" | "onChange" | "onSubmit" | "children"
> {
/** The prompt text, for controlled use. */
value?: string;
/** The initial prompt text when uncontrolled. Default: "" */
defaultValue?: string;
/** Called with the new text on every edit. */
onValueChange?: (value: string) => void;
/** Models listed in the model menu. Hidden when empty. */
models?: PromptModel[];
/** The selected model's value, for controlled use. */
model?: string;
/** The initial model when uncontrolled. Default: the first model */
defaultModel?: string;
/** Called with the model's value when a model is picked. */
onModelChange?: (model: string) => void;
/** Items in the add menu next to the input. Hidden when empty. */
actions?: PromptAction[];
/** Called with the action's value when an add menu item is chosen. */
onAction?: (action: string) => void;
/** Slash commands. Typing `/` at the start of a word lists them above the input. Hidden when empty. */
commands?: PromptCommand[];
/** Called with the command's value when a slash command is picked. */
onCommand?: (command: string) => void;
/** Called with the trimmed prompt and selected model on Enter or the send button. */
onSubmit?: (value: string, model?: string) => void | Promise<void>;
/** Swaps send for a stop button and blocks new prompts. Default: false */
loading?: boolean;
/** Called when the stop button is pressed while loading. */
onStop?: () => void;
/** Height of the empty input, in text rows. Default: 2 */
minRows?: number;
/** Rows the input grows to before it scrolls. Default: 8 */
maxRows?: number;
/** Extra controls placed between the add menu and the model menu. */
leadingAction?: ReactNode;
/** Override any built-in string. */
labels?: Partial<PromptInputMessages>;
/** Classes merged onto the form element. */
className?: string;
}
export function PromptInput({
value,
defaultValue = "",
onValueChange,
models = [],
model,
defaultModel,
onModelChange,
actions = [],
onAction,
commands = NO_COMMANDS,
onCommand,
onSubmit,
loading = false,
onStop,
minRows = 2,
maxRows = 8,
leadingAction,
labels,
className,
disabled,
placeholder,
"aria-label": ariaLabel,
onKeyDown,
...textareaProps
}: PromptInputProps) {
const t = useMessages("promptInput", promptInputMessages, labels);
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 [modelsOpen, setModelsOpen] = 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;
// Slash commands: the word before the caret, when it starts with `/`.
const [caret, setCaret] = useState(currentValue.length);
// Escape closes the list for the slash it was opened by, until another one.
const [dismissedAt, setDismissedAt] = useState(-1);
const baseId = useId();
const slash = commands.length
? /(?:^|\s)\/([\w-]*)$/.exec(currentValue.slice(0, caret))
: null;
const query = slash ? slash[1].toLowerCase() : "";
const slashAt = slash ? caret - slash[1].length - 1 : -1;
const matches = slash
? commands.filter(
(command) =>
command.value.toLowerCase().includes(query) ||
command.label.toLowerCase().includes(query),
)
: NO_COMMANDS;
const slashOpen = matches.length > 0 && slashAt !== dismissedAt && !disabled;
const commandRows = matches.map((command) => ({ id: command.value }));
const { activeIndex, moveTo, moveActive } = useRowCursor(commandRows, query);
const activeCommand = slashOpen ? matches[activeIndex] : undefined;
const listId = `${baseId}-commands`;
const optionId = (value: string) => `${baseId}-command-${value}`;
// Pointer moves glide the highlight; arrow keys jump it, a spring would
// only trail behind fast arrowing.
const [glide, setGlide] = useState(false);
const pickCommand = (command: PromptCommand) => {
const inserted = `/${command.value} `;
const next =
currentValue.slice(0, slashAt) + inserted + currentValue.slice(caret);
const nextCaret = slashAt + inserted.length;
setValue(next);
setCaret(nextCaret);
onCommand?.(command.value);
requestAnimationFrame(() => {
textareaRef.current?.focus({ preventScroll: true });
textareaRef.current?.setSelectionRange(nextCaret, nextCaret);
});
};
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 (slashOpen && !event.defaultPrevented && !event.nativeEvent.isComposing) {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
setGlide(false);
moveActive(event.key === "ArrowDown" ? 1 : -1);
return;
}
if ((event.key === "Enter" && !event.shiftKey) || event.key === "Tab") {
event.preventDefault();
if (activeCommand) pickCommand(activeCommand);
return;
}
if (event.key === "Escape") {
event.preventDefault();
setDismissedAt(slashAt);
return;
}
}
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-3xl 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>
{/* The list rises a few px out of the input as it fades in, and drops
back faster. Focus stays in the input, which drives it with the arrow
keys. As you filter, its top edge glides (the list is anchored at its
bottom, above the input), leaving rows fade and the rest slide into
place, instead of the edge and rows jumping. */}
<AnimatePresence>
{slashOpen ? (
<motion.div
key="commands"
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={
reduce
? { opacity: 0, pointerEvents: "none", transition: LIST_OUT }
: { opacity: 0, y: 4, pointerEvents: "none", transition: LIST_OUT }
}
transition={LIST_IN}
style={{ transformOrigin: "bottom left" }}
className="absolute inset-x-0 bottom-full z-20 mb-2"
>
<ClipResizeFrame edge="top" contentClassName="p-2">
<div
id={listId}
role="listbox"
aria-label={t("commands")}
className="relative max-h-60 overflow-y-auto overscroll-contain"
>
<AnimatePresence initial={false} mode="popLayout">
{matches.map((command, index) => {
const active = index === activeIndex;
return (
<motion.button
layout={reduce ? false : "position"}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0, transition: ROW_OUT }}
transition={ROW_MOVE}
key={command.value}
id={optionId(command.value)}
type="button"
role="option"
aria-selected={active}
tabIndex={-1}
onPointerMove={() => {
if (active) return;
setGlide(true);
moveTo(command.value);
}}
onPointerDown={(event) => event.preventDefault()}
onClick={() => pickCommand(command)}
className={cn(MENU_ITEM_CLASS, "cursor-default gap-2.5 text-foreground")}
>
{active ? (
<MenuItemHighlight
layoutId={`${baseId}-command-highlight`}
reduce={reduce}
instant={!glide}
/>
) : null}
{command.icon ? (
<span
aria-hidden="true"
className="flex shrink-0 text-muted-foreground [&_svg]:size-4"
>
{command.icon}
</span>
) : null}
<span className="shrink-0">{command.label}</span>
{command.description ? (
<span className="min-w-0 truncate text-xs text-muted-foreground">
{command.description}
</span>
) : null}
<span className="ml-auto shrink-0 font-mono text-xs text-muted-foreground/70">
/{command.value}
</span>
</motion.button>
);
})}
</AnimatePresence>
</div>
</ClipResizeFrame>
</motion.div>
) : null}
</AnimatePresence>
<textarea
ref={textareaRef}
value={currentValue}
disabled={disabled}
placeholder={placeholder ?? t("placeholder")}
aria-label={ariaLabel ?? t("label")}
rows={minRows}
{...textareaProps}
aria-autocomplete={commands.length ? "list" : undefined}
aria-controls={slashOpen ? listId : undefined}
aria-activedescendant={activeCommand ? optionId(activeCommand.value) : undefined}
onChange={(event) => {
setValue(event.target.value);
setCaret(event.target.selectionStart);
}}
onSelect={(event) => setCaret(event.currentTarget.selectionStart)}
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 ? (
// The library menu: arrow keys and typeahead, a highlight that
// glides between rows, and no animation when the keyboard opens it.
<DropdownMenu open={actionsOpen} onOpenChange={setActionsOpen}>
<Tooltip content={t("addToPrompt")} side="top">
<AddButton
open={actionsOpen}
reduce={reduce}
disabled={disabled || loading}
aria-label={t("addToPrompt")}
/>
</Tooltip>
<DropdownMenuContent side="top" align="start" sideOffset={8} className="w-72">
{actions.map((action) => (
<DropdownMenuItem
key={action.value}
disabled={action.disabled}
onSelect={() => onAction?.(action.value)}
textValue={typeof action.label === "string" ? action.label : undefined}
className="items-start"
>
{action.icon ? (
<span aria-hidden="true" className="mt-0.5 flex shrink-0">
{action.icon}
</span>
) : null}
{/* One line each: a menu row is read at a glance. */}
<span className="min-w-0 flex-1">
<span className="block truncate">{action.label}</span>
{action.description ? (
<span className="block truncate text-xs leading-4 text-muted-foreground">
{action.description}
</span>
) : null}
</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
) : null}
{leadingAction}
{models.length ? (
// The same menu as the plus: a model is a pick from a short list,
// with the check at the end of the chosen row.
<DropdownMenu open={modelsOpen} onOpenChange={setModelsOpen}>
<DropdownMenuTrigger disabled={disabled || loading}>
<button
type="button"
disabled={disabled || loading}
className="inline-flex h-8 min-w-0 max-w-52 items-center gap-1.5 rounded-full px-3 text-xs text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none data-[state=open]:bg-foreground/[0.06] data-[state=open]:text-foreground"
>
{currentModel?.icon ? (
<span aria-hidden="true" className="flex size-4 shrink-0 items-center justify-center [&_svg]:size-3.5">
{currentModel.icon}
</span>
) : null}
<span className="truncate">{currentModel?.label ?? t("chooseModel")}</span>
<motion.span
aria-hidden="true"
animate={{ rotate: modelsOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="flex shrink-0"
>
<ChevronDown className="size-3.5" />
</motion.span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start" sideOffset={8} className="w-56">
<DropdownMenuRadioGroup value={currentModelValue ?? ""} onValueChange={setModel}>
{models.map((option) => (
<DropdownMenuRadioItem
key={option.value}
value={option.value}
disabled={option.disabled}
closeOnSelect
textValue={typeof option.label === "string" ? option.label : undefined}
>
{option.icon ? (
<span aria-hidden="true" className="flex shrink-0">
{option.icon}
</span>
) : null}
<span className="min-w-0 truncate">{option.label}</span>
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
) : null}
<span className="relative ml-auto flex">
<Tooltip content={loading ? t("stop") : t("send")} side="top">
<Button
type={loading ? "button" : "submit"}
size="icon"
disabled={loading ? !onStop : !canSubmit}
aria-label={loading ? t("stop") : t("send")}
onClick={loading ? onStop : undefined}
className={cn(
"size-8 rounded-full",
// Nothing to send: a quiet gray chip, not a dimmed primary. It
// lights up the moment there is a prompt.
!loading && !canSubmit && "bg-foreground/[0.06] text-muted-foreground disabled:opacity-100",
)}
>
<AnimatePresence initial={false} mode="popLayout">
<motion.span
key={loading ? "stop" : "send"}
// A little blur melts the arrow into the square, so the swap
// reads as one icon changing rather than two crossing.
initial={reduce ? { opacity: 1 } : { opacity: 0, y: 3, scale: 0.8, filter: "blur(2px)" }}
animate={{ opacity: 1, y: 0, scale: 1, filter: "blur(0px)" }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3, scale: 0.8, filter: "blur(2px)" }}
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>
</Tooltip>
{/* While the agent works, a thin arc circles the stop button. */}
<AnimatePresence>
{loading ? (
<motion.svg
key="working"
aria-hidden="true"
viewBox="0 0 40 40"
initial={{ opacity: 0, scale: reduce ? 1 : 0.9 }}
animate={{ opacity: 1, scale: 1, rotate: reduce ? 0 : 360 }}
exit={{ opacity: 0, transition: { duration: 0.15, ease: EASE_OUT } }}
transition={{
opacity: { duration: 0.2, ease: EASE_OUT },
scale: { duration: 0.2, ease: EASE_OUT },
rotate: { duration: 1, ease: "linear", repeat: Number.POSITIVE_INFINITY },
}}
className="pointer-events-none absolute -inset-1 size-10 text-primary"
>
<circle cx="20" cy="20" r="19" fill="none" stroke="currentColor" strokeOpacity={0.15} strokeWidth="1.5" />
<circle
cx="20"
cy="20"
r="19"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeDasharray="30 90"
/>
</motion.svg>
) : null}
</AnimatePresence>
</span>
</div>
</form>
);
}
/**
* The plus that opens the add menu. Its own component so the tooltip around it
* and the menu trigger inside both reach the button: the plus turns into a
* cross while the menu is open.
*/
function AddButton({
open,
reduce,
...props
}: ComponentProps<typeof Button> & { open: boolean; reduce: boolean }) {
return (
<DropdownMenuTrigger disabled={props.disabled}>
<Button
type="button"
variant="ghost"
size="icon"
{...props}
className="size-8 rounded-full data-[state=open]:bg-foreground/[0.06] data-[state=open]:text-foreground"
>
<motion.span
aria-hidden="true"
animate={{ rotate: open ? 45 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="flex"
>
<Plus className="size-4" />
</motion.span>
</Button>
</DropdownMenuTrigger>
);
}
"use client";
import {
Check,
ChevronDown,
Copy,
RotateCcw,
ThumbsDown,
ThumbsUp,
} 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 {
type CitationItem,
CitationList,
CitationStack,
} from "@/components/agents/citations";
import { IconSwap as ActionIcon } from "@/components/agents/icon-swap";
import { Tooltip } from "@/components/motion/tooltip";
import { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { useCopy } from "@/lib/hooks/use-copy";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export type StreamingResponseStatus = "streaming" | "complete" | "error";
export type StreamingResponseFeedback = "up" | "down" | null;
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const streamingResponseMessages = {
copy: "Copy response",
copied: "Copied",
retry: "Retry response",
helpful: "Helpful",
notHelpful: "Not helpful",
source: "{count} source",
sources: "{count} sources",
};
export type StreamingResponseMessages = typeof streamingResponseMessages;
export interface StreamingResponseProps {
/** Rendered response content. Pass plain text or the output of a Markdown renderer. */
children: ReactNode;
/** Stream state; actions appear once it leaves "streaming". Default: "streaming" */
status?: StreamingResponseStatus;
/** Plain-text value copied by the built-in copy action. */
copyText?: string;
/** Overrides the built-in clipboard action. */
onCopy?: () => void | Promise<void>;
/** Called when the retry action is pressed. The action shows only when set. */
onRetry?: () => void;
/** Optional sources shown as a compact footer disclosure after streaming. */
sources?: CitationItem[];
/** Whether the sources list is expanded, for controlled use. */
sourcesOpen?: boolean;
/** Whether the sources list starts expanded when uncontrolled. Default: false */
defaultSourcesOpen?: boolean;
/** Called with the next state when the sources list expands or collapses. */
onSourcesOpenChange?: (open: boolean) => void;
/** Prefix for source row ids that `Citation` markers link to. Generated when omitted. */
sourceIdPrefix?: string;
/** The thumbs up or down rating, for controlled use. */
feedback?: StreamingResponseFeedback;
/** The initial rating when uncontrolled. Default: null */
defaultFeedback?: StreamingResponseFeedback;
/** Called with the new rating, or `null` when it is toggled off. */
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;
/** Override any built-in string. `{count}` fills `source` (one) and `sources` (many). */
labels?: Partial<StreamingResponseMessages>;
/** Classes merged onto the root element. */
className?: string;
/** Classes merged onto the wrapper around the response content. */
contentClassName?: string;
/** Classes merged onto the row of completion actions. */
actionsClassName?: string;
}
function ResponseAction({
label,
active,
onClick,
children,
}: {
label: string;
/** Set for toggle actions; exposed as `aria-pressed`. */
active?: boolean;
onClick: () => void;
children: ReactNode;
}) {
const reduce = useReducedMotion() ?? false;
return (
<Tooltip content={label} side="top">
<motion.button
type="button"
aria-label={label}
aria-pressed={active}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.95 }}
transition={SPRING_PRESS}
className={cn(
// A foreground tint, not bg-muted: muted is the bubble colour, so a
// muted hover would vanish inside a soft bubble.
"grid size-7 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
active && "bg-foreground/[0.06] text-foreground",
)}
>
{children}
</motion.button>
</Tooltip>
);
}
export function StreamingResponse({
children,
status = "streaming",
copyText,
onCopy,
onRetry,
sources = [],
sourcesOpen,
defaultSourcesOpen = false,
onSourcesOpenChange,
sourceIdPrefix,
feedback,
defaultFeedback = null,
onFeedbackChange,
announce = true,
showActions = true,
labels,
className,
contentClassName,
actionsClassName,
}: StreamingResponseProps) {
const t = useMessages("streamingResponse", streamingResponseMessages, labels);
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const { copied, copy: handleCopy } = useCopy({ text: copyText, onCopy });
const [internalFeedback, setInternalFeedback] =
useState<StreamingResponseFeedback>(defaultFeedback);
const [internalSourcesOpen, setInternalSourcesOpen] =
useState(defaultSourcesOpen);
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, "")}`;
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 ? t("copied") : t("copy")}
onClick={handleCopy}
>
<ActionIcon id={copied ? "copied" : "copy"}>
{copied ? (
<Check className="size-3.5" />
) : (
<Copy className="size-3.5" />
)}
</ActionIcon>
</ResponseAction>
) : null}
{onRetry ? (
<ResponseAction label={t("retry")} onClick={onRetry}>
<RotateCcw className="size-3.5" />
</ResponseAction>
) : null}
{complete ? (
<>
<ResponseAction
label={t("helpful")}
active={currentFeedback === "up"}
onClick={() => setFeedback("up")}
>
{/* A chosen rating fills in, so the choice reads at a glance. */}
<ActionIcon id={currentFeedback === "up" ? "up-on" : "up"}>
<ThumbsUp
className={cn("size-3.5", currentFeedback === "up" && "fill-current")}
/>
</ActionIcon>
</ResponseAction>
<ResponseAction
label={t("notHelpful")}
active={currentFeedback === "down"}
onClick={() => setFeedback("down")}
>
<ActionIcon id={currentFeedback === "down" ? "down-on" : "down"}>
<ThumbsDown
className={cn("size-3.5", currentFeedback === "down" && "fill-current")}
/>
</ActionIcon>
</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-full 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">
{t(sources.length === 1 ? "source" : "sources", {
count: sources.length,
})}
</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-2xl border border-border p-2"
/>
</AgentDisclosure>
) : null}
</motion.div>
) : null}
</AnimatePresence>
</div>
);
}
"use client";
import {
type AnimationPlaybackControls,
animate,
type HTMLMotionProps,
motion,
useMotionValue,
useReducedMotion,
useTransform,
} from "motion/react";
import { type CSSProperties, type ReactNode, useLayoutEffect, useRef } from "react";
import { EASE_OUT, SPRING_MORPH } from "@/lib/ease";
import { cn } from "@/lib/utils";
// The bottom edge glides to the new size; a little quicker when shrinking,
// since the content inside has already gone.
const GROW = { duration: 0.3, ease: EASE_OUT } as const;
const SHRINK = { duration: 0.24, ease: EASE_OUT } as const;
export interface ClipResizeFrameProps extends Omit<HTMLMotionProps<"div">, "children" | "style"> {
style?: CSSProperties;
/**
* Which size follows the content. "y": the bottom edge glides as the height
* changes. "x": both ends glide in or out from the centre as the width
* changes, on a morph spring, for pills and chips. Default: "y"
*/
axis?: "x" | "y";
/**
* With axis "y", which edge moves. "top" is for a panel anchored at its
* bottom, such as a list opening above an input: its top edge glides and its
* content stays against the bottom. Default: "bottom"
*/
edge?: "top" | "bottom";
/** Outer corner radius in px. The surface inside uses one less. */
radius?: number;
/** Classes for the content box (padding goes here). */
contentClassName?: string;
children: ReactNode;
}
/**
* A bordered card whose bottom edge glides when its content grows or shrinks,
* without animating height. The layout changes at once; a clip on the card
* hides the difference and slides it away. The border is the 1px gap between
* two clipped layers (the frame in the border colour, the surface inside it),
* so the bottom line travels with the edge instead of being clipped off.
*/
export function ClipResizeFrame({
axis = "y",
edge = "bottom",
radius = 16,
className,
contentClassName,
style,
children,
...props
}: ClipResizeFrameProps) {
const reduce = useReducedMotion() ?? false;
const horizontal = axis === "x";
const fromTop = !horizontal && edge === "top";
const surfaceRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
// How much of the surface (px) is hidden right now: at the moving edge, or
// split evenly between the two ends.
const gap = useMotionValue(0);
const clip = (value: number, round: number) =>
horizontal
? `inset(0 ${value / 2}px 0 ${value / 2}px round ${round}px)`
: fromTop
? `inset(${value}px 0 0 0 round ${round}px)`
: `inset(0 0 ${value}px 0 round ${round}px)`;
const frameClip = useTransform(gap, (value) =>
Math.abs(value) > 0.5 ? clip(value, radius) : "none",
);
const surfaceClip = useTransform(gap, (value) =>
Math.abs(value) > 0.5 ? clip(value, radius - 1) : "none",
);
useLayoutEffect(() => {
const surface = surfaceRef.current;
const content = contentRef.current;
if (!surface || !content || typeof ResizeObserver === "undefined") return;
const measure = () => (horizontal ? content.offsetWidth : content.offsetHeight);
const side = horizontal ? "width" : "height";
let last = measure();
// While shrinking, the surface keeps its old size so the edge has
// somewhere to glide from; null when the surface sizes to its content.
let held: number | null = null;
let controls: AnimationPlaybackControls | undefined;
const release = () => {
held = null;
surface.style[side] = "";
gap.set(0);
};
// Runs after layout and before paint, so the held size lands in the
// same frame as the content change: the edge never jumps.
const observer = new ResizeObserver(() => {
const next = measure();
if (next === last) return;
const visible = (held ?? last) - gap.get();
last = next;
controls?.stop();
if (reduce) {
release();
return;
}
const from = Math.max(next, visible);
held = from > next ? from : null;
surface.style[side] = held === null ? "" : `${held}px`;
gap.set(from - visible);
controls = animate(gap, from - next, {
...(horizontal ? SPRING_MORPH : next < visible ? SHRINK : GROW),
// The edge has reached the content: hand the size back to layout.
onComplete: () => {
if (held !== null) release();
},
});
});
observer.observe(content);
return () => {
observer.disconnect();
controls?.stop();
};
}, [gap, reduce, horizontal]);
return (
<motion.div
{...props}
style={{ ...style, borderRadius: radius, clipPath: frameClip }}
className={cn("bg-border p-px", horizontal && "w-fit", className)}
>
<motion.div
ref={surfaceRef}
style={{ borderRadius: radius - 1, clipPath: surfaceClip }}
// Held wider than its content while shrinking, the surface keeps the
// content centred, so the two ends close in on it evenly.
// Held taller than its content, a top-edge surface keeps the content
// against its anchored bottom.
className={cn(
"overflow-hidden bg-background",
horizontal && "flex justify-center",
fromTop && "flex flex-col justify-end",
)}
>
<div ref={contentRef} className={cn(horizontal && "w-max shrink-0", contentClassName)}>
{children}
</div>
</motion.div>
</motion.div>
);
}
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,
StatefulButtonMessages,
StatefulButtonProps,
} from "./stateful";
export { StatefulButton, statefulButtonMessages } from "./stateful";
"use client";
import { Check, ChevronRight } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
type MutableRefObject,
type ReactElement,
type ReactNode,
type Ref,
useCallback,
useContext,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { enabledItems } from "@/components/motion/menu/use-menu-navigation";
import { SPRING_PANEL } from "@/lib/ease";
import { type DismissReason, useDismiss } from "@/lib/hooks/use-dismiss";
import { PresenceGate } from "@/lib/presence-gate";
import { useSound } from "@/lib/sound";
import { closeSound } from "@/lib/sounds/close";
import { openSound } from "@/lib/sounds/open";
import { selectSound } from "@/lib/sounds/select";
import { assignRef } from "@/lib/merge-refs";
import { cn } from "@/lib/utils";
import { type FocusTarget, RootContext, type RootContextValue, useLevel, useRoot } from "./dropdown-menu/context";
import { type DropdownMenuItemProps, ItemBase } from "./dropdown-menu/item-base";
import { MenuPanel } from "./dropdown-menu/menu-panel";
import type { Align } from "./dropdown-menu/placement";
export type { DropdownMenuItemProps } from "./dropdown-menu/item-base";
// Long enough to skip the submenus a pointer crosses on its way somewhere else.
const SUB_OPEN_DELAY = 100;
// How long a pointer heading for an open submenu may cross sibling rows.
const SUB_GRACE = 300;
type TriggerElementProps = React.HTMLAttributes<HTMLElement> & {
ref?: Ref<HTMLElement>;
"data-state"?: "open" | "closed";
};
/* -------------------------------------------------------------------------- */
/* Root */
/* -------------------------------------------------------------------------- */
export interface DropdownMenuProps {
children: ReactNode;
/** Whether the menu is open, for controlled use. */
open?: boolean;
/** Whether the menu starts open when uncontrolled. Default: false */
defaultOpen?: boolean;
/** Called with the new open state when the menu opens or closes. */
onOpenChange?: (open: boolean) => void;
/**
* Play a soft sweep as the menu opens and closes, and a tick for checkbox
* and radio rows. Off by default; a `SoundProvider` can mute it app-wide.
*/
sound?: boolean;
}
export function DropdownMenu({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
sound = false,
}: DropdownMenuProps) {
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const [focusTarget, setFocusTarget] = useState<FocusTarget>("first");
const [instant, setInstant] = useState(false);
const [mounted, setMounted] = useState(false);
const controlled = controlledOpen !== undefined;
const open = controlled ? controlledOpen : internalOpen;
const triggerRef = useRef<HTMLElement | null>(null);
const menuId = useId();
const triggerId = useId();
const reduce = useReducedMotion() ?? false;
const playOpen = useSound(openSound, { enabled: sound });
const playClose = useSound(closeSound, { enabled: sound });
const playSelect = useSound(selectSound, { enabled: sound });
useEffect(() => setMounted(true), []);
const setOpen = useCallback(
(next: boolean, focus: FocusTarget = "first", now = false) => {
if (next !== open) {
if (next) playOpen();
else playClose();
setInstant(now);
}
if (next) setFocusTarget(focus);
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange, open, playOpen, playClose],
);
// Focus goes back to the trigger when the menu closes from inside it, or
// with nothing focused. A click elsewhere keeps the focus it landed on.
const wasOpen = useRef(open);
useEffect(() => {
if (wasOpen.current === open) return;
wasOpen.current = open;
if (open) return;
const active = document.activeElement;
if (
!active ||
active === document.body ||
active.closest(`[data-menu-root="${CSS.escape(menuId)}"]`)
) {
triggerRef.current?.focus({ preventScroll: true });
}
}, [open, menuId]);
const value = useMemo<RootContextValue>(
() => ({
open,
setOpen,
focusTarget,
instant,
menuId,
triggerId,
triggerRef,
reduce,
mounted,
playSelect,
}),
[open, setOpen, focusTarget, instant, menuId, triggerId, reduce, mounted, playSelect],
);
return <RootContext.Provider value={value}>{children}</RootContext.Provider>;
}
/* -------------------------------------------------------------------------- */
/* Trigger */
/* -------------------------------------------------------------------------- */
export interface DropdownMenuTriggerProps {
/** A single focusable element, usually a button. */
children: ReactElement<TriggerElementProps>;
/** Stops clicks and arrow keys from opening the menu. Default: false */
disabled?: boolean;
}
export function DropdownMenuTrigger({ children, disabled = false }: DropdownMenuTriggerProps) {
const root = useRoot("DropdownMenuTrigger");
if (!isValidElement(children)) {
throw new Error("<DropdownMenuTrigger> requires a single React element");
}
const childProps = children.props;
const childRef = children.props.ref;
return cloneElement(children, {
ref: (node: HTMLElement | null) => {
root.triggerRef.current = node;
assignRef(childRef, node);
},
id: childProps.id ?? root.triggerId,
"aria-haspopup": "menu",
"aria-expanded": root.open,
"aria-controls": root.open ? root.menuId : undefined,
"data-state": root.open ? "open" : "closed",
onClick: (event: ReactMouseEvent<HTMLElement>) => {
childProps.onClick?.(event);
if (event.defaultPrevented || disabled) return;
// `detail` is 0 for a click the keyboard synthesized from Enter or Space:
// that opener wants the first row and no animation, a pointer wants no
// row picked yet and the menu to grow out of the trigger.
const keyboard = event.detail === 0;
root.setOpen(!root.open, keyboard ? "first" : "panel", keyboard);
},
onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => {
childProps.onKeyDown?.(event);
if (event.defaultPrevented || disabled) return;
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
root.setOpen(true, event.key === "ArrowDown" ? "first" : "last", true);
}
},
});
}
/* -------------------------------------------------------------------------- */
/* Content */
/* -------------------------------------------------------------------------- */
export interface DropdownMenuContentProps {
children: ReactNode;
/** Classes merged onto the menu panel. */
className?: string;
/** Preferred side. Flips when the viewport has no room. Default "bottom". */
side?: "top" | "bottom";
/** Default "start". */
align?: Align;
/** Gap between trigger and menu in px. Default 6. */
sideOffset?: number;
}
export function DropdownMenuContent({
children,
className,
side = "bottom",
align = "start",
sideOffset = 6,
}: DropdownMenuContentProps) {
const root = useRoot("DropdownMenuContent");
const panelRef = useRef<HTMLDivElement | null>(null);
const { setOpen, triggerRef, menuId } = root;
// Escape and Tab are keys, so the menu goes at once; a press outside lets it fold away.
const dismiss = useCallback(
(reason: DismissReason) => setOpen(false, "first", reason === "escape"),
[setOpen],
);
const closeFromKey = useCallback(() => setOpen(false, "first", true), [setOpen]);
const ignore = useCallback(
(target: Element) =>
Boolean(triggerRef.current?.contains(target)) ||
Boolean(target.closest(`[data-menu-root="${CSS.escape(menuId)}"]`)),
[triggerRef, menuId],
);
useDismiss(root.open, dismiss, null, { ignore });
if (!root.mounted) return null;
return (
<AnimatePresence custom={root.instant}>
{root.open && (
<PresenceGate>
{({ isPresent, gate }) => (
<MenuPanel
id={root.menuId}
anchorRef={root.triggerRef}
panelRef={panelRef}
side={side}
align={align}
sideOffset={sideOffset}
focus={root.focusTarget}
instant={root.instant}
present={isPresent}
gate={gate}
labelledBy={root.triggerRef.current?.id ?? root.triggerId}
onClose={closeFromKey}
className={className}
>
{children}
</MenuPanel>
)}
</PresenceGate>
)}
</AnimatePresence>
);
}
/* -------------------------------------------------------------------------- */
/* Items */
/* -------------------------------------------------------------------------- */
export function DropdownMenuItem(props: DropdownMenuItemProps) {
return <ItemBase {...props} />;
}
export interface DropdownMenuCheckboxItemProps extends Omit<DropdownMenuItemProps, "onSelect" | "tone" | "inset"> {
/** Whether the row is checked. */
checked: boolean;
/** Called with the new checked state when the row is toggled. */
onCheckedChange?: (checked: boolean) => void;
}
/** Stays open after a toggle by default, so the check can be seen landing. */
export function DropdownMenuCheckboxItem({
checked,
onCheckedChange,
closeOnSelect = false,
children,
...props
}: DropdownMenuCheckboxItemProps) {
const root = useRoot("DropdownMenuCheckboxItem");
return (
<ItemBase
{...props}
role="menuitemcheckbox"
checked={checked}
closeOnSelect={closeOnSelect}
onSelect={() => {
if (!closeOnSelect) root.playSelect();
onCheckedChange?.(!checked);
}}
>
{children}
{/* The mark sits at the end of the row, never before the label. */}
<span aria-hidden="true" className="ml-auto flex size-4 shrink-0 items-center justify-center">
<AnimatePresence initial={false}>
{checked ? (
<motion.span
key="check"
initial={root.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}
animate={{ opacity: 1, scale: 1 }}
exit={root.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}
transition={root.reduce ? { duration: 0.1 } : SPRING_PANEL}
className="flex"
>
<Check className="size-3.5 text-foreground" strokeWidth={2.4} />
</motion.span>
) : null}
</AnimatePresence>
</span>
</ItemBase>
);
}
interface RadioGroupContextValue {
value: string;
onValueChange?: (value: string) => void;
}
const RadioGroupContext = createContext<RadioGroupContextValue | null>(null);
export interface DropdownMenuRadioGroupProps {
/** The `value` of the checked radio row. */
value: string;
/** Called with the picked row's value when a radio row is selected. */
onValueChange?: (value: string) => void;
children: ReactNode;
/** Classes merged onto the group wrapper. */
className?: string;
}
export function DropdownMenuRadioGroup({ value, onValueChange, children, className }: DropdownMenuRadioGroupProps) {
const context = useMemo(() => ({ value, onValueChange }), [value, onValueChange]);
return (
<RadioGroupContext.Provider value={context}>
<div className={className}>{children}</div>
</RadioGroupContext.Provider>
);
}
export interface DropdownMenuRadioItemProps extends Omit<DropdownMenuItemProps, "onSelect" | "tone" | "inset"> {
/** The row's value. Checked when it matches the group's `value`. */
value: string;
}
/** Stays open after a pick by default, so the check can be seen moving. */
export function DropdownMenuRadioItem({ value, closeOnSelect = false, children, ...props }: DropdownMenuRadioItemProps) {
const root = useRoot("DropdownMenuRadioItem");
const group = useContext(RadioGroupContext);
if (!group) throw new Error("DropdownMenuRadioItem must be used within <DropdownMenuRadioGroup>");
const checked = group.value === value;
return (
<ItemBase
{...props}
role="menuitemradio"
checked={checked}
closeOnSelect={closeOnSelect}
onSelect={() => {
// A pick that closes the menu sounds through the close sweep instead.
if (!closeOnSelect && !checked) root.playSelect();
group.onValueChange?.(value);
}}
>
{children}
{/* The mark sits at the end of the row, never before the label. */}
<span aria-hidden="true" className="ml-auto flex size-4 shrink-0 items-center justify-center">
<motion.span
initial={false}
animate={root.reduce ? { opacity: checked ? 1 : 0 } : { opacity: checked ? 1 : 0, scale: checked ? 1 : 0.6 }}
transition={root.reduce ? { duration: 0.1 } : SPRING_PANEL}
className="flex"
>
<Check className="size-3.5 text-foreground" strokeWidth={2.4} />
</motion.span>
</span>
</ItemBase>
);
}
/* -------------------------------------------------------------------------- */
/* Submenus */
/* -------------------------------------------------------------------------- */
interface SubContextValue {
id: string;
contentId: string;
open: boolean;
focus: FocusTarget;
triggerRef: MutableRefObject<HTMLElement | null>;
panelRef: MutableRefObject<HTMLDivElement | null>;
setOpen: (open: boolean, focus?: FocusTarget, instant?: boolean) => void;
}
const SubContext = createContext<SubContextValue | null>(null);
function useSub(component: string) {
const context = useContext(SubContext);
if (!context) throw new Error(`${component} must be used within <DropdownMenuSub>`);
return context;
}
export interface DropdownMenuSubProps {
children: ReactNode;
}
export function DropdownMenuSub({ children }: DropdownMenuSubProps) {
const level = useLevel("DropdownMenuSub");
const id = useId();
const contentId = useId();
const triggerRef = useRef<HTMLElement | null>(null);
const panelRef = useRef<HTMLDivElement | null>(null);
// Closes with its parent: an exiting menu takes its submenu out with it.
const open = level.openSub === id && level.present;
const { setOpenSub } = level;
const setOpen = useCallback(
(next: boolean, focus: FocusTarget = "none", instant?: boolean) =>
setOpenSub(next ? id : null, focus, instant),
[setOpenSub, id],
);
const value = useMemo(
() => ({ id, contentId, open, focus: level.subFocus, triggerRef, panelRef, setOpen }),
[id, contentId, open, level.subFocus, setOpen],
);
return <SubContext.Provider value={value}>{children}</SubContext.Provider>;
}
export interface DropdownMenuSubTriggerProps {
children: ReactNode;
/** Stops hover, click and keys from opening the submenu. */
disabled?: boolean;
/** Indent to line up with rows that start with an icon. */
inset?: boolean;
/** Text matched by typeahead when the label is not plain text. */
textValue?: string;
/** Classes merged onto the trigger row. */
className?: string;
}
export function DropdownMenuSubTrigger({ children, disabled, inset, textValue, className }: DropdownMenuSubTriggerProps) {
const level = useLevel("DropdownMenuSubTrigger");
const sub = useSub("DropdownMenuSubTrigger");
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const clearTimer = useCallback(() => {
if (timer.current) clearTimeout(timer.current);
timer.current = null;
}, []);
useEffect(() => clearTimer, [clearTimer]);
return (
<ItemBase
disabled={disabled}
inset={inset}
textValue={textValue}
className={className}
subTrigger={{
id: sub.id,
open: sub.open,
controls: sub.contentId,
ref: sub.triggerRef,
onPointerMove: (event) => {
if (document.activeElement !== event.currentTarget) {
event.currentTarget.focus({ preventScroll: true });
}
if (disabled || sub.open || timer.current) return;
// Another row's submenu closes as soon as the pointer settles here.
if (level.openSub) level.setOpenSub(null);
timer.current = setTimeout(() => {
timer.current = null;
sub.setOpen(true, "none");
}, SUB_OPEN_DELAY);
},
onPointerLeave: (event) => {
clearTimer();
const panel = sub.panelRef.current;
if (!sub.open || !panel || event.pointerType === "touch") return;
// Leave a corridor from the pointer to the submenu's near edge, so a
// diagonal path across the rows below does not close it.
const rect = panel.getBoundingClientRect();
const right = rect.left >= event.clientX;
const edge = right ? rect.left : rect.right;
const back = right ? -5 : 5;
level.grace.current = {
polygon: [
{ x: event.clientX + back, y: event.clientY },
{ x: edge, y: rect.top },
{ x: edge, y: rect.bottom },
],
until: Date.now() + SUB_GRACE,
};
},
onKeyDown: (event) => {
if (disabled) return;
if (event.key === "ArrowRight" || event.key === "Enter" || event.key === " ") {
event.preventDefault();
event.stopPropagation();
sub.setOpen(true, "first");
// Already open from a hover: the panel's focus effect will not run
// again, so hand focus in here.
if (sub.open) enabledItems(sub.panelRef.current)[0]?.focus();
}
},
// Keys open the submenu in onKeyDown, so a click here is a pointer or a tap.
onClick: () => {
if (!disabled) sub.setOpen(true, "first", false);
},
}}
>
{children}
<ChevronRight aria-hidden="true" className="ml-auto size-4" />
</ItemBase>
);
}
export interface DropdownMenuSubContentProps {
children: ReactNode;
/** Classes merged onto the submenu panel. */
className?: string;
/** Gap between the menu's edge and the submenu in px. Default 6. */
sideOffset?: number;
}
export function DropdownMenuSubContent({ children, className, sideOffset = 6 }: DropdownMenuSubContentProps) {
const root = useRoot("DropdownMenuSubContent");
const level = useLevel("DropdownMenuSubContent");
const sub = useSub("DropdownMenuSubContent");
return (
<AnimatePresence custom={level.subInstant}>
{sub.open && (
<PresenceGate>
{({ isPresent, gate }) => (
<MenuPanel
id={sub.contentId}
anchorRef={sub.triggerRef}
panelRef={sub.panelRef}
side="right"
align="start"
sideOffset={sideOffset}
focus={sub.focus}
instant={level.subInstant}
present={isPresent}
gate={gate}
labelledBy={sub.id}
onClose={() => root.setOpen(false, "first", true)}
onPointerEnter={() => {
level.grace.current = null;
}}
onKeyDown={(event) => {
if (event.key !== "ArrowLeft") return false;
event.preventDefault();
sub.setOpen(false, "none", true);
sub.triggerRef.current?.focus({ preventScroll: true });
return true;
}}
className={className}
>
{children}
</MenuPanel>
)}
</PresenceGate>
)}
</AnimatePresence>
);
}
/* -------------------------------------------------------------------------- */
/* Decoration */
/* -------------------------------------------------------------------------- */
export interface DropdownMenuLabelProps {
children: ReactNode;
/** Indent to line up with rows that start with an icon. */
inset?: boolean;
/** Classes merged onto the label element. */
className?: string;
}
export function DropdownMenuLabel({ children, inset, className }: DropdownMenuLabelProps) {
return (
<div className={cn("px-3 py-1.5 text-xs font-medium text-muted-foreground", inset && "pl-9", className)}>
{children}
</div>
);
}
export interface DropdownMenuSeparatorProps {
/** Classes merged onto the separator line. */
className?: string;
}
export function DropdownMenuSeparator({ className }: DropdownMenuSeparatorProps) {
return <hr className={cn("-mx-2 my-1 h-px border-0 bg-border", className)} />;
}
export interface DropdownMenuShortcutProps {
children: ReactNode;
/** Classes merged onto the shortcut text. */
className?: string;
}
export function DropdownMenuShortcut({ children, className }: DropdownMenuShortcutProps) {
return (
<span aria-hidden="true" className={cn("ml-auto pl-4 text-xs tracking-wide text-muted-foreground", className)}>
{children}
</span>
);
}
"use client";
import { motion } from "motion/react";
import { SPRING_LAYOUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
/** The row shape every menu item shares. Menus add their own gap and states. */
export const MENU_ITEM_CLASS =
"relative isolate flex w-full select-none items-center rounded-lg px-3 py-1.5 text-left text-sm outline-none";
export interface MenuItemHighlightProps {
/** Shared by every row of one panel, so the highlight glides between them. */
layoutId: string;
tone?: "default" | "destructive";
reduce: boolean;
/**
* Jump instead of gliding: the highlight was moved by the keyboard, where a
* spring only trails behind fast arrowing.
*/
instant?: boolean;
}
/** The highlight behind the active row. Render it only inside the active row. */
export function MenuItemHighlight({
layoutId,
tone = "default",
reduce,
instant = false,
}: MenuItemHighlightProps) {
return (
<motion.span
aria-hidden="true"
layoutId={layoutId}
className={cn(
"absolute inset-0 -z-10 rounded-lg",
tone === "destructive" ? "bg-destructive/10" : "bg-foreground/[0.07]",
)}
transition={reduce || instant ? { duration: 0 } : SPRING_LAYOUT}
/>
);
}
"use client";
import { motion, type HTMLMotionProps, useReducedMotion } from "motion/react";
import { type CSSProperties, useState } 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 reveal for collapsible agent content: a clip, fade and short drop,
* never an animated height. The box takes its height as soon as it opens and
* gives it up only once the closing reveal has played, so the exit is seen
* and mirrors the entrance.
*/
export function AgentDisclosure({
open,
openHeight = "auto",
className,
style,
transition,
onAnimationComplete,
...props
}: AgentDisclosureProps) {
const reduce = useReducedMotion() ?? false;
const [collapsed, setCollapsed] = useState(!open);
if (open && collapsed) setCollapsed(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,
}
}
onAnimationComplete={(definition) => {
if (!open) setCollapsed(true);
onAnimationComplete?.(definition);
}}
className={cn("overflow-hidden", className)}
style={{
...style,
height: collapsed ? 0 : openHeight,
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,
useEffect,
useId,
useLayoutEffect,
useRef,
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 { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export const citationsMessages = {
title: "Sources",
viewCitation: "View citation {index}",
};
export type CitationsMessages = typeof citationsMessages;
export interface CitationItem {
/** Unique key for the source, matched by a `Citation` marker's `citationId`. */
id: string;
/** Source name shown as the row's main text. */
title: ReactNode;
/** Muted text after the title, such as the site's host. */
domain?: ReactNode;
/** Link opened in a new tab and the favicon source. Omit for a plain row. */
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 {
/** Sources listed in order, numbered from 1. */
citations: CitationItem[];
/** Text of the toggle button. Default: "Sources" */
title?: ReactNode;
/** Whether the list is expanded, for controlled use. */
open?: boolean;
/** Whether the list starts expanded when uncontrolled. Default: false */
defaultOpen?: boolean;
/** Called with the new state when the list expands or collapses. */
onOpenChange?: (open: boolean) => void;
/** Prefix for row ids that `Citation` markers link to. Generated when omitted. */
idPrefix?: string;
/** Classes merged onto the root element. */
className?: string;
/** Override any built-in string. */
labels?: Partial<CitationsMessages>;
}
export interface CitationProps {
/** Id of the `CitationItem` this marker links to. */
citationId: string;
/** Number shown on the marker. */
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;
/** Classes merged onto the marker link. */
className?: string;
}
export interface CitationListProps {
/** Sources listed in order, numbered from 1. */
citations: CitationItem[];
/** Prefix for row ids that `Citation` markers link to. Generated when omitted. */
idPrefix?: string;
/** The citation a marker just led to; its row is lit. */
highlightedId?: string;
/** Classes merged onto the root element. */
className?: string;
}
export interface CitationStackProps {
/** Sources whose favicons are stacked. */
citations: CitationItem[];
/** Most favicons to show. Default: 3 */
limit?: number;
/** Classes merged onto the root element. */
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) {
const t = useMessages("citations", citationsMessages);
return (
<a
href={`#${citationTargetId(idPrefix, citationId)}`}
aria-label={label ?? t("viewCitation", { index })}
className={cn(
// A foreground tint, not bg-muted: muted is the bubble colour, so a
// muted marker would vanish inside a soft bubble.
"mx-0.5 inline-flex min-w-4 -translate-y-0.5 items-center justify-center rounded-full bg-foreground/[0.07] px-1 py-0.5 text-[11px] font-medium leading-none text-muted-foreground no-underline outline-none transition-colors hover:bg-foreground/[0.12] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
className,
)}
>
{index}
</a>
);
}
export function CitationFavicon({
url,
icon,
className,
}: {
/** Page whose site favicon is shown. A globe icon shows when absent or broken. */
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 ? (
<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,
highlighted,
}: {
citation: CitationItem;
index: number;
idPrefix: string;
highlighted: boolean;
}) {
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-full bg-foreground/[0.05] text-[11px] font-medium 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>
</>
);
// The row a marker just led to is lit, so the reader sees which source they
// landed on: `highlighted` from Citations, or `:target` after a plain jump.
const className = cn(
"group/citation flex scroll-my-3 items-center gap-2 rounded-lg px-1.5 py-1 outline-none transition-colors duration-200 hover:bg-foreground/[0.04] focus-visible:ring-2 focus-visible:ring-ring target:bg-foreground/[0.07]",
highlighted && "bg-foreground/[0.07] hover:bg-foreground/[0.07]",
);
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,
highlightedId,
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}
highlighted={citation.id === highlightedId}
/>
</motion.div>
))}
</AnimatePresence>
</div>
);
}
export function Citations({
citations,
title,
open,
defaultOpen = false,
onOpenChange,
idPrefix,
className,
labels,
}: CitationsProps) {
const t = useMessages("citations", citationsMessages, labels);
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],
);
// A marker links to its source row. While the list is folded that row is
// hidden, so the jump would land on nothing: open the list, then bring the
// row into view once it is shown.
const [highlightedId, setHighlightedId] = useState<string>();
const latest = useRef({ currentOpen, setOpen, citations, reduce });
useLayoutEffect(() => {
latest.current = { currentOpen, setOpen, citations, reduce };
});
useEffect(() => {
// Returns true when the hash names one of this list's sources.
const reveal = (hash: string) => {
const now = latest.current;
const citation = now.citations.find(
(item) => citationTargetId(resolvedPrefix, item.id) === hash,
);
if (!citation) return false;
if (!now.currentOpen) now.setOpen(true);
setHighlightedId(citation.id);
// After the list has opened, bring the row just into view: no jump to
// the top of the page, where a sticky header would cover it.
window.setTimeout(() => {
document.getElementById(hash)?.scrollIntoView({
block: "nearest",
behavior: now.reduce ? "auto" : "smooth",
});
}, 0);
return true;
};
const onHash = () => reveal(decodeURIComponent(window.location.hash.slice(1)));
// Marker clicks are handled here rather than as a plain jump, which
// lands on nothing while the list is folded and pins the row under the
// page header when it is open.
const onClick = (event: MouseEvent) => {
const link = (event.target as Element | null)?.closest?.("a[href^='#']");
if (!link) return;
if (reveal(decodeURIComponent(link.getAttribute("href")?.slice(1) ?? ""))) {
event.preventDefault();
}
};
window.addEventListener("hashchange", onHash);
document.addEventListener("click", onClick);
return () => {
window.removeEventListener("hashchange", onHash);
document.removeEventListener("click", onClick);
};
}, [resolvedPrefix]);
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-full 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 ?? t("title")}</span>
<span className="rounded-full bg-foreground/[0.06] px-1.5 py-0.5 text-[11px] font-medium 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}
highlightedId={highlightedId}
className="mt-1"
/>
</AgentDisclosure>
</div>
);
}
"use client";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import type { ReactNode } from "react";
import { SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface IconSwapProps {
/** Changes whenever the icon should change (copy → copied, running → done). */
id: string;
children: ReactNode;
className?: string;
}
/**
* Crossfades one status icon into the next with a little scale and a 2px
* blur, so the change reads as one icon morphing rather than two crossing.
* Reduced motion keeps the fade and drops the scale.
*/
export function IconSwap({ id, children, className }: IconSwapProps) {
const reduce = useReducedMotion() ?? false;
return (
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={id}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: "blur(2px)" }}
animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: "blur(2px)" }}
transition={reduce ? { duration: 0.12 } : SPRING_SWAP}
className={cn("grid place-items-center", className)}
>
{children}
</motion.span>
</AnimatePresence>
);
}
"use client";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
type MouseEvent,
type PointerEvent,
type ReactNode,
useCallback,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { useSound } from "@/lib/sound";
import { pressSound } from "@/lib/sounds/press";
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"
> {
/** Visual style: filled, card, ghost or outline. Default: "primary" */
variant?: ButtonVariant;
/** Height and padding; "icon" is a square icon-only button. Default: "md" */
size?: ButtonSize;
/** Scale while pressed. Default 0.97: subtle, so the press reads as feedback, not a squash. */
pressScale?: number;
/** Spawn a Material-style ripple from the press point. Off by default. */
ripple?: boolean;
/** Play a soft press sound. Off by default; a `SoundProvider` can mute it app-wide. */
sound?: boolean;
children?: ReactNode;
}
export interface ButtonLinkProps extends Omit<
HTMLMotionProps<"a">,
"children"
> {
/** Visual style: filled, card, ghost or outline. Default: "primary" */
variant?: ButtonVariant;
/** Height and padding; "icon" is a square icon-only link. Default: "md" */
size?: ButtonSize;
/** Scale while pressed. Default 0.97. */
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-full",
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
function Button(
{
variant = "primary",
size = "md",
pressScale = 0.97,
ripple = false,
sound = false,
className,
children,
onPointerDown,
onClick,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const [ripples, setRipples] = useState<Ripple[]>([]);
const nextId = useRef(0);
const play = useSound(pressSound, { enabled: sound });
const handleClick = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
// `detail` is 0 for a click the keyboard made; a pointer press already sounded.
if (event.detail === 0) play();
onClick?.(event);
},
[play, onClick],
);
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLButtonElement>) => {
play();
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, play],
);
return (
// Hover changes colour only: a hover scale blurs the label, and buttons
// are hovered far too often for movement to earn its place.
<motion.button
ref={ref}
type="button"
whileTap={reduce ? undefined : { scale: pressScale }}
transition={SPRING_PRESS}
onPointerDown={handlePointerDown}
onClick={handleClick}
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: 0.8, 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.97,
className,
children,
...rest
},
ref,
) {
const reduce = useReducedMotion();
return (
<motion.a
ref={ref}
whileTap={reduce ? undefined : { scale: pressScale }}
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, EASE_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,
};
// One quick sweep on hover. Leaving resets it instantly: both ends sit outside
// the button, so the jump is invisible and no reverse sweep plays.
const CHROME_SHIMMER = {
duration: 0.9,
ease: EASE_OUT,
};
const CHROME_RESET = { duration: 0 };
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 : hovered ? CHROME_SHIMMER : CHROME_RESET}
/>
<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 { useMessages } from "@/lib/i18n";
import { Button, type ButtonProps } from "./base";
export type ButtonState = "idle" | "loading" | "success" | "error";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const statefulButtonMessages = {
loading: "Loading",
success: "Done",
error: "Try again",
};
export type StatefulButtonMessages = typeof statefulButtonMessages;
export interface StatefulButtonProps extends Omit<ButtonProps, "children"> {
/** Which state to show. Loading also disables the button. Default: "idle" */
state?: ButtonState;
children: ReactNode;
/** Text shown while loading. Default: "Loading" */
loadingText?: ReactNode;
/** Text shown on success. Default: "Done" */
successText?: ReactNode;
/** Text shown on error. Default: "Try again" */
errorText?: ReactNode;
/** Trailing icon shown only while idle. */
icon?: ReactNode;
/** Override any built-in string. */
labels?: Partial<StatefulButtonMessages>;
}
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,
successText,
errorText,
icon,
labels,
disabled,
...rest
},
ref,
) {
const t = useMessages("statefulButton", statefulButtonMessages, labels);
const isBusy = state === "loading";
const stateText =
state === "loading"
? (loadingText ?? t("loading"))
: state === "success"
? (successText ?? t("success"))
: state === "error"
? (errorText ?? t("error"))
: children;
const textKey =
typeof stateText === "string" ? `${state}-${stateText}` : state;
return (
<Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} {...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 { createContext, type MutableRefObject, useContext } from "react";
import type { Point } from "./placement";
export type FocusTarget = "first" | "last" | "panel" | "none";
export interface RootContextValue {
open: boolean;
/**
* `instant` skips the open or close animation: the keyboard asked for it,
* and keyboard users open and close menus far too often to wait on motion.
*/
setOpen: (open: boolean, focus?: FocusTarget, instant?: boolean) => void;
focusTarget: FocusTarget;
/** Whether the latest open or close skips its animation. */
instant: boolean;
menuId: string;
triggerId: string;
triggerRef: MutableRefObject<HTMLElement | null>;
reduce: boolean;
mounted: boolean;
/** Plays the select sound when the menu's `sound` prop is on. */
playSelect: () => void;
}
export const RootContext = createContext<RootContextValue | null>(null);
export function useRoot(component: string) {
const context = useContext(RootContext);
if (!context) throw new Error(`${component} must be used within <DropdownMenu>`);
return context;
}
/** One open panel: the root menu or a submenu. */
export interface LevelContextValue {
levelId: string;
present: boolean;
panelRef: MutableRefObject<HTMLDivElement | null>;
activeId: string | null;
setActiveId: (id: string | null) => void;
/** The highlight glides after the pointer, and jumps after a key. */
glide: boolean;
openSub: string | null;
/** `instant` defaults to true when a focus target says the keyboard opened it. */
setOpenSub: (id: string | null, focus?: FocusTarget, instant?: boolean) => void;
subFocus: FocusTarget;
/** Whether the submenu's latest open or close skips its animation. */
subInstant: boolean;
/** A pointer on its way from a submenu trigger to the submenu it opened. */
grace: MutableRefObject<{ polygon: Point[]; until: number } | null>;
}
export const LevelContext = createContext<LevelContextValue | null>(null);
export function useLevel(component: string) {
const context = useContext(LevelContext);
if (!context) {
throw new Error(`${component} must be used within <DropdownMenuContent>`);
}
return context;
}
"use client";
import { type MutableRefObject, type KeyboardEvent as ReactKeyboardEvent, type ReactNode, useId } from "react";
import { MENU_ITEM_CLASS, MenuItemHighlight } from "@/components/motion/menu/menu-item-highlight";
import { cn } from "@/lib/utils";
import { useLevel, useRoot } from "./context";
import { insidePolygon } from "./placement";
type ItemTone = "default" | "destructive";
export interface DropdownMenuItemProps {
children: ReactNode;
/** Called when the item is chosen by click, Enter or Space. */
onSelect?: () => void;
/** Dims the item and blocks selecting it. Default: false */
disabled?: boolean;
/** Close the whole menu after selecting. Default true. */
closeOnSelect?: boolean;
/** "destructive" tints the row for dangerous actions. Default: "default" */
tone?: ItemTone;
/** Indent to line up with rows that start with an icon. */
inset?: boolean;
/** Text matched by typeahead when the label is not plain text. */
textValue?: string;
/** Classes merged onto the item row. */
className?: string;
}
interface ItemBaseProps extends DropdownMenuItemProps {
role?: "menuitem" | "menuitemcheckbox" | "menuitemradio";
checked?: boolean;
subTrigger?: {
id: string;
open: boolean;
controls: string;
onPointerMove: (event: React.PointerEvent<HTMLButtonElement>) => void;
onPointerLeave: (event: React.PointerEvent<HTMLButtonElement>) => void;
onKeyDown: (event: ReactKeyboardEvent<HTMLButtonElement>) => void;
onClick: () => void;
ref: MutableRefObject<HTMLElement | null>;
};
}
/** The row every item kind renders: plain, checkbox, radio and submenu trigger. */
export function ItemBase({
children,
onSelect,
disabled = false,
closeOnSelect = true,
tone = "default",
inset = false,
textValue,
className,
role = "menuitem",
checked,
subTrigger,
}: ItemBaseProps) {
const root = useRoot("DropdownMenuItem");
const level = useLevel("DropdownMenuItem");
const ownId = useId();
const id = subTrigger?.id ?? ownId;
const active = level.activeId === id;
return (
<button
type="button"
ref={(node) => {
if (subTrigger) subTrigger.ref.current = node;
}}
id={id}
role={role}
{...(role === "menuitem" ? {} : { "aria-checked": checked })}
aria-haspopup={subTrigger ? "menu" : undefined}
aria-expanded={subTrigger ? subTrigger.open : undefined}
aria-controls={subTrigger?.open ? subTrigger.controls : undefined}
aria-disabled={disabled || undefined}
tabIndex={-1}
data-menu-item=""
data-level={level.levelId}
data-disabled={disabled ? "" : undefined}
data-highlighted={active ? "" : undefined}
data-text-value={textValue}
onFocus={() => {
level.setActiveId(id);
// Moving to another row of this menu closes a submenu it does not own.
if (level.openSub && level.openSub !== subTrigger?.id) level.setOpenSub(null);
}}
onPointerMove={(event) => {
if (event.pointerType === "touch") return;
// On the way to an open submenu, crossing this row changes nothing.
const grace = level.grace.current;
if (grace && Date.now() < grace.until && insidePolygon({ x: event.clientX, y: event.clientY }, grace.polygon)) {
return;
}
level.grace.current = null;
if (subTrigger) {
subTrigger.onPointerMove(event);
return;
}
if (level.openSub) level.setOpenSub(null);
if (disabled) {
if (level.panelRef.current?.contains(document.activeElement)) {
level.panelRef.current.focus({ preventScroll: true });
}
return;
}
if (document.activeElement !== event.currentTarget) {
event.currentTarget.focus({ preventScroll: true });
}
}}
onPointerLeave={subTrigger?.onPointerLeave}
onKeyDown={subTrigger?.onKeyDown}
onClick={(event) => {
if (disabled) return;
if (subTrigger) {
subTrigger.onClick();
return;
}
onSelect?.();
// `detail` is 0 when Enter or Space picked the row: close without animating.
if (closeOnSelect) root.setOpen(false, "first", event.detail === 0);
}}
className={cn(
MENU_ITEM_CLASS,
"cursor-default gap-2",
"[&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0",
inset && "pl-9",
disabled && "opacity-50",
tone === "destructive" ? "text-destructive [&_svg]:text-destructive" : "[&_svg]:text-muted-foreground",
className,
)}
>
{active && !disabled ? (
<MenuItemHighlight
layoutId={`${level.levelId}-highlight`}
tone={tone}
reduce={root.reduce}
instant={!level.glide}
/>
) : null}
{children}
</button>
);
}
"use client";
import { motion, type Variants } from "motion/react";
import {
type MutableRefObject,
type KeyboardEvent as ReactKeyboardEvent,
type ReactNode,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { enabledItems, useMenuNavigation } from "@/components/motion/menu/use-menu-navigation";
import { usePopoverPortalPosition } from "@/components/motion/popover-position";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { type FocusTarget, LevelContext, type LevelContextValue, useRoot } from "./context";
import { type Align, type Placement, type Point, place, type Side } from "./placement";
const EXIT = { duration: 0.12, ease: EASE_OUT };
// The panel grows out of its trigger from this scale and distance.
const OPEN_SCALE = 0.94;
const OPEN_TRAVEL = 6;
const OPEN = { duration: 0.2, ease: EASE_OUT };
const INSTANT = { duration: 0 };
interface PanelProps {
children: ReactNode;
className?: string;
id: string;
anchorRef: MutableRefObject<HTMLElement | null>;
side: Side;
align: Align;
sideOffset: number;
focus: FocusTarget;
/** Show without animating; the AnimatePresence around it carries the same flag to the exit. */
instant: boolean;
present: boolean;
gate: { inert: boolean; style: { pointerEvents: "auto" | "none" } };
labelledBy: string;
onClose: () => void;
onKeyDown?: (event: ReactKeyboardEvent<HTMLDivElement>) => boolean;
onPointerEnter?: () => void;
panelRef: MutableRefObject<HTMLDivElement | null>;
}
/** One panel, shared by the menu and its submenus. */
export function MenuPanel({
children,
className,
id,
anchorRef,
side,
align,
sideOffset,
focus,
instant,
present,
gate,
labelledBy,
onClose,
onKeyDown,
onPointerEnter,
panelRef,
}: PanelProps) {
const root = useRoot("DropdownMenuContent");
const parent = useContext(LevelContext);
const levelId = useId();
const [activeId, setActiveId] = useState<string | null>(null);
const [glide, setGlide] = useState(true);
const [openSub, setOpenSubState] = useState<string | null>(null);
const [subFocus, setSubFocus] = useState<FocusTarget>("none");
const [subInstant, setSubInstant] = useState(false);
const grace = useRef<{ polygon: Point[]; until: number } | null>(null);
const navigate = useMenuNavigation();
const layout = usePopoverPortalPosition(anchorRef, panelRef, true);
// Held once placed: an exiting panel stays where it was, even if the
// trigger scrolls away under it.
const [placement, setPlacement] = useState<Placement | null>(null);
useLayoutEffect(() => {
if (!layout || !present) return;
// A submenu measures its gap from the parent panel's edge, not from the
// row inside it, so the two panels never touch.
const edge = parent?.panelRef.current?.getBoundingClientRect();
const anchor = edge ? { ...layout.trigger, left: edge.left, width: edge.width } : layout.trigger;
setPlacement(place(anchor, layout.content, side, align, sideOffset));
}, [layout, present, side, align, sideOffset, parent]);
const setOpenSub = useCallback(
(next: string | null, nextFocus: FocusTarget = "none", now = nextFocus !== "none") => {
setSubFocus(nextFocus);
setSubInstant(now);
setOpenSubState(next);
},
[],
);
// Waits for the first placement: the panel is `visibility: hidden` until
// then, and the browser will not focus anything inside it.
const placed = placement !== null;
useEffect(() => {
const panel = panelRef.current;
// `present` too: reopening during the exit brings this same panel back.
if (!placed || !present || !panel || focus === "none") return;
if (focus === "panel") {
panel.focus({ preventScroll: true });
return;
}
const items = enabledItems(panel);
(focus === "last" ? items[items.length - 1] : items[0])?.focus({ preventScroll: true });
}, [placed, present, focus, panelRef]);
const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
// Submenus render inside this panel's React tree, so their keys bubble
// here too. Each panel answers only for its own rows.
const panel = panelRef.current;
const target = event.target as HTMLElement;
if (!panel || target.closest("[data-menu-panel]") !== panel) return;
// Set before the key moves focus, so the highlight it lands on jumps.
setGlide(false);
if (onKeyDown?.(event)) return;
if (event.key === "Tab") {
event.preventDefault();
onClose();
return;
}
navigate(event, panel);
};
const level = useMemo<LevelContextValue>(
() => ({
levelId,
present,
panelRef,
activeId,
setActiveId,
glide,
openSub,
setOpenSub,
subFocus,
subInstant,
grace,
}),
[levelId, present, panelRef, activeId, glide, openSub, setOpenSub, subFocus, subInstant],
);
// The panel starts tucked toward its trigger and springs out of it.
const used = placement?.side ?? side;
const toward = used === "top" || used === "left" ? 1 : -1;
const vertical = used === "top" || used === "bottom";
const offset = (distance: number) => (vertical ? { y: distance * toward } : { x: distance * toward });
// `custom` is the instant flag. An exiting panel reads it from its
// AnimatePresence, so Escape removes the menu at once even after it has
// already left the React tree.
const variants: Variants = root.reduce
? {
hidden: { opacity: 0 },
shown: (now = false) => ({
opacity: 1,
transition: now ? INSTANT : { duration: 0.15, ease: EASE_OUT },
}),
gone: (now = false) => ({ opacity: 0, transition: now ? INSTANT : EXIT }),
}
: {
hidden: { opacity: 0, scale: OPEN_SCALE, ...offset(OPEN_TRAVEL) },
shown: (now = false) => ({
opacity: 1,
scale: 1,
x: 0,
y: 0,
transition: now
? INSTANT
: {
...OPEN,
opacity: { duration: 0.12, ease: EASE_OUT },
},
}),
gone: (now = false) => ({
opacity: 0,
scale: 0.97,
...offset(OPEN_TRAVEL / 2),
transition: now ? INSTANT : EXIT,
}),
};
return createPortal(
<motion.div
{...gate}
ref={panelRef}
id={id}
role="menu"
aria-labelledby={labelledBy}
aria-orientation="vertical"
tabIndex={-1}
data-menu-panel=""
data-menu-root={root.menuId}
data-level={levelId}
data-side={placement?.side ?? side}
custom={instant}
variants={variants}
initial="hidden"
animate="shown"
exit="gone"
onKeyDown={handleKeyDown}
onPointerMove={(event) => {
if (event.pointerType !== "touch") setGlide(true);
}}
onFocus={(event) => {
if (event.target === event.currentTarget) setActiveId(null);
}}
onPointerEnter={onPointerEnter}
onPointerLeave={(event) => {
// Leaving the panel drops the highlight, unless the row it sits on
// owns the open submenu the pointer is heading into.
if (event.pointerType === "touch" || openSub) return;
const panel = panelRef.current;
if (panel?.contains(document.activeElement)) panel.focus({ preventScroll: true });
}}
style={{
...gate.style,
left: placement?.left ?? 0,
top: placement?.top ?? 0,
transformOrigin: placement?.origin,
maxHeight: placement?.maxHeight,
visibility: placement ? undefined : "hidden",
}}
className={cn(
"fixed z-[100] min-w-48 overflow-y-auto overscroll-contain rounded-2xl border border-border bg-background p-2 text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)] outline-none",
parent && "z-[101]",
className,
)}
>
<LevelContext.Provider value={level}>{children}</LevelContext.Provider>
</motion.div>,
document.body,
);
}
export const VIEWPORT_PADDING = 8;
// The panel's border and padding, so a submenu's first row lines up with the
// row that opened it.
export const SUB_ALIGN_OFFSET = 9;
// How far a submenu stacked under its row sits in, so it reads as nested.
export const SUB_STACK_INDENT = 16;
export type Side = "top" | "bottom" | "left" | "right";
export type Align = "start" | "center" | "end";
export type Point = { x: number; y: number };
export type Placement = {
left: number;
top: number;
side: Side;
origin: string;
/** The room on the chosen side; a taller menu scrolls inside it. */
maxHeight: number;
};
export type Rect = { left: number; top: number; width: number; height: number };
export function clamp(value: number, min: number, max: number) {
return Math.min(Math.max(value, min), Math.max(min, max));
}
export function insidePolygon(point: Point, polygon: Point[]) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const a = polygon[i];
const b = polygon[j];
if (
a.y > point.y !== b.y > point.y &&
point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x
) {
inside = !inside;
}
}
return inside;
}
export function placeVertical(
trigger: Rect,
size: { width: number; height: number },
side: "top" | "bottom",
align: Align,
offset: number,
): Placement {
const viewWidth = document.documentElement.clientWidth;
const viewHeight = window.innerHeight;
const below = trigger.top + trigger.height + offset;
const roomBelow = viewHeight - VIEWPORT_PADDING - below;
const roomAbove = trigger.top - offset - VIEWPORT_PADDING;
// The preferred side when the menu fits there, otherwise the roomier one.
const used =
side === "bottom"
? size.height <= roomBelow || roomBelow >= roomAbove
? "bottom"
: "top"
: size.height <= roomAbove || roomAbove >= roomBelow
? "top"
: "bottom";
const maxHeight = Math.max(used === "bottom" ? roomBelow : roomAbove, 0);
const height = Math.min(size.height, maxHeight);
const start =
align === "start"
? trigger.left
: align === "end"
? trigger.left + trigger.width - size.width
: trigger.left + trigger.width / 2 - size.width / 2;
const x = clamp(start, VIEWPORT_PADDING, viewWidth - size.width - VIEWPORT_PADDING);
const y = used === "bottom" ? below : trigger.top - offset - height;
// Grow from the aligned edge, so that edge holds still while the panel
// scales in instead of sliding sideways into place.
const anchorX =
align === "start"
? trigger.left
: align === "end"
? trigger.left + trigger.width
: trigger.left + trigger.width / 2;
const originX = clamp(anchorX - x, 0, size.width);
return {
left: x,
top: y,
side: used,
origin: `${originX}px ${used === "bottom" ? 0 : height}px`,
maxHeight,
};
}
export function place(
trigger: Rect,
size: { width: number; height: number },
side: Side,
align: Align,
offset: number,
): Placement {
if (side === "top" || side === "bottom") {
return placeVertical(trigger, size, side, align, offset);
}
const viewWidth = document.documentElement.clientWidth;
const viewHeight = window.innerHeight;
const right = trigger.left + trigger.width + offset;
const left = trigger.left - size.width - offset;
const fitsRight = right + size.width <= viewWidth - VIEWPORT_PADDING;
const fitsLeft = left >= VIEWPORT_PADDING;
// A narrow screen has room on neither side: drop below the row instead of
// covering it, the way a phone stacks a submenu.
if (!fitsRight && !fitsLeft) {
return placeVertical(
{ ...trigger, left: trigger.left + SUB_STACK_INDENT, width: trigger.width - SUB_STACK_INDENT },
size,
"bottom",
"start",
2,
);
}
const used: Side = side === "right" ? (fitsRight ? "right" : "left") : fitsLeft ? "left" : "right";
const maxHeight = viewHeight - VIEWPORT_PADDING * 2;
const height = Math.min(size.height, maxHeight);
const x = used === "right" ? right : left;
const y = clamp(trigger.top - SUB_ALIGN_OFFSET, VIEWPORT_PADDING, viewHeight - height - VIEWPORT_PADDING);
const originY = clamp(trigger.top + trigger.height / 2 - y, 0, height);
return {
left: x,
top: y,
side: used,
origin: `${used === "right" ? 0 : size.width}px ${originY}px`,
maxHeight,
};
}
"use client";
import { type KeyboardEvent, useCallback, useEffect, useRef } from "react";
const TYPEAHEAD_RESET = 500;
/**
* The enabled rows of one menu panel, in order. Rows carry `data-menu-item`
* and the panel's `data-level`, so a submenu rendered inside the panel keeps
* its own rows to itself.
*/
export function enabledItems(panel: HTMLElement | null) {
if (!panel) return [];
return Array.from(
panel.querySelectorAll<HTMLElement>(
`[data-menu-item][data-level="${panel.dataset.level}"]:not([data-disabled])`,
),
);
}
/**
* Arrow keys, Home, End and typeahead for a menu panel. The returned handler
* moves focus between the panel's rows and says whether it used the key.
* Typeahead matches a row's `data-text-value`, or its text.
*/
export function useMenuNavigation() {
const query = useRef("");
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(
() => () => {
if (timer.current) clearTimeout(timer.current);
},
[],
);
return useCallback((event: KeyboardEvent<HTMLElement>, panel: HTMLElement | null) => {
const items = enabledItems(panel);
const index = items.indexOf(event.target as HTMLElement);
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (items.length === 0) return true;
const step = event.key === "ArrowDown" ? 1 : -1;
const next =
index < 0
? step === 1
? 0
: items.length - 1
: (index + step + items.length) % items.length;
items[next]?.focus();
return true;
}
if (event.key === "Home" || event.key === "End") {
event.preventDefault();
items[event.key === "Home" ? 0 : items.length - 1]?.focus();
return true;
}
const typed = event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;
// A space with nothing typed yet presses the row instead.
if (!typed || (event.key === " " && query.current === "")) return false;
query.current += event.key.toLocaleLowerCase();
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => {
query.current = "";
}, TYPEAHEAD_RESET);
// Start after the current row, so repeating a letter cycles its matches.
const ordered = [...items.slice(index + 1), ...items.slice(0, index + 1)];
const typedSoFar = query.current;
const repeated = typedSoFar.length > 1 && [...typedSoFar].every((char) => char === typedSoFar[0]);
const needle = repeated ? typedSoFar[0] : typedSoFar;
const match = ordered.find((item) =>
(item.dataset.textValue ?? item.textContent ?? "").trim().toLocaleLowerCase().startsWith(needle),
);
if (!match) return false;
event.preventDefault();
match.focus();
return true;
}, []);
}
"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>
);
}
"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;
}
from"user" | "assistant"Who sent it; "user" rows align to the end, "assistant" rows to the start.
animateIn?booleanPlays a trailing-edge pop-up once when this message row mounts.
falselabels?Partial<{ user: string; assistant: string; typing: string; }>Override any built-in string.
className?stringClasses merged onto the root element.
spacing?"compact" | "default"Gap between messages: 6 px for "compact", 16 px for "default". Default: "compact"
compactclassName?stringClasses merged onto the root element.
placeholder?booleanKeep an empty avatar slot so grouped messages remain aligned.
falseclassName?stringClasses merged onto the root element.
label?stringScreen reader text for the typing dots. Default: "Responding"
className?stringClasses merged onto the root element.
variant?"solid" | "soft" | "tint" | "outline" | "ghost" | "danger"Fill and border style of the bubble. Default: "soft"
softalign?"end" | "start"Defaults to the surrounding Message alignment when omitted.
animateIn?booleanPlays the bubble entrance once when this component mounts.
falselabels?Partial<{ showMore: string; showLess: string; }>Override any built-in string.
className?stringClasses merged onto the root element.
open?booleanWhether the full text shows, for controlled use.
defaultOpen?booleanWhether the full text shows at first when uncontrolled. Default: false
falseonOpenChange?((open: boolean) => void)Called with the new state when the text expands or collapses.
collapsedLines?2 | 6 | 3 | 4 | 5Lines shown while collapsed. Default: 4
4moreLabel?ReactNodeText of the expand button. Default: "Show more"
lessLabel?ReactNodeText of the collapse button. Default: "Show less"
contentClassName?stringClasses merged onto the clamped text wrapper.
triggerClassName?stringClasses merged onto the show more button.
className?stringClasses merged onto the root element.
render?ReactElement<unknown, string | JSXElementConstructor<any>>Replaces the content element while preserving bubble styling.
className?stringClasses merged onto the root element.
spacing?"compact" | "default"Gap between bubbles. Default: "compact"
compactclassName?stringClasses merged onto the root element.
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.
busy?booleanMarks the transcript as waiting for more streamed content.
navigation?"rail"Adds a compact rail for navigating between rendered Message rows.
jumpButton?booleanShows a button back to the latest message once the reader scrolls up. Default true.
truenavigationLabel?stringAccessible label for the optional message navigation rail.
viewportClassName?stringClasses merged onto the scrolling viewport.
contentClassName?stringClasses merged onto the log element that wraps the messages.
railClassName?stringClasses merged onto the navigation rail, used with `navigation="rail"`.
viewportRef?Ref<HTMLElement>Ref to the scrolling viewport element.
viewportProps?Omit<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "children" | "ref" | "className">Extra props for the scrolling viewport. Its event handlers still run.
contentProps?Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "children" | "ref" | "className">Extra props for the log element that wraps the messages.
labels?Partial<{ label: string; jumpToLatest: string; navigationLabel: string; preview: string; goToUser: string; goToAssistant: string; goToMessage: string; }>Override any built-in string.
className?stringClasses merged onto the root element.
Build each conversation row from independent identity, content, and metadata primitives.
MessageGroup
└── Message
├── MessageAvatar
└── MessageContent
├── MessageHeader
├── MessageBubble
└── MessageFooterNote: Message Bubble supplies the visual surface inside the row. Message Scroller positions message rows inside a reader-aware transcript. Agent Activity renders progressive agent work as message content.
A message is a conversation row. It coordinates the avatar, metadata, content surface, and delivery details while allowing the content itself to be a bubble, an agent activity, a tool result, or a composed response.
Message Scroller
A reader-aware conversation viewport that follows streamed output at the live edge and releases control when the reader moves away.
Chat App
A complete agent conversation workspace composing navigation, messages, streaming, planning, approvals, tools, code, diffs, generated media, sources, and prompt input.
Message Bubble
A focused conversational surface with visual tones, independent alignment, grouped messages, expandable content, and interactive link or button support.
Updated