Message Actions
Assistant message action row (`MessageActions`) with copy that morphs into a drawn check, regenerate that spins (continuously while its promise runs), exclusive thumbs up/down that pop in filled, a thumbs-down reason popover with toggle chips and comment, share and a more menu; reveals on message hover or focus and stays visible on touch or with `visibility="always"` for the last message — a standalone, richer counterpart to StreamingResponse's built-in actions.
Preview
Install
Add it with the shadcn CLI, or copy the source manually.
shadcn init? You are set. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
"use client";
import { type RefObject, useEffect } from "react";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Return true for an outside target that should *not* dismiss. Must be stable. */
ignore?: (target: Element) => boolean;
}
/**
* What every currently open dismiss scope counts as inside itself. A consumed
* dismissal reads this to tell a stray gesture from one that belongs to an
* overlay in front of it: overlays have no shared z-order to consult, but the
* one the gesture landed in has said as much by registering it.
*/
const openScopes = new Set<(target: Element) => boolean>();
function claimedByAnotherScope(
self: (target: Element) => boolean,
target: Element,
) {
for (const scope of openScopes) {
if (scope !== self && scope(target)) return true;
}
return false;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over. `onDismiss` and `ignore` must be stable (wrap in
* useCallback) so the listeners aren't re-bound every render while open.
*/
export function useDismiss(
open: boolean,
onDismiss: () => void,
ref: RefObject<HTMLElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
ignore,
}: DismissOptions = {},
) {
useEffect(() => {
if (!open) return;
const inside = (target: Element) =>
Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));
const onKey = (event: KeyboardEvent) => {
if (dismissOnEscape && event.key === "Escape") onDismiss();
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside one that is also open: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !claimedByAnotherScope(inside, target)) {
consumeActivation(event);
}
onDismiss();
};
openScopes.add(inside);
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer, true);
return () => {
openScopes.delete(inside);
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
};
}, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);
}
// 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";
/**
* Grow a small control's *hit area* to at least 44×44px (WCAG 2.5.5, Apple
* HIG) on a coarse pointer, without changing what it looks like or the space
* it takes in layout. An invisible `::after` box, centered on the control and
* `max(100%, 2.75rem)` on each axis, catches the taps: a 32px icon button
* reaches 6px past each edge, a wide 40px button only grows vertically, and a
* control already 44px or larger is left as it is. Hit-testing a pseudo
* element lands on its owner, so handlers, focus and `:active` all behave.
*
* Mouse and trackpad rendering is untouched — nothing here applies outside
* `pointer: coarse`. Requirements on the element it goes on:
* - It must be the containing block: add `relative` (and keep it mergeable, so
* a consumer's `absolute` still wins through `cn`).
* - It must not clip itself (`overflow-hidden`), or the overhang is clipped
* away along with its hit area.
* - It must render children: `<input>` and other void elements have no
* `::after`. Put it on the wrapper or label instead.
* - It must not already use `::after` for something visible.
*
* Centered 44px means two 32px buttons with a 4px gap overlap by 8px; the
* later one wins that strip, which still ends well short of the earlier
* button's visual center. Below a ~32px pitch the later neighbour starts
* eating into that center — use `TOUCH_TARGET_Y_CLASS` for such dense rows.
*
* The overhang is real geometry: inside a scroll container it counts as
* scrollable overflow, so a control flush against a scroller's edge can add a
* few pixels of scroll on touch screens. Give such a scroller a little padding
* on that side.
*/
export const TOUCH_TARGET_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:top-1/2 pointer-coarse:after:left-1/2 pointer-coarse:after:size-[max(100%,2.75rem)] pointer-coarse:after:-translate-x-1/2 pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* `TOUCH_TARGET_CLASS` on the vertical axis only, for controls packed tighter
* than ~32px apart in a row (pagination dots, dense swatches), where growing
* sideways would hand most of each control to its neighbour. Same rules.
*/
export const TOUCH_TARGET_Y_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:top-1/2 pointer-coarse:after:h-[max(100%,2.75rem)] pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* 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 { useEffect, useState } from "react";
/**
* Returns true only on devices that have a true hover (mouse / trackpad).
* Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere
* — gate hover-only effects (scale lifts, magnetic pulls) behind this.
*/
export function useHoverCapable() {
const [canHover, setCanHover] = useState(false);
useEffect(() => {
if (typeof window === "undefined" || !window.matchMedia) return;
const mq = window.matchMedia("(hover: hover) and (pointer: fine)");
const update = () => setCanHover(mq.matches);
update();
mq.addEventListener?.("change", update);
return () => mq.removeEventListener?.("change", update);
}, []);
return canHover;
}
"use client";
import { useCallback, useState } from "react";
import { getFaviconUrl } from "@/lib/favicon";
/**
* Resolves a site favicon and drops it once it is known to be unusable, so
* callers can draw their own glyph instead of a broken image. Plenty of sites
* answer `/favicon.ico` with a 403 or 404, and `onError` is not enough to catch
* it: an image the browser starts loading from server-rendered HTML usually
* fails before React attaches a handler, and that event is never replayed.
* `decode()` settles on the image's final state instead of relying on an event
* firing at the right moment.
*/
export function useFavicon(url?: string) {
const resolved = url ? getFaviconUrl(url) : null;
const [failedSrc, setFailedSrc] = useState<string | null>(null);
const src = resolved && resolved !== failedSrc ? resolved : null;
const ref = useCallback(
(img: HTMLImageElement | null) => {
if (!img || !src) return;
let released = false;
img.decode().catch(() => {
if (!released) setFailedSrc(src);
});
// The node is going away or the source changed; a late rejection then
// describes an image we are no longer showing.
return () => {
released = true;
};
},
[src],
);
return { src, ref };
}
"use client";
import { 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;
},
}),
[],
);
}
/** Resolve a website URL to its conventional root favicon location. */
export function getFaviconUrl(value: string) {
try {
return new URL("/favicon.ico", value).toString();
} catch {
return null;
}
}
Copy the source code
"use client";
// karaui.kamisama-v0.my.id/components/agents/message-actions
import {
Copy,
MoreHorizontal,
RotateCw,
Share,
ThumbsDown,
ThumbsUp,
} from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
type ComponentPropsWithRef,
type ReactNode,
useEffect,
useRef,
useState,
} from "react";
import { Button } from "@/components/motion/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/motion/dropdown-menu";
import {
MorphPopover,
MorphPopoverContent,
} from "@/components/motion/popover-morph";
import { Textarea } from "@/components/motion/textarea";
import { ToggleGroup, ToggleGroupItem } from "@/components/motion/toggle-group";
import { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type MessageFeedback = "up" | "down" | null;
export interface MessageFeedbackReason {
value: string;
label: string;
}
export interface MessageFeedbackDetails {
reasons: string[];
comment: string;
}
export interface MessageMoreAction {
value: string;
label: string;
icon?: ReactNode;
destructive?: boolean;
disabled?: boolean;
}
export interface MessageActionsProps
extends Omit<ComponentPropsWithRef<"div">, "children"> {
/** Plain text copied by the copy action. */
copyText?: string;
/** Overrides the built-in clipboard write. */
onCopy?: () => void | Promise<void>;
/** Shows the regenerate action. A returned promise keeps the icon spinning. */
onRegenerate?: () => void | Promise<void>;
feedback?: MessageFeedback;
defaultFeedback?: MessageFeedback;
onFeedbackChange?: (feedback: MessageFeedback) => void;
/** Reasons offered after a thumbs-down. Pass `[]` to skip the popover. */
feedbackReasons?: MessageFeedbackReason[];
onFeedbackSubmit?: (details: MessageFeedbackDetails) => void;
onShare?: () => void;
moreActions?: MessageMoreAction[];
onMoreAction?: (value: string) => void;
/**
* `hover` reveals the row while the surrounding `Message` / message group is
* hovered or focused (always visible on touch); `always` keeps it shown —
* use it for the last message.
*/
visibility?: "hover" | "always";
}
export const DEFAULT_FEEDBACK_REASONS: MessageFeedbackReason[] = [
{ value: "incorrect", label: "Incorrect" },
{ value: "unhelpful", label: "Not helpful" },
{ value: "incomplete", label: "Incomplete" },
{ value: "instructions", label: "Ignored instructions" },
{ value: "unsafe", label: "Harmful" },
];
function ActionButton({
label,
pressed,
onClick,
children,
className,
}: {
label: string;
pressed?: boolean;
onClick?: () => void;
children: ReactNode;
className?: string;
}) {
const reduce = useReducedMotion() ?? false;
return (
<motion.button
type="button"
aria-label={label}
title={label}
aria-pressed={pressed}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.88 }}
transition={SPRING_PRESS}
className={cn(
"relative grid size-7 place-items-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
pressed && "text-foreground",
className,
)}
>
{children}
</motion.button>
);
}
function DrawnCheck({ reduce }: { reduce: boolean }) {
return (
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.25"
strokeLinecap="round"
strokeLinejoin="round"
className="size-3.5"
>
<motion.path
d="M5 12.5l4.5 4.5L19 7.5"
initial={{ pathLength: reduce ? 1 : 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: reduce ? 0 : 0.28, ease: EASE_OUT, delay: 0.04 }}
/>
</svg>
);
}
/** Outline thumb with a filled twin that pops in over it when active. */
function Thumb({
direction,
active,
reduce,
}: {
direction: "up" | "down";
active: boolean;
reduce: boolean;
}) {
const Icon = direction === "up" ? ThumbsUp : ThumbsDown;
return (
<span className="relative grid size-3.5 place-items-center">
<Icon aria-hidden="true" className="size-3.5" />
<AnimatePresence initial={false}>
{active ? (
<motion.span
key="fill"
aria-hidden="true"
className="absolute inset-0 grid place-items-center"
initial={
reduce ? { opacity: 0 } : { opacity: 0, scale: 0.4, rotate: 0 }
}
animate={
reduce
? { opacity: 1 }
: {
opacity: 1,
scale: [0.4, 1.28, 1],
rotate: [0, direction === "up" ? -14 : 14, 0],
}
}
exit={{ opacity: 0, scale: reduce ? 1 : 0.6, transition: { duration: 0.12 } }}
transition={
reduce ? { duration: 0.12 } : { duration: 0.42, ease: EASE_OUT }
}
>
<Icon className="size-3.5 fill-current" />
</motion.span>
) : null}
</AnimatePresence>
</span>
);
}
export function MessageActions({
copyText,
onCopy,
onRegenerate,
feedback,
defaultFeedback = null,
onFeedbackChange,
feedbackReasons = DEFAULT_FEEDBACK_REASONS,
onFeedbackSubmit,
onShare,
moreActions = [],
onMoreAction,
visibility = "hover",
className,
...props
}: MessageActionsProps) {
const reduce = useReducedMotion() ?? false;
const [copied, setCopied] = useState(false);
const [spins, setSpins] = useState(0);
const [regenerating, setRegenerating] = useState(false);
const [internalFeedback, setInternalFeedback] =
useState<MessageFeedback>(defaultFeedback);
const [popoverOpen, setPopoverOpen] = useState(false);
const [menuOpen, setMenuOpen] = useState(false);
const [reasons, setReasons] = useState<string[]>([]);
const [comment, setComment] = useState("");
const [thanked, setThanked] = useState(false);
const [announcement, setAnnouncement] = useState("");
const copyTimer = useRef<number | undefined>(undefined);
const thanksTimer = useRef<number | undefined>(undefined);
const downRef = useRef<HTMLSpanElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
const current = feedback ?? internalFeedback;
const canCopy = Boolean(copyText || onCopy);
useEffect(
() => () => {
window.clearTimeout(copyTimer.current);
window.clearTimeout(thanksTimer.current);
},
[],
);
const copy = async () => {
try {
if (onCopy) await onCopy();
else if (copyText) await navigator.clipboard?.writeText(copyText);
} catch {
setAnnouncement("Copy failed");
return;
}
setCopied(true);
setAnnouncement("Copied to clipboard");
window.clearTimeout(copyTimer.current);
copyTimer.current = window.setTimeout(() => setCopied(false), 1600);
};
const regenerate = async () => {
if (!onRegenerate || regenerating) return;
setSpins((count) => count + 1);
const result = onRegenerate();
if (result && typeof result.then === "function") {
setRegenerating(true);
try {
await result;
} finally {
setRegenerating(false);
}
}
};
const setFeedback = (next: MessageFeedback) => {
if (feedback === undefined) setInternalFeedback(next);
onFeedbackChange?.(next);
};
const openPopover = (next: boolean) => {
if (!next && panelRef.current?.contains(document.activeElement)) {
downRef.current?.querySelector("button")?.focus({ preventScroll: true });
}
setPopoverOpen(next);
if (next) {
setReasons([]);
setComment("");
setThanked(false);
}
};
const toggleUp = () => {
openPopover(false);
setFeedback(current === "up" ? null : "up");
};
const toggleDown = () => {
if (current === "down") {
setFeedback(null);
openPopover(false);
return;
}
setFeedback("down");
if (feedbackReasons.length) openPopover(true);
};
const submit = () => {
onFeedbackSubmit?.({ reasons, comment: comment.trim() });
setThanked(true);
setAnnouncement("Thanks for the feedback");
window.clearTimeout(thanksTimer.current);
thanksTimer.current = window.setTimeout(() => openPopover(false), 1100);
};
// Move focus into the panel once it has mounted and been measured.
useEffect(() => {
if (!popoverOpen) return;
const frame = requestAnimationFrame(() =>
panelRef.current
?.querySelector<HTMLElement>("[aria-pressed], textarea")
?.focus({ preventScroll: true }),
);
return () => cancelAnimationFrame(frame);
}, [popoverOpen]);
const pinned = visibility === "always" || popoverOpen || menuOpen;
return (
<div
data-slot="message-actions"
data-visible={pinned || undefined}
className={cn(
"flex items-center gap-0.5 transition-[opacity,translate] duration-200 ease-out motion-reduce:translate-y-0",
pinned
? "translate-y-0 opacity-100"
: "translate-y-0.5 opacity-0 focus-within:translate-y-0 focus-within:opacity-100 group-hover/message:translate-y-0 group-hover/message:opacity-100 group-hover/message-group:translate-y-0 group-hover/message-group:opacity-100 [@media(hover:none)]:translate-y-0 [@media(hover:none)]:opacity-100",
className,
)}
{...props}
>
{canCopy ? (
<ActionButton label={copied ? "Copied" : "Copy"} onClick={copy}>
<AnimatePresence initial={false} mode="popLayout">
<motion.span
key={copied ? "check" : "copy"}
className="grid place-items-center"
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}
animate={{ opacity: 1, scale: 1 }}
exit={
reduce
? { opacity: 0, transition: { duration: 0.1 } }
: { opacity: 0, scale: 0.6, transition: { duration: 0.1 } }
}
transition={reduce ? { duration: 0.12 } : SPRING_SWAP}
>
{copied ? (
<DrawnCheck reduce={reduce} />
) : (
<Copy aria-hidden="true" className="size-3.5" />
)}
</motion.span>
</AnimatePresence>
</ActionButton>
) : null}
{onRegenerate ? (
<ActionButton
label={regenerating ? "Regenerating" : "Regenerate"}
onClick={regenerate}
>
<motion.span
aria-hidden="true"
className="grid place-items-center"
animate={
reduce
? undefined
: regenerating
? { rotate: [spins * 360, spins * 360 + 360] }
: { rotate: spins * 360 }
}
transition={
regenerating
? {
duration: 0.8,
ease: "linear",
repeat: Number.POSITIVE_INFINITY,
}
: { duration: 0.55, ease: EASE_OUT }
}
>
<RotateCw className="size-3.5" />
</motion.span>
</ActionButton>
) : null}
<ActionButton label="Good response" pressed={current === "up"} onClick={toggleUp}>
<Thumb direction="up" active={current === "up"} reduce={reduce} />
</ActionButton>
<MorphPopover open={popoverOpen} onOpenChange={openPopover}>
<span ref={downRef} className="inline-flex">
<ActionButton
label="Bad response"
pressed={current === "down"}
onClick={toggleDown}
>
<Thumb direction="down" active={current === "down"} reduce={reduce} />
</ActionButton>
</span>
<MorphPopoverContent side="bottom" align="start" radius={14} className="w-72">
<div ref={panelRef} className="p-3">
<AnimatePresence mode="popLayout" initial={false}>
{thanked ? (
<motion.div
key="thanks"
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
transition={reduce ? { duration: 0.12 } : SPRING_SWAP}
className="flex items-center gap-2 py-6 text-sm text-foreground"
>
<span className="mx-auto flex items-center gap-2">
<span className="grid size-6 place-items-center rounded-full bg-muted">
<DrawnCheck reduce={reduce} />
</span>
Thanks for the feedback
</span>
</motion.div>
) : (
<motion.div
key="form"
exit={{ opacity: 0, transition: { duration: 0.1 } }}
>
<p className="text-sm font-medium text-foreground">
What went wrong?
</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Pick any that apply.
</p>
<ToggleGroup
type="multiple"
size="sm"
variant="default"
value={reasons}
onValueChange={setReasons}
aria-label="Feedback reasons"
className="mt-2.5 flex w-full flex-wrap gap-1.5 rounded-none border-0 bg-transparent p-0"
>
{feedbackReasons.map((reason) => (
<ToggleGroupItem
key={reason.value}
value={reason.value}
className="rounded-full border border-border px-2.5"
>
{reason.label}
</ToggleGroupItem>
))}
</ToggleGroup>
<Textarea
value={comment}
onChange={setComment}
placeholder="Tell us more (optional)"
aria-label="Additional feedback"
minRows={2}
maxRows={4}
className="mt-2.5"
/>
<div className="mt-2.5 flex justify-end gap-1.5">
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => openPopover(false)}
>
Cancel
</Button>
<Button
type="button"
size="sm"
disabled={!reasons.length && !comment.trim()}
onClick={submit}
>
Submit
</Button>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
</MorphPopoverContent>
</MorphPopover>
{onShare ? (
<ActionButton label="Share" onClick={onShare}>
<Share aria-hidden="true" className="size-3.5" />
</ActionButton>
) : null}
{moreActions.length ? (
<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
<DropdownMenuTrigger>
<button
type="button"
aria-label="More actions"
title="More actions"
className="grid size-7 place-items-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:bg-muted data-[state=open]:text-foreground"
>
<MoreHorizontal aria-hidden="true" className="size-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-48">
{moreActions.map((action) => (
<DropdownMenuItem
key={action.value}
icon={action.icon}
variant={action.destructive ? "destructive" : "default"}
disabled={action.disabled}
onSelect={() => onMoreAction?.(action.value)}
>
{action.label}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
) : null}
<span aria-live="polite" className="sr-only">
{announcement}
</span>
</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 { ButtonState, StatefulButtonProps } from "./stateful";
export { StatefulButton } from "./stateful";
"use client";
import { Check, ChevronRight } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
type MutableRefObject,
type ReactElement,
type FocusEvent as ReactFocusEvent,
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
type ReactNode,
type PointerEvent as ReactPointerEvent,
type Ref,
useCallback,
useContext,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import {
type PlacementAlign,
type PlacementSide,
resolvePlacement,
} from "@/components/motion/anchored-placement";
import { usePopoverPortalPosition } from "@/components/motion/popover-position";
import { EASE_OUT, SPRING_LAYOUT, SPRING_PANEL } from "@/lib/ease";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { cn } from "@/lib/utils";
/* -------------------------------------------------------------------------- */
/* Levels */
/* -------------------------------------------------------------------------- */
/** Where focus lands when a panel opens. */
type FocusIntent = "first" | "last" | "content" | "none";
// Hovering a sub trigger waits this long before opening, so a pointer just
// passing over the row on its way down the list doesn't flash a submenu.
const SUB_OPEN_DELAY = 100;
// Leaving the sub trigger (or hovering a sibling) closes the submenu only
// after this grace, so a diagonal move toward the submenu that clips a
// neighbouring row doesn't snap it shut.
const SUB_CLOSE_DELAY = 220;
const TYPEAHEAD_RESET = 500;
/**
* One open panel: the root menu or a submenu. Items, the active-row
* highlight and keyboard navigation all read the nearest level, so a submenu
* is the same machinery one step down.
*/
interface MenuLevel {
/** Shared by every panel and the trigger of one menu tree (dismissal scope). */
rootId: string;
/** Scope for this panel's layoutId highlight. */
levelId: string;
open: boolean;
isSub: boolean;
triggerId: string;
contentId: string;
triggerRef: MutableRefObject<HTMLElement | null>;
contentRef: MutableRefObject<HTMLDivElement | null>;
focusIntent: MutableRefObject<FocusIntent>;
activeId: string | null;
setActiveId: (id: string | null) => void;
/** Id of the child submenu currently open from this panel. */
openSub: string | null;
setOpenSub: (id: string | null) => void;
scheduleSubClose: () => void;
cancelSubClose: () => void;
/** Close this panel only (root: the whole menu). */
close: (restoreFocus: boolean) => void;
/** Close the whole menu tree. */
closeAll: (restoreFocus: boolean) => void;
/** Open the root menu (used by the trigger). */
openRoot: () => void;
reduce: boolean;
}
const MenuLevelContext = createContext<MenuLevel | null>(null);
function useMenuLevel(component: string) {
const level = useContext(MenuLevelContext);
if (!level) throw new Error(`${component} must be used within <DropdownMenu>`);
return level;
}
/** Per-panel state shared by the root and every submenu. */
function useLevelCore(open: boolean) {
const [activeId, setActiveId] = useState<string | null>(null);
const [openSub, setOpenSubState] = useState<string | null>(null);
const subCloseTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const cancelSubClose = useCallback(() => {
if (subCloseTimer.current) clearTimeout(subCloseTimer.current);
subCloseTimer.current = null;
}, []);
const setOpenSub = useCallback(
(id: string | null) => {
cancelSubClose();
setOpenSubState(id);
},
[cancelSubClose],
);
const scheduleSubClose = useCallback(() => {
cancelSubClose();
subCloseTimer.current = setTimeout(() => {
subCloseTimer.current = null;
setOpenSubState(null);
}, SUB_CLOSE_DELAY);
}, [cancelSubClose]);
// Reset the highlight when the panel opens, not when it closes: removing
// the layoutId highlight while the panel is still animating out leaves
// motion waiting on it forever, so the closed panel never unmounts.
useEffect(() => {
if (open) {
setActiveId(null);
return;
}
cancelSubClose();
setOpenSubState(null);
}, [open, cancelSubClose]);
useEffect(() => cancelSubClose, [cancelSubClose]);
return useMemo(
() => ({
activeId,
setActiveId,
openSub,
setOpenSub,
scheduleSubClose,
cancelSubClose,
}),
[activeId, openSub, setOpenSub, scheduleSubClose, cancelSubClose],
);
}
function getItems(container: HTMLElement | null) {
if (!container) return [];
return Array.from(
container.querySelectorAll<HTMLElement>(
'[data-dropdown-menu-item]:not([data-disabled="true"])',
),
);
}
function focusByIntent(container: HTMLElement | null, intent: FocusIntent) {
if (!container || intent === "none") return;
const items = getItems(container);
const target =
intent === "first"
? items[0]
: intent === "last"
? items[items.length - 1]
: container;
(target ?? container).focus({ preventScroll: true });
}
function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
if (typeof ref === "function") ref(value);
else if (ref) (ref as MutableRefObject<T | null>).current = value;
}
/* -------------------------------------------------------------------------- */
/* Root */
/* -------------------------------------------------------------------------- */
export interface DropdownMenuProps {
children: ReactNode;
/** Controlled open state. */
open?: boolean;
/** Uncontrolled initial open state. */
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
className?: string;
}
/**
* Composable dropdown menu following the WAI-ARIA menu button pattern. The
* panel scales out of the trigger side, an active-row highlight glides
* between items, and submenus open on hover intent or ArrowRight.
*/
export function DropdownMenu({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
className,
}: DropdownMenuProps) {
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const controlled = controlledOpen !== undefined;
const open = controlled ? controlledOpen : internalOpen;
const baseId = useId();
const triggerRef = useRef<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const focusIntent = useRef<FocusIntent>("content");
const reduce = useReducedMotion() ?? false;
const core = useLevelCore(open);
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const closeAll = useCallback(
(restoreFocus: boolean) => {
setOpen(false);
if (restoreFocus) triggerRef.current?.focus({ preventScroll: true });
},
[setOpen],
);
const dismiss = useCallback(() => setOpen(false), [setOpen]);
const openRoot = useCallback(() => setOpen(true), [setOpen]);
const insideTree = useCallback(
(target: Element) =>
Boolean(target.closest(`[data-dropdown-menu="${baseId}"]`)),
[baseId],
);
// Escape is handled by the focused panel, which knows whether it is a
// submenu (close one level) or the root (close and refocus the trigger).
useDismiss(open, dismiss, null, { escape: false, ignore: insideTree });
// Focus moves into the panel on open: the first/last item for keyboard
// opens, the panel itself for pointer opens so arrows work immediately.
useEffect(() => {
if (!open) return;
const frame = requestAnimationFrame(() =>
focusByIntent(contentRef.current, focusIntent.current),
);
return () => cancelAnimationFrame(frame);
}, [open]);
const level = useMemo<MenuLevel>(
() => ({
rootId: baseId,
levelId: `${baseId}-root`,
open,
isSub: false,
triggerId: `${baseId}-trigger`,
contentId: `${baseId}-content`,
triggerRef,
contentRef,
focusIntent,
...core,
close: closeAll,
closeAll,
openRoot,
reduce,
}),
[baseId, open, core, closeAll, openRoot, reduce],
);
return (
<MenuLevelContext.Provider value={level}>
<div className={cn("relative inline-flex", className)}>{children}</div>
</MenuLevelContext.Provider>
);
}
/* -------------------------------------------------------------------------- */
/* Trigger */
/* -------------------------------------------------------------------------- */
type TriggerChildProps = React.HTMLAttributes<HTMLElement> & {
ref?: Ref<HTMLElement>;
[key: `data-${string}`]: string | undefined;
};
export interface DropdownMenuTriggerProps {
/** A single element, normally a `<button>`. Its own handlers still run. */
children: ReactElement<TriggerChildProps>;
className?: string;
}
export function DropdownMenuTrigger({
children,
className,
}: DropdownMenuTriggerProps) {
const level = useMenuLevel("DropdownMenuTrigger");
if (!isValidElement(children)) {
throw new Error("<DropdownMenuTrigger> requires a single React element");
}
const childProps = children.props;
const childRef = childProps.ref;
const openWith = (intent: FocusIntent) => {
level.focusIntent.current = intent;
if (!level.open) {
level.openRoot();
} else {
focusByIntent(level.contentRef.current, intent);
}
};
return cloneElement(children, {
ref: (node: HTMLElement | null) => {
level.triggerRef.current = node;
assignRef(childRef, node);
},
id: level.triggerId,
"aria-haspopup": "menu",
"aria-expanded": level.open,
"aria-controls": level.open ? level.contentId : undefined,
"data-state": level.open ? "open" : "closed",
"data-dropdown-menu": level.rootId,
className: cn(childProps.className, className),
onClick: (event: ReactMouseEvent<HTMLElement>) => {
childProps.onClick?.(event);
if (event.defaultPrevented) return;
if (level.open) {
level.closeAll(false);
return;
}
// `detail` is 0 for a click synthesized by the keyboard.
openWith(event.detail === 0 ? "first" : "content");
},
onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => {
childProps.onKeyDown?.(event);
if (event.defaultPrevented) return;
if (
event.key === "ArrowDown" ||
event.key === "Enter" ||
event.key === " "
) {
event.preventDefault();
openWith("first");
} else if (event.key === "ArrowUp") {
event.preventDefault();
openWith("last");
}
},
});
}
/* -------------------------------------------------------------------------- */
/* Panel */
/* -------------------------------------------------------------------------- */
interface MenuPanelProps {
level: MenuLevel;
children: ReactNode;
side: PlacementSide;
align: PlacementAlign;
sideOffset: number;
alignOffset: number;
className?: string;
ariaLabel?: string;
onPanelEnter?: () => void;
}
function MenuPanel({
level,
children,
side,
align,
sideOffset,
alignOffset,
className,
ariaLabel,
onPanelEnter,
}: MenuPanelProps) {
const [portalReady, setPortalReady] = useState(false);
const typeahead = useRef("");
const typeaheadTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const layout = usePopoverPortalPosition(
level.triggerRef,
level.contentRef,
portalReady && level.open,
);
useEffect(() => setPortalReady(true), []);
useEffect(
() => () => {
if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);
},
[],
);
const moveFocus = (direction: 1 | -1) => {
const items = getItems(level.contentRef.current);
if (items.length === 0) return;
const current = items.indexOf(document.activeElement as HTMLElement);
const next =
current < 0
? direction === 1
? 0
: items.length - 1
: (current + direction + items.length) % items.length;
items[next]?.focus();
};
const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
// React bubbles events through portals: a submenu's keys would reach its
// parent panel too. Only answer keys pressed inside this panel's DOM.
if (!event.currentTarget.contains(event.target as Node)) return;
if (event.defaultPrevented) return;
const { key } = event;
if (key === "Escape") {
event.preventDefault();
level.close(true);
return;
}
if (key === "ArrowLeft" && level.isSub) {
event.preventDefault();
level.close(true);
return;
}
if (key === "Tab") {
event.preventDefault();
level.closeAll(true);
return;
}
if (key === "ArrowDown" || key === "ArrowUp") {
event.preventDefault();
moveFocus(key === "ArrowDown" ? 1 : -1);
return;
}
if (key === "Home" || key === "End") {
event.preventDefault();
const items = getItems(level.contentRef.current);
items[key === "Home" ? 0 : items.length - 1]?.focus();
return;
}
const printable =
key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;
// A leading space is activation, not a search character.
if (!printable || (key === " " && typeahead.current === "")) return;
event.preventDefault();
typeahead.current += key.toLocaleLowerCase();
if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);
typeaheadTimer.current = setTimeout(() => {
typeahead.current = "";
}, TYPEAHEAD_RESET);
const items = getItems(level.contentRef.current);
const start = items.indexOf(document.activeElement as HTMLElement);
// Search from the row after the current one so repeating a letter cycles.
const ordered =
typeahead.current.length === 1 && start >= 0
? [...items.slice(start + 1), ...items.slice(0, start + 1)]
: items;
const match = ordered.find((item) =>
(item.dataset.label ?? item.textContent ?? "")
.trim()
.toLocaleLowerCase()
.startsWith(typeahead.current),
);
match?.focus();
};
if (!portalReady) return null;
const placement = layout
? resolvePlacement(layout, { side, align, sideOffset, alignOffset })
: null;
return createPortal(
<AnimatePresence>
{level.open ? (
<motion.div
ref={level.contentRef}
id={level.contentId}
role="menu"
aria-label={ariaLabel}
aria-labelledby={ariaLabel ? undefined : level.triggerId}
aria-orientation="vertical"
tabIndex={-1}
data-dropdown-menu={level.rootId}
data-side={placement?.side ?? side}
initial={level.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.94 }}
animate={{ opacity: 1, scale: 1 }}
// pointerEvents flips at the start of the exit, so a closing panel
// can never be hovered or clicked through.
exit={
level.reduce
? { opacity: 0, pointerEvents: "none", transition: { duration: 0.1 } }
: {
opacity: 0,
scale: 0.96,
pointerEvents: "none",
transition: { duration: 0.12, ease: EASE_OUT },
}
}
transition={
level.reduce
? { duration: 0.12, ease: EASE_OUT }
: { ...SPRING_PANEL, opacity: { duration: 0.16, ease: EASE_OUT } }
}
style={{
left: placement?.left ?? 0,
top: placement?.top ?? 0,
// The panel grows out of the trigger's side — transform-origin on
// an HTML element is safe for motion's scale.
transformOrigin: placement?.origin ?? "50% 0%",
visibility: placement ? "visible" : "hidden",
}}
onKeyDown={onKeyDown}
onFocus={(event: ReactFocusEvent<HTMLDivElement>) => {
if (event.target === event.currentTarget) level.setActiveId(null);
else onPanelEnter?.();
}}
onPointerEnter={onPanelEnter}
className={cn(
"fixed z-[100] min-w-52 rounded-xl border border-border bg-card p-1.5 text-foreground shadow-[0_18px_40px_-12px_rgba(0,0,0,0.28)] outline-none",
className,
)}
>
{children}
</motion.div>
) : null}
</AnimatePresence>,
document.body,
);
}
export interface DropdownMenuContentProps {
children: ReactNode;
/** Preferred side; flips when the viewport lacks room. Default "bottom". */
side?: "bottom" | "top";
/** Alignment against the trigger. Default "start". */
align?: PlacementAlign;
/** Gap between trigger and panel, in px. Default 6. */
sideOffset?: number;
alignOffset?: number;
/** Accessible name; defaults to the trigger's text via aria-labelledby. */
ariaLabel?: string;
className?: string;
}
export function DropdownMenuContent({
children,
side = "bottom",
align = "start",
sideOffset = 6,
alignOffset = 0,
ariaLabel,
className,
}: DropdownMenuContentProps) {
const level = useMenuLevel("DropdownMenuContent");
return (
<MenuPanel
level={level}
side={side}
align={align}
sideOffset={sideOffset}
alignOffset={alignOffset}
ariaLabel={ariaLabel}
className={className}
>
{children}
</MenuPanel>
);
}
/* -------------------------------------------------------------------------- */
/* Items */
/* -------------------------------------------------------------------------- */
type ItemVariant = "default" | "destructive";
interface ItemBaseProps {
children: ReactNode;
itemId?: string;
role?: "menuitem" | "menuitemcheckbox" | "menuitemradio";
ariaChecked?: boolean;
disabled?: boolean;
variant?: ItemVariant;
inset?: boolean;
textValue?: string;
className?: string;
closeOnSelect: boolean;
onActivate?: (event: ReactMouseEvent<HTMLButtonElement>) => void;
isSubTrigger?: boolean;
extraProps?: React.ButtonHTMLAttributes<HTMLButtonElement> & {
ref?: Ref<HTMLButtonElement>;
[key: `data-${string}`]: string | undefined;
};
}
function ItemBase({
children,
itemId,
role = "menuitem",
ariaChecked,
disabled = false,
variant = "default",
inset = false,
textValue,
className,
closeOnSelect,
onActivate,
isSubTrigger = false,
extraProps,
}: ItemBaseProps) {
const level = useMenuLevel("DropdownMenuItem");
const autoId = useId();
const id = itemId ?? autoId;
const highlighted = level.activeId === id;
const checkedProps =
role === "menuitem" ? {} : { "aria-checked": ariaChecked ?? false };
const { onPointerEnter, onPointerLeave, onKeyDown, ref, ...rest } =
extraProps ?? {};
return (
<button
{...rest}
ref={ref}
type="button"
id={id}
role={role}
{...checkedProps}
disabled={disabled}
tabIndex={-1}
data-dropdown-menu-item=""
data-disabled={disabled ? "true" : undefined}
data-highlighted={highlighted ? "" : undefined}
data-label={textValue}
onFocus={() => level.setActiveId(id)}
onPointerEnter={(event: ReactPointerEvent<HTMLButtonElement>) => {
onPointerEnter?.(event);
if (!isSubTrigger && event.pointerType !== "touch") {
level.scheduleSubClose();
}
}}
onPointerMove={(event: ReactPointerEvent<HTMLButtonElement>) => {
if (disabled || event.pointerType === "touch") return;
if (document.activeElement !== event.currentTarget) {
event.currentTarget.focus({ preventScroll: true });
}
}}
onPointerLeave={(event: ReactPointerEvent<HTMLButtonElement>) => {
onPointerLeave?.(event);
if (event.pointerType === "touch" || isSubTrigger) return;
// Clearing focus to the panel drops the highlight when the pointer
// leaves the rows, the way native menus behave.
if (document.activeElement === event.currentTarget) {
level.contentRef.current?.focus({ preventScroll: true });
}
}}
onKeyDown={onKeyDown}
onClick={(event) => {
if (disabled) return;
onActivate?.(event);
if (closeOnSelect && !event.defaultPrevented) level.closeAll(true);
}}
className={cn(
"relative isolate flex w-full select-none items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left text-[13px] outline-none",
"disabled:pointer-events-none disabled:opacity-40",
"[&_svg]:size-4 [&_svg]:shrink-0",
inset && "pl-8",
variant === "destructive"
? "text-destructive [&_svg]:text-destructive"
: "text-foreground [&_svg]:text-muted-foreground",
className,
)}
>
{/* Its own presence boundary: a layoutId element registers with the
nearest AnimatePresence, and the panel's exit would otherwise wait
on the highlight's layout animation and never unmount. */}
<AnimatePresence initial={false}>
{highlighted ? (
<motion.span
aria-hidden="true"
layoutId={`${level.levelId}-highlight`}
className={cn(
"absolute inset-0 -z-10 rounded-lg",
variant === "destructive"
? "bg-destructive/10"
: "bg-foreground/[0.07]",
)}
transition={level.reduce ? { duration: 0 } : SPRING_LAYOUT}
/>
) : null}
</AnimatePresence>
{children}
</button>
);
}
function Shortcut({ children }: { children: ReactNode }) {
return (
<span
aria-hidden="true"
className="ml-auto pl-4 font-mono text-[11px] tracking-wide text-muted-foreground"
>
{children}
</span>
);
}
export interface DropdownMenuItemProps {
children: ReactNode;
/** Leading icon (sized to 16px). */
icon?: ReactNode;
/** Trailing shortcut hint, e.g. "⌘K" or a `KbdCombo`. Decorative. */
shortcut?: ReactNode;
variant?: ItemVariant;
disabled?: boolean;
/** Indent to line up with checkbox/radio rows. */
inset?: boolean;
/** Text used by typeahead when children aren't plain text. */
textValue?: string;
/** Call `event.preventDefault()` to keep the menu open. */
onSelect?: (event: ReactMouseEvent<HTMLButtonElement>) => void;
/** Default true. */
closeOnSelect?: boolean;
className?: string;
}
export function DropdownMenuItem({
children,
icon,
shortcut,
onSelect,
closeOnSelect = true,
...props
}: DropdownMenuItemProps) {
return (
<ItemBase {...props} closeOnSelect={closeOnSelect} onActivate={onSelect}>
{icon}
<span className="min-w-0 flex-1 truncate">{children}</span>
{shortcut ? <Shortcut>{shortcut}</Shortcut> : null}
</ItemBase>
);
}
function Indicator({
checked,
kind,
reduce,
}: {
checked: boolean;
kind: "check" | "dot";
reduce: boolean;
}) {
return (
<span
aria-hidden="true"
className="absolute left-2.5 flex size-4 items-center justify-center"
>
<AnimatePresence initial={false}>
{checked ? (
<motion.span
key={kind}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}
animate={{ opacity: 1, scale: 1 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}
transition={reduce ? { duration: 0.08 } : SPRING_PANEL}
className="flex items-center justify-center text-foreground"
>
{kind === "check" ? (
<Check className="size-3.5! text-foreground!" strokeWidth={2.6} />
) : (
<span className="size-1.5 rounded-full bg-current" />
)}
</motion.span>
) : null}
</AnimatePresence>
</span>
);
}
export interface DropdownMenuCheckboxItemProps
extends Omit<DropdownMenuItemProps, "onSelect" | "inset" | "icon"> {
checked?: boolean;
defaultChecked?: boolean;
onCheckedChange?: (checked: boolean) => void;
}
/** A toggle row. Stays open on select by default so several can be flipped. */
export function DropdownMenuCheckboxItem({
children,
checked: controlledChecked,
defaultChecked = false,
onCheckedChange,
shortcut,
closeOnSelect = false,
...props
}: DropdownMenuCheckboxItemProps) {
const level = useMenuLevel("DropdownMenuCheckboxItem");
const [internal, setInternal] = useState(defaultChecked);
const checked = controlledChecked ?? internal;
return (
<ItemBase
{...props}
inset
role="menuitemcheckbox"
ariaChecked={checked}
closeOnSelect={closeOnSelect}
onActivate={() => {
if (controlledChecked === undefined) setInternal(!checked);
onCheckedChange?.(!checked);
}}
>
<Indicator checked={checked} kind="check" reduce={level.reduce} />
<span className="min-w-0 flex-1 truncate">{children}</span>
{shortcut ? <Shortcut>{shortcut}</Shortcut> : null}
</ItemBase>
);
}
interface RadioGroupContextValue {
value: string | undefined;
select: (value: string) => void;
}
const RadioGroupContext = createContext<RadioGroupContextValue | null>(null);
export interface DropdownMenuRadioGroupProps {
children: ReactNode;
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/** Accessible name for the group. */
ariaLabel?: string;
className?: string;
}
export function DropdownMenuRadioGroup({
children,
value: controlledValue,
defaultValue,
onValueChange,
ariaLabel,
className,
}: DropdownMenuRadioGroupProps) {
const [internal, setInternal] = useState(defaultValue);
const value = controlledValue ?? internal;
const ctx = useMemo<RadioGroupContextValue>(
() => ({
value,
select: (next) => {
if (controlledValue === undefined) setInternal(next);
onValueChange?.(next);
},
}),
[value, controlledValue, onValueChange],
);
return (
<RadioGroupContext.Provider value={ctx}>
<fieldset
aria-label={ariaLabel}
className={cn("m-0 min-w-0 border-0 p-0", className)}
>
{children}
</fieldset>
</RadioGroupContext.Provider>
);
}
export interface DropdownMenuRadioItemProps
extends Omit<DropdownMenuItemProps, "onSelect" | "inset" | "icon"> {
value: string;
}
export function DropdownMenuRadioItem({
children,
value,
shortcut,
closeOnSelect = false,
...props
}: DropdownMenuRadioItemProps) {
const level = useMenuLevel("DropdownMenuRadioItem");
const group = useContext(RadioGroupContext);
if (!group) {
throw new Error(
"DropdownMenuRadioItem must be used within <DropdownMenuRadioGroup>",
);
}
const checked = group.value === value;
return (
<ItemBase
{...props}
inset
role="menuitemradio"
ariaChecked={checked}
closeOnSelect={closeOnSelect}
onActivate={() => group.select(value)}
>
<Indicator checked={checked} kind="dot" reduce={level.reduce} />
<span className="min-w-0 flex-1 truncate">{children}</span>
{shortcut ? <Shortcut>{shortcut}</Shortcut> : null}
</ItemBase>
);
}
export interface DropdownMenuLabelProps {
children: ReactNode;
inset?: boolean;
className?: string;
}
export function DropdownMenuLabel({
children,
inset = false,
className,
}: DropdownMenuLabelProps) {
return (
<div
className={cn(
"px-2.5 pb-1 pt-1.5 text-[11px] font-medium text-muted-foreground",
inset && "pl-8",
className,
)}
>
{children}
</div>
);
}
export interface DropdownMenuGroupProps {
children: ReactNode;
ariaLabel?: string;
className?: string;
}
export function DropdownMenuGroup({
children,
ariaLabel,
className,
}: DropdownMenuGroupProps) {
return (
<fieldset
aria-label={ariaLabel}
className={cn("m-0 min-w-0 border-0 p-0", className)}
>
{children}
</fieldset>
);
}
export function DropdownMenuSeparator({ className }: { className?: string }) {
return <hr className={cn("-mx-1.5 my-1.5 h-px border-0 bg-border", className)} />;
}
/* -------------------------------------------------------------------------- */
/* Submenus */
/* -------------------------------------------------------------------------- */
interface SubContextValue {
level: MenuLevel;
parent: MenuLevel;
triggerItemId: string;
openTimer: MutableRefObject<ReturnType<typeof setTimeout> | null>;
openWith: (intent: FocusIntent) => void;
}
const SubContext = createContext<SubContextValue | null>(null);
function useSub(component: string) {
const sub = useContext(SubContext);
if (!sub) throw new Error(`${component} must be used within <DropdownMenuSub>`);
return sub;
}
export interface DropdownMenuSubProps {
children: ReactNode;
}
/** A nested menu opened from a `DropdownMenuSubTrigger` row. */
export function DropdownMenuSub({ children }: DropdownMenuSubProps) {
const parent = useMenuLevel("DropdownMenuSub");
const subId = useId();
const open = parent.open && parent.openSub === subId;
const triggerRef = useRef<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const focusIntent = useRef<FocusIntent>("none");
const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const core = useLevelCore(open);
const triggerItemId = `${subId}-trigger`;
useEffect(
() => () => {
if (openTimer.current) clearTimeout(openTimer.current);
},
[],
);
// Open submenus take focus only when asked to (keyboard); a hover open
// leaves it on the trigger row.
useEffect(() => {
if (!open) return;
const frame = requestAnimationFrame(() =>
focusByIntent(contentRef.current, focusIntent.current),
);
return () => cancelAnimationFrame(frame);
}, [open]);
const { setOpenSub } = parent;
const close = useCallback(
(restoreFocus: boolean) => {
setOpenSub(null);
if (restoreFocus) triggerRef.current?.focus({ preventScroll: true });
},
[setOpenSub],
);
const openWith = useCallback(
(intent: FocusIntent) => {
if (openTimer.current) clearTimeout(openTimer.current);
openTimer.current = null;
focusIntent.current = intent;
if (open) focusByIntent(contentRef.current, intent);
else setOpenSub(subId);
},
[open, setOpenSub, subId],
);
const level = useMemo<MenuLevel>(
() => ({
rootId: parent.rootId,
levelId: `${subId}-level`,
open,
isSub: true,
triggerId: triggerItemId,
contentId: `${subId}-content`,
triggerRef,
contentRef,
focusIntent,
...core,
close,
closeAll: parent.closeAll,
openRoot: parent.openRoot,
reduce: parent.reduce,
}),
[
parent.rootId,
parent.closeAll,
parent.openRoot,
parent.reduce,
subId,
open,
triggerItemId,
core,
close,
],
);
const ctx = useMemo<SubContextValue>(
() => ({ level, parent, triggerItemId, openTimer, openWith }),
[level, parent, triggerItemId, openWith],
);
return <SubContext.Provider value={ctx}>{children}</SubContext.Provider>;
}
export interface DropdownMenuSubTriggerProps {
children: ReactNode;
icon?: ReactNode;
disabled?: boolean;
inset?: boolean;
textValue?: string;
className?: string;
}
export function DropdownMenuSubTrigger({
children,
icon,
...props
}: DropdownMenuSubTriggerProps) {
const { level, parent, triggerItemId, openTimer, openWith } = useSub(
"DropdownMenuSubTrigger",
);
const clearOpenTimer = () => {
if (openTimer.current) clearTimeout(openTimer.current);
openTimer.current = null;
};
return (
<ItemBase
{...props}
itemId={triggerItemId}
isSubTrigger
closeOnSelect={false}
onActivate={(event) => openWith(event.detail === 0 ? "first" : "none")}
extraProps={{
ref: (node: HTMLButtonElement | null) => {
level.triggerRef.current = node;
},
"aria-haspopup": "menu",
"aria-expanded": level.open,
"aria-controls": level.open ? level.contentId : undefined,
"data-state": level.open ? "open" : "closed",
onPointerEnter: (event) => {
if (event.pointerType === "touch" || props.disabled) return;
parent.cancelSubClose();
if (level.open) return;
clearOpenTimer();
openTimer.current = setTimeout(() => {
openTimer.current = null;
openWith("none");
}, SUB_OPEN_DELAY);
},
onPointerLeave: (event) => {
if (event.pointerType === "touch") return;
clearOpenTimer();
parent.scheduleSubClose();
},
onKeyDown: (event) => {
if (event.key === "ArrowRight") {
event.preventDefault();
openWith("first");
}
},
}}
>
{icon}
<span className="min-w-0 flex-1 truncate">{children}</span>
<ChevronRight
aria-hidden="true"
className="-mr-1 ml-auto size-3.5! text-muted-foreground"
/>
</ItemBase>
);
}
export interface DropdownMenuSubContentProps {
children: ReactNode;
/** Preferred side; flips when the viewport lacks room. Default "right". */
side?: "right" | "left";
/** Gap from the parent panel, in px. Default 8. */
sideOffset?: number;
/** Shift so the first row lines up with the trigger row. Default -7. */
alignOffset?: number;
ariaLabel?: string;
className?: string;
}
export function DropdownMenuSubContent({
children,
side = "right",
sideOffset = 8,
alignOffset = -7,
ariaLabel,
className,
}: DropdownMenuSubContentProps) {
const { level, parent, triggerItemId } = useSub("DropdownMenuSubContent");
const { cancelSubClose, setActiveId } = parent;
// While the pointer or focus is in the submenu, its trigger row keeps the
// parent's highlight and the pending close is called off.
const onPanelEnter = useCallback(() => {
cancelSubClose();
setActiveId(triggerItemId);
}, [cancelSubClose, setActiveId, triggerItemId]);
return (
<MenuLevelContext.Provider value={level}>
<MenuPanel
level={level}
side={side}
align="start"
sideOffset={sideOffset}
alignOffset={alignOffset}
ariaLabel={ariaLabel}
className={cn("min-w-44", className)}
onPanelEnter={onPanelEnter}
>
{children}
</MenuPanel>
</MenuLevelContext.Provider>
);
}
"use client";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
type ReactElement,
type ReactNode,
type Ref,
useCallback,
useContext,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { usePopoverPortalPosition } from "@/components/motion/popover-position";
import { EASE_OUT, SPRING_PANEL } from "@/lib/ease";
import { cn } from "@/lib/utils";
type Side = "top" | "bottom";
type Align = "start" | "end";
type MorphContextValue = {
open: boolean;
setOpen: (open: boolean) => void;
toggle: () => void;
triggerId: string;
contentId: string;
/** The element the panel measures against — see `registerTrigger`. */
triggerRef: React.MutableRefObject<HTMLElement | null>;
registerTrigger: (node: HTMLElement | null) => void;
contentRef: React.MutableRefObject<HTMLDivElement | null>;
};
const MorphContext = createContext<MorphContextValue | null>(null);
function useMorphContext(component: string) {
const ctx = useContext(MorphContext);
if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);
return ctx;
}
export interface MorphPopoverProps {
children: ReactNode;
/** Controlled open state. */
open?: boolean;
/** Uncontrolled initial open state. */
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
className?: string;
}
/**
* A popover whose panel morphs open from the trigger corner: it's laid out at
* full size but clipped to the corner nearest the trigger, then unclips as one
* piece. Closes on outside pointer / Escape. Controlled or uncontrolled.
*/
export function MorphPopover({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
className,
}: MorphPopoverProps) {
const baseId = useId();
const [root, setRoot] = useState<HTMLDivElement | null>(null);
const [trigger, setTrigger] = useState<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const controlled = controlledOpen !== undefined;
const open = controlled ? controlledOpen : internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const toggle = useCallback(() => setOpen(!open), [setOpen, open]);
// A trigger normally registers itself through MorphPopoverTrigger. It can't
// when something else already clones the element — a Tooltip wrapping the
// button, say — and an unregistered trigger leaves the panel with nothing to
// measure against, so it renders permanently invisible. The root boxes the
// trigger exactly (the content portals out of it), so it stands in until a
// real trigger registers, and stands in again if that one unmounts. Both are
// state, so a trigger arriving while the panel is open re-anchors it.
const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(
() => ({ current: trigger ?? root }),
[root, trigger],
);
// The panel is a `role="dialog"` and goes inert the moment it closes, so
// focus cannot be left sitting inside it: a dismissal hands it back to the
// trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes
// the focus onward itself when it lands on something focusable — this only
// catches the case where it would otherwise be stranded. When no trigger has
// registered, the root anchor stands in only if it can actually hold focus;
// there is nowhere better than where the keyboard already is, so leave it.
const close = useCallback(() => {
setOpen(false);
const focused = document.activeElement;
const inPanel =
focused instanceof HTMLElement && contentRef.current?.contains(focused);
if (!inPanel) return;
const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);
restore?.focus();
}, [root, setOpen, trigger]);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && close();
const onPointer = (e: PointerEvent) => {
const target = e.target as Node;
if (
root &&
!root.contains(target) &&
!contentRef.current?.contains(target)
)
close();
};
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer);
};
}, [open, root, close]);
const ctx = useMemo<MorphContextValue>(
() => ({
open,
setOpen,
toggle,
triggerId: `${baseId}-trigger`,
contentId: `${baseId}-content`,
triggerRef: anchorRef,
registerTrigger: setTrigger,
contentRef,
}),
[open, setOpen, toggle, baseId, anchorRef],
);
return (
<MorphContext.Provider value={ctx}>
<div ref={setRoot} className={cn("relative inline-flex", className)}>
{children}
</div>
</MorphContext.Provider>
);
}
export interface MorphPopoverTriggerProps {
children: ReactElement;
}
function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {
return (node: T | null) => {
for (const ref of refs) {
if (typeof ref === "function") ref(node);
else if (ref && typeof ref === "object")
(ref as React.MutableRefObject<T | null>).current = node;
}
};
}
/** Wraps a single element, toggling the popover on click. */
export function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {
const ctx = useMorphContext("MorphPopoverTrigger");
if (!isValidElement(children)) return children;
const child = children as ReactElement<Record<string, unknown>>;
const childOnClick = child.props.onClick as
| ((e: unknown) => void)
| undefined;
const childRef = (child.props as { ref?: Ref<HTMLElement> }).ref;
return cloneElement(child, {
id: ctx.triggerId,
ref: mergeRefs(childRef, ctx.registerTrigger),
onClick: (e: unknown) => {
childOnClick?.(e);
ctx.toggle();
},
"aria-haspopup": "dialog",
"aria-expanded": ctx.open,
"aria-controls": ctx.open ? ctx.contentId : undefined,
});
}
const originFor = (side: Side, align: Align) =>
`${side === "bottom" ? "top" : "bottom"} ${align === "end" ? "right" : "left"}`;
// A clip that hides everything but the corner nearest the trigger, so the
// panel appears to grow out of it. inset(top right bottom left).
function clipHidden(side: Side, align: Align, radius: number) {
const top = side === "bottom" ? "0%" : "92%";
const bottom = side === "bottom" ? "92%" : "0%";
const right = align === "end" ? "0%" : "92%";
const left = align === "end" ? "92%" : "0%";
return `inset(${top} ${right} ${bottom} ${left} round ${radius}px)`;
}
const clipShown = (radius: number) => `inset(0% 0% 0% 0% round ${radius}px)`;
// Preserve the original spring character on the wrapper, but tween the complex
// clip-path so it cannot snap when the spring resolves its final distance.
const MORPH_CLIP_TRANSITION = { duration: 0.32, ease: EASE_OUT } as const;
export interface MorphPopoverContentProps {
children: ReactNode;
side?: Side;
align?: Align;
/** Gap between trigger and panel, in px. Default 8. */
sideOffset?: number;
/** Panel corner radius, in px. Default 16. */
radius?: number;
className?: string;
}
export function MorphPopoverContent({
children,
side = "bottom",
align = "end",
sideOffset = 8,
radius = 16,
className,
}: MorphPopoverContentProps) {
const ctx = useMorphContext("MorphPopoverContent");
const reduce = useReducedMotion() ?? false;
const [portalReady, setPortalReady] = useState(false);
const layout = usePopoverPortalPosition(
ctx.triggerRef,
ctx.contentRef,
portalReady && ctx.open,
);
useEffect(() => setPortalReady(true), []);
const left = layout
? align === "end"
? layout.trigger.left + layout.trigger.width - layout.content.width
: layout.trigger.left
: 0;
const top = layout
? side === "bottom"
? layout.trigger.top + layout.trigger.height + sideOffset
: layout.trigger.top - layout.content.height - sideOffset
: 0;
// Both directions travel between the exact same hidden/show states. Exit
// targets "hidden" directly instead of introducing separate choreography.
const wrap = reduce
? undefined
: {
hidden: { opacity: 0, scale: 0.96, transition: SPRING_PANEL },
show: { opacity: 1, scale: 1, transition: SPRING_PANEL },
};
const clip = reduce
? undefined
: {
hidden: {
clipPath: clipHidden(side, align, radius),
transition: MORPH_CLIP_TRANSITION,
},
show: {
clipPath: clipShown(radius),
transition: MORPH_CLIP_TRANSITION,
},
};
// Keep the server and first client render identical, then mount the portal.
if (!portalReady) return null;
return createPortal(
<AnimatePresence>
{ctx.open ? (
<motion.div
data-morph-popover-portal=""
// Wrapper carries the shadow as a drop-shadow filter, which hugs the
// clipped shape below (box-shadow would just get clipped away).
variants={wrap}
initial={reduce ? { opacity: 0 } : "hidden"}
animate={reduce ? { opacity: 1 } : "show"}
exit={reduce ? { opacity: 0 } : "hidden"}
transition={reduce ? { duration: 0.12 } : undefined}
style={{
left,
top,
visibility: layout ? "visible" : "hidden",
transformOrigin: originFor(side, align),
}}
className="fixed z-[9999] [filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]"
>
<motion.div
ref={ctx.contentRef}
id={ctx.contentId}
role="dialog"
aria-labelledby={ctx.triggerId}
variants={clip}
style={{ borderRadius: radius }}
className={cn(
"overflow-hidden border border-border bg-background",
className,
)}
>
{children}
</motion.div>
</motion.div>
) : null}
</AnimatePresence>,
document.body,
);
}
"use client";
import {
AnimatePresence,
animate,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
useCallback,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
type TextareaHTMLAttributes,
} from "react";
import { EASE_OUT_CSS, SPRING_PRESS } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type TextareaClassNames = {
root?: string;
label?: string;
description?: string;
field?: string;
textarea?: string;
counter?: string;
errorMessage?: string;
};
export interface TextareaProps
extends Omit<
TextareaHTMLAttributes<HTMLTextAreaElement>,
"value" | "defaultValue" | "onChange" | "rows"
> {
label?: string;
/** Helper text under the label, linked through aria-describedby. */
description?: string;
value?: string;
defaultValue?: string;
onChange?: (value: string) => void;
/** Truthy error triggers a shake, red border and (if a string) a message. */
error?: string | boolean;
/** Rows shown when empty; the field never shrinks below this. */
minRows?: number;
/** Rows the field grows to before it starts scrolling. */
maxRows?: number;
/** Shows the character counter. Defaults to true when `maxLength` is set. */
showCount?: boolean;
/** Fraction of `maxLength` at which the counter turns to the warning color. */
warnAt?: number;
className?: string;
classNames?: TextareaClassNames;
}
const SHAKE = { x: [0, -6, 6, -4, 4, -2, 0] };
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(
function Textarea(
{
label,
description,
value: valueProp,
defaultValue,
onChange,
onFocus,
onBlur,
error,
minRows = 3,
maxRows = 8,
maxLength,
showCount,
warnAt = 0.9,
placeholder,
className,
classNames,
disabled,
id: idProp,
...rest
},
forwardedRef,
) {
const reactId = useId();
const id = idProp ?? reactId;
const reduce = useReducedMotion();
const controlled = valueProp !== undefined;
const [internal, setInternal] = useState(defaultValue ?? "");
const value = controlled ? (valueProp ?? "") : internal;
const [focused, setFocused] = useState(false);
const [height, setHeight] = useState<number | null>(null);
const [scrolls, setScrolls] = useState(false);
const fieldRef = useRef<HTMLDivElement>(null);
const counterRef = useRef<HTMLSpanElement>(null);
const mirrorRef = useRef<HTMLTextAreaElement>(null);
const innerRef = useRef<HTMLTextAreaElement | null>(null);
const setRefs = useCallback(
(node: HTMLTextAreaElement | null) => {
innerRef.current = node;
if (typeof forwardedRef === "function") forwardedRef(node);
else if (forwardedRef) forwardedRef.current = node;
},
[forwardedRef],
);
const hasError = Boolean(error);
const errorMessage = typeof error === "string" ? error : null;
const countVisible = showCount ?? maxLength !== undefined;
const count = value.length;
const ratio = maxLength ? count / maxLength : 0;
const atLimit = maxLength !== undefined && count >= maxLength;
const nearLimit = maxLength !== undefined && ratio >= warnAt && !atLimit;
// Measure the content with an invisible twin so the real field can
// transition between pixel heights (resetting it to `auto` would kill the
// transition). Height is this component's purpose, so it animates layout.
const measure = useCallback(() => {
const mirror = mirrorRef.current;
if (!mirror) return;
const style = getComputedStyle(mirror);
const lineHeight = Number.parseFloat(style.lineHeight) || 24;
const padY =
Number.parseFloat(style.paddingTop) +
Number.parseFloat(style.paddingBottom);
const min = lineHeight * minRows + padY;
const max = lineHeight * Math.max(minRows, maxRows) + padY;
const content = mirror.scrollHeight;
setHeight(Math.min(max, Math.max(min, content)));
setScrolls(content > max + 1);
}, [minRows, maxRows]);
useLayoutEffect(() => {
if (mirrorRef.current) mirrorRef.current.value = value || " ";
measure();
}, [value, measure]);
// Width changes rewrap the text, so re-measure on resize.
useEffect(() => {
const field = fieldRef.current;
if (!field || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => measure());
observer.observe(field);
return () => observer.disconnect();
}, [measure]);
// Shake the field when an error appears.
useEffect(() => {
if (!fieldRef.current || reduce || !hasError) return;
animate(fieldRef.current, SHAKE, { duration: 0.45 });
}, [hasError, reduce]);
const nudgeCounter = useCallback(() => {
if (!counterRef.current || reduce) return;
animate(
counterRef.current,
{ x: [0, -4, 4, -3, 3, 0] },
{ duration: 0.35 },
);
}, [reduce]);
// Typing or pasting past `maxLength` is blocked natively; catch the
// attempt first so the counter can shake. Native listener because React's
// onBeforeInput misses paste and line breaks.
useEffect(() => {
const el = innerRef.current;
if (!el || maxLength === undefined) return;
const onBeforeInput = (event: InputEvent) => {
if (!event.inputType.startsWith("insert")) return;
const data =
event.data ??
event.dataTransfer?.getData("text/plain") ??
(event.inputType === "insertLineBreak" ? "\n" : "");
const selected = el.selectionEnd - el.selectionStart;
if (el.value.length - selected + data.length > maxLength) {
nudgeCounter();
}
};
el.addEventListener("beforeinput", onBeforeInput);
return () => el.removeEventListener("beforeinput", onBeforeInput);
}, [maxLength, nudgeCounter]);
const handleChange = (next: string) => {
if (!controlled) setInternal(next);
onChange?.(next);
};
const describedBy =
[
description ? `${id}-description` : null,
countVisible ? `${id}-count` : null,
errorMessage ? `${id}-error` : null,
]
.filter(Boolean)
.join(" ") || undefined;
const sharedText =
"block w-full resize-none bg-transparent px-3.5 py-2.5 text-base leading-6";
return (
<div
className={cn("flex flex-col gap-1.5", className, classNames?.root)}
>
{label || description ? (
<div className="flex flex-col gap-0.5 px-1">
{label ? (
<label
htmlFor={id}
className={cn(
"text-sm font-medium text-foreground",
classNames?.label,
)}
>
{label}
</label>
) : null}
{description ? (
<p
id={`${id}-description`}
className={cn(
"text-xs text-muted-foreground",
classNames?.description,
)}
>
{description}
</p>
) : null}
</div>
) : null}
<div
ref={fieldRef}
data-state={hasError ? "error" : focused ? "focused" : "idle"}
className={cn(
"relative overflow-hidden rounded-2xl border transition-colors duration-200",
"border-border",
focused && !hasError && "border-foreground/40 ring-2 ring-ring/40",
hasError && "border-destructive ring-2 ring-destructive/25",
disabled && "opacity-60",
classNames?.field,
)}
>
<textarea
ref={mirrorRef}
aria-hidden="true"
tabIndex={-1}
readOnly
rows={1}
className={cn(
sharedText,
"pointer-events-none invisible absolute inset-x-0 top-0 h-0 overflow-hidden",
classNames?.textarea,
)}
/>
<textarea
ref={setRefs}
id={id}
rows={minRows}
value={value}
disabled={disabled}
maxLength={maxLength}
placeholder={placeholder}
aria-invalid={hasError || undefined}
aria-describedby={describedBy}
{...rest}
onChange={(e) => handleChange(e.target.value)}
onFocus={(event) => {
setFocused(true);
onFocus?.(event);
}}
onBlur={(event) => {
setFocused(false);
onBlur?.(event);
}}
style={{
height: height ?? undefined,
transition: reduce ? undefined : `height 160ms ${EASE_OUT_CSS}`,
...rest.style,
}}
className={cn(
sharedText,
"text-foreground caret-foreground outline-none",
"placeholder:text-muted-foreground/60",
scrolls
? "overflow-y-auto [scrollbar-color:var(--border-strong)_transparent] [scrollbar-width:thin]"
: "overflow-y-hidden",
disabled && "cursor-not-allowed",
classNames?.textarea,
)}
/>
{countVisible ? (
<div className="flex justify-end px-3.5 pb-2">
<span
ref={counterRef}
id={`${id}-count`}
className={cn(
"inline-block text-xs tabular-nums text-muted-foreground transition-colors duration-200",
nearLimit && "text-warning",
atLimit && "text-destructive",
classNames?.counter,
)}
>
<motion.span
key={atLimit ? "limit" : "count"}
className="inline-block"
initial={reduce || !atLimit ? false : { scale: 1.2 }}
animate={{ scale: 1 }}
transition={SPRING_PRESS}
>
{maxLength !== undefined ? `${count}/${maxLength}` : count}
</motion.span>
<span className="sr-only">
{maxLength !== undefined
? ` characters used, ${maxLength - count} remaining`
: " characters"}
</span>
</span>
</div>
) : null}
</div>
<AnimatePresence initial={false}>
{errorMessage ? (
<motion.p
id={`${id}-error`}
role="alert"
initial={
reduce
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(4px)" }
}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={
reduce
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(4px)" }
}
transition={{ duration: 0.2 }}
className={cn(
"px-1 text-xs text-destructive",
classNames?.errorMessage,
)}
>
{errorMessage}
</motion.p>
) : null}
</AnimatePresence>
</div>
);
},
);
"use client";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
createContext,
forwardRef,
type KeyboardEvent,
type ReactNode,
useCallback,
useContext,
useEffect,
useId,
useRef,
useState,
} from "react";
import { SPRING_LAYOUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { TOUCH_TARGET_CLASS } from "@/lib/touch";
import { cn } from "@/lib/utils";
// Toggle / ToggleGroup vs SegmentedControl: `SegmentedControl`
// (segmented-control.tsx) is a radiogroup form control that always holds one
// value and ships a data-driven `ToggleGroup` for quick `items` arrays. This
// file is the composable, shadcn-shaped toolbar primitive: a standalone
// `Toggle`, and a `ToggleGroup` you fill with `ToggleGroupItem` children
// (icons, labels, tooltips, anything), with `default`/`outline` variants. In
// single mode one pressed surface glides between items; in multiple mode each
// item pops its own surface in and out.
export type ToggleVariant = "default" | "outline";
export type ToggleSize = "sm" | "md" | "lg";
const sizeClass: Record<ToggleSize, string> = {
sm: "h-7 min-w-7 gap-1.5 px-2 text-xs [&_svg]:size-3.5",
md: "h-9 min-w-9 gap-2 px-2.5 text-sm [&_svg]:size-4",
lg: "h-11 min-w-11 gap-2 px-3.5 text-sm [&_svg]:size-[18px]",
};
const surfaceClass: Record<ToggleVariant, string> = {
default: "bg-muted ring-1 ring-border-strong",
outline: "bg-muted",
};
const itemBase =
"relative isolate inline-flex shrink-0 select-none items-center justify-center whitespace-nowrap font-medium outline-none transition-colors duration-200 focus-visible:z-10 focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50";
function useControllable<T>(
value: T | undefined,
defaultValue: T,
onChange: ((next: T) => void) | undefined,
) {
const [internal, setInternal] = useState<T>(defaultValue);
const controlled = value !== undefined;
const current = controlled ? value : internal;
const set = useCallback(
(next: T) => {
if (!controlled) setInternal(next);
onChange?.(next);
},
[controlled, onChange],
);
return [current, set] as const;
}
type ButtonBaseProps = Omit<HTMLMotionProps<"button">, "children" | "value" | "type">;
/** The pressed surface that pops in and out behind a standalone toggle or a multiple-mode item. */
function PopSurface({ show, variant }: { show: boolean; variant: ToggleVariant }) {
const reduce = useReducedMotion();
return (
<AnimatePresence initial={false}>
{show ? (
<motion.span
key="on"
aria-hidden
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}
animate={{ opacity: 1, scale: 1 }}
exit={
reduce
? { opacity: 0 }
: { opacity: 0, scale: 0.75, transition: { duration: 0.12 } }
}
transition={SPRING_SWAP}
className={cn("absolute inset-0 -z-10 rounded-[inherit]", surfaceClass[variant])}
/>
) : null}
</AnimatePresence>
);
}
/* ------------------------------------------------------------------------ */
/* Toggle */
/* ------------------------------------------------------------------------ */
export interface ToggleProps extends ButtonBaseProps {
pressed?: boolean;
defaultPressed?: boolean;
onPressedChange?: (pressed: boolean) => void;
variant?: ToggleVariant;
size?: ToggleSize;
children?: ReactNode;
}
/** A two-state button (`aria-pressed`) whose pressed surface springs in and out. */
export const Toggle = forwardRef<HTMLButtonElement, ToggleProps>(function Toggle(
{
pressed,
defaultPressed = false,
onPressedChange,
variant = "default",
size = "md",
disabled,
className,
children,
onClick,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const [on, setOn] = useControllable(pressed, defaultPressed, onPressedChange);
return (
<motion.button
ref={ref}
type="button"
aria-pressed={on}
data-state={on ? "on" : "off"}
disabled={disabled}
whileTap={reduce || disabled ? undefined : { scale: 0.9 }}
transition={SPRING_PRESS}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) setOn(!on);
}}
className={cn(
itemBase,
TOUCH_TARGET_CLASS,
"rounded-lg focus-visible:ring-offset-1 focus-visible:ring-offset-background",
sizeClass[size],
variant === "outline" && "border border-border",
on
? "text-foreground"
: "text-muted-foreground enabled:hover:bg-muted/60 enabled:hover:text-foreground",
className,
)}
{...rest}
>
<PopSurface show={on} variant={variant} />
{children}
</motion.button>
);
});
/* ------------------------------------------------------------------------ */
/* ToggleGroup */
/* ------------------------------------------------------------------------ */
interface ToggleGroupContextValue {
type: "single" | "multiple";
pressed: string[];
toggle: (value: string) => void;
variant: ToggleVariant;
size: ToggleSize;
disabled: boolean;
layoutId: string;
tabStop: string | null;
setTabStop: (value: string) => void;
}
const ToggleGroupContext = createContext<ToggleGroupContextValue | null>(null);
type ToggleGroupBase = Omit<
HTMLMotionProps<"div">,
"children" | "defaultValue" | "onChange" | "dir"
> & {
variant?: ToggleVariant;
size?: ToggleSize;
disabled?: boolean;
/** Arrow-key axis for roving focus. Default "horizontal" (both axes still work). */
orientation?: "horizontal" | "vertical";
children?: ReactNode;
};
export type ToggleGroupSingleProps = ToggleGroupBase & {
type: "single";
/** The pressed item, or `""` when none is pressed. */
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/** Disallow un-pressing the active item, so one is always pressed. */
required?: boolean;
};
export type ToggleGroupMultipleProps = ToggleGroupBase & {
type: "multiple";
value?: string[];
defaultValue?: string[];
onValueChange?: (value: string[]) => void;
};
export type ToggleGroupProps = ToggleGroupSingleProps | ToggleGroupMultipleProps;
const ITEM_SELECTOR = "[data-toggle-group-item]";
function enabledItems(root: HTMLElement | null) {
if (!root) return [];
return Array.from(root.querySelectorAll<HTMLButtonElement>(ITEM_SELECTOR)).filter(
(el) => !el.disabled && el.closest("[data-toggle-group]") === root,
);
}
/**
* Toolbar-style group of `ToggleGroupItem`s. `type="single"` behaves like a
* set of mutually exclusive toggles (deselectable unless `required`) whose
* pressed surface glides between items; `type="multiple"` presses any subset.
* One tab stop, arrow keys / Home / End rove between items, Space/Enter press.
*/
export function ToggleGroup(props: ToggleGroupProps) {
const {
type,
value: _value,
defaultValue: _defaultValue,
onValueChange: _onValueChange,
variant = "default",
size = "md",
disabled = false,
orientation = "horizontal",
className,
children,
onKeyDown,
...rest
} = props;
// `required` only exists on the single variant; keep it off the DOM.
const { required: _required, ...domProps } = rest as typeof rest & { required?: boolean };
const single = props.type === "single";
const required = props.type === "single" && Boolean(props.required);
const [pressed, setPressed] = useControllable<string[]>(
props.value === undefined
? undefined
: props.type === "single"
? props.value
? [props.value]
: []
: props.value,
props.type === "single"
? props.defaultValue
? [props.defaultValue]
: []
: (props.defaultValue ?? []),
(next) => {
if (props.type === "single") props.onValueChange?.(next[0] ?? "");
else props.onValueChange?.(next);
},
);
const layoutId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const [tabStop, setTabStop] = useState<string | null>(pressed[0] ?? null);
// Keep exactly one reachable tab stop: if the remembered item vanished or
// got disabled, fall back to the first pressed item, then the first enabled.
useEffect(() => {
const items = enabledItems(rootRef.current);
if (items.some((el) => el.dataset.value === tabStop)) return;
const fallback =
items.find((el) => pressed.includes(el.dataset.value ?? "")) ?? items[0];
const next = fallback?.dataset.value ?? null;
if (next !== tabStop) setTabStop(next);
});
const toggle = (itemValue: string) => {
const isOn = pressed.includes(itemValue);
if (single) {
if (isOn && required) return;
setPressed(isOn ? [] : [itemValue]);
} else {
setPressed(isOn ? pressed.filter((v) => v !== itemValue) : [...pressed, itemValue]);
}
};
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
onKeyDown?.(event);
if (event.defaultPrevented) return;
const items = enabledItems(rootRef.current);
const index = items.indexOf(document.activeElement as HTMLButtonElement);
if (index < 0) return;
const forward = orientation === "vertical" ? "ArrowDown" : "ArrowRight";
const backward = orientation === "vertical" ? "ArrowUp" : "ArrowLeft";
let next: number;
if (event.key === forward || event.key === "ArrowDown" || event.key === "ArrowRight")
next = (index + 1) % items.length;
else if (event.key === backward || event.key === "ArrowUp" || event.key === "ArrowLeft")
next = (index - 1 + items.length) % items.length;
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = items.length - 1;
else return;
event.preventDefault();
// Focus moves; pressing stays on Space/Enter — these are toggles, not radios.
items[next].focus();
};
return (
<ToggleGroupContext.Provider
value={{
type,
pressed,
toggle,
variant,
size,
disabled,
layoutId,
tabStop,
setTabStop,
}}
>
{/* layoutRoot keeps the gliding surface's projection local to the group,
so scrolled or transformed ancestors never skew the glide. */}
<motion.div
ref={rootRef}
layoutRoot
role="group"
data-toggle-group=""
data-orientation={orientation}
aria-disabled={disabled || undefined}
onKeyDown={handleKeyDown}
className={cn(
"inline-flex w-fit items-center",
orientation === "vertical" && "flex-col items-stretch",
variant === "default"
? "gap-0.5 rounded-xl border border-border bg-card p-1"
: "rounded-lg",
disabled && "opacity-60",
className,
)}
{...domProps}
>
{children}
</motion.div>
</ToggleGroupContext.Provider>
);
}
export interface ToggleGroupItemProps extends ButtonBaseProps {
value: string;
children?: ReactNode;
}
export const ToggleGroupItem = forwardRef<HTMLButtonElement, ToggleGroupItemProps>(
function ToggleGroupItem(
{ value, disabled: itemDisabled, className, children, onClick, onFocus, ...rest },
ref,
) {
const ctx = useContext(ToggleGroupContext);
if (!ctx) throw new Error("ToggleGroupItem must be used inside <ToggleGroup>.");
const reduce = useReducedMotion();
const disabled = ctx.disabled || Boolean(itemDisabled);
const on = ctx.pressed.includes(value);
const outline = ctx.variant === "outline";
return (
<motion.button
ref={ref}
type="button"
data-toggle-group-item=""
data-value={value}
data-state={on ? "on" : "off"}
aria-pressed={on}
disabled={disabled}
tabIndex={ctx.tabStop === value ? 0 : -1}
whileTap={reduce || disabled ? undefined : { scale: 0.88 }}
transition={SPRING_PRESS}
onFocus={(event) => {
ctx.setTabStop(value);
onFocus?.(event);
}}
onClick={(event) => {
onClick?.(event);
if (event.defaultPrevented) return;
ctx.setTabStop(value);
ctx.toggle(value);
}}
className={cn(
itemBase,
TOUCH_TARGET_CLASS,
sizeClass[ctx.size],
outline
? // Joined segments: neighbours overlap their shared border.
"rounded-none border border-border bg-card -ml-px first:ml-0 first:rounded-l-lg last:rounded-r-lg in-data-[orientation=vertical]:-mt-px in-data-[orientation=vertical]:ml-0 in-data-[orientation=vertical]:first:mt-0 in-data-[orientation=vertical]:first:rounded-l-none in-data-[orientation=vertical]:first:rounded-t-lg in-data-[orientation=vertical]:last:rounded-r-none in-data-[orientation=vertical]:last:rounded-b-lg"
: "rounded-lg focus-visible:ring-offset-1 focus-visible:ring-offset-card",
on
? "text-foreground"
: "text-muted-foreground enabled:hover:bg-muted/60 enabled:hover:text-foreground",
className,
)}
{...rest}
>
{ctx.type === "single" ? (
on ? (
<motion.span
layoutId={ctx.layoutId}
aria-hidden
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
className={cn(
"absolute inset-0 -z-10 rounded-[inherit]",
surfaceClass[ctx.variant],
)}
/>
) : null
) : (
<PopSurface show={on} variant={ctx.variant} />
)}
{children}
</motion.button>
);
},
);
"use client";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
type PointerEvent,
type ReactNode,
useCallback,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { TOUCH_TARGET_CLASS } from "@/lib/touch";
import { cn } from "@/lib/utils";
export type ButtonVariant = "primary" | "secondary" | "ghost" | "outline";
export type ButtonSize = "sm" | "md" | "lg" | "icon";
export interface ButtonProps extends Omit<
HTMLMotionProps<"button">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
/** Spawn a Material-style ripple from the press point. Off by default. */
ripple?: boolean;
children?: ReactNode;
}
export interface ButtonLinkProps extends Omit<
HTMLMotionProps<"a">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
children?: ReactNode;
}
type Ripple = { id: number; x: number; y: number; size: number };
const VARIANT_CLASS: Record<ButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
ghost: "text-muted-foreground hover:text-foreground hover:bg-primary/5",
outline:
"border border-border bg-transparent text-foreground hover:bg-primary/5",
};
const SIZE_CLASS: Record<ButtonSize, string> = {
sm: "h-8 px-3 text-xs gap-1.5 rounded-full",
md: "h-10 px-5 text-sm gap-2 rounded-full",
lg: "h-12 px-6 text-base gap-2 rounded-full",
icon: "h-8 w-8 rounded-lg",
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
function Button(
{
variant = "primary",
size = "md",
pressScale = 0.93,
ripple = false,
className,
children,
onPointerDown,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
const [ripples, setRipples] = useState<Ripple[]>([]);
const nextId = useRef(0);
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLButtonElement>) => {
if (ripple && !reduce) {
const rect = event.currentTarget.getBoundingClientRect();
const size = Math.max(rect.width, rect.height) * 2;
const id = nextId.current++;
setRipples((prev) => [
...prev,
{
id,
x: event.clientX - rect.left,
y: event.clientY - rect.top,
size,
},
]);
}
onPointerDown?.(event);
},
[ripple, reduce, onPointerDown],
);
return (
<motion.button
ref={ref}
type="button"
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
onPointerDown={handlePointerDown}
className={cn(
"relative inline-flex items-center justify-center font-medium select-none",
"transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
// The ripple layer clips itself, so on a touch screen the button can
// stop clipping and let its enlarged hit area overhang.
ripple && "overflow-hidden pointer-coarse:overflow-visible",
TOUCH_TARGET_CLASS,
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{ripple && !reduce ? (
<span className="pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]">
<AnimatePresence>
{ripples.map((r) => (
<motion.span
key={r.id}
className="absolute rounded-full bg-current"
style={{
left: r.x,
top: r.y,
width: r.size,
height: r.size,
x: "-50%",
y: "-50%",
}}
initial={{ scale: 0.05, opacity: 0.3 }}
animate={{ scale: 1, opacity: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: 1.6, ease: EASE_OUT }}
onAnimationComplete={() =>
setRipples((prev) => prev.filter((x) => x.id !== r.id))
}
/>
))}
</AnimatePresence>
</span>
) : null}
{children}
</motion.button>
);
},
);
export const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(
function ButtonLink(
{
variant = "primary",
size = "md",
pressScale = 0.93,
className,
children,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
return (
<motion.a
ref={ref}
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
className={cn(
"relative inline-flex items-center justify-center font-medium select-none",
"transition-colors",
TOUCH_TARGET_CLASS,
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 { Check, Loader2, X } from "lucide-react";
import {
AnimatePresence,
motion,
useReducedMotion,
type Variants,
} from "motion/react";
import {
forwardRef,
type ReactNode,
useLayoutEffect,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { Button, type ButtonProps } from "./base";
export type ButtonState = "idle" | "loading" | "success" | "error";
export interface StatefulButtonProps extends Omit<ButtonProps, "children"> {
state?: ButtonState;
children: ReactNode;
loadingText?: ReactNode;
successText?: ReactNode;
errorText?: ReactNode;
icon?: ReactNode;
}
const CASCADE_STAGGER = 0.025;
const ROLL_BLUR = "blur(6px)";
const CASCADE_LETTER_VARIANTS: Variants = {
initial: { opacity: 0, y: "105%", filter: ROLL_BLUR },
animate: (delay: number = 0) => ({
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: { ...SPRING_SWAP, delay },
}),
exit: (delay: number = 0) => ({
opacity: 0,
y: "-105%",
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },
}),
};
const ICON_VARIANTS: Variants = {
// Width collapses too, so the icon adds/removes its own space smoothly
// instead of popping the row width in a single frame.
initial: { opacity: 0, width: 0, scale: 0.7, filter: ROLL_BLUR },
animate: {
opacity: 1,
width: "1.5rem",
scale: 1,
filter: "blur(0px)",
transition: SPRING_SWAP,
},
exit: {
opacity: 0,
width: 0,
scale: 0.7,
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT },
},
};
function IconSlot({ keyId, children }: { keyId: string; children: ReactNode }) {
const reduce = useReducedMotion();
return (
<motion.span
key={keyId}
variants={ICON_VARIANTS}
initial={reduce ? { opacity: 0 } : "initial"}
animate={reduce ? { opacity: 1 } : "animate"}
exit={reduce ? { opacity: 0 } : "exit"}
transition={reduce ? { duration: 0.15 } : undefined}
className="inline-grid shrink-0 place-items-center overflow-hidden"
>
{children}
</motion.span>
);
}
function TextSlot({
value,
children,
}: {
value: string;
children: ReactNode;
}) {
const reduce = useReducedMotion();
const measureRef = useRef<HTMLSpanElement>(null);
const [width, setWidth] = useState<number>();
const label = typeof children === "string" ? children : null;
const cascade = label !== null && !reduce;
// Measure strings with the same per-letter layout as the cascade. Measuring
// the whole string preserves kerning, which can make it narrower than the
// inline-block letters and clip the final glyph during the width animation.
useLayoutEffect(() => {
const nextWidth = measureRef.current?.offsetWidth;
if (!nextWidth) return;
setWidth((current) => (current === nextWidth ? current : nextWidth));
});
return (
<motion.span
initial={false}
animate={{ width }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="relative inline-block overflow-hidden whitespace-nowrap align-bottom"
>
<span
ref={measureRef}
aria-hidden
className="invisible inline-block whitespace-nowrap"
>
{cascade
? label.split("").map((char, index) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
className="inline-block whitespace-pre"
>
{char}
</span>
))
: children}
</span>
{cascade ? (
<>
<span className="sr-only">{label}</span>
<AnimatePresence initial={false}>
<motion.span
key={`cascade-${value}`}
aria-hidden
initial="initial"
animate="animate"
exit="exit"
className="absolute left-0 top-0 inline-block whitespace-pre"
>
{label.split("").map((char, index) => (
<motion.span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
custom={index * CASCADE_STAGGER}
variants={CASCADE_LETTER_VARIANTS}
className="inline-block whitespace-pre will-change-[opacity,filter,transform]"
>
{char}
</motion.span>
))}
</motion.span>
</AnimatePresence>
</>
) : (
<AnimatePresence initial={false}>
<motion.span
key={`text-${value}`}
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: ROLL_BLUR }}
animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: "blur(0px)" }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: ROLL_BLUR }}
transition={reduce ? { duration: 0.15 } : SPRING_SWAP}
className="absolute left-0 top-0 inline-block will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
)}
</motion.span>
);
}
export const StatefulButton = forwardRef<HTMLButtonElement, StatefulButtonProps>(function StatefulButton(
{
state = "idle",
children,
loadingText = "Loading",
successText = "Done",
errorText = "Try again",
icon,
disabled,
...rest
},
ref,
) {
const isBusy = state === "loading";
const stateText =
state === "loading"
? loadingText
: state === "success"
? successText
: state === "error"
? errorText
: children;
const textKey =
typeof stateText === "string" ? `${state}-${stateText}` : state;
return (
<Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} whileHover={undefined} {...rest}>
<span
aria-live="polite"
className="relative inline-flex items-center justify-center overflow-hidden"
>
<AnimatePresence initial={false}>
{state === "loading" ? (
<IconSlot keyId="loading-icon">
<Loader2 className="h-4 w-4 animate-spin" />
</IconSlot>
) : null}
{state === "success" ? (
<IconSlot keyId="success-icon">
<Check className="h-4 w-4" />
</IconSlot>
) : null}
{state === "error" ? (
<IconSlot keyId="error-icon">
<X className="h-4 w-4" />
</IconSlot>
) : null}
</AnimatePresence>
<TextSlot value={textKey}>{stateText}</TextSlot>
<AnimatePresence initial={false}>
{state === "idle" && icon ? (
<IconSlot keyId="idle-icon">{icon}</IconSlot>
) : null}
</AnimatePresence>
</span>
</Button>
);
});
import type { PortalLayout } from "@/components/motion/popover-position";
export type PlacementSide = "top" | "right" | "bottom" | "left";
export type PlacementAlign = "start" | "center" | "end";
export interface PlacementOptions {
side: PlacementSide;
align: PlacementAlign;
/** Gap between trigger and panel along the side axis, in px. */
sideOffset?: number;
/** Shift along the align axis, in px. */
alignOffset?: number;
/** Minimum distance kept from the viewport edges, in px. */
padding?: number;
}
export interface Placement {
left: number;
top: number;
/** The side actually used — differs from the requested one after a flip. */
side: PlacementSide;
/** Trigger-facing point of the panel, as a CSS transform-origin (px). */
origin: string;
}
const OPPOSITE: Record<PlacementSide, PlacementSide> = {
top: "bottom",
bottom: "top",
left: "right",
right: "left",
};
function clamp(value: number, min: number, max: number) {
return Math.min(Math.max(value, min), Math.max(min, max));
}
/**
* Places a portalled panel against its trigger in viewport coordinates
* (pair with `usePopoverPortalPosition`). Flips to the opposite side when the
* requested one lacks room and the other has more, then clamps the panel into
* the viewport on both axes. The returned origin is the trigger's center
* projected onto the panel's facing edge, so a scale entrance grows out of the
* trigger even after a flip or a clamp.
*/
export function resolvePlacement(
layout: PortalLayout,
{
side: requested,
align,
sideOffset = 6,
alignOffset = 0,
padding = 8,
}: PlacementOptions,
): Placement {
const { trigger, content } = layout;
const vw = window.innerWidth;
const vh = window.innerHeight;
const space: Record<PlacementSide, number> = {
top: trigger.top - sideOffset - padding,
bottom: vh - (trigger.top + trigger.height) - sideOffset - padding,
left: trigger.left - sideOffset - padding,
right: vw - (trigger.left + trigger.width) - sideOffset - padding,
};
const vertical = requested === "top" || requested === "bottom";
const need = vertical ? content.height : content.width;
const opposite = OPPOSITE[requested];
const side =
space[requested] < need && space[opposite] > space[requested]
? opposite
: requested;
let left: number;
let top: number;
if (vertical) {
top =
side === "bottom"
? trigger.top + trigger.height + sideOffset
: trigger.top - content.height - sideOffset;
left =
align === "start"
? trigger.left
: align === "end"
? trigger.left + trigger.width - content.width
: trigger.left + trigger.width / 2 - content.width / 2;
left = clamp(left + alignOffset, padding, vw - content.width - padding);
top = clamp(top, padding, vh - content.height - padding);
} else {
left =
side === "right"
? trigger.left + trigger.width + sideOffset
: trigger.left - content.width - sideOffset;
top =
align === "start"
? trigger.top
: align === "end"
? trigger.top + trigger.height - content.height
: trigger.top + trigger.height / 2 - content.height / 2;
top = clamp(top + alignOffset, padding, vh - content.height - padding);
left = clamp(left, padding, vw - content.width - padding);
}
const cx = clamp(trigger.left + trigger.width / 2 - left, 0, content.width);
const cy = clamp(trigger.top + trigger.height / 2 - top, 0, content.height);
const origin =
side === "bottom"
? `${cx}px 0px`
: side === "top"
? `${cx}px ${content.height}px`
: side === "right"
? `0px ${cy}px`
: `${content.width}px ${cy}px`;
return { left, top, side, origin };
}
"use client";
import {
type MutableRefObject,
useCallback,
useLayoutEffect,
useState,
} from "react";
export type PortalLayout = {
trigger: {
left: number;
top: number;
width: number;
height: number;
};
content: {
width: number;
height: number;
};
};
function sameLayout(a: PortalLayout | null, b: PortalLayout) {
return (
a?.trigger.left === b.trigger.left &&
a.trigger.top === b.trigger.top &&
a.trigger.width === b.trigger.width &&
a.trigger.height === b.trigger.height &&
a.content.width === b.content.width &&
a.content.height === b.content.height
);
}
/** Measures a trigger and portalled panel in viewport coordinates. */
export function usePopoverPortalPosition<
TriggerElement extends HTMLElement,
ContentElement extends HTMLElement,
>(
triggerRef: MutableRefObject<TriggerElement | null>,
contentRef: MutableRefObject<ContentElement | null>,
active: boolean,
) {
const [layout, setLayout] = useState<PortalLayout | null>(null);
const update = useCallback(() => {
const trigger = triggerRef.current;
const content = contentRef.current;
if (!trigger || !content) return;
const rect = trigger.getBoundingClientRect();
const next: PortalLayout = {
trigger: {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
},
content: {
width: content.offsetWidth,
height: content.offsetHeight,
},
};
setLayout((current) => (sameLayout(current, next) ? current : next));
}, [contentRef, triggerRef]);
useLayoutEffect(() => {
update();
if (!active) return;
const trigger = triggerRef.current;
const content = contentRef.current;
const observer = new ResizeObserver(update);
if (trigger) observer.observe(trigger);
if (content) observer.observe(content);
window.addEventListener("scroll", update, true);
window.addEventListener("resize", update);
return () => {
observer.disconnect();
window.removeEventListener("scroll", update, true);
window.removeEventListener("resize", update);
};
}, [active, contentRef, triggerRef, update]);
return layout;
}
"use client";
import { motion, useMotionValue, useReducedMotion, useSpring } from "motion/react";
import { useRef, type ReactNode } from "react";
import { SPRING_MOUSE } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { cn } from "@/lib/utils";
export interface MagneticProps {
children: ReactNode;
strength?: number;
className?: string;
}
export function Magnetic({ children, strength = 0.35, className }: MagneticProps) {
const ref = useRef<HTMLDivElement>(null);
const reduce = useReducedMotion();
const canHover = useHoverCapable();
// Decorative cursor-follow: skip on touch (phantom hover) and reduced motion.
const enabled = !reduce && canHover;
const x = useMotionValue(0);
const y = useMotionValue(0);
const sx = useSpring(x, SPRING_MOUSE);
const sy = useSpring(y, SPRING_MOUSE);
const onMove = (e: React.MouseEvent<HTMLDivElement>) => {
const el = ref.current;
if (!el || !enabled) return;
const rect = el.getBoundingClientRect();
x.set((e.clientX - rect.left - rect.width / 2) * strength);
y.set((e.clientY - rect.top - rect.height / 2) * strength);
};
const onLeave = () => {
x.set(0);
y.set(0);
};
return (
<motion.div
ref={ref}
onMouseMove={onMove}
onMouseLeave={onLeave}
style={{ x: sx, y: sy }}
className={cn("inline-block", className)}
>
{children}
</motion.div>
);
}
"use client";
import { motion, useReducedMotion } from "motion/react";
import {
type ComponentPropsWithRef,
createContext,
type ReactNode,
useContext,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { MessageSideContext } from "@/components/agents/message-context";
export {
MessageBubble,
MessageBubbleCollapsible,
MessageBubbleContent,
MessageBubbleGroup,
} from "@/components/agents/message-bubble";
export { MessageScroller } from "@/components/agents/message-scroller";
export type { MessageScrollerProps } from "@/components/agents/message-scroller";
export type MessageFrom = "user" | "assistant";
interface MessageContextValue {
from: MessageFrom;
}
const MessageContext = createContext<MessageContextValue>({
from: "assistant",
});
export interface MessageProps
extends Omit<ComponentPropsWithRef<typeof motion.article>, "children"> {
from: MessageFrom;
/** Plays a trailing-edge pop-up once when this message row mounts. */
animateIn?: boolean;
children: ReactNode;
}
export interface MessageGroupProps extends ComponentPropsWithRef<"div"> {
spacing?: "compact" | "default";
}
export interface MessageAvatarProps extends ComponentPropsWithRef<"div"> {
/** Keep an empty avatar slot so grouped messages remain aligned. */
placeholder?: boolean;
}
export type MessageContentProps = ComponentPropsWithRef<"div">;
export type MessageHeaderProps = ComponentPropsWithRef<"div">;
export type MessageFooterProps = ComponentPropsWithRef<"div">;
export type MessageMarkerProps = ComponentPropsWithRef<"div">;
export interface MessageTypingProps extends ComponentPropsWithRef<"span"> {
label?: string;
}
// A sent row should rise from the live edge without changing measured layout.
const MESSAGE_POP_UP = {
type: "spring",
stiffness: 480,
damping: 32,
mass: 0.62,
} as const;
export function Message({
from,
animateIn = false,
children,
className,
initial,
animate,
transition,
exit,
style,
...props
}: MessageProps) {
const reduce = useReducedMotion() ?? false;
return (
<MessageSideContext.Provider value={from === "user" ? "end" : "start"}>
<MessageContext.Provider value={{ from }}>
<motion.article
data-slot="message"
data-from={from}
aria-label={props["aria-label"] ?? `${from} message`}
initial={
initial ??
(animateIn && !reduce
? {
opacity: 0,
transform: "translateY(8px) scale(0.95)",
}
: false)
}
animate={
animate ??
(animateIn && !reduce
? {
opacity: 1,
transform: "translateY(0px) scale(1)",
}
: { opacity: 1 })
}
exit={
exit ??
(reduce
? { opacity: 0 }
: {
opacity: 0,
transform: "translateY(-3px) scale(0.99)",
})
}
transition={
transition ?? (reduce ? { duration: 0.12 } : MESSAGE_POP_UP)
}
style={{
transformOrigin: from === "user" ? "100% 100%" : "0% 100%",
...style,
}}
className={cn(
"group/message flex w-full items-start gap-2",
from === "user" ? "flex-row-reverse" : "flex-row",
className,
)}
{...props}
>
{children}
</motion.article>
</MessageContext.Provider>
</MessageSideContext.Provider>
);
}
export function MessageGroup({
spacing = "compact",
className,
...props
}: MessageGroupProps) {
return (
<div
data-slot="message-group"
className={cn(
"flex w-full flex-col",
spacing === "compact" ? "gap-1.5" : "gap-4",
className,
)}
{...props}
/>
);
}
export function MessageAvatar({
placeholder = false,
children,
className,
...props
}: MessageAvatarProps) {
return (
<div
data-slot="message-avatar"
aria-hidden={placeholder || undefined}
className={cn(
"grid size-7 shrink-0 place-items-center overflow-hidden rounded-full bg-muted text-xs font-medium text-muted-foreground [&_img]:size-full [&_img]:object-cover [&_svg]:size-3.5",
placeholder && "invisible",
className,
)}
{...props}
>
{children}
</div>
);
}
export function MessageContent({ className, ...props }: MessageContentProps) {
const { from } = useContext(MessageContext);
return (
<div
data-slot="message-content"
className={cn(
"flex min-w-0 flex-1 flex-col gap-1.5",
from === "user" ? "items-end" : "items-start",
className,
)}
{...props}
/>
);
}
export function MessageHeader({ className, ...props }: MessageHeaderProps) {
const { from } = useContext(MessageContext);
return (
<div
data-slot="message-header"
className={cn(
"flex items-center gap-1.5 px-1 text-[11px] leading-none text-muted-foreground",
from === "user" ? "justify-end" : "justify-start",
className,
)}
{...props}
/>
);
}
export function MessageFooter({ className, ...props }: MessageFooterProps) {
const { from } = useContext(MessageContext);
return (
<div
data-slot="message-footer"
className={cn(
"flex min-h-5 items-center gap-1 px-1 text-[11px] text-muted-foreground",
from === "user" ? "justify-end" : "justify-start",
className,
)}
{...props}
/>
);
}
export function MessageMarker({ className, ...props }: MessageMarkerProps) {
return (
<div
data-slot="message-marker"
className={cn(
"mx-auto flex w-fit max-w-[88%] items-center gap-1.5 rounded-full bg-muted/70 px-2.5 py-1 text-center text-xs text-muted-foreground",
className,
)}
{...props}
/>
);
}
export function MessageTyping({
label = "Responding",
className,
...props
}: MessageTypingProps) {
const reduce = useReducedMotion() ?? false;
return (
<span
data-slot="message-typing"
className={cn("inline-flex h-5 items-center gap-1", className)}
{...props}
>
<span className="sr-only">{label}</span>
{[0, 1, 2].map((index) => (
<motion.span
key={index}
aria-hidden="true"
className="size-1 rounded-full bg-current"
animate={
reduce
? { opacity: 0.45 }
: { opacity: [0.28, 0.85, 0.28], y: [0, -2, 0] }
}
transition={{
duration: 1.05,
ease: EASE_OUT,
repeat: Number.POSITIVE_INFINITY,
delay: index * 0.14,
}}
/>
))}
</span>
);
}
"use client";
import { ChevronDown } from "lucide-react";
import {
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
cloneElement,
type ComponentPropsWithRef,
createContext,
type ReactElement,
type ReactNode,
type Ref,
useCallback,
useContext,
useId,
useState,
} from "react";
import {
EASE_OUT,
SPRING_LAYOUT,
SPRING_SWAP,
} from "@/lib/ease";
import { cn } from "@/lib/utils";
import { MessageSideContext } from "@/components/agents/message-context";
export type MessageBubbleVariant =
| "solid"
| "soft"
| "tint"
| "outline"
| "ghost"
| "danger";
export type MessageBubbleAlign = "start" | "end";
interface MessageBubbleContextValue {
align?: MessageBubbleAlign;
animateIn: boolean;
variant: MessageBubbleVariant;
}
const MessageBubbleContext = createContext<MessageBubbleContextValue>({
animateIn: true,
variant: "soft",
});
const MessageBubbleLayoutContext = createContext<() => void>(() => {});
export interface MessageBubbleProps
extends Omit<HTMLMotionProps<"div">, "children"> {
variant?: MessageBubbleVariant;
/** Defaults to the surrounding Message alignment when omitted. */
align?: MessageBubbleAlign;
/** Plays the bubble entrance once when this component mounts. */
animateIn?: boolean;
children?: ReactNode;
}
export interface MessageBubbleContentProps
extends ComponentPropsWithRef<"div"> {
/** Replaces the content element while preserving bubble styling. */
render?: ReactElement;
}
export interface MessageBubbleGroupProps extends ComponentPropsWithRef<"div"> {
spacing?: "compact" | "default";
}
export interface MessageBubbleCollapsibleProps
extends ComponentPropsWithRef<"div"> {
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
collapsedLines?: 2 | 3 | 4 | 5 | 6;
moreLabel?: ReactNode;
lessLabel?: ReactNode;
contentClassName?: string;
triggerClassName?: string;
children?: ReactNode;
}
function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {
return (node: T | null) => {
for (const ref of refs) {
if (typeof ref === "function") ref(node);
else if (ref) ref.current = node;
}
};
}
const BUBBLE_CONTENT_REVEAL = {
duration: 0.12,
ease: EASE_OUT,
delay: 0.04,
} as const;
// Sent bubbles should pop into place quickly with one restrained overshoot.
const BUBBLE_POP = {
type: "spring",
stiffness: 520,
damping: 27,
mass: 0.52,
} as const;
export function MessageBubble({
variant = "soft",
align,
animateIn = false,
className,
children,
initial,
animate,
exit,
transition,
layout,
...props
}: MessageBubbleProps) {
const reduce = useReducedMotion() ?? false;
const messageSide = useContext(MessageSideContext);
const resolvedAlign = align ?? messageSide ?? "start";
return (
<MessageBubbleContext.Provider
value={{ align: resolvedAlign, animateIn, variant }}
>
<motion.div
data-slot="message-bubble"
data-align={resolvedAlign}
data-variant={variant}
layout={layout}
initial={initial ?? false}
animate={animate}
exit={
exit ??
(reduce ? { opacity: 0 } : { opacity: 0, y: -3, scale: 0.99 })
}
transition={transition ?? (reduce ? { duration: 0.12 } : SPRING_LAYOUT)}
className={cn(
"group/bubble flex w-full flex-col",
resolvedAlign === "end" ? "items-end" : "items-start",
className,
)}
{...props}
>
{children}
</motion.div>
</MessageBubbleContext.Provider>
);
}
function bubbleContentClass(
variant: MessageBubbleVariant,
interactive: boolean,
) {
return cn(
"relative z-0 min-w-9 max-w-[82%] rounded-2xl px-3.5 py-2.5 text-sm leading-6 text-foreground",
"[&_a]:font-medium [&_a]:underline [&_a]:underline-offset-4 [&_code]:rounded [&_code]:bg-background/60 [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.9em] [&_ol]:my-2 [&_ol]:list-decimal [&_ol]:pl-5 [&_p+p]:mt-2 [&_pre]:my-2 [&_pre]:overflow-x-auto [&_pre]:rounded-xl [&_pre]:bg-background/60 [&_pre]:p-3 [&_ul]:my-2 [&_ul]:list-disc [&_ul]:pl-5",
variant === "solid" && "text-background",
variant === "ghost" && "w-full max-w-none rounded-none px-0 py-0",
variant === "danger" && "text-destructive",
interactive &&
"cursor-pointer text-left outline-none transition-[background-color,color,transform] duration-150 hover:brightness-[0.98] focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.99]",
);
}
function bubbleSurfaceClass(
variant: MessageBubbleVariant,
align: MessageBubbleAlign,
) {
return cn(
"pointer-events-none absolute inset-0 -z-10 rounded-[inherit]",
align === "end" ? "origin-bottom-right" : "origin-bottom-left",
variant === "solid" && "bg-foreground",
variant === "soft" && "bg-muted",
variant === "tint" && "bg-primary/10",
variant === "outline" && "border border-border/70 bg-background",
variant === "danger" && "bg-destructive/10",
);
}
export function MessageBubbleContent({
render,
className,
children,
ref,
...props
}: MessageBubbleContentProps) {
const reduce = useReducedMotion() ?? false;
const { align = "start", animateIn, variant } =
useContext(MessageBubbleContext);
const [layoutVersion, setLayoutVersion] = useState(0);
const notifyLayout = useCallback(
() => setLayoutVersion((version) => version + 1),
[],
);
const interactive =
render?.type === "button" || render?.type === "a";
const classes = cn(bubbleContentClass(variant, interactive), className);
const composedChildren = (
<>
{variant !== "ghost" ? (
<motion.span
aria-hidden="true"
layout={reduce ? false : "size"}
layoutDependency={layoutVersion}
initial={
animateIn && !reduce
? {
opacity: 0,
scale: 0.92,
}
: false
}
animate={{ opacity: 1, scale: 1 }}
transition={
reduce
? { duration: 0 }
: {
opacity: { duration: 0.12, ease: EASE_OUT },
scale: BUBBLE_POP,
layout: SPRING_LAYOUT,
}
}
className={bubbleSurfaceClass(variant, align)}
/>
) : null}
<MessageBubbleLayoutContext.Provider value={notifyLayout}>
<motion.div
initial={
animateIn
? reduce
? { opacity: 0 }
: { opacity: 0 }
: false
}
animate={{ opacity: 1 }}
transition={
reduce ? { duration: 0.12, ease: EASE_OUT } : BUBBLE_CONTENT_REVEAL
}
className="relative"
>
{children}
</motion.div>
</MessageBubbleLayoutContext.Provider>
</>
);
if (render) {
const child = render as ReactElement<
Record<string, unknown> & { className?: string; ref?: Ref<HTMLElement> }
>;
return cloneElement(child, {
...props,
ref: mergeRefs(child.props.ref, ref as Ref<HTMLElement> | undefined),
className: cn(classes, child.props.className),
children: composedChildren,
"data-slot": "message-bubble-content",
});
}
return (
<div
ref={ref}
data-slot="message-bubble-content"
className={classes}
{...props}
>
{composedChildren}
</div>
);
}
export function MessageBubbleGroup({
spacing = "compact",
className,
...props
}: MessageBubbleGroupProps) {
return (
<div
data-slot="message-bubble-group"
className={cn(
"flex w-full flex-col",
spacing === "compact" ? "gap-1.5" : "gap-3",
className,
)}
{...props}
/>
);
}
const LINE_CLAMP_CLASS = {
2: "line-clamp-2",
3: "line-clamp-3",
4: "line-clamp-4",
5: "line-clamp-5",
6: "line-clamp-6",
} as const;
export function MessageBubbleCollapsible({
open,
defaultOpen = false,
onOpenChange,
collapsedLines = 4,
moreLabel = "Show more",
lessLabel = "Show less",
contentClassName,
triggerClassName,
className,
children,
...props
}: MessageBubbleCollapsibleProps) {
const reduce = useReducedMotion() ?? false;
const contentId = useId();
const notifyLayout = useContext(MessageBubbleLayoutContext);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const currentOpen = open ?? internalOpen;
const setOpen = useCallback(
(next: boolean) => {
notifyLayout();
if (open === undefined) setInternalOpen(next);
onOpenChange?.(next);
},
[notifyLayout, onOpenChange, open],
);
return (
<div
data-slot="message-bubble-collapsible"
data-state={currentOpen ? "open" : "closed"}
className={cn("w-full", className)}
{...props}
>
<div
id={contentId}
className={cn(
"transition-[mask-image] duration-200",
!currentOpen && LINE_CLAMP_CLASS[collapsedLines],
!currentOpen &&
"[mask-image:linear-gradient(to_bottom,#000_68%,transparent_100%)]",
contentClassName,
)}
>
{children}
</div>
<button
type="button"
aria-expanded={currentOpen}
aria-controls={contentId}
onClick={() => setOpen(!currentOpen)}
className={cn(
"mt-2 inline-flex h-7 items-center gap-1 rounded-full px-2 text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
triggerClassName,
)}
>
<span>{currentOpen ? lessLabel : moreLabel}</span>
<motion.span
aria-hidden="true"
animate={{ rotate: currentOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
>
<ChevronDown className="size-3.5" />
</motion.span>
</button>
</div>
);
}
"use client";
import {
Check,
ChevronDown,
Copy,
RotateCcw,
ThumbsDown,
ThumbsUp,
} from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
type ReactNode,
useCallback,
useEffect,
useId,
useRef,
useState,
} from "react";
import {
type CitationItem,
CitationList,
CitationStack,
} from "@/components/agents/citations";
import { AgentDisclosure } from "@/components/agents/agent-disclosure";
import { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type StreamingResponseStatus = "streaming" | "complete" | "error";
export type StreamingResponseFeedback = "up" | "down" | null;
export interface StreamingResponseProps {
/** Rendered response content. Pass plain text or the output of a Markdown renderer. */
children: ReactNode;
status?: StreamingResponseStatus;
/** Plain-text value copied by the built-in copy action. */
copyText?: string;
/** Overrides the built-in clipboard action. */
onCopy?: () => void | Promise<void>;
onRetry?: () => void;
/** Optional sources shown as a compact footer disclosure after streaming. */
sources?: CitationItem[];
sourcesOpen?: boolean;
defaultSourcesOpen?: boolean;
onSourcesOpenChange?: (open: boolean) => void;
sourceIdPrefix?: string;
feedback?: StreamingResponseFeedback;
defaultFeedback?: StreamingResponseFeedback;
onFeedbackChange?: (feedback: StreamingResponseFeedback) => void;
/** Set false when a surrounding conversation log announces streamed text. */
announce?: boolean;
/** Hides the built-in completion actions without changing response status. */
showActions?: boolean;
className?: string;
contentClassName?: string;
actionsClassName?: string;
}
function ResponseAction({
label,
active = false,
onClick,
children,
}: {
label: string;
active?: boolean;
onClick: () => void;
children: ReactNode;
}) {
const reduce = useReducedMotion() ?? false;
return (
<motion.button
type="button"
aria-label={label}
title={label}
aria-pressed={label === "Helpful" || label === "Not helpful" ? active : undefined}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.9 }}
transition={SPRING_PRESS}
className={cn(
"grid size-7 place-items-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
active && "bg-muted text-foreground",
)}
>
{children}
</motion.button>
);
}
export function StreamingResponse({
children,
status = "streaming",
copyText,
onCopy,
onRetry,
sources = [],
sourcesOpen,
defaultSourcesOpen = false,
onSourcesOpenChange,
sourceIdPrefix,
feedback,
defaultFeedback = null,
onFeedbackChange,
announce = true,
showActions = true,
className,
contentClassName,
actionsClassName,
}: StreamingResponseProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const [copied, setCopied] = useState(false);
const [internalFeedback, setInternalFeedback] =
useState<StreamingResponseFeedback>(defaultFeedback);
const [internalSourcesOpen, setInternalSourcesOpen] =
useState(defaultSourcesOpen);
const copyTimer = useRef<number | undefined>(undefined);
const currentFeedback = feedback ?? internalFeedback;
const currentSourcesOpen = sourcesOpen ?? internalSourcesOpen;
const streaming = status === "streaming";
const complete = status === "complete";
const canCopy = Boolean(copyText || onCopy);
const hasSources = sources.length > 0;
const shouldShowActions =
showActions && !streaming && (canCopy || onRetry || complete || hasSources);
const sourcesContentId = `${baseId}-sources`;
const resolvedSourcePrefix =
sourceIdPrefix ?? `response-source-${baseId.replace(/:/g, "")}`;
useEffect(
() => () => {
if (copyTimer.current) window.clearTimeout(copyTimer.current);
},
[],
);
const handleCopy = useCallback(async () => {
if (onCopy) await onCopy();
else if (copyText) await navigator.clipboard?.writeText(copyText);
setCopied(true);
if (copyTimer.current) window.clearTimeout(copyTimer.current);
copyTimer.current = window.setTimeout(() => setCopied(false), 1600);
}, [copyText, onCopy]);
const setFeedback = (next: Exclude<StreamingResponseFeedback, null>) => {
const value = currentFeedback === next ? null : next;
if (feedback === undefined) setInternalFeedback(value);
onFeedbackChange?.(value);
};
const setSourcesOpen = useCallback(
(next: boolean) => {
if (sourcesOpen === undefined) setInternalSourcesOpen(next);
onSourcesOpenChange?.(next);
},
[onSourcesOpenChange, sourcesOpen],
);
return (
<div
data-state={status}
aria-busy={streaming}
className={cn("w-full", className)}
>
<div
aria-live={announce ? "polite" : "off"}
className={cn(
"text-sm leading-6 text-foreground/90 [&_a]:font-medium [&_a]:underline [&_a]:underline-offset-4 [&_code]:rounded [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.9em] [&_ol]:my-3 [&_ol]:list-decimal [&_ol]:space-y-1 [&_ol]:pl-5 [&_p+p]:mt-3 [&_pre]:my-3 [&_pre]:overflow-x-auto [&_pre]:rounded-xl [&_pre]:border [&_pre]:border-border [&_pre]:bg-muted/45 [&_pre]:p-3 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_ul]:my-3 [&_ul]:list-disc [&_ul]:space-y-1 [&_ul]:pl-5",
contentClassName,
)}
>
{children}
</div>
<AnimatePresence initial={false}>
{shouldShowActions ? (
<motion.div
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: reduce ? 0.12 : 0.22, ease: EASE_OUT }}
className="mt-3"
>
<div className={cn("flex items-center gap-0.5", actionsClassName)}>
{canCopy ? (
<ResponseAction
label={copied ? "Copied" : "Copy response"}
onClick={handleCopy}
>
{copied ? (
<Check className="size-3.5" />
) : (
<Copy className="size-3.5" />
)}
</ResponseAction>
) : null}
{onRetry ? (
<ResponseAction label="Retry response" onClick={onRetry}>
<RotateCcw className="size-3.5" />
</ResponseAction>
) : null}
{complete ? (
<>
<ResponseAction
label="Helpful"
active={currentFeedback === "up"}
onClick={() => setFeedback("up")}
>
<ThumbsUp className="size-3.5" />
</ResponseAction>
<ResponseAction
label="Not helpful"
active={currentFeedback === "down"}
onClick={() => setFeedback("down")}
>
<ThumbsDown className="size-3.5" />
</ResponseAction>
</>
) : null}
{hasSources ? (
<button
type="button"
aria-expanded={currentSourcesOpen}
aria-controls={sourcesContentId}
onClick={() => setSourcesOpen(!currentSourcesOpen)}
className="group ml-1 inline-flex min-h-7 items-center gap-2 rounded-md px-1.5 text-xs text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<CitationStack citations={sources} />
<span className="tabular-nums">
{sources.length} {sources.length === 1 ? "source" : "sources"}
</span>
<motion.span
aria-hidden="true"
animate={{ rotate: currentSourcesOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="text-muted-foreground/50 group-hover:text-muted-foreground"
>
<ChevronDown className="size-3" />
</motion.span>
</button>
) : null}
</div>
{hasSources ? (
<AgentDisclosure
id={sourcesContentId}
open={currentSourcesOpen}
>
<CitationList
citations={sources}
idPrefix={resolvedSourcePrefix}
className="mt-2 rounded-xl bg-muted p-2"
/>
</AgentDisclosure>
) : null}
</motion.div>
) : null}
</AnimatePresence>
</div>
);
}
"use client";
import { createContext } from "react";
export type MessageSide = "start" | "end";
export const MessageSideContext = createContext<MessageSide | undefined>(
undefined,
);
"use client";
import { useReducedMotion } from "motion/react";
import {
type ComponentPropsWithRef,
type Ref,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
import {
PreviewRail,
type PreviewRailItem,
} from "@/components/motion/preview-rail";
import { cn } from "@/lib/utils";
const PREVIEW_TITLE_LENGTH = 56;
const PREVIEW_DESCRIPTION_LENGTH = 88;
function truncateMessageText(text: string, limit: number) {
if (text.length <= limit) return text;
const excerpt = text.slice(0, limit);
const boundary = excerpt.lastIndexOf(" ");
return `${excerpt.slice(0, boundary > limit * 0.65 ? boundary : limit).trim()}…`;
}
function getMessageText(message: HTMLElement) {
const surface =
message.querySelector<HTMLElement>('[data-slot="message-bubble-content"]') ??
message.querySelector<HTMLElement>('[data-slot="message-content"]') ??
message;
return (surface.textContent ?? "").replace(/\s+/g, " ").trim();
}
function getMessagePreview(
message: HTMLElement,
assistantResponse?: HTMLElement,
) {
const text = getMessageText(message);
if (!text) {
return { label: "Message", description: undefined };
}
if (text.length <= PREVIEW_TITLE_LENGTH) {
const responseText = assistantResponse
? getMessageText(assistantResponse)
: "";
return {
label: text,
description: responseText
? truncateMessageText(responseText, PREVIEW_DESCRIPTION_LENGTH)
: undefined,
};
}
const titleExcerpt = text.slice(0, PREVIEW_TITLE_LENGTH);
const titleBoundary = titleExcerpt.lastIndexOf(" ");
const titleEnd =
titleBoundary > PREVIEW_TITLE_LENGTH * 0.65
? titleBoundary
: PREVIEW_TITLE_LENGTH;
const label = `${text.slice(0, titleEnd).trim()}…`;
const responseText = assistantResponse
? getMessageText(assistantResponse)
: text.slice(titleEnd).trim();
return {
label,
description: responseText
? truncateMessageText(responseText, PREVIEW_DESCRIPTION_LENGTH)
: undefined,
};
}
export interface MessageScrollerProps extends ComponentPropsWithRef<"div"> {
/** Keep streamed output pinned while the reader remains near the end. */
followOutput?: boolean;
/** Distance from the end that still counts as following the output. */
followThreshold?: number;
/** Smoothly follow growing content. */
smooth?: boolean;
/** Reports when the reader leaves or returns to the live edge. */
onFollowChange?: (following: boolean) => void;
/** Accessible label for the scrollable transcript. */
label?: string;
/** Marks the transcript as waiting for more streamed content. */
busy?: boolean;
/** Adds a compact rail for navigating between rendered Message rows. */
navigation?: "rail";
/** Accessible label for the optional message navigation rail. */
navigationLabel?: string;
viewportClassName?: string;
contentClassName?: string;
railClassName?: string;
viewportRef?: Ref<HTMLElement>;
viewportProps?: Omit<
ComponentPropsWithRef<"section">,
"children" | "className" | "ref"
>;
contentProps?: Omit<
ComponentPropsWithRef<"div">,
"children" | "className" | "ref"
>;
}
export function MessageScroller({
followOutput = true,
followThreshold = 56,
smooth = true,
onFollowChange,
label = "Conversation",
busy,
navigation,
navigationLabel = "Message navigation",
viewportClassName,
contentClassName,
railClassName,
viewportRef: externalViewportRef,
viewportProps,
contentProps,
className,
children,
...props
}: MessageScrollerProps) {
const reduce = useReducedMotion() ?? false;
const viewportRef = useRef<HTMLElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const followingRef = useRef(followOutput);
const programmaticScrollRef = useRef(false);
const scrollTimerRef = useRef<number | undefined>(undefined);
const frameRef = useRef<number | undefined>(undefined);
const railFrameRef = useRef<number | undefined>(undefined);
const railIdRef = useRef(new WeakMap<HTMLElement, string>());
const railIdCounterRef = useRef(0);
const railTargetsRef = useRef(new Map<string, HTMLElement>());
const [railItems, setRailItems] = useState<PreviewRailItem[]>([]);
const [activeRailId, setActiveRailId] = useState("");
const [railOverflowing, setRailOverflowing] = useState(false);
const {
onScroll: onViewportScroll,
onWheel: onViewportWheel,
onTouchStart: onViewportTouchStart,
onKeyDown: onViewportKeyDown,
...restViewportProps
} = viewportProps ?? {};
const setViewportRef = useCallback(
(node: HTMLElement | null) => {
viewportRef.current = node;
if (typeof externalViewportRef === "function") {
externalViewportRef(node);
} else if (externalViewportRef) {
externalViewportRef.current = node;
}
},
[externalViewportRef],
);
const setFollowing = useCallback(
(next: boolean) => {
if (followingRef.current === next) return;
followingRef.current = next;
onFollowChange?.(next);
},
[onFollowChange],
);
const updateActiveRailItem = useCallback(() => {
if (navigation !== "rail") return;
const viewport = viewportRef.current;
const targets = [...railTargetsRef.current.entries()];
if (!viewport || targets.length === 0) return;
const viewportRect = viewport.getBoundingClientRect();
if (viewport.scrollTop <= followThreshold) {
const firstId = targets[0]?.[0] ?? "";
setActiveRailId((current) => (current === firstId ? current : firstId));
return;
}
const distanceFromEnd =
viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
if (distanceFromEnd <= followThreshold) {
const lastId = targets.at(-1)?.[0] ?? "";
setActiveRailId((current) => (current === lastId ? current : lastId));
return;
}
const viewportCenter = viewportRect.top + viewportRect.height / 2;
let nearestId = targets[0]?.[0] ?? "";
let nearestDistance = Number.POSITIVE_INFINITY;
for (const [id, element] of targets) {
const rect = element.getBoundingClientRect();
const messageCenter = rect.top + rect.height / 2;
const distance = Math.abs(messageCenter - viewportCenter);
if (distance < nearestDistance) {
nearestDistance = distance;
nearestId = id;
}
}
setActiveRailId((current) =>
current === nearestId ? current : nearestId,
);
}, [followThreshold, navigation]);
const syncRailItems = useCallback(() => {
if (navigation !== "rail") return;
const content = contentRef.current;
const viewport = viewportRef.current;
if (!content || !viewport) return;
const messages = Array.from(
content.querySelectorAll<HTMLElement>('[data-slot="message"]'),
);
const targets = new Map<string, HTMLElement>();
const nextItems = messages.map((message, index) => {
let id = railIdRef.current.get(message);
if (!id) {
railIdCounterRef.current += 1;
id = `message-rail-${railIdCounterRef.current}`;
railIdRef.current.set(message, id);
}
targets.set(id, message);
const sender = message.dataset.from ?? "conversation";
const assistantResponse =
sender === "user"
? messages
.slice(index + 1)
.find((candidate) => candidate.dataset.from === "assistant")
: undefined;
const preview = getMessagePreview(message, assistantResponse);
return {
id,
label: preview.label,
description: preview.description,
ariaLabel: `Go to ${sender} message ${index + 1} of ${messages.length}`,
};
});
railTargetsRef.current = targets;
setRailItems((current) => {
const unchanged =
current.length === nextItems.length &&
current.every(
(item, index) =>
item.id === nextItems[index]?.id &&
item.label === nextItems[index]?.label &&
item.description === nextItems[index]?.description &&
item.ariaLabel === nextItems[index]?.ariaLabel,
);
return unchanged ? current : nextItems;
});
setRailOverflowing(
viewport.scrollHeight > viewport.clientHeight + 1 && messages.length > 1,
);
}, [navigation]);
const scheduleRailSync = useCallback(() => {
if (navigation !== "rail") return;
if (railFrameRef.current) cancelAnimationFrame(railFrameRef.current);
railFrameRef.current = requestAnimationFrame(() => {
syncRailItems();
updateActiveRailItem();
});
}, [navigation, syncRailItems, updateActiveRailItem]);
const scrollToEnd = useCallback((behavior: ScrollBehavior) => {
const viewport = viewportRef.current;
if (!viewport) return;
programmaticScrollRef.current = true;
if (typeof viewport.scrollTo === "function") {
viewport.scrollTo({ top: viewport.scrollHeight, behavior });
} else {
viewport.scrollTop = viewport.scrollHeight;
}
if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);
scrollTimerRef.current = window.setTimeout(() => {
programmaticScrollRef.current = false;
}, behavior === "smooth" ? 320 : 0);
}, []);
const handleScroll = useCallback(() => {
const viewport = viewportRef.current;
if (!viewport || programmaticScrollRef.current) return;
const distance =
viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
setFollowing(distance <= followThreshold);
updateActiveRailItem();
}, [followThreshold, setFollowing, updateActiveRailItem]);
const leaveLiveEdge = useCallback(() => {
programmaticScrollRef.current = false;
}, []);
useLayoutEffect(() => {
followingRef.current = followOutput;
if (!followOutput) return;
frameRef.current = requestAnimationFrame(() => scrollToEnd("auto"));
return () => {
if (frameRef.current) cancelAnimationFrame(frameRef.current);
};
}, [followOutput, scrollToEnd]);
useEffect(() => {
const content = contentRef.current;
if (!content || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => {
scheduleRailSync();
if (!followOutput || !followingRef.current) return;
scrollToEnd(reduce || !smooth ? "auto" : "smooth");
});
observer.observe(content);
return () => observer.disconnect();
}, [followOutput, reduce, scheduleRailSync, scrollToEnd, smooth]);
useEffect(() => {
if (navigation !== "rail") {
railTargetsRef.current.clear();
setRailItems([]);
setRailOverflowing(false);
return;
}
const content = contentRef.current;
const viewport = viewportRef.current;
if (!content || !viewport) return;
scheduleRailSync();
const mutationObserver =
typeof MutationObserver === "undefined"
? null
: new MutationObserver(scheduleRailSync);
mutationObserver?.observe(content, {
childList: true,
characterData: true,
subtree: true,
});
const resizeObserver =
typeof ResizeObserver === "undefined"
? null
: new ResizeObserver(scheduleRailSync);
resizeObserver?.observe(content);
resizeObserver?.observe(viewport);
return () => {
mutationObserver?.disconnect();
resizeObserver?.disconnect();
};
}, [navigation, scheduleRailSync]);
useEffect(
() => () => {
if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);
if (frameRef.current) cancelAnimationFrame(frameRef.current);
if (railFrameRef.current) cancelAnimationFrame(railFrameRef.current);
},
[],
);
const scrollToRailItem = useCallback(
(item: PreviewRailItem) => {
const viewport = viewportRef.current;
const target = railTargetsRef.current.get(item.id);
if (!viewport || !target) return;
const lastItem = railItems.at(-1)?.id === item.id;
setActiveRailId(item.id);
if (lastItem) {
setFollowing(true);
scrollToEnd(reduce || !smooth ? "auto" : "smooth");
return;
}
setFollowing(false);
programmaticScrollRef.current = true;
const viewportRect = viewport.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();
const top =
viewport.scrollTop +
targetRect.top -
viewportRect.top -
(viewport.clientHeight - targetRect.height) / 2;
const behavior = reduce || !smooth ? "auto" : "smooth";
if (typeof viewport.scrollTo === "function") {
viewport.scrollTo({ top, behavior });
} else {
viewport.scrollTop = top;
}
if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);
scrollTimerRef.current = window.setTimeout(() => {
programmaticScrollRef.current = false;
}, behavior === "smooth" ? 320 : 0);
},
[railItems, reduce, scrollToEnd, setFollowing, smooth],
);
const viewport = (
<section
ref={setViewportRef}
aria-label={label}
{...restViewportProps}
onScroll={(event) => {
handleScroll();
onViewportScroll?.(event);
}}
onWheel={(event) => {
leaveLiveEdge();
onViewportWheel?.(event);
}}
onTouchStart={(event) => {
leaveLiveEdge();
onViewportTouchStart?.(event);
}}
onKeyDown={(event) => {
if (["ArrowUp", "PageUp", "Home"].includes(event.key)) {
leaveLiveEdge();
}
onViewportKeyDown?.(event);
}}
className={cn(
"h-full overflow-y-auto overscroll-contain outline-none [overflow-anchor:none] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
navigation === "rail"
? "[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
: "[scrollbar-gutter:stable]",
viewportClassName,
navigation === "rail" && railOverflowing && "pr-10",
)}
>
<div
ref={contentRef}
role="log"
aria-live="polite"
aria-relevant="additions text"
aria-busy={busy}
className={contentClassName}
{...contentProps}
>
{children}
</div>
</section>
);
return (
<div
data-slot="message-scroller"
className={cn("min-h-0", className)}
{...props}
>
{navigation === "rail" ? (
<PreviewRail
items={railOverflowing ? railItems : []}
label={navigationLabel}
activeId={activeRailId}
onItemSelect={scrollToRailItem}
previewSide="before"
highlightActive
itemSize={14}
className="h-full min-h-0 overflow-hidden"
previewContainerClassName="right-8 left-3"
previewClassName="mr-1 w-64 max-w-full [&_[data-slot=preview-rail-card]]:h-20 [&_[data-slot=preview-rail-card]]:overflow-hidden [&_[data-slot=preview-rail-card]]:p-3 [&_[data-slot=preview-rail-title]]:line-clamp-1 [&_[data-slot=preview-rail-title]]:text-xs [&_[data-slot=preview-rail-title]]:leading-4 [&_[data-slot=preview-rail-description]]:line-clamp-2 [&_[data-slot=preview-rail-description]]:text-xs [&_[data-slot=preview-rail-description]]:leading-4"
railClassName={cn(
"absolute inset-y-3 right-1 w-7 content-center py-1 [&_[data-slot=preview-rail-item]]:w-7 [&_[data-slot=preview-rail-item]]:justify-end [&_[data-slot=preview-rail-tick]]:h-px [&_[data-slot=preview-rail-tick]]:w-4 [&_[data-slot=preview-rail-tick]]:origin-right",
railOverflowing
? "pointer-events-auto opacity-100"
: "pointer-events-none opacity-0",
railClassName,
)}
>
{viewport}
</PreviewRail>
) : (
viewport
)}
</div>
);
}
"use client";
import { motion, type HTMLMotionProps, useReducedMotion } from "motion/react";
import type { CSSProperties } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface AgentDisclosureProps
extends Omit<HTMLMotionProps<"div">, "animate" | "initial"> {
open: boolean;
openHeight?: CSSProperties["height"];
}
/** Shared transform-only reveal for collapsible agent content. */
export function AgentDisclosure({
open,
openHeight = "auto",
className,
style,
transition,
...props
}: AgentDisclosureProps) {
const reduce = useReducedMotion() ?? false;
return (
<motion.div
{...props}
aria-hidden={!open}
inert={!open}
initial={false}
animate={
reduce
? { opacity: open ? 1 : 0 }
: {
opacity: open ? 1 : 0,
clipPath: open ? "inset(0 0 0% 0)" : "inset(0 0 100% 0)",
y: open ? 0 : -4,
}
}
transition={
transition ?? {
duration: reduce ? 0 : open ? 0.22 : 0.14,
ease: EASE_OUT,
}
}
className={cn("overflow-hidden", className)}
style={{
...style,
height: open ? openHeight : 0,
pointerEvents: open ? undefined : "none",
transformOrigin: "top",
}}
/>
);
}
"use client";
import { BookOpenText, ChevronDown, ExternalLink, Globe2 } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
type ReactNode,
useCallback,
useId,
useState,
} from "react";
import { AgentDisclosure } from "@/components/agents/agent-disclosure";
import { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from "@/lib/ease";
import { useFavicon } from "@/lib/hooks/use-favicon";
import { cn } from "@/lib/utils";
export interface CitationItem {
id: string;
title: ReactNode;
domain?: ReactNode;
url?: string;
}
export interface CitationsProps {
citations: CitationItem[];
title?: ReactNode;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
idPrefix?: string;
className?: string;
}
export interface CitationProps {
citationId: string;
index: number;
/** Must match the related Citations idPrefix. */
idPrefix: string;
className?: string;
}
export interface CitationListProps {
citations: CitationItem[];
idPrefix?: string;
className?: string;
}
export interface CitationStackProps {
citations: CitationItem[];
limit?: number;
className?: string;
}
function citationTargetId(prefix: string, citationId: string) {
return `${prefix}-${citationId.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
}
export function Citation({
citationId,
index,
idPrefix,
className,
}: CitationProps) {
return (
<a
href={`#${citationTargetId(idPrefix, citationId)}`}
aria-label={`View citation ${index}`}
className={cn(
"mx-0.5 inline-flex min-w-4 -translate-y-0.5 items-center justify-center rounded-md bg-muted/60 px-1 py-0.5 text-[10px] font-semibold leading-none text-muted-foreground no-underline outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
className,
)}
>
{index}
</a>
);
}
export function CitationFavicon({
url,
className,
}: {
url?: string;
className?: string;
}) {
const favicon = useFavicon(url);
return (
<span
aria-hidden="true"
className={cn(
"grid size-5 shrink-0 place-items-center text-muted-foreground",
className,
)}
>
{favicon.src ? (
// biome-ignore lint/performance/noImgElement: Dynamic cross-site favicons keep this framework-agnostic registry component portable.
<img
ref={favicon.ref}
src={favicon.src}
alt=""
width={16}
height={16}
referrerPolicy="no-referrer"
className="size-4 rounded-sm object-contain"
/>
) : (
<Globe2 className="size-3.5" />
)}
</span>
);
}
export function CitationStack({
citations,
limit = 3,
className,
}: CitationStackProps) {
return (
<span
aria-hidden="true"
className={cn("flex -space-x-1.5", className)}
>
{citations.slice(0, limit).map((citation) => (
<CitationFavicon
key={citation.id}
url={citation.url}
className="size-6 rounded-full bg-background ring-2 ring-background"
/>
))}
</span>
);
}
function CitationRow({
citation,
index,
idPrefix,
}: {
citation: CitationItem;
index: number;
idPrefix: string;
}) {
const content = (
<>
<CitationFavicon url={citation.url} />
<span className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5">
<span className="truncate text-sm font-medium text-foreground/80 transition-colors group-hover/citation:text-foreground">
{citation.title}
</span>
{citation.domain ? (
<span className="min-w-0 truncate text-xs text-muted-foreground/60">
{citation.domain}
</span>
) : null}
</span>
<span className="flex shrink-0 items-center gap-1.5">
<span className="grid size-5 place-items-center rounded-md bg-foreground/[0.05] text-[10px] font-semibold tabular-nums text-muted-foreground">
{index}
</span>
{citation.url ? (
<ExternalLink className="size-3.5 text-muted-foreground/40 transition-colors group-hover/citation:text-muted-foreground" />
) : null}
</span>
</>
);
const className =
"group/citation flex items-center gap-2 rounded-md px-1.5 py-1 outline-none focus-visible:ring-2 focus-visible:ring-ring";
const id = citationTargetId(idPrefix, citation.id);
return citation.url ? (
<a
id={id}
href={citation.url}
target="_blank"
rel="noreferrer noopener"
className={className}
>
{content}
</a>
) : (
<div id={id} className={className}>
{content}
</div>
);
}
export function CitationList({
citations,
idPrefix,
className,
}: CitationListProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const resolvedPrefix =
idPrefix ?? `citation-list-${baseId.replace(/:/g, "")}`;
return (
<div className={cn("grid gap-0.5", className)}>
<AnimatePresence mode="popLayout">
{citations.map((citation, index) => (
<motion.div
layout="position"
key={citation.id}
initial={reduce ? { opacity: 1 } : { opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3 }}
transition={
reduce
? { duration: 0 }
: {
opacity: { duration: 0.18, ease: EASE_OUT },
y: SPRING_LAYOUT,
layout: SPRING_LAYOUT,
}
}
>
<CitationRow
citation={citation}
index={index + 1}
idPrefix={resolvedPrefix}
/>
</motion.div>
))}
</AnimatePresence>
</div>
);
}
export function Citations({
citations,
title = "Sources",
open,
defaultOpen = false,
onOpenChange,
idPrefix,
className,
}: CitationsProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const contentId = `${baseId}-content`;
const resolvedPrefix =
idPrefix ?? `citation-${baseId.replace(/:/g, "")}`;
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const currentOpen = open ?? internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (open === undefined) setInternalOpen(next);
onOpenChange?.(next);
},
[onOpenChange, open],
);
return (
<div className={cn("w-full text-sm", className)}>
<button
type="button"
aria-expanded={currentOpen}
aria-controls={contentId}
onClick={() => setOpen(!currentOpen)}
className="group -ml-1 flex min-h-8 items-center gap-2 rounded-lg px-1 text-left text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<BookOpenText className="size-4" />
<span className="font-medium">{title}</span>
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-semibold tabular-nums">
{citations.length}
</span>
<motion.span
aria-hidden="true"
animate={{ rotate: currentOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="text-muted-foreground/60"
>
<ChevronDown className="size-3.5" />
</motion.span>
</button>
<AgentDisclosure
id={contentId}
open={currentOpen}
>
<CitationList
citations={citations}
idPrefix={resolvedPrefix}
className="mt-1"
/>
</AgentDisclosure>
</div>
);
}
"use client";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
type MouseEvent,
type PointerEvent,
type ReactNode,
useCallback,
useId,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_LAYOUT } from "@/lib/ease";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { cn } from "@/lib/utils";
export interface PreviewRailItem {
id: string;
label: string;
ariaLabel?: string;
description?: ReactNode;
href?: string;
target?: "_blank" | "_self" | "_parent" | "_top";
rel?: string;
}
export interface PreviewRailProps {
items: PreviewRailItem[];
label?: string;
orientation?: "vertical" | "horizontal";
activeId?: string;
defaultActiveId?: string;
onActiveChange?: (id: string) => void;
onItemSelect?: (item: PreviewRailItem) => void;
renderPreview?: (item: PreviewRailItem) => ReactNode;
showPreview?: boolean;
previewSide?: "before" | "after";
highlightActive?: boolean;
itemSize?: number;
children?: ReactNode;
className?: string;
railClassName?: string;
previewContainerClassName?: string;
previewClassName?: string;
}
function DefaultPreview({ item }: { item: PreviewRailItem }) {
return (
<div
data-slot="preview-rail-card"
className="rounded-2xl border border-border bg-card p-4 shadow-sm"
>
<p
data-slot="preview-rail-title"
className="font-medium text-card-foreground"
>
{item.label}
</p>
{item.description ? (
<div
data-slot="preview-rail-description"
className="mt-1 text-sm leading-6 text-muted-foreground"
>
{item.description}
</div>
) : null}
</div>
);
}
export function PreviewRail({
items,
label = "Section navigation",
orientation = "vertical",
activeId,
defaultActiveId,
onActiveChange,
onItemSelect,
renderPreview,
showPreview = true,
previewSide = "after",
highlightActive = false,
itemSize = 24,
children,
className,
railClassName,
previewContainerClassName,
previewClassName,
}: PreviewRailProps) {
const uid = useId();
const reduce = useReducedMotion();
const rootRef = useRef<HTMLDivElement>(null);
const [internalActiveId, setInternalActiveId] = useState(
defaultActiveId ?? items[0]?.id ?? "",
);
const [hoveredId, setHoveredId] = useState<string | null>(null);
// A finger cannot hover, so a tap lights the tick instead. Kept apart from
// the hovered one: they end in different ways, and a stray mouse move must
// not clear a tick the keyboard or a tap chose.
const [pinnedId, setPinnedId] = useState<string | null>(null);
const [focusedId, setFocusedId] = useState<string | null>(null);
// A click carries no pointerType, so the pointerdown before it is what says
// whether the activation was a tap. Keyboard activation has none at all.
const tap = useTapGesture<boolean>();
const hover = useHoverGesture();
const clearPinned = useCallback(() => setPinnedId(null), []);
// The next tap outside the rail stands in for the pointer leaving it. The
// card is a preview, so that tap passes through to whatever it landed on.
useDismiss(pinnedId !== null, clearPinned, rootRef);
const requestedActiveId = activeId ?? internalActiveId;
const selectedId = items.some((item) => item.id === requestedActiveId)
? requestedActiveId
: (items[0]?.id ?? "");
const displayedId = hoveredId ?? pinnedId ?? focusedId ?? "";
const highlightedId = displayedId || (highlightActive ? selectedId : "");
const displayedIndex = items.findIndex((item) => item.id === highlightedId);
const rowTemplate = items.length
? `repeat(${items.length}, ${itemSize}px)`
: undefined;
const isHorizontal = orientation === "horizontal";
const selectItem = (id: string) => {
if (activeId === undefined) setInternalActiveId(id);
onActiveChange?.(id);
};
return (
<motion.div
layoutRoot
ref={rootRef}
onBlur={(event) => {
// Both tick sources leave with the focus: a tap does not always land
// focus, but when it does, tabbing away must not strand the card.
if (!event.currentTarget.contains(event.relatedTarget)) {
setFocusedId(null);
setPinnedId(null);
}
}}
className={cn(
"isolate relative flex w-full overflow-visible",
isHorizontal
? "min-h-64 flex-col items-center justify-center"
: "min-h-80",
className,
)}
>
<nav
aria-label={label}
onPointerLeave={(event) => {
// A touch pointer leaves on lift, which would clear the tick the tap
// just chose — that one is cleared by the outside tap instead.
if (hover.leave(event)) setHoveredId(null);
}}
style={
isHorizontal
? { gridTemplateColumns: rowTemplate }
: { gridTemplateRows: rowTemplate }
}
className={cn(
"relative z-10 grid shrink-0",
isHorizontal
? "h-12 w-fit max-w-full self-center justify-center"
: "w-12 content-center",
railClassName,
)}
>
{items.map((item, index) => {
const selected = item.id === selectedId;
const highlighted = item.id === highlightedId;
const distance =
displayedIndex < 0 ? Number.POSITIVE_INFINITY : Math.abs(index - displayedIndex);
const scale = highlighted
? 1
: distance === 1
? 0.68
: distance === 2
? 0.44
: 0.25;
const itemContent = (
<>
<motion.span
data-slot="preview-rail-tick"
aria-hidden="true"
animate={isHorizontal ? { scaleY: scale } : { scaleX: scale }}
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
className={cn(
"block bg-current",
isHorizontal
? "h-12 w-0.5 origin-bottom"
: "h-0.5 w-12 origin-left",
highlighted ? "text-foreground" : undefined,
)}
/>
</>
);
const sharedClassName = cn(
"relative flex text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
isHorizontal
? "h-12 w-6 items-end justify-center"
: "h-6 w-12 items-center",
);
const sharedStyle = isHorizontal
? { width: itemSize }
: { height: itemSize };
const handlePointerEnter = (event: PointerEvent<HTMLElement>) => {
if (hover.enter(event)) setHoveredId(item.id);
};
const handlePointerDown = (event: PointerEvent<HTMLElement>) => {
tap.start(event, pinnedId === item.id);
setFocusedId(null);
};
// A gesture the platform takes away sends no click, and a key press
// starts an activation that never had a pointer behind it: either
// one leaves a record the next click would read as a tap of its own.
const dropGesture = () => tap.drop();
const handleFocus = (currentTarget: HTMLElement) => {
if (currentTarget.matches(":focus-visible")) {
setFocusedId(item.id);
}
};
const handleSelect = (event: MouseEvent<HTMLElement>) => {
const gesture = tap.take();
const tapped =
gesture !== null && gesture.pointerType !== "mouse";
if (tapped) {
// A link would otherwise show its preview and leave the page in
// the same tap, so the card is never read: the first tap lights
// the tick, the second follows the link.
if (item.href && !gesture.state) {
event.preventDefault();
setPinnedId(item.id);
return;
}
setPinnedId(item.id);
}
selectItem(item.id);
onItemSelect?.(item);
};
return item.href ? (
<a
key={item.id}
data-slot="preview-rail-item"
href={item.href}
target={item.target}
rel={
item.rel ??
(item.target === "_blank" ? "noreferrer noopener" : undefined)
}
aria-label={item.ariaLabel ?? item.label}
aria-current={selected ? "page" : undefined}
onPointerEnter={handlePointerEnter}
onPointerDown={handlePointerDown}
onPointerCancel={dropGesture}
onKeyDown={dropGesture}
onFocus={(event) => handleFocus(event.currentTarget)}
onClick={handleSelect}
style={sharedStyle}
className={sharedClassName}
>
{itemContent}
</a>
) : (
<button
key={item.id}
data-slot="preview-rail-item"
type="button"
aria-label={item.ariaLabel ?? item.label}
aria-current={selected ? "location" : undefined}
onPointerEnter={handlePointerEnter}
onPointerDown={handlePointerDown}
onPointerCancel={dropGesture}
onKeyDown={dropGesture}
onFocus={(event) => handleFocus(event.currentTarget)}
onClick={handleSelect}
style={sharedStyle}
className={sharedClassName}
>
{itemContent}
</button>
);
})}
</nav>
{showPreview ? (
<div
aria-hidden="true"
style={
isHorizontal
? { gridTemplateColumns: rowTemplate }
: { gridTemplateRows: rowTemplate }
}
className={cn(
"pointer-events-none absolute z-50 grid",
isHorizontal
? "top-1/2 left-1/2 h-5 w-fit max-w-full -translate-x-1/2 -translate-y-1/2 justify-center"
: previewSide === "before"
? "inset-y-0 right-16 left-4 content-center"
: "inset-y-0 right-4 left-16 content-center",
previewContainerClassName,
)}
>
{items.map((item) => (
<div
key={item.id}
style={
isHorizontal ? { width: itemSize } : { height: itemSize }
}
className={cn(
"relative flex items-center",
isHorizontal ? "justify-center" : undefined,
)}
>
{item.id === displayedId ? (
<div
className={cn(
isHorizontal
? "absolute bottom-12 left-1/2 w-72 -translate-x-1/2"
: cn(
"w-full max-w-sm",
previewSide === "before" && "ml-auto",
),
previewClassName,
)}
>
<motion.div
layoutId={`preview-rail-card-${uid}`}
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
>
<AnimatePresence mode="wait" initial={false}>
<motion.div
key={item.id}
initial={
reduce
? { opacity: 0 }
: { opacity: 0, y: 4, filter: "blur(6px)" }
}
animate={
reduce
? { opacity: 1 }
: { opacity: 1, y: 0, filter: "blur(0px)" }
}
exit={
reduce
? { opacity: 0 }
: {
opacity: 0,
y: -2,
filter: "blur(4px)",
transition: {
duration: 0.12,
ease: EASE_OUT,
},
}
}
transition={{
duration: reduce ? 0 : 0.18,
ease: EASE_OUT,
}}
>
{renderPreview ? (
renderPreview(item)
) : (
<DefaultPreview item={item} />
)}
</motion.div>
</AnimatePresence>
</motion.div>
</div>
) : null}
</div>
))}
</div>
) : null}
{children ? (
<div className="min-h-0 min-w-0 flex-1">{children}</div>
) : null}
</motion.div>
);
}
@karaui not found? Add it to components.json
{
"registries": {
"@karaui": "https://karaui.kamisama-v0.my.id/r/{name}.json"
}
}@karaui is in shadcn's public registry directory, so the latest CLI needs no setup. On an older CLI, merge this into the existing file once and every @karaui/… install resolves.
API Reference
copyText?stringPlain text copied by the copy action.
—onCopy?(() => void | Promise<void>)Overrides the built-in clipboard write.
—onRegenerate?(() => void | Promise<void>)Shows the regenerate action. A returned promise keeps the icon spinning.
—feedback?MessageFeedback—defaultFeedback?MessageFeedbacknullonFeedbackChange?((feedback: MessageFeedback) => void)—feedbackReasons?MessageFeedbackReason[]Reasons offered after a thumbs-down. Pass `[]` to skip the popover.
[
{ value: "incorrect", label: "Incorrect" },
{ value: "unhelpful", label: "Not helpful" },
{ value: "incomplete", label: "Incomplete" },
{ value: "instructions", label: "Ignored instructions" },
{ value: "unsafe", label: "Harmful" },
]onFeedbackSubmit?((details: MessageFeedbackDetails) => void)—onShare?(() => void)—moreActions?MessageMoreAction[][]onMoreAction?((value: string) => void)—visibility?"hover" | "always"`hover` reveals the row while the surrounding `Message` / message group is hovered or focused (always visible on touch); `always` keeps it shown — use it for the last message.
hoverclassName?string—Updated