Thinking
The agent's reasoning condenses into its label. While it thinks the lines stream under a rippling “Thinking”; when it ends they fold up, bottom line first, into “Thought for 12s”, and pour back out on click.
npx shadcn@latest add https://captain-ui.vercel.app/r/thinking.jsoncheckout.spec.ts is flaky again. Can you find out why?
…
"use client";
// Captain UI · Thinking, MIT. The reasoning condenses into its label: when thinking ends, the streamed lines fold up, bottom first, into "Thought for 12s", and pour back out of it on click.
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useEffect, useId, useRef, useState } from "react";
import { EASE, SPRING, cx, useIsoLayoutEffect } from "@/registry/captain/ui/captain";
import { Icon } from "@/registry/captain/ui/icons";
type ThinkingProps = {
/** True while the model is still reasoning. */
active: boolean;
/** The reasoning text so far. It can grow while active. */
children?: string;
/** When reasoning started, for the timer. Defaults to when `active` first became true. */
startedAt?: number;
/** Seconds it took, when you already know. */
seconds?: number;
/** Open while active, so people can watch it think. It folds into the label when thinking ends. */
openWhileActive?: boolean;
defaultOpen?: boolean;
className?: string;
};
const MAX_H = 220;
const LINE_MS = 170;
const TOTAL_MS = 280;
const EASE_CSS = "cubic-bezier(0.23, 1, 0.32, 1)";
function useElapsed(active: boolean, startedAt?: number) {
const start = useRef<number | null>(startedAt ?? null);
const [s, setS] = useState(0);
useEffect(() => {
if (!active) return;
if (start.current == null) start.current = startedAt ?? Date.now();
const tick = () => setS(Math.max(0, Math.floor((Date.now() - (start.current ?? Date.now())) / 1000)));
tick();
const t = setInterval(tick, 250);
return () => clearInterval(t);
}, [active, startedAt]);
return s;
}
/** A line's path into the label. It is gone by just past halfway, so lines never pile up visibly where they converge. */
function into(dx: number, dy: number): Keyframe[] {
const at = (f: number) => `translate(${dx * f}px, ${dy * f}px) scale(${1 - 0.45 * f})`;
return [
{ opacity: 1, transform: "none" },
{ opacity: 0, transform: at(0.55), offset: 0.55 },
{ opacity: 0, transform: at(1) },
];
}
/** The visible words of the body, grouped into the lines they wrapped onto, top line first. */
function linesOf(box: HTMLElement) {
const view = box.getBoundingClientRect();
const rows = new Map<number, { el: HTMLElement; r: DOMRect }[]>();
box.querySelectorAll<HTMLElement>("[data-w]").forEach((el) => {
const r = el.getBoundingClientRect();
if (r.bottom <= view.top || r.top >= view.bottom) return;
const key = Math.round(r.top);
rows.set(key, [...(rows.get(key) ?? []), { el, r }]);
});
return [...rows.entries()].sort((a, b) => a[0] - b[0]).map(([, ws]) => ws);
}
export function Thinking({ active, children = "", startedAt, seconds, openWhileActive = false, defaultOpen = false, className }: ThinkingProps) {
const elapsed = useElapsed(active, startedAt);
const [open, setOpen] = useState(defaultOpen || (active && openWhileActive));
const reduce = useReducedMotion();
const id = useId();
const took = seconds ?? elapsed;
const body = useRef<HTMLDivElement>(null);
const label = useRef<HTMLButtonElement>(null);
const busy = useRef(false);
const live = useRef(active);
live.current = active;
const unfold = useRef(false);
/** Each line travels up into the label and shrinks into it, the bottom line first, while the body closes over them. */
const fold = () => {
const box = body.current;
const lab = label.current;
if (!box || !lab || busy.current) return setOpen(false);
busy.current = true;
const target = lab.getBoundingClientRect();
const lines = linesOf(box).reverse();
const stagger = lines.length > 1 ? Math.min(32, (TOTAL_MS - LINE_MS) / (lines.length - 1)) : 0;
lines.forEach((ws, i) => {
const left = ws[0]!.r.left;
for (const { el, r } of ws) {
// A line rises at most a line-height toward the label, and is gone (opacity 0 at 55%) before it reaches
// the line above, so no line ever crosses another, however far the label is.
const dy = Math.max(-r.height, target.top + target.height / 2 + (lines.length - 1 - i) * 2 - (r.top + r.height / 2));
const dx = Math.max(-24, (target.left + 8 - left) * 0.6);
el.style.transformOrigin = `${left - r.left}px 50%`;
el.animate(reduce ? [{ opacity: 1 }, { opacity: 0 }] : into(dx, dy), { duration: LINE_MS, delay: i * stagger, easing: EASE_CSS, fill: "forwards" });
}
});
const end = reduce ? LINE_MS : TOTAL_MS;
// The body closes a beat behind the lines, so it never clips one mid-flight.
box.parentElement?.animate([{ height: `${box.parentElement.offsetHeight}px` }, { height: "0px" }], { duration: end, easing: "cubic-bezier(0.55, 0, 0.45, 1)", fill: "forwards" });
setTimeout(() => {
busy.current = false;
// If thinking started again mid-fold (a rewound transcript), stay open for it.
if (live.current && openWhileActive) box.parentElement?.getAnimations({ subtree: true }).forEach((a) => a.cancel());
else setOpen(false);
}, end);
};
const toggle = () => {
if (busy.current) return;
if (open) fold();
else {
unfold.current = true;
setOpen(true);
}
};
// Thinking just ended with the reasoning on show: condense it into the label.
const wasActive = useRef(active);
useEffect(() => {
if (wasActive.current && !active && openWhileActive && open) fold();
else if (!wasActive.current && active && openWhileActive && !open) {
unfold.current = true;
setOpen(true);
}
wasActive.current = active;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active, openWhileActive]);
// Opened by a click: the lines pour back out of the label, top line first.
useIsoLayoutEffect(() => {
if (!open || !unfold.current) return;
unfold.current = false;
const box = body.current;
const lab = label.current;
const wrap = box?.parentElement;
if (!box || !lab || !wrap) return;
const h = Math.min(MAX_H, box.scrollHeight) + 12;
const source = lab.getBoundingClientRect();
const lines = linesOf(box);
const stagger = lines.length > 1 ? Math.min(32, (TOTAL_MS - LINE_MS) / (lines.length - 1)) : 0;
lines.forEach((ws, i) => {
const left = ws[0]!.r.left;
for (const { el, r } of ws) {
// Out of the label and down into place, from a short drop so no line crosses another.
const dy = Math.max(-18, source.top + source.height / 2 - (r.top + r.height / 2));
const dx = 0;
el.style.transformOrigin = `${left - r.left}px 50%`;
el.animate(reduce ? [{ opacity: 0 }, { opacity: 1 }] : into(dx, dy).reverse().map((k, j) => ({ ...k, offset: j === 1 ? 0.45 : undefined })), {
duration: LINE_MS,
delay: i * stagger,
easing: EASE_CSS,
fill: "backwards",
});
}
});
if (!reduce) wrap.animate([{ height: "0px" }, { height: `${h}px` }], { duration: TOTAL_MS, easing: EASE_CSS });
}, [open]);
// Keep the newest reasoning in view while it streams.
useEffect(() => {
if (active && open && body.current) body.current.scrollTop = body.current.scrollHeight;
}, [children, active, open]);
const text = active ? "Thinking" : took < 1 ? "Thought for a moment" : `Thought for ${took}s`;
const paras = (children || (active ? "…" : "")).split("\n");
return (
<div className={cx("w-full max-w-[560px]", className)}>
<button
ref={label}
type="button"
aria-expanded={open}
aria-controls={id}
onClick={toggle}
className="group -ml-2 flex h-9 items-center gap-1.5 rounded-[8px] px-2 text-[14px] transition-colors hover:bg-hover focus-visible:bg-hover"
>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={active ? "on" : "off"}
// The finished label rises into place as the lines land in it.
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 5, scale: 0.97 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, transition: { duration: 0.1 } }}
transition={{ duration: 0.22, ease: EASE, delay: active ? 0 : 0.08 }}
className={cx("relative origin-left", active ? "text-ink" : "text-ink-2 group-hover:text-ink")}
aria-label={text}
>
{active && !reduce
? Array.from(text).map((ch, i) => (
<span key={i} aria-hidden="true" className="cu-wave" style={{ animationDelay: `${i * 70}ms` }}>
{ch}
</span>
))
: text}
</motion.span>
</AnimatePresence>
{active && elapsed > 0 ? <span className="tnum text-[13px] text-ink-3">{elapsed}s</span> : null}
<motion.span animate={{ rotate: open ? 90 : 0 }} transition={reduce ? { duration: 0 } : SPRING} className="grid place-items-center text-ink-3">
<Icon name="chevronRight" size={15} />
</motion.span>
</button>
{open ? (
<div id={id} className="overflow-hidden">
<div ref={body} className="mt-1 mb-2 overflow-y-auto pl-2" style={{ maxHeight: MAX_H }}>
<div className="text-[13.5px] leading-[1.6] text-ink-2" aria-live={active ? "polite" : undefined}>
{paras.map((p, i) =>
p.trim() ? (
<p key={i} className={cx(i > 0 && paras[i - 1]!.trim() === "" && "mt-[0.8em]")}>
{p.split(" ").map((w, j, all) => (
<span key={j}>
<span data-w="" className="inline-block">
{w}
</span>
{j < all.length - 1 ? " " : null}
</span>
))}
</p>
) : null,
)}
</div>
</div>
</div>
) : null}
<style>{`
.cu-wave{display:inline-block;white-space:pre;animation:cu-wave 1.4s ease-in-out infinite}
@keyframes cu-wave{0%,100%{opacity:.38}35%{opacity:1}}
`}</style>
</div>
);
}Usage
import { Thinking } from "@/components/ui/thinking"
<Thinking active={part.state === "streaming"}>{part.text}</Thinking>Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| active | boolean | True while the model is still reasoning. | |
| children | string | The reasoning so far. It can grow while active. | |
| startedAt | number | Epoch ms when reasoning started, for the timer. | |
| seconds | number | How long it took, if you already know. | |
| openWhileActive | boolean | false | Show the reasoning as it streams, then fold it into the label when thinking ends. |
| defaultOpen | boolean | false | Start open. |
Keyboard
- Enter / Space
- Open or close the reasoning
Accessibility
- A disclosure button with aria-expanded.
- The label is read once, not letter by letter.
- Streaming text is a polite live region while open.
- Under reduced motion the ripple stops and the fold is a plain fade.