Preview
"use client";
import { RotateCcw } from "lucide-react";
import { useState } from "react";
import {
FileDiff,
type FileDiffLine,
} from "@/components/agents/file-diff";
import { useToolResultDemo } from "./use-tool-result-demo";
const DIFF_LINES: FileDiffLine[] = [
{ id: "1", oldLine: 18, newLine: 18, content: "export async function runTask() {" },
{
id: "2",
type: "removed",
oldLine: 19,
content: " return execute(task);",
},
{
id: "3",
type: "added",
newLine: 19,
content: " const result = await execute(task);",
},
{
id: "4",
type: "added",
newLine: 20,
content: " return normalize(result);",
},
{ id: "5", oldLine: 20, newLine: 21, content: "}" },
];
function FileRun() {
const { visible, status } = useToolResultDemo(DIFF_LINES.length, 360);
return (
<FileDiff
file="src/runner.ts"
lines={DIFF_LINES.slice(0, visible)}
status={status === "success" ? "complete" : "streaming"}
copyText={DIFF_LINES.map((line) => line.content).join("\n")}
maxHeight={150}
/>
);
}
export function FileDiffPreview() {
const [run, setRun] = useState(0);
return (
<div className="relative h-[300px] w-full max-w-lg">
<FileRun key={run} />
<button
type="button"
onClick={() => setRun((value) => value + 1)}
className="absolute bottom-0 left-0 inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 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"
>
<RotateCcw className="size-3" />
Replay
</button>
</div>
);
}
"use client";
// beui.dev/components/agents/file-diff
import {
Check,
ChevronDown,
Copy,
FileCode2,
LoaderCircle,
} from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { type ReactNode, useId, useLayoutEffect, useRef } from "react";
import {
type AgentCodeLanguage,
AgentCodeLine,
useAgentCodeTokens,
} from "@/components/agents/agent-code";
import { AgentDisclosure } from "@/components/agents/agent-disclosure";
import { IconSwap } from "@/components/agents/icon-swap";
import { Tooltip } from "@/components/motion/tooltip";
import { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
const DIFFSTAT_BLOCKS = 5;
// A streamed line settles quickly: lines can arrive many times a second.
const LINE_IN = { duration: 0.18, ease: EASE_OUT } as const;
import { useCopy } from "@/lib/hooks/use-copy";
import { useStatusOpen } from "@/lib/hooks/use-status-open";
import { formatNumber, useLocale, useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export type FileDiffStatus = "streaming" | "complete";
export type FileDiffLineType = "added" | "removed" | "context";
export interface FileDiffLine {
/** Stable key, so streamed lines keep their place. */
id: string;
/** Marks the line added (green, +), removed (red, −) or unchanged. Default: "context" */
type?: FileDiffLineType;
/** Line number in the old file, shown in the first gutter. Blank when not set. */
oldLine?: number;
/** Line number in the new file, shown in the second gutter. Blank when not set. */
newLine?: number;
/** The line's code, without the + or − marker. Syntax highlighted. */
content: string;
}
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const fileDiffMessages = {
applying: "Applying changes",
applied: "Changes applied",
changes: "File changes",
copy: "Copy diff",
copied: "Copied",
};
export type FileDiffMessages = typeof fileDiffMessages;
export interface FileDiffProps {
/** File name or path shown in the header. */
file: ReactNode;
/** Diff lines, each added, removed or context, with optional line numbers. */
lines: FileDiffLine[];
/** "streaming" while lines arrive, "complete" once the edit lands. Default: "streaming" */
status?: FileDiffStatus;
/** Whether the diff is expanded, for controlled use. */
open?: boolean;
/** Whether the diff starts expanded when uncontrolled. Default: true */
defaultOpen?: boolean;
/** Called with the new state when the diff expands or collapses. */
onOpenChange?: (open: boolean) => void;
/** Fold the diff when status moves from streaming to complete. Default: true */
collapseOnComplete?: boolean;
/** Tallest the line viewport grows before it scrolls (px). Default: 220 */
maxHeight?: number;
/** Language used for syntax highlighting. Default: "typescript" */
language?: AgentCodeLanguage;
/** Text the copy button writes to the clipboard. Shows the button when set. */
copyText?: string;
/** Runs instead of the clipboard write when the copy button is pressed. */
onCopy?: () => void | Promise<void>;
/** Override any built-in string. */
labels?: Partial<FileDiffMessages>;
/** Classes merged onto the root element. */
className?: string;
}
function ChangeCount({ value, type }: { value: number; type: "added" | "removed" }) {
const { locale } = useLocale();
if (!value) return null;
return (
<span
className={cn(
"font-mono text-xs tabular-nums",
type === "added"
? "text-emerald-600 dark:text-emerald-400"
: "text-rose-600 dark:text-rose-400",
)}
>
{type === "added" ? "+" : "−"}
{formatNumber(value, locale)}
</span>
);
}
/**
* Five blocks split between additions and deletions, so the size and shape
* of the change reads at a glance. The counts beside it carry the numbers.
*/
function DiffStat({ additions, deletions }: { additions: number; deletions: number }) {
const total = additions + deletions;
if (!total) return null;
const added = Math.round((additions / total) * DIFFSTAT_BLOCKS);
return (
<span aria-hidden="true" className="flex shrink-0 gap-0.5">
{Array.from({ length: DIFFSTAT_BLOCKS }, (_, index) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: fixed blocks
key={index}
className={cn(
"size-1.5 rounded-[2px] transition-colors duration-200",
index < added ? "bg-emerald-500" : "bg-rose-500",
)}
/>
))}
</span>
);
}
export function FileDiff({
file,
lines,
status = "streaming",
open,
defaultOpen = true,
onOpenChange,
collapseOnComplete = true,
maxHeight = 220,
language = "typescript",
copyText,
onCopy,
labels,
className,
}: FileDiffProps) {
const t = useMessages("fileDiff", fileDiffMessages, labels);
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const triggerId = `${baseId}-trigger`;
const contentId = `${baseId}-content`;
const viewportRef = useRef<HTMLDivElement>(null);
const { copied, copy: handleCopy } = useCopy({ text: copyText, onCopy });
// Opens when streaming starts; folds when it completes, if asked to.
const [currentOpen, setOpen] = useStatusOpen({
status,
open,
defaultOpen,
onOpenChange,
decide: (previous, next) => {
if (previous !== "streaming" && next === "streaming") return true;
if (previous === "streaming" && next === "complete" && collapseOnComplete) return false;
return undefined;
},
});
const streaming = status === "streaming";
const additions = lines.filter((line) => line.type === "added").length;
const deletions = lines.filter((line) => line.type === "removed").length;
const canCopy = Boolean(copyText || onCopy);
const code = lines.map((line) => line.content).join("\n");
const tokens = useAgentCodeTokens(code, language);
useLayoutEffect(() => {
const viewport = viewportRef.current;
if (!viewport || !currentOpen || !streaming) return;
const frame = requestAnimationFrame(() => {
if (viewport.scrollHeight <= viewport.clientHeight) return;
if (typeof viewport.scrollTo === "function") {
viewport.scrollTo({
top: viewport.scrollHeight,
behavior: reduce ? "auto" : "smooth",
});
} else {
viewport.scrollTop = viewport.scrollHeight;
}
});
return () => cancelAnimationFrame(frame);
});
return (
<div
data-state={status}
aria-busy={streaming}
className={cn("w-full text-sm", className)}
>
<button
id={triggerId}
type="button"
aria-expanded={currentOpen}
aria-controls={contentId}
onClick={() => setOpen(!currentOpen)}
className="group flex min-h-9 w-full items-center gap-2 rounded-full py-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<FileCode2
aria-hidden="true"
className="size-4 shrink-0 text-muted-foreground"
/>
<span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground/80">
{file}
</span>
<span className="flex shrink-0 items-center gap-2">
<ChangeCount value={additions} type="added" />
<ChangeCount value={deletions} type="removed" />
<DiffStat additions={additions} deletions={deletions} />
</span>
<span className="grid size-4 shrink-0 place-items-center text-muted-foreground/60">
<IconSwap id={streaming ? "applying" : "applied"}>
{streaming ? (
<LoaderCircle
aria-label={t("applying")}
className={cn("size-3.5", !reduce && "animate-spin")}
/>
) : (
<Check aria-label={t("applied")} className="size-3.5" />
)}
</IconSwap>
</span>
<motion.span
aria-hidden="true"
animate={{ rotate: currentOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="shrink-0 text-muted-foreground/45 transition-colors group-hover:text-muted-foreground"
>
<ChevronDown className="size-3.5" />
</motion.span>
</button>
<AgentDisclosure
id={contentId}
role="region"
aria-labelledby={triggerId}
open={currentOpen}
>
<div className="pl-6 pt-1.5">
<div className="group/diff relative overflow-hidden rounded-xl bg-muted/80">
<div
ref={viewportRef}
data-slot="file-diff-viewport"
aria-live="polite"
className="scrollbar-hide overflow-auto"
style={{ maxHeight }}
>
<div className="font-mono text-xs leading-5">
<span className="sr-only">{t("changes")}</span>
{/* Lines that stream in fade in, opacity only: a moving line
fights the auto-scroll that follows the stream. Lines
already there when the diff mounts are simply shown. */}
<AnimatePresence initial={false}>
{lines.map((line, index) => {
const type = line.type ?? "context";
// A streamed line waits for its syntax colours before it
// shows: shown at once, it would flash as plain text and
// then recolour mid-fade. Before the highlighter has run at
// all (`tokens` null), lines show plain.
const ready = tokens === null || Boolean(tokens[index]);
return (
<motion.div
key={line.id}
initial={{ opacity: 0 }}
animate={{ opacity: ready ? 1 : 0 }}
transition={LINE_IN}
className={cn(
"grid grid-cols-[2.25rem_2.25rem_1rem_minmax(0,1fr)]",
// A tint plus a 2px edge: the edge still marks the
// line where a faint tint melts into the panel.
type === "added" &&
"bg-emerald-500/10 shadow-[inset_2px_0_0_var(--color-emerald-500)]",
type === "removed" &&
"bg-rose-500/10 shadow-[inset_2px_0_0_var(--color-rose-500)]",
)}
>
<span className="select-none pr-2 text-right tabular-nums text-muted-foreground/40">
{line.oldLine}
</span>
<span className="select-none pr-2 text-right tabular-nums text-muted-foreground/40">
{line.newLine}
</span>
<span
className={cn(
"select-none text-center text-muted-foreground/45",
type === "added" &&
"text-emerald-600 dark:text-emerald-400",
type === "removed" &&
"text-rose-600 dark:text-rose-400",
)}
>
{type === "added"
? "+"
: type === "removed"
? "−"
: ""}
</span>
<AgentCodeLine
code={line.content}
tokens={tokens?.[index]}
className="min-w-0 whitespace-pre px-1.5"
/>
</motion.div>
);
})}
</AnimatePresence>
</div>
</div>
{canCopy ? (
// Floats in the corner instead of taking a row of its own. It
// shows on hover or focus where there is a pointer, always on
// touch, and stays while "Copied" is showing.
<div
className={cn(
"absolute top-1.5 right-1.5 transition-opacity duration-150 group-focus-within/diff:opacity-100 group-hover/diff:opacity-100 [@media(hover:none)]:opacity-100",
copied ? "opacity-100" : "opacity-0",
)}
>
<Tooltip content={copied ? t("copied") : t("copy")} side="top">
<motion.button
type="button"
aria-label={copied ? t("copied") : t("copy")}
onClick={handleCopy}
whileTap={reduce ? undefined : { scale: 0.95 }}
transition={SPRING_PRESS}
className="grid size-7 place-items-center rounded-full border border-border bg-background text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<IconSwap id={copied ? "copied" : "copy"}>
{copied ? (
<Check className="size-3.5" />
) : (
<Copy className="size-3.5" />
)}
</IconSwap>
</motion.button>
</Tooltip>
</div>
) : null}
</div>
</div>
</AgentDisclosure>
</div>
);
}
Add it with the shadcn CLI, or copy the source manually.
npx shadcn add https://beui.dev/r/theme.json. Theme setupInstall dependencies
npm i @floating-ui/dom clsx lucide-react motion shiki tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */
export const EASE_IN = [0.55, 0, 1, 0.45] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps - label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances - modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides - pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) - critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
/** Shared-surface morphs: a trigger growing into its panel and back on one
* weighted spring, so opening and closing travel the same path. */
export const SPRING_MORPH = {
type: "spring",
duration: 0.5,
bounce: 0.22,
} as const;
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
/** How long the copied state holds after a copy, in ms. */
const COPIED_MS = 1600;
/**
* A copy action and a `copied` flag that holds for a moment after it works.
*
* `copy` runs `onCopy` when given, else writes `text` to the clipboard. The
* flag turns on only once that succeeded: no clipboard (an insecure origin),
* a refused write or a throwing `onCopy` leave it off rather than claiming a
* copy that never happened.
*/
export function useCopy({
text,
onCopy,
}: {
text?: string;
onCopy?: () => void | Promise<void>;
}) {
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
const copy = useCallback(async () => {
try {
if (onCopy) await onCopy();
else if (text !== undefined && navigator.clipboard) {
await navigator.clipboard.writeText(text);
} else return;
} catch {
return;
}
setCopied(true);
clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(false), COPIED_MS);
}, [onCopy, text]);
return { copied, copy };
}
"use client";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useControllable } from "@/lib/hooks/use-controllable";
/**
* Open state for a disclosure that opens or closes itself when a status
* changes: a tool result that opens while it runs, a todo list that folds
* when the work completes. Controlled through `open`, or uncontrolled from
* `defaultOpen`.
*
* `decide(previous, next)` runs in the render that first sees a new status
* and returns `true` to open, `false` to close, or `undefined` to leave it.
* An uncontrolled panel flips in that same render, so it never shows one
* commit in the old state. Telling the consumer through `onOpenChange` is a
* side effect, so it waits for the commit.
*/
export function useStatusOpen<Status>({
status,
initialStatus = status,
decide,
open,
defaultOpen,
onOpenChange,
}: {
status: Status;
/**
* The status to treat as already seen at mount. Defaults to `status`, so
* mounting is not a change; pass another value to let the first render
* count as one.
*/
initialStatus?: Status;
decide: (previous: Status, next: Status) => boolean | undefined;
open?: boolean;
defaultOpen: boolean;
onOpenChange?: (open: boolean) => void;
}) {
const [currentOpen, setOpen, setInternal] = useControllable(open, defaultOpen, onOpenChange);
const [seenStatus, setSeenStatus] = useState(initialStatus);
const [request, setRequest] = useState<{ open: boolean; from: boolean } | null>(null);
if (status !== seenStatus) {
setSeenStatus(status);
const wanted = decide(seenStatus, status);
if (wanted !== undefined) {
if (open === undefined) setInternal(wanted);
setRequest({ open: wanted, from: currentOpen });
}
}
const notify = useRef(onOpenChange);
useLayoutEffect(() => {
notify.current = onOpenChange;
});
useEffect(() => {
if (request && request.open !== request.from) notify.current?.(request.open);
}, [request]);
return [currentOpen, setOpen] as const;
}
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useMemo,
} from "react";
/**
* A component's messages. Plain strings with `{name}` placeholders, so a
* dictionary stays JSON-serializable and can be passed from a server layout.
* There are no plural forms: write messages that read correctly for any count.
*/
export type Messages = Record<string, string>;
/** A language file: component namespace → any subset of that component's messages. */
export type LocaleMessages = Record<string, Partial<Messages>>;
type LocaleContextValue = {
locale?: string;
messages: LocaleMessages;
};
const NO_MESSAGES: LocaleMessages = {};
const LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });
/** Without a locale, digits stay plain so server and client render the same text. */
export function formatNumber(value: number, locale?: string) {
return locale ? new Intl.NumberFormat(locale).format(value) : String(value);
}
export interface LocaleProviderProps {
/** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */
locale: string;
/**
* Component namespace → translated strings. Missing keys fall back to English.
* Pass a stable object (a module constant, imported JSON or a memoized value):
* a new object each render gives every translated component a new `t`.
*/
messages?: LocaleMessages;
children: ReactNode;
}
export function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {
const value = useMemo(() => ({ locale, messages }), [locale, messages]);
return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;
}
export function useLocale(): { locale?: string } {
return { locale: useContext(LocaleContext).locale };
}
/**
* Resolves a component's strings: `labels` prop, then the provider's
* messages for `namespace`, then the component's English `defaults`.
* Numbers passed as values are formatted for the provider's locale.
*/
export function useMessages<T extends Messages>(
namespace: string,
defaults: T,
labels?: Partial<T>,
) {
const { locale, messages } = useContext(LocaleContext);
const provided = messages[namespace];
// Inline `labels={{ … }}` is a new object every render. Keying it by content
// keeps `t` one identity until a label changes, so effects and memos that
// depend on `t` don't re-run per render, and render-time reads never lag.
const labelsKey = labels ? JSON.stringify(labels) : "";
const stableLabels = useMemo(
() => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),
[labelsKey],
);
return useCallback(
(key: keyof T & string, values?: Record<string, string | number>) => {
const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];
if (!values) return template;
return template.replace(/\{(\w+)\}/g, (match, name: string) => {
const value = values[name];
if (value === undefined) return match;
return typeof value === "number" ? formatNumber(value, locale) : value;
});
},
[defaults, stableLabels, locale, provided],
);
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
"use client";
import { type RefObject, useEffect, useLayoutEffect, useRef } from "react";
import { inOtherLayer, type Layer, openLayer, ownsEscape } from "@/lib/layers";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident - the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */
export type DismissReason = "escape" | "pointer" | "focus";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */
focusOutside?: boolean;
/**
* Dismiss on a pointerdown outside. Default true. Turn it off for an overlay
* whose own backdrop handles presses and only needs Escape and layering.
*/
outsidePress?: boolean;
/** Return true for an outside target that should *not* dismiss. */
ignore?: (target: Element) => boolean;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it - the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over.
*
* Each open dismissal is a layer in `lib/layers.ts`, so only the innermost
* open overlay answers Escape (a menu inside a drawer closes, the drawer
* stays), and a drawer's focus trap leaves focus in a menu it portaled out.
*/
export function useDismiss(
open: boolean,
onDismiss: (reason: DismissReason) => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
focusOutside = false,
outsidePress = true,
ignore,
}: DismissOptions = {},
) {
// Read through refs, so a callback rebuilt each render neither re-binds the
// listeners nor moves this layer to the top of the stack.
const dismissRef = useRef(onDismiss);
const ignoreRef = useRef(ignore);
useLayoutEffect(() => {
dismissRef.current = onDismiss;
ignoreRef.current = ignore;
});
useEffect(() => {
if (!open) return;
const inside = (target: Node) =>
Boolean(ref?.current?.contains(target)) ||
(target instanceof Element && Boolean(ignoreRef.current?.(target)));
const layer: Layer = { contains: inside, escape: dismissOnEscape };
const closeLayer = openLayer(layer);
const onKey = (event: KeyboardEvent) => {
if (!dismissOnEscape || event.key !== "Escape" || !ownsEscape(layer, event)) return;
event.preventDefault();
dismissRef.current("escape");
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside another open one: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !inOtherLayer(layer, target, { traps: false })) {
consumeActivation(event);
}
dismissRef.current("pointer");
};
const onFocus = (event: FocusEvent) => {
const target = event.target;
if (target instanceof Node && !inside(target)) dismissRef.current("focus");
};
window.addEventListener("keydown", onKey);
if (outsidePress) window.addEventListener("pointerdown", onPointer, true);
if (focusOutside) window.addEventListener("focusin", onFocus);
return () => {
closeLayer();
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
window.removeEventListener("focusin", onFocus);
};
}, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);
}
"use client";
import { useMemo, useRef } from "react";
import { isHoveringPointer } from "@/lib/touch";
interface BoundaryEvent {
pointerId: number;
pointerType: string;
buttons: number;
}
export interface HoverGesture {
/** True when this enter starts a hover: the pointer arrived resting, not pressing. */
enter: (event: BoundaryEvent) => boolean;
/** True when this leave ends a hover that entered as one. */
leave: (event: BoundaryEvent) => boolean;
}
/**
* Pairs a surface's enter with its leave, per pointer.
*
* `isHoveringPointer` answers the question the *enter* asks - is this pointer
* resting on the surface or pressing it - and both boundary cases go wrong if
* the leave is asked the same question again:
*
* - A pen with no hover never rests. It arrives in contact, taps, and the spec
* then requires its boundary events after `pointerup`, so the leave carries
* `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid
* the tap - the panel the pen had just opened closed under it.
* - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.
* Skipping teardown there strands the surface open: the release happens
* outside, and no second leave ever comes.
*
* So the state a hover holds is released by the pointer that took it, whatever
* the buttons say at the boundary, and a pointer that arrived in contact never
* took it in the first place. Contact is the exception tracked here, not
* hover: a leave from a pointer this surface never saw enter - mounted under
* the cursor, say - still counts, since the alternative is state with no way
* out.
*/
export function useHoverGesture(): HoverGesture {
const contact = useRef(new Set<number>());
return useMemo(
() => ({
enter: (event) => {
if (isHoveringPointer(event)) {
contact.current.delete(event.pointerId);
return true;
}
contact.current.add(event.pointerId);
return false;
},
leave: (event) => {
const arrivedInContact = contact.current.delete(event.pointerId);
return !arrivedInContact && event.pointerType !== "touch";
},
}),
[],
);
}
"use client";
import { useMemo, useRef } from "react";
/** What a pointerdown recorded, read back by the click that ends its gesture. */
export interface TapRecord<S> {
/** Which input started the gesture. */
pointerType: string;
/** What the surface was showing when it started. */
state: S;
}
export interface TapGesture<S> {
/** Record the gesture a pointerdown starts, with the state it starts in. */
start: (event: { pointerType: string }, state: S) => void;
/** Read the record and clear it. `null` when no pointer is behind this click. */
take: () => TapRecord<S> | null;
/** Drop the record: this gesture will never spend it on a click. */
drop: () => void;
}
/**
* The pointer gesture behind a click, recorded where the click cannot report
* it. A `click` carries no `pointerType` in the engines that matter, so the
* `pointerdown` before it is the only thing that says which input activated
* the control - and whether one did at all, since keyboard activation
* synthesizes a click with no pointer behind it.
*
* State goes in with the record because a click reports that no better: a
* browser that focuses a control on contact can open the very panel the tap
* was meant to open, and reading "is it open" at click time then undoes it.
* What the gesture started against is what it acts on.
*
* The record is spent by one click and dropped by everything else, because a
* record that outlives its gesture is worse than none:
*
* - A scroll or an OS gesture takes the touch away - `pointercancel`, no click
* ever - and the finger would sit in the record until some later click.
* - That later click is often `Enter` on a keyboard, which arrives with no
* pointerdown of its own and would inherit the abandoned finger. A keydown
* is the start of a keyboard activation and never part of a tap, so it drops
* the record too.
*
* Both ends have to be wired by the surface: `drop` on `onPointerCancel` and
* on `onKeyDown`.
*/
export function useTapGesture<S>(): TapGesture<S> {
const record = useRef<TapRecord<S> | null>(null);
return useMemo(
() => ({
start: (event, state) => {
record.current = { pointerType: event.pointerType, state };
},
take: () => {
const spent = record.current;
record.current = null;
return spent;
},
drop: () => {
record.current = null;
},
}),
[],
);
}
import type { Ref } from "react";
/** Points a callback or object ref at `value`. */
export function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
if (typeof ref === "function") ref(value);
else if (ref) ref.current = value;
}
/** One callback ref that sets every ref it is given. */
export function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {
return (node: T | null) => {
for (const ref of refs) assignRef(ref, node);
};
}
"use client";
import { useCallback, useLayoutEffect, useRef, useState } from "react";
/**
* A value that is controlled when `value` is defined and uncontrolled
* otherwise. Returns the current value, a setter whose identity never changes,
* and the raw internal setter for callers that resolve state during render.
*
* The setter calls `onChange` only when the value actually changes, so a
* consumer is never told about a no-op.
*/
export function useControllable<T>(
value: T | undefined,
defaultValue: T,
onChange?: (next: T) => void,
) {
const [internal, setInternal] = useState(defaultValue);
const latest = useRef({ value, internal, onChange });
useLayoutEffect(() => {
latest.current = { value, internal, onChange };
});
const set = useCallback((next: T) => {
const current = latest.current;
if (current.value === undefined) setInternal(next);
if ((current.value === undefined ? current.internal : current.value) !== next)
current.onChange?.(next);
}, []);
return [value === undefined ? internal : value, set, setInternal] as const;
}
/**
* Every open overlay on the page, innermost last: focus traps, modal scopes
* and dismissable menus all register here. Overlays have no shared z-order to
* consult, and a menu inside a drawer portals out of it, so this stack is how
* they agree on who answers Escape and where focus may go.
*/
export interface Layer {
/** Whether `target` belongs to this layer (its panel, portals, trigger). */
contains: (target: Node) => boolean;
/** True for focus traps and modal scopes, which pull stray focus back. */
traps?: boolean;
/** False for a layer that ignores Escape, so the key reaches the one below. */
escape?: boolean;
}
const stack: Layer[] = [];
// The innermost layer when each Escape began, read before any handler runs,
// so a layer that closes itself mid-event can't hand the key to the one below.
const escapeOwners = new WeakMap<Event, Layer | undefined>();
let listening = false;
function innermostEscapeLayer() {
for (let index = stack.length - 1; index >= 0; index--) {
if (stack[index].escape !== false) return stack[index];
}
return undefined;
}
function recordEscapeOwner(event: KeyboardEvent) {
if (event.key === "Escape") escapeOwners.set(event, innermostEscapeLayer());
}
/** Registers an open layer. Call the returned function when it closes. */
export function openLayer(layer: Layer) {
if (!listening) {
document.addEventListener("keydown", recordEscapeOwner, true);
listening = true;
}
stack.push(layer);
return () => {
const index = stack.indexOf(layer);
if (index !== -1) stack.splice(index, 1);
};
}
/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */
export function ownsEscape(layer: Layer, event: KeyboardEvent) {
if (event.defaultPrevented) return false;
const owner = escapeOwners.has(event)
? escapeOwners.get(event)
: innermostEscapeLayer();
return owner === layer;
}
/** Whether `target` sits in a layer opened on top of `layer`. */
export function inLayerAbove(layer: Layer, target: Node) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.contains(target));
}
/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */
export function trapAbove(layer: Layer) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.traps);
}
/**
* Whether `target` belongs to any open layer other than `layer`. Pass
* `traps: false` to count only dismissable overlays, not the traps under them.
*/
export function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {
return stack.some(
(other) => other !== layer && (traps || !other.traps) && other.contains(target),
);
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page - the long-press selection callout and the selection it drags in with
// it - and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant - which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing - the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis - leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures - a coarse
* pointer - so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction - the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal - a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs - routine on iOS, where the
* system can claim the touch first - and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active - implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer - a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger - so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it - `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
Copy the source code
"use client";
// beui.dev/components/agents/file-diff
import {
Check,
ChevronDown,
Copy,
FileCode2,
LoaderCircle,
} from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { type ReactNode, useId, useLayoutEffect, useRef } from "react";
import {
type AgentCodeLanguage,
AgentCodeLine,
useAgentCodeTokens,
} from "@/components/agents/agent-code";
import { AgentDisclosure } from "@/components/agents/agent-disclosure";
import { IconSwap } from "@/components/agents/icon-swap";
import { Tooltip } from "@/components/motion/tooltip";
import { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
const DIFFSTAT_BLOCKS = 5;
// A streamed line settles quickly: lines can arrive many times a second.
const LINE_IN = { duration: 0.18, ease: EASE_OUT } as const;
import { useCopy } from "@/lib/hooks/use-copy";
import { useStatusOpen } from "@/lib/hooks/use-status-open";
import { formatNumber, useLocale, useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export type FileDiffStatus = "streaming" | "complete";
export type FileDiffLineType = "added" | "removed" | "context";
export interface FileDiffLine {
/** Stable key, so streamed lines keep their place. */
id: string;
/** Marks the line added (green, +), removed (red, −) or unchanged. Default: "context" */
type?: FileDiffLineType;
/** Line number in the old file, shown in the first gutter. Blank when not set. */
oldLine?: number;
/** Line number in the new file, shown in the second gutter. Blank when not set. */
newLine?: number;
/** The line's code, without the + or − marker. Syntax highlighted. */
content: string;
}
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const fileDiffMessages = {
applying: "Applying changes",
applied: "Changes applied",
changes: "File changes",
copy: "Copy diff",
copied: "Copied",
};
export type FileDiffMessages = typeof fileDiffMessages;
export interface FileDiffProps {
/** File name or path shown in the header. */
file: ReactNode;
/** Diff lines, each added, removed or context, with optional line numbers. */
lines: FileDiffLine[];
/** "streaming" while lines arrive, "complete" once the edit lands. Default: "streaming" */
status?: FileDiffStatus;
/** Whether the diff is expanded, for controlled use. */
open?: boolean;
/** Whether the diff starts expanded when uncontrolled. Default: true */
defaultOpen?: boolean;
/** Called with the new state when the diff expands or collapses. */
onOpenChange?: (open: boolean) => void;
/** Fold the diff when status moves from streaming to complete. Default: true */
collapseOnComplete?: boolean;
/** Tallest the line viewport grows before it scrolls (px). Default: 220 */
maxHeight?: number;
/** Language used for syntax highlighting. Default: "typescript" */
language?: AgentCodeLanguage;
/** Text the copy button writes to the clipboard. Shows the button when set. */
copyText?: string;
/** Runs instead of the clipboard write when the copy button is pressed. */
onCopy?: () => void | Promise<void>;
/** Override any built-in string. */
labels?: Partial<FileDiffMessages>;
/** Classes merged onto the root element. */
className?: string;
}
function ChangeCount({ value, type }: { value: number; type: "added" | "removed" }) {
const { locale } = useLocale();
if (!value) return null;
return (
<span
className={cn(
"font-mono text-xs tabular-nums",
type === "added"
? "text-emerald-600 dark:text-emerald-400"
: "text-rose-600 dark:text-rose-400",
)}
>
{type === "added" ? "+" : "−"}
{formatNumber(value, locale)}
</span>
);
}
/**
* Five blocks split between additions and deletions, so the size and shape
* of the change reads at a glance. The counts beside it carry the numbers.
*/
function DiffStat({ additions, deletions }: { additions: number; deletions: number }) {
const total = additions + deletions;
if (!total) return null;
const added = Math.round((additions / total) * DIFFSTAT_BLOCKS);
return (
<span aria-hidden="true" className="flex shrink-0 gap-0.5">
{Array.from({ length: DIFFSTAT_BLOCKS }, (_, index) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: fixed blocks
key={index}
className={cn(
"size-1.5 rounded-[2px] transition-colors duration-200",
index < added ? "bg-emerald-500" : "bg-rose-500",
)}
/>
))}
</span>
);
}
export function FileDiff({
file,
lines,
status = "streaming",
open,
defaultOpen = true,
onOpenChange,
collapseOnComplete = true,
maxHeight = 220,
language = "typescript",
copyText,
onCopy,
labels,
className,
}: FileDiffProps) {
const t = useMessages("fileDiff", fileDiffMessages, labels);
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const triggerId = `${baseId}-trigger`;
const contentId = `${baseId}-content`;
const viewportRef = useRef<HTMLDivElement>(null);
const { copied, copy: handleCopy } = useCopy({ text: copyText, onCopy });
// Opens when streaming starts; folds when it completes, if asked to.
const [currentOpen, setOpen] = useStatusOpen({
status,
open,
defaultOpen,
onOpenChange,
decide: (previous, next) => {
if (previous !== "streaming" && next === "streaming") return true;
if (previous === "streaming" && next === "complete" && collapseOnComplete) return false;
return undefined;
},
});
const streaming = status === "streaming";
const additions = lines.filter((line) => line.type === "added").length;
const deletions = lines.filter((line) => line.type === "removed").length;
const canCopy = Boolean(copyText || onCopy);
const code = lines.map((line) => line.content).join("\n");
const tokens = useAgentCodeTokens(code, language);
useLayoutEffect(() => {
const viewport = viewportRef.current;
if (!viewport || !currentOpen || !streaming) return;
const frame = requestAnimationFrame(() => {
if (viewport.scrollHeight <= viewport.clientHeight) return;
if (typeof viewport.scrollTo === "function") {
viewport.scrollTo({
top: viewport.scrollHeight,
behavior: reduce ? "auto" : "smooth",
});
} else {
viewport.scrollTop = viewport.scrollHeight;
}
});
return () => cancelAnimationFrame(frame);
});
return (
<div
data-state={status}
aria-busy={streaming}
className={cn("w-full text-sm", className)}
>
<button
id={triggerId}
type="button"
aria-expanded={currentOpen}
aria-controls={contentId}
onClick={() => setOpen(!currentOpen)}
className="group flex min-h-9 w-full items-center gap-2 rounded-full py-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<FileCode2
aria-hidden="true"
className="size-4 shrink-0 text-muted-foreground"
/>
<span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground/80">
{file}
</span>
<span className="flex shrink-0 items-center gap-2">
<ChangeCount value={additions} type="added" />
<ChangeCount value={deletions} type="removed" />
<DiffStat additions={additions} deletions={deletions} />
</span>
<span className="grid size-4 shrink-0 place-items-center text-muted-foreground/60">
<IconSwap id={streaming ? "applying" : "applied"}>
{streaming ? (
<LoaderCircle
aria-label={t("applying")}
className={cn("size-3.5", !reduce && "animate-spin")}
/>
) : (
<Check aria-label={t("applied")} className="size-3.5" />
)}
</IconSwap>
</span>
<motion.span
aria-hidden="true"
animate={{ rotate: currentOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="shrink-0 text-muted-foreground/45 transition-colors group-hover:text-muted-foreground"
>
<ChevronDown className="size-3.5" />
</motion.span>
</button>
<AgentDisclosure
id={contentId}
role="region"
aria-labelledby={triggerId}
open={currentOpen}
>
<div className="pl-6 pt-1.5">
<div className="group/diff relative overflow-hidden rounded-xl bg-muted/80">
<div
ref={viewportRef}
data-slot="file-diff-viewport"
aria-live="polite"
className="scrollbar-hide overflow-auto"
style={{ maxHeight }}
>
<div className="font-mono text-xs leading-5">
<span className="sr-only">{t("changes")}</span>
{/* Lines that stream in fade in, opacity only: a moving line
fights the auto-scroll that follows the stream. Lines
already there when the diff mounts are simply shown. */}
<AnimatePresence initial={false}>
{lines.map((line, index) => {
const type = line.type ?? "context";
// A streamed line waits for its syntax colours before it
// shows: shown at once, it would flash as plain text and
// then recolour mid-fade. Before the highlighter has run at
// all (`tokens` null), lines show plain.
const ready = tokens === null || Boolean(tokens[index]);
return (
<motion.div
key={line.id}
initial={{ opacity: 0 }}
animate={{ opacity: ready ? 1 : 0 }}
transition={LINE_IN}
className={cn(
"grid grid-cols-[2.25rem_2.25rem_1rem_minmax(0,1fr)]",
// A tint plus a 2px edge: the edge still marks the
// line where a faint tint melts into the panel.
type === "added" &&
"bg-emerald-500/10 shadow-[inset_2px_0_0_var(--color-emerald-500)]",
type === "removed" &&
"bg-rose-500/10 shadow-[inset_2px_0_0_var(--color-rose-500)]",
)}
>
<span className="select-none pr-2 text-right tabular-nums text-muted-foreground/40">
{line.oldLine}
</span>
<span className="select-none pr-2 text-right tabular-nums text-muted-foreground/40">
{line.newLine}
</span>
<span
className={cn(
"select-none text-center text-muted-foreground/45",
type === "added" &&
"text-emerald-600 dark:text-emerald-400",
type === "removed" &&
"text-rose-600 dark:text-rose-400",
)}
>
{type === "added"
? "+"
: type === "removed"
? "−"
: ""}
</span>
<AgentCodeLine
code={line.content}
tokens={tokens?.[index]}
className="min-w-0 whitespace-pre px-1.5"
/>
</motion.div>
);
})}
</AnimatePresence>
</div>
</div>
{canCopy ? (
// Floats in the corner instead of taking a row of its own. It
// shows on hover or focus where there is a pointer, always on
// touch, and stays while "Copied" is showing.
<div
className={cn(
"absolute top-1.5 right-1.5 transition-opacity duration-150 group-focus-within/diff:opacity-100 group-hover/diff:opacity-100 [@media(hover:none)]:opacity-100",
copied ? "opacity-100" : "opacity-0",
)}
>
<Tooltip content={copied ? t("copied") : t("copy")} side="top">
<motion.button
type="button"
aria-label={copied ? t("copied") : t("copy")}
onClick={handleCopy}
whileTap={reduce ? undefined : { scale: 0.95 }}
transition={SPRING_PRESS}
className="grid size-7 place-items-center rounded-full border border-border bg-background text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<IconSwap id={copied ? "copied" : "copy"}>
{copied ? (
<Check className="size-3.5" />
) : (
<Copy className="size-3.5" />
)}
</IconSwap>
</motion.button>
</Tooltip>
</div>
) : null}
</div>
</div>
</AgentDisclosure>
</div>
);
}
"use client";
import {
type CSSProperties,
Fragment,
useEffect,
useState,
} from "react";
import { createHighlighter, type Highlighter } from "shiki";
import { cn } from "@/lib/utils";
export type AgentCodeLanguage =
| "bash"
| "diff"
| "json"
| "text"
| "tsx"
| "typescript";
export interface AgentCodeToken {
content: string;
offset: number;
light?: string;
dark?: string;
}
export type AgentCodeTokenLines = AgentCodeToken[][];
export interface AgentCodeProps {
code: string;
language?: AgentCodeLanguage;
className?: string;
}
export interface AgentCodeLineProps {
code: string;
tokens?: AgentCodeToken[];
className?: string;
}
const LIGHT_THEME = "github-light-high-contrast";
const DARK_THEME = "github-dark-high-contrast";
let agentCodeHighlighter: Promise<Highlighter> | null = null;
// Streamed code changes on every chunk, and each version is a new key, so the
// cache keeps only the most recently used entries.
const TOKEN_CACHE_LIMIT = 50;
const tokenCache = new Map<string, AgentCodeTokenLines>();
function readTokens(key: string) {
const lines = tokenCache.get(key);
if (lines) {
tokenCache.delete(key);
tokenCache.set(key, lines);
}
return lines;
}
function storeTokens(key: string, lines: AgentCodeTokenLines) {
tokenCache.delete(key);
tokenCache.set(key, lines);
while (tokenCache.size > TOKEN_CACHE_LIMIT) {
const oldest = tokenCache.keys().next().value;
if (oldest === undefined) break;
tokenCache.delete(oldest);
}
}
function getAgentCodeHighlighter() {
if (!agentCodeHighlighter) {
agentCodeHighlighter = createHighlighter({
themes: [LIGHT_THEME, DARK_THEME],
langs: ["bash", "diff", "json", "tsx", "typescript"],
});
// A failed load is not kept, so the next block tries again.
agentCodeHighlighter.catch(() => {
agentCodeHighlighter = null;
});
}
return agentCodeHighlighter;
}
function tokenCacheKey(code: string, language: AgentCodeLanguage) {
return `${language}\u0000${code}`;
}
export function useAgentCodeTokens(
code: string,
language: AgentCodeLanguage,
) {
const key = tokenCacheKey(code, language);
const cached = tokenCache.get(key);
const [result, setResult] = useState<{
key: string;
code: string;
language: AgentCodeLanguage;
lines: AgentCodeTokenLines;
} | null>(cached ? { key, code, language, lines: cached } : null);
useEffect(() => {
const current = readTokens(key);
if (current) {
setResult({ key, code, language, lines: current });
return;
}
let cancelled = false;
getAgentCodeHighlighter().then((highlighter) => {
if (cancelled) return;
const lines = highlighter
.codeToTokensWithThemes(code, {
lang: language,
themes: {
light: LIGHT_THEME,
dark: DARK_THEME,
},
})
.map((line) =>
line.map((token) => ({
content: token.content,
offset: token.offset,
light: token.variants.light?.color,
dark: token.variants.dark?.color,
})),
);
storeTokens(key, lines);
setResult({ key, code, language, lines });
}, () => {
// Highlighting is decoration: the code still renders as plain text.
});
return () => {
cancelled = true;
};
}, [code, key, language]);
if (result?.key === key) return result.lines;
if (result?.language === language && code.startsWith(result.code)) {
return result.lines;
}
return null;
}
export function AgentCodeLine({
code,
tokens,
className,
}: AgentCodeLineProps) {
// While code streams, the tokens can lag a few characters behind the line.
// Keep the coloured part and show the new characters plain after it: the
// text is always current, and nothing already coloured flashes back to plain.
const tokenText = tokens?.map((token) => token.content).join("") ?? "";
const usable = tokens && code.startsWith(tokenText) ? tokens : undefined;
const rest = usable ? code.slice(tokenText.length) : "";
return (
<span className={className}>
{usable
? usable.map((token) => (
<span
key={`${token.offset}-${token.content}`}
style={
{
"--agent-code-light": token.light ?? "currentColor",
"--agent-code-dark": token.dark ?? token.light ?? "currentColor",
} as CSSProperties
}
className="text-[var(--agent-code-light)] dark:text-[var(--agent-code-dark)]"
>
{token.content}
</span>
))
: code}
{rest}
</span>
);
}
export function AgentCode({
code,
language = "bash",
className,
}: AgentCodeProps) {
const tokens = useAgentCodeTokens(code, language);
let offset = 0;
const lines = code.split("\n").map((content) => {
const line = { content, offset };
offset += content.length + 1;
return line;
});
return (
<pre
className={cn(
"m-0 overflow-x-auto whitespace-pre font-mono text-xs leading-5 text-foreground/85",
className,
)}
>
<code>
{lines.map((line, index) => (
<Fragment key={line.offset}>
<AgentCodeLine code={line.content} tokens={tokens?.[index]} />
{index < lines.length - 1 ? "\n" : null}
</Fragment>
))}
</code>
</pre>
);
}
"use client";
import { motion, type HTMLMotionProps, useReducedMotion } from "motion/react";
import { type CSSProperties, useState } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface AgentDisclosureProps
extends Omit<HTMLMotionProps<"div">, "animate" | "initial"> {
open: boolean;
openHeight?: CSSProperties["height"];
}
/**
* Shared reveal for collapsible agent content: a clip, fade and short drop,
* never an animated height. The box takes its height as soon as it opens and
* gives it up only once the closing reveal has played, so the exit is seen
* and mirrors the entrance.
*/
export function AgentDisclosure({
open,
openHeight = "auto",
className,
style,
transition,
onAnimationComplete,
...props
}: AgentDisclosureProps) {
const reduce = useReducedMotion() ?? false;
const [collapsed, setCollapsed] = useState(!open);
if (open && collapsed) setCollapsed(false);
return (
<motion.div
{...props}
aria-hidden={!open}
inert={!open}
initial={false}
animate={
reduce
? { opacity: open ? 1 : 0 }
: {
opacity: open ? 1 : 0,
clipPath: open ? "inset(0 0 0% 0)" : "inset(0 0 100% 0)",
y: open ? 0 : -4,
}
}
transition={
transition ?? {
duration: reduce ? 0 : open ? 0.22 : 0.14,
ease: EASE_OUT,
}
}
onAnimationComplete={(definition) => {
if (!open) setCollapsed(true);
onAnimationComplete?.(definition);
}}
className={cn("overflow-hidden", className)}
style={{
...style,
height: collapsed ? 0 : openHeight,
pointerEvents: open ? undefined : "none",
transformOrigin: "top",
}}
/>
);
}
"use client";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import type { ReactNode } from "react";
import { SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface IconSwapProps {
/** Changes whenever the icon should change (copy → copied, running → done). */
id: string;
children: ReactNode;
className?: string;
}
/**
* Crossfades one status icon into the next with a little scale and a 2px
* blur, so the change reads as one icon morphing rather than two crossing.
* Reduced motion keeps the fade and drops the scale.
*/
export function IconSwap({ id, children, className }: IconSwapProps) {
const reduce = useReducedMotion() ?? false;
return (
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={id}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: "blur(2px)" }}
animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: "blur(2px)" }}
transition={reduce ? { duration: 0.12 } : SPRING_SWAP}
className={cn("grid place-items-center", className)}
>
{children}
</motion.span>
</AnimatePresence>
);
}
"use client";
import { AnimatePresence } from "motion/react";
import {
type ComponentProps,
type PointerEvent as ReactPointerEvent,
cloneElement,
createContext,
isValidElement,
type ReactElement,
type ReactNode,
type Ref,
type RefObject,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { TooltipSurface } from "@/components/motion/tooltip-surface";
import { type DismissReason, useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { assignRef } from "@/lib/merge-refs";
import { cn } from "@/lib/utils";
import { focusFromKeyboard, graceArea, inBox, inPolygon, watchModality } from "./tooltip/grace";
import { TooltipArrow, TooltipPositioner } from "./tooltip/positioner";
import {
type TooltipAlign,
type TooltipAnchor,
type TooltipPoint,
type TooltipSide,
useTooltipPointer,
} from "./tooltip/use-position";
export type { TooltipAlign, TooltipSide };
/* -------------------------------------------------------------------------- */
/* Provider */
/* -------------------------------------------------------------------------- */
interface TooltipTiming {
/** Delay before a hover opens a tooltip (ms). */
delay: number;
/** Delay before a tooltip closes once the pointer has left it (ms). */
closeDelay: number;
/** After one tooltip closes, others open instantly for this long (ms). */
skipDelay: number;
}
const TimingContext = createContext<TooltipTiming>({ delay: 120, closeDelay: 0, skipDelay: 300 });
export interface TooltipProviderProps extends Partial<TooltipTiming> {
children: ReactNode;
}
/** Shared timing for every tooltip inside it. Optional: tooltips work without one. */
export function TooltipProvider({ children, ...timing }: TooltipProviderProps) {
const parent = useContext(TimingContext);
const { delay = parent.delay, closeDelay = parent.closeDelay, skipDelay = parent.skipDelay } =
timing;
const value = useMemo(() => ({ delay, closeDelay, skipDelay }), [delay, closeDelay, skipDelay]);
return <TimingContext.Provider value={value}>{children}</TimingContext.Provider>;
}
/* -------------------------------------------------------------------------- */
/* Root */
/* -------------------------------------------------------------------------- */
// Moving along a toolbar should feel instant after the first label, and only
// one label may show at a time: a keyboard-focused control and a hovered one
// would otherwise both claim the screen.
let lastClosedAt = 0;
let current: { close: () => void } | null = null;
function isEmpty(content: ReactNode) {
return content == null || content === false || content === "";
}
interface TooltipContextValue {
open: boolean;
/** Show and hide without animating (keyboard focus, a warm toolbar, a replaced label). */
instant: boolean;
contentId: string;
labelId: string;
asLabel: boolean;
empty: boolean;
followCursor: boolean;
anchor: TooltipAnchor | null;
/** True when a TooltipTrigger owns the anchor; false for an external `anchorRef`. */
triggered: boolean;
floatingRef: RefObject<HTMLSpanElement | null>;
pointer: ReturnType<typeof useTooltipPointer>;
setTrigger: (element: TooltipAnchor | null) => void;
setEmpty: (empty: boolean) => void;
close: () => void;
onContentEnter: () => void;
onContentLeave: (event: ReactPointerEvent) => void;
}
const TooltipContext = createContext<TooltipContextValue | null>(null);
function useTooltipContext(part: string) {
const context = useContext(TooltipContext);
if (!context) throw new Error(`${part} must be used inside <Tooltip>`);
return context;
}
export interface TooltipRootProps {
children?: ReactNode;
/** Whether the tooltip is shown, for controlled use. */
open?: boolean;
/** Whether the tooltip starts shown when uncontrolled. Default: false */
defaultOpen?: boolean;
/** Called with the new state when the tooltip shows or hides. */
onOpenChange?: (open: boolean) => void;
/** Delay before showing on hover (ms). Keyboard focus shows immediately. */
delay?: number;
/** Delay before hiding once the pointer has left (ms). */
closeDelay?: number;
/** Never show, e.g. while the label it carries is already visible. */
disabled?: boolean;
/**
* Use the tooltip as the trigger's accessible name rather than its
* description. For icon-only controls whose only label is the tooltip.
*/
asLabel?: boolean;
/** Follow real pointer coordinates; keyboard focus still uses the anchor. */
followCursor?: boolean;
/** Existing anchor for controlled integrations such as chart cells. */
anchorRef?: RefObject<TooltipAnchor | null>;
/** Id of the tooltip surface, for anchors that reference it themselves. */
id?: string;
}
function TooltipRoot({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
delay: delayProp,
closeDelay: closeDelayProp,
disabled = false,
asLabel = false,
followCursor = false,
anchorRef,
id,
initialEmpty = false,
}: TooltipRootProps & { initialEmpty?: boolean }) {
const timing = useContext(TimingContext);
const delay = delayProp ?? timing.delay;
const closeDelay = closeDelayProp ?? timing.closeDelay;
const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
const open = controlledOpen ?? uncontrolledOpen;
// Keyboard focus and a warm toolbar show the label at once; animating
// something seen this often only makes it feel slow.
const [instant, setInstant] = useState(false);
const [empty, setEmpty] = useState(initialEmpty);
const [trigger, setTrigger] = useState<TooltipAnchor | null>(null);
const [external, setExternal] = useState<TooltipAnchor | null>(null);
const anchor = anchorRef ? external : trigger;
const generatedId = useId();
const contentId = id ?? `${generatedId}-content`;
const labelId = `${generatedId}-label`;
const floatingRef = useRef<HTMLSpanElement | null>(null);
const anchorObject = useRef<TooltipAnchor | null>(null);
const pointer = useTooltipPointer(anchor, followCursor);
// An external ref can attach after this component renders; read it once it has.
useLayoutEffect(() => {
if (!anchorRef) return;
const element = anchorRef.current ?? null;
if (element !== external) setExternal(element);
});
// Everything the event listeners read, current without re-binding them.
const latest = useRef({ open, delay, closeDelay, disabled, empty, onOpenChange, controlled: false });
useLayoutEffect(() => {
anchorObject.current = anchor;
latest.current = {
open,
delay,
closeDelay,
disabled,
empty,
onOpenChange,
controlled: controlledOpen !== undefined,
};
});
const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const grace = useRef<(() => void) | null>(null);
const self = useRef<{ close: () => void }>({ close: () => {} });
const clearTimers = useCallback(() => {
if (openTimer.current) clearTimeout(openTimer.current);
if (closeTimer.current) clearTimeout(closeTimer.current);
openTimer.current = null;
closeTimer.current = null;
}, []);
const stopGrace = useCallback(() => {
grace.current?.();
grace.current = null;
}, []);
// Only a real change reaches the consumer: a pointer leaving a closed
// tooltip is not news.
const commit = useCallback((next: boolean) => {
if (latest.current.open === next) return;
if (!latest.current.controlled) setUncontrolledOpen(next);
latest.current.onOpenChange?.(next);
}, []);
const openNow = useCallback(
(now = false) => {
clearTimers();
stopGrace();
if (latest.current.disabled || latest.current.empty) return;
// The label being replaced leaves at once, so two never show together.
if (current && current !== self.current) current.close();
current = self.current;
setInstant(now);
commit(true);
},
[clearTimers, stopGrace, commit],
);
const finish = useCallback(
(now: boolean) => {
clearTimers();
stopGrace();
if (latest.current.open) lastClosedAt = Date.now();
if (current === self.current) current = null;
if (latest.current.open) setInstant(now);
commit(false);
},
[clearTimers, stopGrace, commit],
);
// Also a listener (window blur, outside press), so it takes no arguments.
const close = useCallback(() => finish(false), [finish]);
useLayoutEffect(() => {
self.current.close = () => finish(true);
}, [finish]);
const requestOpen = useCallback(() => {
clearTimers();
if (latest.current.open || latest.current.disabled || latest.current.empty) return;
// Warm: another label is still showing (the pointer is crossing to this
// one), or one closed a moment ago. Either way, skip the delay and the fade.
const warm =
(current !== null && current !== self.current) ||
Date.now() - lastClosedAt < timing.skipDelay;
if (warm) openNow(true);
else if (latest.current.delay <= 0) openNow();
else openTimer.current = setTimeout(() => openNow(), latest.current.delay);
}, [clearTimers, openNow, timing.skipDelay]);
const requestClose = useCallback(() => {
clearTimers();
if (latest.current.closeDelay > 0) {
closeTimer.current = setTimeout(close, latest.current.closeDelay);
} else close();
}, [clearTimers, close]);
// Hold the label open while the pointer crosses from one box toward the other.
const startGrace = useCallback(
(exit: TooltipPoint, from: Element, to: Element | null) => {
stopGrace();
if (!to) return requestClose();
const target = to.getBoundingClientRect();
const origin = from.getBoundingClientRect();
const corridor = graceArea(exit, target);
const onMove = (event: PointerEvent) => {
const point = { x: event.clientX, y: event.clientY };
if (inBox(point, target) || inBox(point, origin)) return;
if (!inPolygon(point, corridor)) requestClose();
};
document.addEventListener("pointermove", onMove);
grace.current = () => document.removeEventListener("pointermove", onMove);
},
[stopGrace, requestClose],
);
const hover = useHoverGesture();
const tap = useTapGesture<boolean>();
// Listeners go on the trigger itself rather than on cloned props, so a
// component that owns its own handlers keeps them, and no wrapper element
// sits between the control and its layout.
useEffect(() => {
if (anchorRef || !trigger) return;
watchModality();
// A mouse press dismisses the label and keeps it away until the pointer
// leaves; hovering a control you just clicked should not bring it back.
let suppressed = false;
// Focus that came from the keyboard holds the label open on its own.
let keyboardFocus = false;
const onEnter = (event: PointerEvent) => {
if (!hover.enter(event)) return;
stopGrace();
if (closeTimer.current) clearTimeout(closeTimer.current);
if (!suppressed) requestOpen();
};
const onLeave = (event: PointerEvent) => {
if (!hover.leave(event)) return;
suppressed = false;
if (keyboardFocus) return;
if (openTimer.current) {
clearTimers();
return;
}
if (latest.current.open && !followCursor) {
startGrace({ x: event.clientX, y: event.clientY }, trigger, floatingRef.current);
} else requestClose();
};
const onDown = (event: PointerEvent) => {
tap.start(event, latest.current.open);
if (event.pointerType === "mouse") {
suppressed = true;
close();
}
};
// A finger never hovers, and Safari does not focus a button on tap either,
// so the label is only reachable if the tap itself toggles it. The click
// carries no pointerType; the pointerdown before it says whether it was a
// tap, and keyboard activation has none at all.
const onClick = () => {
const gesture = tap.take();
if (!gesture || gesture.pointerType === "mouse") return;
if (gesture.state) close();
else openNow();
};
const onKey = () => tap.drop();
const onFocusIn = () => {
if (!focusFromKeyboard()) return;
keyboardFocus = true;
openNow(true);
};
const onFocusOut = (event: FocusEvent) => {
if (trigger.contains(event.relatedTarget as Node | null)) return;
const fromKeyboard = keyboardFocus;
keyboardFocus = false;
finish(fromKeyboard);
};
// Both element kinds dispatch the same events; one type keeps the listeners typed.
const el = trigger as HTMLElement;
el.addEventListener("pointerenter", onEnter);
el.addEventListener("pointerleave", onLeave);
el.addEventListener("pointerdown", onDown);
el.addEventListener("pointercancel", tap.drop);
el.addEventListener("click", onClick);
el.addEventListener("keydown", onKey);
el.addEventListener("focusin", onFocusIn);
el.addEventListener("focusout", onFocusOut);
return () => {
el.removeEventListener("pointerenter", onEnter);
el.removeEventListener("pointerleave", onLeave);
el.removeEventListener("pointerdown", onDown);
el.removeEventListener("pointercancel", tap.drop);
el.removeEventListener("click", onClick);
el.removeEventListener("keydown", onKey);
el.removeEventListener("focusin", onFocusIn);
el.removeEventListener("focusout", onFocusOut);
};
}, [
anchorRef,
trigger,
followCursor,
hover,
tap,
requestOpen,
requestClose,
openNow,
close,
finish,
clearTimers,
stopGrace,
startGrace,
]);
// While open, a trigger that turns disabled loses focus without a blur event,
// and a window that loses focus never reports the pointer leaving.
useEffect(() => {
if (!open || anchorRef || !trigger) return;
const observer = new MutationObserver(() => {
if (trigger.matches(":disabled, [aria-disabled='true']")) close();
});
observer.observe(trigger, { attributes: true, attributeFilter: ["disabled", "aria-disabled"] });
window.addEventListener("blur", close);
return () => {
observer.disconnect();
window.removeEventListener("blur", close);
};
}, [open, anchorRef, trigger, close]);
// A chart drives its own open state and swaps content as it goes; only a
// trigger-owned label closes itself for having nothing to say.
useEffect(() => {
if (disabled || (empty && !anchorRef)) close();
}, [disabled, empty, anchorRef, close]);
useEffect(
() => () => {
clearTimers();
stopGrace();
if (current === self.current) current = null;
},
[clearTimers, stopGrace],
);
const insideTooltip = useCallback(
(target: Element) => Boolean(floatingRef.current?.contains(target)),
[],
);
// ...and closed by the next tap that lands somewhere else, or Escape. The
// label covers nothing interactive, so that tap passes through to what it hit.
// Escape is a key press, so the label goes at once.
const dismiss = useCallback((reason: DismissReason) => finish(reason === "escape"), [finish]);
useDismiss(open, dismiss, anchorObject, { ignore: insideTooltip });
const onContentEnter = useCallback(() => {
stopGrace();
clearTimers();
}, [stopGrace, clearTimers]);
const onContentLeave = useCallback(
(event: ReactPointerEvent) => {
const floating = floatingRef.current;
if (!floating) return;
if (anchorRef) {
// Bridge the small gap back onto a chart; it reopens on its own terms.
clearTimers();
closeTimer.current = setTimeout(close, 100);
return;
}
startGrace({ x: event.clientX, y: event.clientY }, floating, anchorObject.current);
},
[anchorRef, clearTimers, close, startGrace],
);
const value = useMemo<TooltipContextValue>(
() => ({
open,
instant,
contentId,
labelId,
asLabel,
empty,
followCursor,
anchor,
triggered: !anchorRef,
floatingRef,
pointer,
setTrigger,
setEmpty,
close,
onContentEnter,
onContentLeave,
}),
[
open,
instant,
contentId,
labelId,
asLabel,
empty,
followCursor,
anchor,
anchorRef,
pointer,
close,
onContentEnter,
onContentLeave,
],
);
return <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>;
}
/* -------------------------------------------------------------------------- */
/* Trigger */
/* -------------------------------------------------------------------------- */
function mergeIds(...ids: unknown[]) {
return ids.filter((value) => typeof value === "string" && value).join(" ") || undefined;
}
export interface TooltipTriggerProps extends ComponentProps<"button"> {
/** Use the single child element as the trigger instead of rendering a button. */
asChild?: boolean;
}
export function TooltipTrigger({ asChild = false, children, ref, ...props }: TooltipTriggerProps) {
const { open, contentId, labelId, asLabel, empty, setTrigger } =
useTooltipContext("TooltipTrigger");
const child = asChild && isValidElement(children) ? children : null;
const childProps = (child?.props ?? props) as Record<string, unknown>;
const childRef = child ? (childProps.ref as Ref<TooltipAnchor> | undefined) : undefined;
const attached = useRef<TooltipAnchor | null>(null);
const setRef = useCallback(
(element: TooltipAnchor | null) => {
attached.current = element;
setTrigger(element);
assignRef(childRef ?? (ref as Ref<TooltipAnchor> | undefined), element);
},
[setTrigger, childRef, ref],
);
useEffect(() => {
if (process.env.NODE_ENV !== "production" && child && !attached.current) {
console.warn(
"TooltipTrigger: the child did not attach a ref, so the tooltip has nothing to listen to. Render a DOM element or a component that passes `ref` through.",
);
}
}, [child]);
const aria = asLabel
? {
"aria-labelledby": empty
? (childProps["aria-labelledby"] as string | undefined)
: labelId,
}
: {
"aria-describedby": mergeIds(
childProps["aria-describedby"],
open && !empty ? contentId : undefined,
),
};
if (asChild) {
if (!child) return children;
return cloneElement(child as ReactElement<Record<string, unknown>>, { ref: setRef, ...aria });
}
return (
<button
type="button"
data-state={open ? "open" : "closed"}
{...props}
ref={setRef as Ref<HTMLButtonElement>}
{...aria}
>
{children}
</button>
);
}
/* -------------------------------------------------------------------------- */
/* Content */
/* -------------------------------------------------------------------------- */
export interface TooltipContentProps {
children?: ReactNode;
/** Preferred side of the anchor. Flips when there is no room. Default: "top" */
side?: TooltipSide;
/** Alignment along the chosen side. Default: "center" */
align?: TooltipAlign;
/** Gap between anchor and tooltip (px). */
sideOffset?: number;
/** Draw an arrow pointing at the anchor. */
arrow?: boolean;
/** Point within the anchor, as fractions of its rendered width and height. */
anchorPoint?: TooltipPoint;
/** Classes merged onto the tooltip surface. */
className?: string;
}
export function TooltipContent({
children,
side = "top",
align = "center",
sideOffset,
arrow = false,
anchorPoint,
className,
}: TooltipContentProps) {
const {
open,
instant,
contentId,
labelId,
asLabel,
followCursor,
anchor,
floatingRef,
pointer,
setEmpty,
close,
onContentEnter,
onContentLeave,
} = useTooltipContext("TooltipContent");
const empty = isEmpty(children);
const arrowRef = useRef<SVGSVGElement | null>(null);
useLayoutEffect(() => {
setEmpty(empty);
}, [empty, setEmpty]);
if (typeof document === "undefined") return null;
return createPortal(
<>
{/* The name has to exist while the label is closed, so it lives apart from the surface. */}
{asLabel && !empty ? (
<span id={labelId} hidden>
{children}
</span>
) : null}
{/* `custom` reaches a surface that is already exiting, so a label closed
from the keyboard or replaced by a neighbour leaves without animating. */}
<AnimatePresence custom={instant}>
{open && !empty ? (
<TooltipPositioner
key="tooltip"
anchor={anchor}
floatingRef={floatingRef}
arrowRef={arrow ? arrowRef : undefined}
anchorPoint={anchorPoint}
followCursor={followCursor}
side={side}
align={align}
sideOffset={sideOffset}
onDismiss={close}
pointer={pointer}
>
{(positioned, isPresent, placedSide) => (
<TooltipSurface
id={asLabel ? undefined : contentId}
aria-hidden={asLabel || undefined}
ready={positioned}
instant={instant}
onPointerEnter={onContentEnter}
onPointerLeave={onContentLeave}
style={{ pointerEvents: isPresent && !followCursor ? "auto" : "none" }}
className={cn(
"max-w-[min(20rem,calc(100vw-16px))] whitespace-normal break-words",
arrow && "relative",
className,
)}
>
{children}
{arrow ? <TooltipArrow ref={arrowRef} side={placedSide} /> : null}
</TooltipSurface>
)}
</TooltipPositioner>
) : null}
</AnimatePresence>
</>,
document.body,
);
}
/* -------------------------------------------------------------------------- */
/* Tooltip (root, or one-line shorthand when given `content`) */
/* -------------------------------------------------------------------------- */
export interface TooltipProps
extends TooltipRootProps,
Omit<TooltipContentProps, "children" | "className"> {
/**
* Shorthand: the tooltip's content. With it, `children` is the trigger
* element; without it, compose `TooltipTrigger` and `TooltipContent`.
*/
content?: ReactNode;
/** Shorthand only: classes for the tooltip surface. */
className?: string;
}
export function Tooltip(props: TooltipProps) {
if (!("content" in props)) return <TooltipRoot {...props} />;
const {
content,
children,
side,
align,
sideOffset,
arrow,
anchorPoint,
className,
...root
} = props;
if (!root.anchorRef && !isValidElement(children)) return children ?? null;
return (
<TooltipRoot {...root} initialEmpty={isEmpty(content)}>
{isValidElement(children) ? <TooltipTrigger asChild>{children}</TooltipTrigger> : null}
<TooltipContent
side={side}
align={align}
sideOffset={sideOffset}
arrow={arrow}
anchorPoint={anchorPoint}
className={className}
>
{content}
</TooltipContent>
</TooltipRoot>
);
}
type Point = { x: number; y: number };
type Box = { left: number; top: number; right: number; bottom: number };
/**
* The corridor a pointer may cross between the trigger and the open tooltip
* without closing it: the convex hull of where it left and the box it is
* heading for. A fixed timeout either cuts a slow diagonal move short or keeps
* the label alive after the pointer has plainly gone elsewhere; this follows
* the path itself.
*/
export function graceArea(exit: Point, target: Box): Point[] {
// A few pixels either side of the exit point give the corridor some width at
// its narrow end, so a hand that drifts sideways while it moves stays inside.
const pad = 5;
return hull([
{ x: exit.x - pad, y: exit.y - pad },
{ x: exit.x + pad, y: exit.y - pad },
{ x: exit.x - pad, y: exit.y + pad },
{ x: exit.x + pad, y: exit.y + pad },
{ x: target.left, y: target.top },
{ x: target.right, y: target.top },
{ x: target.right, y: target.bottom },
{ x: target.left, y: target.bottom },
]);
}
export function inBox(point: Point, box: Box) {
return (
point.x >= box.left && point.x <= box.right && point.y >= box.top && point.y <= box.bottom
);
}
export function inPolygon(point: Point, polygon: Point[]) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const a = polygon[i];
const b = polygon[j];
if (
a.y > point.y !== b.y > point.y &&
point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x
) {
inside = !inside;
}
}
return inside;
}
// Monotone chain; the corridor is always convex, so a hull is all it needs.
function hull(points: Point[]) {
const sorted = [...points].sort((a, b) => a.x - b.x || a.y - b.y);
const cross = (o: Point, a: Point, b: Point) =>
(a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
const lower: Point[] = [];
for (const p of sorted) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {
lower.pop();
}
lower.push(p);
}
const upper: Point[] = [];
for (let i = sorted.length - 1; i >= 0; i--) {
const p = sorted[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {
upper.pop();
}
upper.push(p);
}
lower.pop();
upper.pop();
return lower.concat(upper);
}
/**
* How the user last reached for the page. A focus that a mouse press caused is
* not a request to read the label: the pointer is already on the control and
* hovering showed it. A focus that followed a key - Tab, or a roving arrow key
* moving focus in script - is the only way a keyboard user sees it at all.
*/
let modality: "keyboard" | "pointer" = "keyboard";
let listening = false;
export function watchModality() {
if (listening || typeof window === "undefined") return;
listening = true;
window.addEventListener("keydown", () => (modality = "keyboard"), true);
window.addEventListener("pointerdown", () => (modality = "pointer"), true);
}
export function focusFromKeyboard() {
return modality === "keyboard";
}
"use client";
import { useIsPresent } from "motion/react";
import { type CSSProperties, type ReactNode, type Ref, useCallback, useState } from "react";
import { type TooltipSide, useTooltipPosition } from "./use-position";
type PositionProps = Parameters<typeof useTooltipPosition>[0];
/** Readiness lives with the mounted overlay, not a trigger ref's attach/detach cycle. */
export function TooltipPositioner({
children,
...position
}: Omit<PositionProps, "open" | "onPosition"> & {
children: (ready: boolean, present: boolean, side: TooltipSide) => ReactNode;
}) {
const present = useIsPresent();
const [ready, setReady] = useState(false);
const [side, setSide] = useState<TooltipSide>(position.side);
const onPosition = useCallback((placed: TooltipSide) => {
setReady(true);
setSide(placed);
}, []);
useTooltipPosition({ ...position, open: present, onPosition });
return (
<span
ref={position.floatingRef}
inert={!present}
aria-hidden={!present || undefined}
className="pointer-events-none fixed left-0 top-0 z-[9999] w-max"
style={{ visibility: "hidden", maxWidth: "calc(100vw - 16px)" }}
>
{children(ready, present, side)}
</span>
);
}
// Each arrow is a 12px box whose base sits on the surface's inner border edge,
// so its fill covers the border beneath it and only the two outer edges stroke.
const ARROW: Record<TooltipSide, { path: string; style: CSSProperties }> = {
top: { path: "M0 6L6 12L12 6", style: { top: "calc(100% - 6px)" } },
bottom: { path: "M0 6L6 0L12 6", style: { bottom: "calc(100% - 6px)" } },
left: { path: "M6 0L12 6L6 12", style: { left: "calc(100% - 6px)" } },
right: { path: "M6 0L0 6L6 12", style: { right: "calc(100% - 6px)" } },
};
export function TooltipArrow({ side, ref }: { side: TooltipSide; ref: Ref<SVGSVGElement> }) {
const { path, style } = ARROW[side];
return (
<svg
ref={ref}
aria-hidden="true"
width="12"
height="12"
viewBox="0 0 12 12"
className="pointer-events-none absolute overflow-visible"
style={style}
>
{/* Redrawn to fit the surface's edge once placed (see arrowShape). */}
<path data-arrow-fill="" d={`${path}Z`} style={{ fill: "var(--tooltip-arrow-fill, transparent)" }} />
<path
data-arrow-stroke=""
d={path}
fill="none"
strokeWidth="1"
style={{ stroke: "var(--tooltip-arrow-stroke, transparent)" }}
/>
</svg>
);
}
"use client";
import {
arrow as arrowMiddleware,
autoUpdate,
computePosition,
flip,
hide,
offset,
type Placement,
shift,
type VirtualElement,
} from "@floating-ui/dom";
import { type RefObject, useCallback, useLayoutEffect, useMemo, useRef } from "react";
export type TooltipSide = "top" | "right" | "bottom" | "left";
export type TooltipAlign = "start" | "center" | "end";
export type TooltipPoint = {
/** Horizontal position; for `anchorPoint`, a 0 to 1 fraction of the anchor's width. */
x: number;
/** Vertical position; for `anchorPoint`, a 0 to 1 fraction of the anchor's height. */
y: number;
};
export type TooltipAnchor = HTMLElement | SVGElement;
const ORIGIN: Record<TooltipSide, string> = {
top: "center bottom",
bottom: "center top",
left: "right center",
right: "left center",
};
/** `top` painted over `bottom`, as one opaque colour. Falls back to `top`. */
function blend(top: string, bottom: string) {
const context = document.createElement("canvas").getContext("2d", { willReadFrequently: true });
if (!context) return top;
context.fillStyle = bottom;
context.fillRect(0, 0, 1, 1);
context.fillStyle = top;
context.fillRect(0, 0, 1, 1);
const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data;
// A see-through background has nothing solid to blend onto.
return a === 255 ? `rgb(${r}, ${g}, ${b})` : top;
}
/** The arrow element's box, which the arrow middleware centres along the edge. */
const ARROW_SIZE = 12;
/** How far the tip reaches past the border's inner edge. */
const ARROW_REACH = 6;
/**
* How far a rounded edge has curved in from its straight line at `position`
* along an edge of `length`, with corners of `radius`. Zero on the straight
* stretch between the corners.
*/
function curveDepth(position: number, length: number, radius: number) {
const offset =
position < radius ? radius - position : position > length - radius ? position - (length - radius) : 0;
if (offset <= 0) return 0;
return radius - Math.sqrt(Math.max(radius * radius - offset * offset, 0));
}
/**
* The arrow's two paths, in the surface's border-box coordinates. Each 45°
* side runs from the tip until it meets the middle of the surface's border,
* wherever that is: on a straight stretch, or partway round a pill's curved
* end. The stroke covers only those two sides, so the border flows straight
* into them. The fill closes a little inside the surface, hiding the stretch
* of border the arrow sits on.
*/
function arrowShape({
side,
center,
width,
height,
radius,
border,
}: {
side: TooltipSide;
center: number;
width: number;
height: number;
radius: number;
border: number;
}) {
const vertical = side === "top" || side === "bottom";
const length = vertical ? width : height;
// Work on one edge: `depth` runs inward from the edge's outer line, `along` runs down it.
const tip = { depth: border - ARROW_REACH, along: center };
// The border's centre line: the stroke meets it there, so the two line up.
const line = border / 2;
// Both sides follow the same rule, so an arrow a pixel off-centre stays symmetric.
const curved =
curveDepth(center - ARROW_SIZE / 2, length, radius) > 0 ||
curveDepth(center + ARROW_SIZE / 2, length, radius) > 0;
const meet = (direction: -1 | 1) => {
// On a straight stretch the 45° side meets the border directly.
if (!curved) {
for (let t = 0; t <= ARROW_SIZE; t += 0.05) {
const along = center + direction * t;
const depth = tip.depth + t;
if (depth >= line) return { depth, along };
}
}
// On a pill's round end a 45° side passes outside the curve, or meets it
// at a kink. Run the side tangent to the curve instead, so the border
// flows into it without a corner.
const curve = radius - line;
const centre = { depth: radius, along: direction < 0 ? radius : length - radius };
const dx = tip.depth - centre.depth;
const dy = tip.along - centre.along;
const distance = Math.hypot(dx, dy);
if (distance <= curve) return { depth: line, along: center + direction * ARROW_REACH };
const base = Math.atan2(dy, dx);
const spread = Math.acos(curve / distance);
const candidates = [base + spread, base - spread].map((angle) => ({
depth: centre.depth + curve * Math.cos(angle),
along: centre.along + curve * Math.sin(angle),
}));
// The tangent on this side of the tip.
return direction < 0
? candidates[0].along < candidates[1].along
? candidates[0]
: candidates[1]
: candidates[0].along > candidates[1].along
? candidates[0]
: candidates[1];
};
const start = meet(-1);
const end = meet(1);
const inside = Math.max(start.depth, end.depth) + border + 1;
const point = ({ depth, along }: { depth: number; along: number }) => {
const [x, y] =
side === "right"
? [depth, along]
: side === "left"
? [width - depth, along]
: side === "bottom"
? [along, depth]
: [along, height - depth];
return `${x.toFixed(2)} ${y.toFixed(2)}`;
};
return {
fill: `M${point(tip)}L${point(start)}L${point({ depth: inside, along: start.along })}L${point({ depth: inside, along: end.along })}L${point(end)}Z`,
stroke: `M${point(start)}L${point(tip)}L${point(end)}`,
};
}
/** Position is geometry, not animation. One write per frame, never a spring chasing a pointer. */
export function useTooltipPosition({
open,
anchor,
floatingRef,
arrowRef,
anchorPoint,
followCursor,
side,
align,
sideOffset,
onDismiss,
onPosition,
pointer,
}: {
open: boolean;
anchor: TooltipAnchor | null;
floatingRef: RefObject<HTMLSpanElement | null>;
arrowRef?: RefObject<SVGSVGElement | null>;
anchorPoint?: TooltipPoint;
followCursor: boolean;
side: TooltipSide;
align: TooltipAlign;
sideOffset?: number;
onDismiss: () => void;
onPosition: (side: TooltipSide) => void;
pointer: ReturnType<typeof useTooltipPointer>;
}) {
const { cursor, onMove } = pointer;
const preferred: Placement = align === "center" ? side : `${side}-${align}`;
const cursorSide = useRef<Placement | null>(null);
useLayoutEffect(() => {
cursorSide.current = open ? preferred : null;
}, [open, preferred]);
const frame = useRef<number | null>(null);
const version = useRef(0);
const update = useRef<() => void>(() => {});
const schedule = useCallback(() => {
// Invalidate older async calculations as soon as new geometry is requested.
version.current++;
if (frame.current !== null) return;
frame.current = requestAnimationFrame(() => {
frame.current = null;
update.current();
});
}, []);
useLayoutEffect(() => {
onMove.current = schedule;
return () => {
onMove.current = null;
};
}, [onMove, schedule]);
const pointX = anchorPoint?.x;
const pointY = anchorPoint?.y;
// Latest committed inputs are read without recreating observers for every period/content update.
useLayoutEffect(() => {
update.current = () => {
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const revision = ++version.current;
const currentCursor = followCursor ? cursor.current : null;
const virtual = Boolean(currentCursor) || pointX !== undefined || pointY !== undefined;
const reference: Element | VirtualElement = virtual
? {
contextElement: anchor,
getBoundingClientRect: () => {
const rect = anchor.getBoundingClientRect();
const x = currentCursor?.x ?? rect.left + rect.width * (pointX ?? 0.5);
const y = currentCursor?.y ?? rect.top + rect.height * (pointY ?? 0.5);
return { x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 };
},
}
: anchor;
const arrowElement = arrowRef?.current ?? null;
void computePosition(reference, floating, {
strategy: "fixed",
placement: currentCursor ? (cursorSide.current ?? preferred) : preferred,
middleware: [
offset(sideOffset ?? (currentCursor ? 12 : 8)),
flip({ padding: 8 }),
shift({ padding: 8 }),
...(arrowElement ? [arrowMiddleware({ element: arrowElement, padding: 10 })] : []),
// A label left floating over whatever scrolled into its trigger's place
// describes nothing there. Points inside a chart move with the chart.
...(virtual ? [] : [hide({ strategy: "referenceHidden" })]),
],
}).then(({ x, y, placement, middlewareData }) => {
if (version.current !== revision || !floating.isConnected) return;
// Hold the chosen side for this hover session. Crossing a flip threshold
// repeatedly must not bounce the surface above and below the pointer.
if (currentCursor) cursorSide.current = placement;
else cursorSide.current = null;
const placedSide = placement.split("-")[0] as TooltipSide;
const dpr = window.devicePixelRatio || 1;
floating.style.transform = `translate3d(${Math.round(x * dpr) / dpr}px, ${Math.round(y * dpr) / dpr}px, 0)`;
floating.style.setProperty("--tooltip-origin", ORIGIN[placedSide]);
// A box with no size has no clipped state to report, only a missing layout.
const box = anchor.getBoundingClientRect();
const clipped =
Boolean(middlewareData.hide?.referenceHidden) && (box.width > 0 || box.height > 0);
floating.style.visibility = clipped ? "hidden" : "visible";
floating.dataset.placement = placement;
const surface = arrowElement?.parentElement;
if (arrowElement && surface) {
// The middleware centres the 12px arrow box along the edge; its
// centre is where the tip points. The paths are drawn in the
// surface's border-box coordinates, so the svg sits at its corner.
const { x: ax, y: ay } = middlewareData.arrow ?? {};
const vertical = placedSide === "top" || placedSide === "bottom";
const width = surface.offsetWidth;
const height = surface.offsetHeight;
const along = (vertical ? ax : ay) ?? ((vertical ? width : height) - ARROW_SIZE) / 2;
const style = getComputedStyle(surface);
const shape = arrowShape({
side: placedSide,
center: along + ARROW_SIZE / 2,
width,
height,
// `rounded-full` resolves to a huge radius; the box clamps it to half its short side.
radius: Math.min(Number.parseFloat(style.borderTopLeftRadius) || 0, width / 2, height / 2),
border: surface.clientLeft,
});
Object.assign(arrowElement.style, {
left: `${-surface.clientLeft}px`,
top: `${-surface.clientTop}px`,
right: "auto",
bottom: "auto",
});
arrowElement.querySelector("[data-arrow-fill]")?.setAttribute("d", shape.fill);
arrowElement.querySelector("[data-arrow-stroke]")?.setAttribute("d", shape.stroke);
// Paint with whatever the surface resolved to, so a restyled tooltip
// keeps a matching arrow without a second set of classes. A
// see-through border is drawn over the surface's own background, so
// the stroke takes that blended colour: half of it sits over the
// page, and it overlaps the border where the two meet.
arrowElement.style.setProperty("--tooltip-arrow-fill", style.backgroundColor);
arrowElement.style.setProperty(
"--tooltip-arrow-stroke",
blend(style.borderTopColor, style.backgroundColor),
);
}
onPosition(placedSide);
});
};
if (open) schedule();
}, [
open,
anchor,
floatingRef,
arrowRef,
followCursor,
pointX,
pointY,
preferred,
sideOffset,
schedule,
onPosition,
cursor,
]);
useLayoutEffect(() => {
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const stop = autoUpdate(anchor, floating, schedule);
const onScroll = () => {
// A stationary pointer no longer describes the same chart point after scrolling.
if (followCursor && cursor.current) onDismiss();
};
window.addEventListener("scroll", onScroll, true);
return () => {
stop();
window.removeEventListener("scroll", onScroll, true);
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
frame.current = null;
};
}, [open, anchor, floatingRef, followCursor, onDismiss, schedule, cursor]);
useLayoutEffect(
() => () => {
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
},
[],
);
}
/** Pointer lifetime belongs to the anchor, including the opening delay. */
export function useTooltipPointer(anchor: TooltipAnchor | null, followCursor: boolean) {
const cursor = useRef<TooltipPoint | null>(null);
const onMove = useRef<(() => void) | null>(null);
const pointerFocus = useRef(false);
useLayoutEffect(() => {
if (!anchor || !followCursor) return;
const point = (event: PointerEvent) => {
if (event.type === "pointermove" && event.pointerType === "touch" && !event.buttons) return;
cursor.current = { x: event.clientX, y: event.clientY };
if (event.type === "pointerdown") pointerFocus.current = true;
onMove.current?.();
};
const keyboard = () => {
cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const focus = () => {
if (!pointerFocus.current) cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const leave = () => {
cursor.current = null;
};
anchor.addEventListener("pointerenter", point as EventListener, { passive: true });
anchor.addEventListener("pointermove", point as EventListener, { passive: true });
anchor.addEventListener("pointerdown", point as EventListener, { passive: true });
anchor.addEventListener("pointerleave", leave);
anchor.addEventListener("pointercancel", leave);
anchor.addEventListener("keydown", keyboard);
anchor.addEventListener("focusin", focus);
return () => {
cursor.current = null;
anchor.removeEventListener("pointerenter", point as EventListener);
anchor.removeEventListener("pointermove", point as EventListener);
anchor.removeEventListener("pointerdown", point as EventListener);
anchor.removeEventListener("pointerleave", leave);
anchor.removeEventListener("pointercancel", leave);
anchor.removeEventListener("keydown", keyboard);
anchor.removeEventListener("focusin", focus);
};
}, [anchor, followCursor]);
return useMemo(() => ({ cursor, onMove }), []);
}
"use client";
import { motion, useReducedMotion, type Variants } from "motion/react";
import type { ComponentProps, ReactNode, Ref } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
const ENTER = { duration: 0.18, ease: EASE_OUT };
const EXIT = { duration: 0.12, ease: EASE_OUT };
const INSTANT = { duration: 0 };
/**
* `custom` is the `instant` flag. An exiting surface reads it from its
* `AnimatePresence`, so a tooltip replaced by a neighbour vanishes at once
* even though it has already left the React tree.
*/
const variants = (reduce: boolean): Variants => ({
closed: (instant = false) => ({
opacity: 0,
scale: reduce ? 1 : 0.97,
transition: instant ? INSTANT : EXIT,
}),
open: (instant = false) => ({
opacity: 1,
scale: 1,
transition: instant ? INSTANT : ENTER,
}),
});
/** Presentation only: the unanimated parent owns measurement and positioning. */
export function TooltipSurface({
children,
className,
ref,
ready = true,
instant = false,
style,
...props
}: Omit<ComponentProps<typeof motion.span>, "children"> & {
children?: ReactNode;
/** Start the entrance only after the positioning layer has been measured. */
ready?: boolean;
/**
* Appear and disappear without animating: a label opened from the keyboard,
* or one of a row of tooltips the pointer is moving along.
*/
instant?: boolean;
ref?: Ref<HTMLSpanElement>;
}) {
const reduce = useReducedMotion() ?? false;
return (
<motion.span
ref={ref}
role="tooltip"
custom={instant}
variants={variants(reduce)}
initial="closed"
animate={ready ? "open" : "closed"}
exit="closed"
style={{ transformOrigin: "var(--tooltip-origin, center)", ...style }}
className={cn(
"block whitespace-nowrap rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)]",
className,
)}
{...props}
>
{children}
</motion.span>
);
}
"use client";
import { useEffect, useState } from "react";
import type { ToolResultStatus } from "@/components/agents/tool-result";
export function useToolResultDemo(
steps: number,
interval = 420,
finalStatus: Exclude<ToolResultStatus, "running"> = "success",
) {
const [visible, setVisible] = useState(0);
const [status, setStatus] = useState<ToolResultStatus>("running");
useEffect(() => {
const timers = Array.from({ length: steps }, (_, index) =>
window.setTimeout(() => setVisible(index + 1), index * interval + 180),
);
timers.push(
window.setTimeout(
() => setStatus(finalStatus),
steps * interval + 480,
),
);
return () => timers.forEach(window.clearTimeout);
}, [finalStatus, interval, steps]);
return { visible, status };
}
"use client";
import {
Ban,
Braces,
Check,
ChevronDown,
CircleCheck,
CircleX,
Copy,
LoaderCircle,
RotateCcw,
SquareTerminal,
Wrench,
} from "lucide-react";
import { motion, useReducedMotion } from "motion/react";
import { type ReactNode, useId, useLayoutEffect, useRef } from "react";
import {
AgentCode,
type AgentCodeLanguage,
} from "@/components/agents/agent-code";
import { AgentDisclosure } from "@/components/agents/agent-disclosure";
import { IconSwap } from "@/components/agents/icon-swap";
import { ActionSwapRollText } from "@/components/motion/action-swap-roll";
import { Tooltip } from "@/components/motion/tooltip";
import { SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { useCopy } from "@/lib/hooks/use-copy";
import { useStatusOpen } from "@/lib/hooks/use-status-open";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export type ToolResultStatus = "running" | "success" | "error" | "cancelled";
export type ToolResultKind = "terminal" | "request" | "custom";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const toolResultMessages = {
running: "Running",
success: "Completed",
error: "Failed",
cancelled: "Cancelled",
copy: "Copy result",
copied: "Copied",
retry: "Run again",
};
export type ToolResultMessages = typeof toolResultMessages;
export interface ToolResultProps {
/** Tool name, shown in small monospace after the title. */
tool: ReactNode;
/** Heading in the header row, rolls to the new text when it changes. */
title: ReactNode;
children: ReactNode;
/** Run state, sets the status badge and auto open or fold. Default: "running" */
status?: ToolResultStatus;
/** Picks the header icon when no `icon` is given. Default: "custom" */
kind?: ToolResultKind;
/** Short muted detail after the title, e.g. a duration or count. */
meta?: ReactNode;
/** Replaces the icon chosen by `kind`. */
icon?: ReactNode;
/** Whether the output panel is open, for controlled use. */
open?: boolean;
/** Whether the output panel starts open when uncontrolled. Default: true */
defaultOpen?: boolean;
/** Called with the new open state when the panel opens or closes. */
onOpenChange?: (open: boolean) => void;
/** Folds the panel when the status leaves "running". Default: true */
collapseOnComplete?: boolean;
/** Maximum height of the scrolling output area, in px. Default: 220 */
maxHeight?: number;
/** Text the copy button writes to the clipboard. Shows the copy button. */
copyText?: string;
/** Runs instead of the clipboard write when copy is pressed. Shows the copy button. */
onCopy?: () => void | Promise<void>;
/** Called when the retry button is pressed. Shows the retry button. */
onRetry?: () => void;
/** Override any built-in string. */
labels?: Partial<ToolResultMessages>;
/** Classes merged onto the root element. */
className?: string;
/** Classes merged onto the padded box around the output. */
contentClassName?: string;
}
export interface ToolResultOutputProps {
children: string;
/** Syntax highlighting language for the output. Default: "bash" */
language?: AgentCodeLanguage;
/** Classes merged onto the code element. */
className?: string;
}
function getSwapKey(value: ReactNode, fallback: string) {
return typeof value === "string" || typeof value === "number"
? String(value)
: fallback;
}
function getStatusClass(status: ToolResultStatus) {
if (status === "running") {
return "text-blue-600 dark:text-blue-400";
}
if (status === "success") {
return "text-emerald-600 dark:text-emerald-400";
}
if (status === "error") {
return "text-rose-600 dark:text-rose-400";
}
return "text-muted-foreground";
}
function KindIcon({ kind }: { kind: ToolResultKind }) {
if (kind === "terminal") return <SquareTerminal className="size-4" />;
if (kind === "request") return <Braces className="size-4" />;
return <Wrench className="size-4" />;
}
function StatusIcon({
status,
reduce,
}: {
status: ToolResultStatus;
reduce: boolean;
}) {
if (status === "running") {
return <LoaderCircle className={cn("size-3", !reduce && "animate-spin")} />;
}
if (status === "success") return <CircleCheck className="size-3" />;
if (status === "error") return <CircleX className="size-3" />;
return <Ban className="size-3" />;
}
function ToolResultAction({
label,
onClick,
children,
}: {
label: string;
onClick: () => void;
children: ReactNode;
}) {
const reduce = useReducedMotion() ?? false;
return (
<Tooltip content={label} side="top">
<motion.button
type="button"
aria-label={label}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.95 }}
transition={SPRING_PRESS}
// A foreground tint: the output panel is already muted, so a muted
// hover would not show.
className="grid size-7 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
{children}
</motion.button>
</Tooltip>
);
}
export function ToolResultOutput({
children,
language = "bash",
className,
}: ToolResultOutputProps) {
return (
<AgentCode
code={children}
language={language}
className={cn(
"whitespace-pre-wrap break-words text-foreground/80",
className,
)}
/>
);
}
export function ToolResult({
tool,
title,
children,
status = "running",
kind = "custom",
meta,
icon,
open,
defaultOpen = true,
onOpenChange,
collapseOnComplete = true,
maxHeight = 220,
copyText,
onCopy,
onRetry,
labels,
className,
contentClassName,
}: ToolResultProps) {
const t = useMessages("toolResult", toolResultMessages, labels);
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const triggerId = `${baseId}-trigger`;
const contentId = `${baseId}-content`;
const viewportRef = useRef<HTMLDivElement>(null);
const { copied, copy: handleCopy } = useCopy({ text: copyText, onCopy });
// Opens when the tool starts running; folds when it stops, if asked to.
const [currentOpen, setOpen] = useStatusOpen({
status,
open,
defaultOpen,
onOpenChange,
decide: (previous, next) => {
if (previous !== "running" && next === "running") return true;
if (previous === "running" && next !== "running" && collapseOnComplete) return false;
return undefined;
},
});
const running = status === "running";
const canCopy = Boolean(copyText || onCopy);
const titleKey = getSwapKey(title, status);
const metaKey = getSwapKey(meta, `${status}-meta`);
const toolKey = getSwapKey(tool, `${status}-tool`);
const statusLabel = t(status);
useLayoutEffect(() => {
const viewport = viewportRef.current;
if (!viewport || !currentOpen || !running) return;
const frame = requestAnimationFrame(() => {
if (typeof viewport.scrollTo === "function") {
viewport.scrollTo({
top: viewport.scrollHeight,
behavior: reduce ? "auto" : "smooth",
});
} else {
viewport.scrollTop = viewport.scrollHeight;
}
});
return () => cancelAnimationFrame(frame);
});
return (
<div
data-state={status}
aria-busy={running}
className={cn("w-full text-sm", className)}
>
<button
id={triggerId}
type="button"
aria-expanded={currentOpen}
aria-controls={contentId}
onClick={() => setOpen(!currentOpen)}
className="group flex min-h-9 w-full items-center gap-2 rounded-full py-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<span
aria-hidden="true"
className="grid size-4 shrink-0 place-items-center text-muted-foreground"
>
{icon ?? <KindIcon kind={kind} />}
</span>
<span className="flex min-w-0 flex-1 items-baseline gap-2">
<span className="min-w-0 truncate font-medium text-foreground/90">
<ActionSwapRollText value={titleKey}>
{title}
</ActionSwapRollText>
</span>
{meta ? (
<span className="shrink-0 text-xs text-muted-foreground/60">
<ActionSwapRollText value={metaKey}>
{meta}
</ActionSwapRollText>
</span>
) : null}
<span className="min-w-0 truncate font-mono text-[11px] text-muted-foreground/55">
<ActionSwapRollText value={toolKey}>
{tool}
</ActionSwapRollText>
</span>
</span>
<span
className={cn(
"inline-flex shrink-0 items-center gap-1 text-[11px] font-medium",
getStatusClass(status),
)}
>
<IconSwap id={status}>
<StatusIcon status={status} reduce={reduce} />
</IconSwap>
<ActionSwapRollText value={status}>{statusLabel}</ActionSwapRollText>
</span>
<motion.span
aria-hidden="true"
animate={{ rotate: currentOpen ? 180 : 0 }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="shrink-0 text-muted-foreground/50 transition-colors group-hover:text-muted-foreground"
>
<ChevronDown className="size-3.5" />
</motion.span>
</button>
<AgentDisclosure
id={contentId}
role="region"
aria-labelledby={triggerId}
open={currentOpen}
>
<div className="pl-6 pt-1.5">
<div className="overflow-hidden rounded-xl bg-muted/80">
<div
ref={viewportRef}
role="log"
aria-live="polite"
className="scrollbar-hide overflow-y-auto"
style={{ maxHeight }}
>
<div className={cn("p-3", contentClassName)}>{children}</div>
</div>
{canCopy || onRetry ? (
<div className="flex items-center gap-0.5 px-2 pb-1.5">
{canCopy ? (
<ToolResultAction
label={copied ? t("copied") : t("copy")}
onClick={handleCopy}
>
<IconSwap id={copied ? "copied" : "copy"}>
{copied ? (
<Check className="size-3.5" />
) : (
<Copy className="size-3.5" />
)}
</IconSwap>
</ToolResultAction>
) : null}
{onRetry ? (
<ToolResultAction label={t("retry")} onClick={onRetry}>
<RotateCcw className="size-3.5" />
</ToolResultAction>
) : null}
</div>
) : null}
</div>
</div>
</AgentDisclosure>
</div>
);
}
"use client";
import {
ActionSwapButton,
ActionSwapIcon,
ActionSwapText,
type ActionSwapButtonProps,
type ActionSwapIconProps,
type ActionSwapTextProps,
} from "./action-swap";
export type {
ActionSwapButtonSize,
ActionSwapButtonVariant,
ActionSwapItem,
} from "./action-swap";
export type ActionSwapRollButtonProps = Omit<ActionSwapButtonProps, "animation">;
export type ActionSwapRollTextProps = Omit<ActionSwapTextProps, "animation">;
export type ActionSwapRollIconProps = Omit<ActionSwapIconProps, "animation">;
export function ActionSwapRollButton(props: ActionSwapRollButtonProps) {
return <ActionSwapButton {...props} animation="roll" />;
}
export function ActionSwapRollText(props: ActionSwapRollTextProps) {
return <ActionSwapText {...props} animation="roll" />;
}
export function ActionSwapRollIcon(props: ActionSwapRollIconProps) {
return <ActionSwapIcon {...props} animation="roll" />;
}
"use client";
import { AnimatePresence, type HTMLMotionProps, motion, useReducedMotion, type Variants } from "motion/react";
import type { ReactNode } from "react";
import { useState } from "react";
import { EASE_OUT, SPRING_LAYOUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type ActionSwapItem = {
/** Unique key, used as the button's value. */
id: string;
/** Text shown on the button while this item is active. Hidden when `iconOnly`. */
label: ReactNode;
/** Icon shown before the label while this item is active. */
icon?: ReactNode;
/** Accessible name while active. Falls back to a string label when `iconOnly`. */
ariaLabel?: string;
};
export type ActionSwapButtonVariant = "primary" | "secondary" | "outline" | "ghost";
export type ActionSwapButtonSize = "sm" | "md" | "lg" | "icon";
export type ActionSwapAnimation = "blur" | "roll" | "cascade";
/** Animations with a single-element variant set (cascade animates per letter). */
type CoreAnimation = "blur" | "roll";
export interface ActionSwapButtonProps extends Omit<
HTMLMotionProps<"button">,
"children" | "onChange"
> {
/** States the button steps through, each with a label and optional icon. */
items: ActionSwapItem[];
/** The id of the shown item, for controlled use. */
value?: string;
/** The initial item id when uncontrolled. Default: the first item. */
defaultValue?: string;
/** Called with the next item's id and the item when a press advances it. */
onValueChange?: (value: string, item: ActionSwapItem) => void;
/** Visual style of the button. Default: "secondary" */
variant?: ActionSwapButtonVariant;
/** Button height and padding. Default: "md" */
size?: ActionSwapButtonSize;
/** How the label and icon swap between items. Default: "blur" */
animation?: ActionSwapAnimation;
/** Show only the icon and use the label as the accessible name. Default: true for size "icon" */
iconOnly?: boolean;
/** Advance to the next item on each press, wrapping at the end. Default: true */
cycle?: boolean;
}
export interface ActionSwapTextProps {
/** Key for the current text; a new value plays the swap. */
value: string;
children: ReactNode;
/** How the old text leaves and the new text enters. Default: "blur" */
animation?: ActionSwapAnimation;
/** Classes merged onto the root element. */
className?: string;
}
export interface ActionSwapIconProps {
/** Key for the current icon; a new value plays the swap. */
value: string;
children: ReactNode;
/** How the old icon leaves and the new one enters. "cascade" plays as "roll". Default: "blur" */
animation?: ActionSwapAnimation;
/** Classes merged onto the root element. */
className?: string;
}
// The arriving layer springs in, so a second press mid-swap bends it toward
// the new target instead of restarting. The leaving layer is a little quicker,
// still long enough to cross the arrival so the swap reads as one morph.
const BLUR_TRANSITION = SPRING_SWAP;
const BLUR_EXIT_TRANSITION = { duration: 0.16, ease: EASE_OUT } as const;
const ROLL_TRANSITION = SPRING_SWAP;
const ROLL_EXIT_TRANSITION = { duration: 0.14, ease: EASE_OUT } as const;
// A light blur softens the crossing without smearing small glyphs.
const SWAP_BLUR = "blur(2px)";
const ROLL_BLUR = "blur(3px)";
// Cascade rolls the label one letter at a time, left to right. The leaving
// and landing strings overlap as independent layers (no shared cells), so
// proportional glyph widths never jitter. Exits cascade at half the enter
// stagger so the tail of the old label lingers briefly.
const CASCADE_STAGGER = 0.025;
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 TEXT_VARIANTS: Record<CoreAnimation, Variants> = {
blur: {
initial: { opacity: 0, scale: 0.9, filter: SWAP_BLUR },
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
transition: BLUR_TRANSITION,
},
exit: {
opacity: 0,
scale: 0.96,
filter: SWAP_BLUR,
transition: BLUR_EXIT_TRANSITION,
},
},
roll: {
initial: { opacity: 0, y: "90%", filter: ROLL_BLUR },
animate: {
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: ROLL_TRANSITION,
},
exit: {
opacity: 0,
y: "-90%",
filter: ROLL_BLUR,
transition: ROLL_EXIT_TRANSITION,
},
},
};
const ICON_VARIANTS: Record<CoreAnimation, Variants> = {
blur: {
initial: { opacity: 0, scale: 0.25, filter: SWAP_BLUR },
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
transition: BLUR_TRANSITION,
},
exit: {
opacity: 0,
scale: 0.25,
filter: SWAP_BLUR,
transition: BLUR_EXIT_TRANSITION,
},
},
roll: {
initial: { opacity: 0, y: 12, filter: ROLL_BLUR },
animate: {
opacity: 1,
y: 0,
filter: "blur(0px)",
transition: ROLL_TRANSITION,
},
exit: {
opacity: 0,
y: -12,
filter: ROLL_BLUR,
transition: ROLL_EXIT_TRANSITION,
},
},
};
const VARIANT_CLASS: Record<ActionSwapButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
outline: "border border-border bg-transparent text-foreground hover:bg-muted/60",
ghost: "text-muted-foreground hover:bg-muted/60 hover:text-foreground",
};
const SIZE_CLASS: Record<ActionSwapButtonSize, string> = {
sm: "h-8 gap-1.5 rounded-full px-3 text-xs",
md: "h-10 gap-2 rounded-full px-4 text-sm",
lg: "h-12 gap-2.5 rounded-full px-5 text-base",
icon: "h-10 w-10 rounded-full",
};
export function ActionSwapText({
value,
children,
animation = "blur",
className,
}: ActionSwapTextProps) {
const reduce = useReducedMotion();
// Cascade needs a plain string to split into letters; non-string content
// and reduced motion fall back to the closest single-element animation.
const label = typeof children === "string" ? children : null;
const cascade = animation === "cascade" && label !== null && !reduce;
const coreAnimation: CoreAnimation =
animation === "cascade" ? "roll" : animation;
return (
<span
className={cn(
"relative -my-[0.08em] inline-block max-w-full whitespace-nowrap py-[0.08em] align-bottom",
className,
)}
style={{
clipPath: "inset(0 -999px)",
WebkitClipPath: "inset(0 -999px)",
}}
>
<span
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 ? (
<>
{/* Letters are decorative fragments; readers get the whole label. */}
<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.08em] inline-block whitespace-pre"
>
{label.split("").map((char, i) => (
<motion.span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity - the letter at a position is exactly what rolls.
key={i}
custom={i * CASCADE_STAGGER}
variants={CASCADE_LETTER_VARIANTS}
// Own states: a label that swaps away and straight back
// re-enters mid-exit, and only owned targets are restored.
initial="initial"
animate="animate"
exit="exit"
className="inline-block whitespace-pre will-change-[opacity,filter,transform]"
>
{char}
</motion.span>
))}
</motion.span>
</AnimatePresence>
</>
) : (
<AnimatePresence initial={false}>
<motion.span
key={`${animation}-${value}`}
variants={TEXT_VARIANTS[coreAnimation]}
initial={reduce ? false : "initial"}
animate={reduce ? { opacity: 1, filter: "blur(0px)", scale: 1, y: 0 } : "animate"}
exit={reduce ? undefined : "exit"}
// Truncation lives on the layer that holds the text - the layer
// moves as a whole, so clipping it never eats the roll.
className="absolute left-0 top-[0.08em] inline-block max-w-full truncate will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
)}
</span>
);
}
export function ActionSwapIcon({
value,
children,
animation = "blur",
className,
}: ActionSwapIconProps) {
const reduce = useReducedMotion();
// Icons are single elements - cascade maps to its closest motion, roll.
const coreAnimation: CoreAnimation =
animation === "cascade" ? "roll" : animation;
return (
<span className={cn("relative inline-grid shrink-0 place-items-center overflow-hidden", className)}>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={`${animation}-${value}`}
aria-hidden
variants={ICON_VARIANTS[coreAnimation]}
initial={reduce ? false : "initial"}
animate={reduce ? { opacity: 1, filter: "blur(0px)", scale: 1, y: 0 } : "animate"}
exit={reduce ? undefined : "exit"}
className="col-start-1 row-start-1 inline-flex items-center justify-center will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
</span>
);
}
export function ActionSwapButton({
items,
value,
defaultValue,
onValueChange,
variant = "secondary",
size = "md",
animation = "blur",
iconOnly = size === "icon",
cycle = true,
className,
disabled,
onClick,
style,
...rest
}: ActionSwapButtonProps) {
const reduce = useReducedMotion();
const [internalValue, setInternalValue] = useState(defaultValue ?? items[0]?.id);
const currentValue = value ?? internalValue;
const activeIndex = Math.max(0, items.findIndex((item) => item.id === currentValue));
const activeItem = items[activeIndex] ?? items[0];
const hasIcon = items.some((item) => item.icon);
const nextItem = cycle && items.length > 0 ? items[(activeIndex + 1) % items.length] : undefined;
if (!activeItem) return null;
const accessibleLabel = activeItem.ariaLabel ?? (iconOnly && typeof activeItem.label === "string" ? activeItem.label : undefined);
const layoutTransition = reduce ? { duration: 0 } : SPRING_LAYOUT;
return (
<motion.button
type="button"
disabled={disabled}
// A label of a different length resizes the button: glide the width on
// the soft layout spring, and only when the value changes, so unrelated
// page reflow never animates the button.
layout
layoutDependency={activeItem.id}
whileTap={reduce || disabled ? undefined : { scale: 0.97 }}
transition={{ ...SPRING_PRESS, layout: layoutTransition }}
// Layout animations only correct a radius set inline.
style={{ borderRadius: 9999, ...style }}
className={cn(
"inline-flex items-center justify-center overflow-hidden font-medium transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
aria-label={accessibleLabel}
onClick={(event) => {
onClick?.(event);
if (event.defaultPrevented || disabled || !cycle || !nextItem) return;
if (value === undefined) setInternalValue(nextItem.id);
onValueChange?.(nextItem.id, nextItem);
}}
{...rest}
>
{/* Position-only layout keeps the contents from stretching with the
button while its width glides. */}
{hasIcon ? (
<motion.span
layout="position"
layoutDependency={activeItem.id}
transition={layoutTransition}
className="inline-flex shrink-0"
>
<ActionSwapIcon value={activeItem.id} animation={animation} className="h-4 w-4">
{activeItem.icon ?? null}
</ActionSwapIcon>
</motion.span>
) : null}
{!iconOnly ? (
<motion.span
layout="position"
layoutDependency={activeItem.id}
transition={layoutTransition}
className="inline-flex min-w-0 max-w-full"
>
<ActionSwapText value={activeItem.id} animation={animation}>
{activeItem.label}
</ActionSwapText>
</motion.span>
) : null}
</motion.button>
);
}
fileReactNodeFile name or path shown in the header.
linesFileDiffLine[]Diff lines, each added, removed or context, with optional line numbers.
status?"complete" | "streaming""streaming" while lines arrive, "complete" once the edit lands. Default: "streaming"
streamingopen?booleanWhether the diff is expanded, for controlled use.
defaultOpen?booleanWhether the diff starts expanded when uncontrolled. Default: true
trueonOpenChange?((open: boolean) => void)Called with the new state when the diff expands or collapses.
collapseOnComplete?booleanFold the diff when status moves from streaming to complete. Default: true
truemaxHeight?numberTallest the line viewport grows before it scrolls (px). Default: 220
220language?"text" | "bash" | "diff" | "json" | "tsx" | "typescript"Language used for syntax highlighting. Default: "typescript"
typescriptcopyText?stringText the copy button writes to the clipboard. Shows the button when set.
onCopy?(() => void | Promise<void>)Runs instead of the clipboard write when the copy button is pressed.
labels?Partial<{ applying: string; applied: string; changes: string; copy: string; copied: string; }>Override any built-in string.
className?stringClasses merged onto the root element.
Place the patch inside the tool output that produced the file change.
ToolResult
└── ToolResultOutput
└── FileDiffNote: Code Block provides the shared syntax presentation for source lines. Tool Result summarizes the command or edit that produced the patch. Agent Activity records the file edit among surrounding agent events.
A file diff explains a proposed or completed edit. It should preserve the relationship between old and new lines while making the scale and status of the change visible at a glance.
Code Block
A syntax-highlighted code surface with stable streaming updates, line numbers, focused lines, smooth following, and copy feedback.
Tool Result
A lightweight execution disclosure for syntax-highlighted terminal output and request responses that collapses into a compact completed state.
Message
Composable conversation primitives for message rows, grouped bubbles, avatars, metadata, live markers, and a mount-only trailing-edge pop-up for newly sent rows.
Updated