AI Stream
Streaming answers: words that sharpen in behind a caret, a skeleton that fills in line by line, and a version pager for regenerated replies.
"use client"
import * as React from "react"
import {
Check,
ChevronLeft,
ChevronRight,
Copy,
RefreshCw,
ThumbsDown,
ThumbsUp,
} from "lucide-react"
import {
AiKitStyles,
AiStyle,
cx,
Face,
Roll,
type AiMood,
type AiShape,
type AiTone,
} from "@/lib/ai-kit"
const CSS = `
.aik-st-msg,.aik-st-skel,.aik-st-vers{display:grid;gap:12px;width:min(100%,380px);align-content:start}
.aik-st-msg{min-height:228px}
.aik-st-who{display:flex;align-items:center;gap:8px;min-width:0}
.aik-st-who .aik-face{--aik-fs:22px}
.aik-st-who b{font-weight:600;font-size:13.5px}
.aik-st-who span:last-child{color:var(--aik-text-3);font-size:12px}
.aik-st-text{font-size:14.5px;line-height:23px;overflow-wrap:anywhere}
.aik-st-text code,.aik-st-vp code,.aik-st-real code{font:12.5px var(--aik-mono);padding:2px 5px;border-radius:5px;background:var(--aik-raised)}
.aik-st-msg:not([data-st="stream"]) .aik-caret{display:none}
.aik-st-msg[data-st="wait"] .aik-st-out:empty::before{content:"Writing";color:var(--aik-text-3)}
.aik-st-acts{display:flex;align-items:center;gap:2px;margin-left:-6px;visibility:hidden;opacity:0;transform:translateY(4px);
transition:opacity var(--aik-d-exit) var(--aik-ease-in),transform var(--aik-d-exit) var(--aik-ease-in),visibility 0s var(--aik-d-exit)}
.aik-st-msg[data-st="done"] .aik-st-acts{visibility:visible;opacity:1;transform:none;transition:opacity var(--aik-d-enter) var(--aik-ease-out),transform var(--aik-d-enter) var(--aik-ease-out)}
.aik-st-acts .aik-btn .ic{color:var(--aik-text-3)}
.aik-st-acts .aik-btn:hover .ic{color:var(--aik-text)}
.aik-st-tok{margin-left:auto;font:11.5px var(--aik-mono);color:var(--aik-text-3);white-space:nowrap}
.aik-st-skel{gap:8px}
.aik-st-rows{display:grid;gap:8px}
.aik-st-row{display:grid;align-items:center;min-height:22px;position:relative}
.aik-st-row > *{grid-area:1/1;min-width:0}
.aik-st-row.b{padding-left:16px}
.aik-st-row.b::before{content:"";position:absolute;left:3px;top:8.5px;inline-size:5px;block-size:5px;border-radius:50%;background:var(--aik-text-3)}
.aik-st-sk{block-size:10px;border-radius:5px;background:var(--aik-line-2);inline-size:var(--w,80%);animation:aik-st-pulse 1.1s ease-in-out infinite alternate;animation-delay:calc(var(--i,0)*120ms);transition:opacity var(--aik-d-exit) var(--aik-ease-in)}
.aik-st-row.h .aik-st-sk{block-size:13px;border-radius:6px;background:var(--aik-line-3)}
.aik-st-real{font-size:14px;line-height:22px;clip-path:inset(0 100% 0 0)}
.aik-st-row.h .aik-st-real{font-weight:600;font-size:15px;letter-spacing:-.01em}
.aik-st-row.e .aik-st-real{color:var(--aik-text-2)}
.aik-st-row[data-on] .aik-st-sk{opacity:0;animation:none}
.aik-st-row[data-on] .aik-st-real{clip-path:inset(0 -2% 0 0);transition:clip-path var(--aik-d-move) var(--aik-ease-out)}
@keyframes aik-st-pulse{to{opacity:.4}}
@media (prefers-reduced-motion: reduce){.aik-st-sk{animation:none}}
@media (prefers-reduced-motion: reduce){.aik-st-real{transition:none}}
.aik-st-vbox{display:grid;min-height:92px;align-content:start}
.aik-st-vbox > *{grid-area:1/1}
.aik-st-vp{font-size:14.5px;line-height:23px}
.aik-st-vp.aik-st-leave{animation:aik-out var(--aik-d-exit) var(--aik-ease-in) both}
.aik-st-vp.aik-st-enter{animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
.aik-st-vbar{display:flex;align-items:center;gap:8px;padding-top:10px;border-top:1px solid var(--aik-line)}
.aik-st-pager{display:inline-flex;align-items:center;gap:2px;margin-left:-6px}
.aik-st-pn{display:inline-flex;align-items:center;gap:4px;font:12px var(--aik-mono);color:var(--aik-text-2);font-variant-numeric:tabular-nums}
.aik-st-pn .aik-roll{color:var(--aik-text);font-weight:500;line-height:16px}
.aik-st-vbar .aik-btn.line{margin-left:auto}
.aik-st-regen.aik-st-go .ic{animation:aik-st-turn var(--aik-d-move) var(--aik-ease-move)}
@keyframes aik-st-turn{to{transform:rotate(360deg)}}
.aik-st-acts .aik-btn svg{color:var(--aik-text-3);transition:color var(--aik-d-state)}
.aik-st-acts .aik-btn:hover svg,.aik-st-acts .aik-btn[aria-pressed="true"] svg{color:var(--aik-text)}
.aik-st-copy{display:inline-grid;place-items:center}
.aik-st-copy > svg{grid-area:1/1;transition:opacity var(--aik-d-state) var(--aik-ease-out),transform var(--aik-d-state) var(--aik-ease-out),color var(--aik-d-state)}
.aik-st-copy > svg:last-child{opacity:0;transform:scale(.4)}
.aik-st-acts .aik-st-copy[data-ok] > svg:first-child{opacity:0;transform:scale(.4)}
.aik-st-acts .aik-st-copy[data-ok] > svg:last-child{opacity:1;transform:none;color:var(--aik-green)}
.aik-st-wait{color:var(--aik-text-3)}
.aik-st-pager .aik-btn:disabled{opacity:.35;cursor:default}
.aik-st-regen[data-busy] .ic{animation:aik-st-turn .8s linear infinite}
@media (prefers-reduced-motion: reduce){.aik-st-regen[data-busy] .ic{animation:none}}
`
export interface AiStreamAgent {
name: string
/** Face colour: a named tone or any CSS colour. */
tone?: AiTone | (string & {})
shape?: AiShape
}
function Who({
agent,
meta,
mood,
}: {
agent: AiStreamAgent
meta?: string
mood: AiMood
}) {
return (
<div className="aik-st-who">
<Face
size={22}
mood={mood}
shape={agent.shape ?? "orb"}
tone={agent.tone ?? "blue"}
/>
<b>{agent.name}</b>
{meta ? <span>{meta}</span> : null}
</div>
)
}
/** Splits text into word spans. Words wrapped in backticks render as inline code. */
function renderWords(text: string, animate: boolean) {
return text.split(/(\s+)/).map((token, at) => {
if (!token) return null
if (/^\s+$/.test(token)) return token
const code = token.match(/^`(.+?)`(.*)$/)
return (
<span key={at} className={animate ? "aik-w" : undefined}>
{code ? (
<>
<code>{code[1]}</code>
{code[2]}
</>
) : (
token
)}
</span>
)
})
}
export interface AiStreamProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"children"
> {
/** The answer so far. Grow this string as tokens arrive. Backticks mark inline code. */
text: string
/** `waiting` before the first token, `streaming` while text grows, `done` when complete. */
status: "waiting" | "streaming" | "done"
agent: AiStreamAgent
/** A short line beside the name, such as a timestamp. */
meta?: string
/** Shown at the end of the actions row, such as "35 words · 2.6s". */
stats?: string
/** The visitor's rating, if any. */
rating?: "up" | "down" | null
/** Called after the text was copied to the clipboard. */
onCopy?: () => void
onRetry?: () => void
onRate?: (rating: "up" | "down") => void
}
/** Words sharpen in behind a caret; the actions row arrives only when the stream ends. */
export function AiStream({
text,
status,
agent,
meta,
stats,
rating,
onCopy,
onRetry,
onRate,
className,
...rest
}: AiStreamProps) {
const [copied, setCopied] = React.useState(false)
React.useEffect(() => {
if (!copied) return
const timer = window.setTimeout(() => setCopied(false), 1400)
return () => window.clearTimeout(timer)
}, [copied])
const copy = async () => {
try {
await navigator.clipboard.writeText(text.replace(/`/g, ""))
} catch {
// Clipboard access can be refused; the button still confirms the press.
}
setCopied(true)
onCopy?.()
}
const done = status === "done"
return (
<div
{...rest}
className={cx("aik aik-st-msg", className)}
data-st={
status === "waiting" ? "wait" : status === "done" ? "done" : "stream"
}
>
<AiKitStyles />
<AiStyle id="ai-stream" css={CSS} />
<Who
agent={agent}
meta={meta}
mood={
status === "streaming"
? "talk"
: status === "waiting"
? "think"
: "idle"
}
/>
<p
className="aik-st-text"
aria-live="polite"
aria-busy={status !== "done"}
>
{text ? (
<span className="aik-st-out">{renderWords(text, true)}</span>
) : (
<span className="aik-st-wait aik-shimmer">Writing</span>
)}
<i className="aik-caret" />
</p>
<div className="aik-st-acts" aria-hidden={!done}>
<button
type="button"
className="aik-btn icon sm ghost aik-st-copy"
aria-label={copied ? "Copied" : "Copy"}
data-ok={copied ? "" : undefined}
tabIndex={done ? 0 : -1}
onClick={copy}
>
<Copy size={14} />
<Check size={14} />
</button>
<button
type="button"
className="aik-btn icon sm ghost"
aria-label="Retry"
tabIndex={done ? 0 : -1}
onClick={onRetry}
>
<RefreshCw size={14} />
</button>
<button
type="button"
className="aik-btn icon sm ghost"
aria-label="Good answer"
aria-pressed={rating === "up"}
tabIndex={done ? 0 : -1}
onClick={() => onRate?.("up")}
>
<ThumbsUp size={14} />
</button>
<button
type="button"
className="aik-btn icon sm ghost"
aria-label="Bad answer"
aria-pressed={rating === "down"}
tabIndex={done ? 0 : -1}
onClick={() => onRate?.("down")}
>
<ThumbsDown size={14} />
</button>
{stats ? <span className="aik-st-tok">{stats}</span> : null}
</div>
</div>
)
}
export interface AiSkeletonRow {
/** A heading, a bulleted line, or a closing line of plain text. */
kind: "heading" | "bullet" | "text"
/** The finished line. Backticks mark inline code. */
text: string
/** Skeleton bar width as a percentage of the row. */
width?: number
}
export interface AiSkeletonStreamProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"children"
> {
/** The shape of the answer, known before its words. */
rows: AiSkeletonRow[]
/** How many rows, from the top, have arrived. */
revealed: number
agent: AiStreamAgent
meta?: string
}
const ROW_CLASS = { heading: "h", bullet: "b", text: "e" } as const
/** The answer's shape shows first; each bar is wiped away by the line it stood for. */
export function AiSkeletonStream({
rows,
revealed,
agent,
meta,
className,
...rest
}: AiSkeletonStreamProps) {
const complete = revealed >= rows.length
return (
<div {...rest} className={cx("aik aik-st-skel", className)}>
<AiKitStyles />
<AiStyle id="ai-stream" css={CSS} />
<Who
agent={agent}
meta={meta}
mood={complete ? "idle" : revealed > 0 ? "talk" : "think"}
/>
<div className="aik-st-rows" aria-live="polite" aria-busy={!complete}>
{rows.map((row, at) => (
<div
key={at}
className={cx("aik-st-row", ROW_CLASS[row.kind])}
data-on={at < revealed ? "" : undefined}
style={
{
"--w": `${row.width ?? 76}%`,
"--i": at,
} as React.CSSProperties
}
>
<i className="aik-st-sk" />
<span className="aik-st-real" aria-hidden={at >= revealed}>
{renderWords(row.text, false)}
</span>
</div>
))}
</div>
</div>
)
}
export interface AiVersionsProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"children"
> {
/** Every answer generated so far, oldest first. */
versions: string[]
/** The version on show. */
index: number
onIndexChange: (index: number) => void
onRegenerate?: () => void
/** Spins the regenerate icon and blocks a second press. */
regenerating?: boolean
agent: AiStreamAgent
}
/** A finished answer with a pager over its earlier versions and a regenerate button. */
export function AiVersions({
versions,
index,
onIndexChange,
onRegenerate,
regenerating = false,
agent,
className,
...rest
}: AiVersionsProps) {
const total = versions.length
const at = Math.min(Math.max(index, 0), Math.max(total - 1, 0))
const current = versions[at] ?? ""
return (
<div {...rest} className={cx("aik aik-st-vers", className)}>
<AiKitStyles />
<AiStyle id="ai-stream" css={CSS} />
<Who
agent={agent}
meta={`${total} ${total === 1 ? "version" : "versions"}`}
mood={regenerating ? "think" : "idle"}
/>
<div className="aik-st-vbox" aria-live="polite">
<p key={at} className="aik-st-vp aik-st-enter">
{renderWords(current, false)}
</p>
</div>
<div className="aik-st-vbar">
<div className="aik-st-pager">
<button
type="button"
className="aik-btn icon sm ghost"
aria-label="Previous version"
disabled={at <= 0}
onClick={() => onIndexChange(at - 1)}
>
<ChevronLeft size={14} />
</button>
<span className="aik-st-pn">
<Roll>{String(at + 1)}</Roll>/<span>{total}</span>
</span>
<button
type="button"
className="aik-btn icon sm ghost"
aria-label="Next version"
disabled={at >= total - 1}
onClick={() => onIndexChange(at + 1)}
>
<ChevronRight size={14} />
</button>
</div>
<button
type="button"
className="aik-btn sm line aik-st-regen"
data-busy={regenerating ? "" : undefined}
disabled={regenerating}
onClick={onRegenerate}
>
<RefreshCw size={14} className="ic" />
Regenerate
</button>
</div>
</div>
)
}
Installation
One command adds ai-stream and the shared AI Kit layer it is built on (tokens, faces, marks and brand icons). No animation library, light and dark built in.
"use client"
import * as React from "react"
import { AiDemo } from "@/lib/ai-demo"
import { paceToken, useAiLoop } from "@/lib/ai-kit"
import {
AiSkeletonStream,
AiStream,
AiVersions,
type AiSkeletonRow,
} from "@/registry/tween/ai-stream"
const ANSWER =
"The headline now reveals word by word. I used `text-skew-reveal` with its default 0.65s and a 0.05s stagger, so the line lands in under a second. Reduced motion shows the finished headline straight away."
function WordFade() {
const root = React.useRef<HTMLDivElement>(null)
const [text, setText] = React.useState(ANSWER)
const [status, setStatus] = React.useState<"waiting" | "streaming" | "done">(
"done"
)
const [rating, setRating] = React.useState<"up" | "down" | null>(null)
const [hands, setHands] = React.useState(false)
useAiLoop(
root,
async ({ sleep }) => {
setRating(null)
setText("")
setStatus("waiting")
await sleep(900)
setStatus("streaming")
let so = ""
for (const word of ANSWER.split(" ")) {
so = so ? `${so} ${word}` : word
setText(so)
await sleep(paceToken(word))
}
setStatus("done")
await sleep(2600)
},
{ gap: 600, enabled: !hands }
)
return (
<div
ref={root}
style={{ display: "grid", width: "min(100%, 380px)" }}
onPointerDown={() => {
setHands(true)
setText(ANSWER)
setStatus("done")
}}
>
<AiStream
text={text}
status={status}
agent={{ name: "Mira" }}
meta="just now"
stats="35 words · 2.6s"
rating={rating}
onRate={(next) => setRating((now) => (now === next ? null : next))}
onRetry={() => setHands(false)}
/>
</div>
)
}
const ROWS: AiSkeletonRow[] = [
{ kind: "heading", text: "Three changes to the hero", width: 58 },
{
kind: "bullet",
text: "Headline reveals with `text-skew-reveal`",
width: 86,
},
{ kind: "bullet", text: "Button moved above the fold", width: 70 },
{ kind: "bullet", text: "Image loads lazily below 768px", width: 78 },
{ kind: "text", text: "All three pass on phone and desktop.", width: 64 },
]
function SkeletonFirst() {
const root = React.useRef<HTMLDivElement>(null)
const [revealed, setRevealed] = React.useState(ROWS.length)
useAiLoop(
root,
async ({ sleep }) => {
setRevealed(0)
await sleep(1300)
for (let at = 1; at <= ROWS.length; at++) {
setRevealed(at)
await sleep(620)
}
await sleep(2200)
},
{ gap: 500 }
)
return (
<div ref={root} style={{ display: "grid", width: "min(100%, 380px)" }}>
<AiSkeletonStream
rows={ROWS}
revealed={revealed}
agent={{ name: "Odo", tone: "violet", shape: "blob" }}
meta="just now"
/>
</div>
)
}
const DRAFTS = [
"Tween is a registry of animated React components built with GSAP and Three.js. You install each one with the shadcn CLI.",
"Tween gives you animated React components as source code. One command adds a component to your project, ready to restyle.",
"Animated React components, delivered as code you own. Add one with a single command and change anything you like.",
"Motion for React, as files in your repo. Pick a component, run one command, and edit it like the rest of your code.",
]
function Versions() {
const root = React.useRef<HTMLDivElement>(null)
const [count, setCount] = React.useState(3)
const [index, setIndex] = React.useState(1)
const [busy, setBusy] = React.useState(false)
const [hands, setHands] = React.useState(false)
useAiLoop(
root,
async ({ sleep }) => {
setCount(3)
setIndex(1)
await sleep(1700)
setIndex(2)
await sleep(1900)
setIndex(0)
await sleep(1900)
setBusy(true)
await sleep(1100)
setBusy(false)
setCount(4)
setIndex(3)
await sleep(2400)
},
{ gap: 400, enabled: !hands }
)
const regenerate = () => {
if (count >= DRAFTS.length) return setIndex(0)
setBusy(true)
window.setTimeout(() => {
setBusy(false)
setCount(count + 1)
setIndex(count)
}, 900)
}
return (
<div
ref={root}
style={{ display: "grid", width: "min(100%, 380px)" }}
onPointerDown={() => setHands(true)}
>
<AiVersions
versions={DRAFTS.slice(0, count)}
index={index}
onIndexChange={setIndex}
regenerating={busy}
onRegenerate={regenerate}
agent={{ name: "Pim", tone: "green", shape: "arch" }}
/>
</div>
)
}
export function AiStreamDemo({ only }: { only?: string }) {
return (
<AiDemo
only={only}
tabs={[
{ name: "Word fade", node: <WordFade /> },
{ name: "Skeleton first", node: <SkeletonFirst /> },
{ name: "Versions", node: <Versions /> },
]}
/>
)
}
Installation
Usage
import {
AiSkeletonStream,
AiStream,
AiVersions,
} from "@/components/ui/ai-stream"<AiStream
text={text}
status={status === "streaming" ? "streaming" : text ? "done" : "waiting"}
agent={{ name: "Mira" }}
meta="just now"
stats="35 words · 2.6s"
rating={rating}
onRate={setRating}
onRetry={regenerate}
/>Grow text as tokens arrive. Each new word fades in on its own, and words wrapped in backticks render as inline code. With the AI SDK, pass the text of the message's text part and map its state to status.
Versions
AiStreamfades each word in behind a caret. The face talks while text arrives, and the actions row (copy, retry, thumbs, stats) appears only oncestatusisdone. Copy writes the text to the clipboard and confirms with a check.AiSkeletonStreamtakes the shape of the answer first. Eachrowsentry shows as a pulsing bar untilrevealedpasses it, then the line wipes in over the bar, so nothing jumps.AiVersionsshows one of several finished answers with a pager and a regenerate button. Changingindexfades the next version into the same space.
Props
AiStream
| Prop | Type | Default | Description |
|---|---|---|---|
text | string | The answer so far. Backticks mark inline code. | |
status | "waiting" | "streaming" | "done" | Waiting shimmers, streaming shows the caret, done shows the actions. | |
agent | { name, tone?, shape? } | The face and name above the message. | |
meta | string | A short line beside the name. | |
stats | string | Shown at the end of the actions row. | |
rating | "up" | "down" | null | Which thumb is pressed. | |
onCopy | () => void | Called after the text is copied. | |
onRetry | () => void | Called from the retry button. | |
onRate | (rating: "up" | "down") => void | Called from the thumbs. |
AiSkeletonStream
| Prop | Type | Default | Description |
|---|---|---|---|
rows | { kind: "heading" | "bullet" | "text", text, width? }[] | The shape of the answer and its lines. | |
revealed | number | How many rows, from the top, have arrived. | |
agent | { name, tone?, shape? } | The face and name above the message. |
AiVersions
| Prop | Type | Default | Description |
|---|---|---|---|
versions | string[] | Every answer so far, oldest first. | |
index | number | The version on show. | |
onIndexChange | (index: number) => void | Called from the pager. | |
onRegenerate | () => void | Called from the regenerate button. | |
regenerating | boolean | false | Spins the icon and blocks a second press. |