Code Block
An AI-response code block that streams in line by line and folds long snippets.
Code
components/thinking-ui/code-block.tsx
"use client";
import { AnimatePresence, motion } from "motion/react";
import { memo, useEffect, useId, useMemo, useState } from "react";
import { TextShimmer } from "@/components/thinking-ui/text-shimmer";
import { useMotion } from "@/lib/motion";
import { cn } from "@/lib/utils";
export type CodeBlockProps = {
/** The code received so far. Pass the growing string while streaming. */
code: string;
/** Language label, e.g. `ts`. Also picks `#` or `//` comments for tinting. */
language?: string;
filename?: string;
/** New lines blur in once and a caret sits at the end. Never collapses. */
streaming?: boolean;
/** Lines shown before the rest folds behind "Show N more lines". */
maxLines?: number;
/** Controlled expanded state. Leave it out for uncontrolled use. */
expanded?: boolean;
defaultExpanded?: boolean;
onExpandedChange?: (expanded: boolean) => void;
/** Lightweight keyword / string / comment tinting. */
highlight?: boolean;
onCopy?: (code: string) => void;
className?: string;
};
/** Every row is exactly this tall, so the folded height is just maths. */
const LINE = 20;
const PAD_Y = 10;
export function CodeBlock({
code,
language,
filename,
streaming = false,
maxLines = 12,
expanded: expandedProp,
defaultExpanded = false,
onExpandedChange,
highlight = true,
onCopy,
className,
}: CodeBlockProps) {
const m = useMotion();
const bodyId = useId();
const [copied, setCopied] = useState(false);
const [innerExpanded, setInnerExpanded] = useState(defaultExpanded);
const [wasStreaming, setWasStreaming] = useState(streaming);
const { ms } = m;
// Code the reader just watched arrive stays open when the stream ends
if (wasStreaming !== streaming) {
setWasStreaming(streaming);
if (!streaming) setInnerExpanded(true);
}
const expanded = expandedProp ?? innerExpanded;
const setExpanded = (next: boolean) => {
if (expandedProp === undefined) setInnerExpanded(next);
onExpandedChange?.(next);
};
useEffect(() => {
if (!copied) return;
const id = setTimeout(() => setCopied(false), ms(1600));
return () => clearTimeout(id);
}, [copied, ms]);
const lines = useMemo(() => code.split("\n"), [code]);
const pattern = highlight ? patternFor(language) : null;
const collapsible = !streaming && lines.length > maxLines;
const open = !collapsible || expanded;
const hidden = lines.length - maxLines;
const copy = () => {
onCopy?.(code);
navigator.clipboard
?.writeText(code)
.then(() => setCopied(true))
.catch(() => {});
};
const pop = m.pop();
return (
<div className={cn("w-full overflow-hidden rounded-card border border-card-line bg-card shadow-card", className)}>
<div className="flex h-9 items-center gap-2 border-b border-line-subtle pl-3 pr-1">
{filename && (
<>
<svg viewBox="0 0 16 16" className="size-icon-sm shrink-0 text-fg-muted" aria-hidden>
<path d="M4 2.5h5l3 3v8H4zM9 2.5v3h3" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" />
</svg>
<span className="truncate font-mono text-xs text-fg-secondary">{filename}</span>
</>
)}
{language && (
<span
className={cn(
"shrink-0 font-mono text-2xs",
filename ? "rounded-chip bg-chip px-1.5 py-px text-chip-fg" : "text-fg-muted",
)}
>
{language}
</span>
)}
<span className="relative ml-auto text-2xs">
<AnimatePresence initial={false}>
{streaming && (
<motion.span key="writing" className="block" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={m.tween("base")}>
<TextShimmer>Writing…</TextShimmer>
</motion.span>
)}
</AnimatePresence>
</span>
<motion.button
type="button"
aria-label={copied ? "Copied" : "Copy code"}
title={copied ? "Copied" : "Copy code"}
onClick={copy}
whileTap={m.press}
transition={m.spring("micro")}
className="transition-ui grid size-control-sm shrink-0 place-items-center rounded-control text-fg-muted hover:bg-fill-muted hover:text-fg"
>
<AnimatePresence mode="popLayout" initial={false}>
{copied ? (
<motion.svg key="check" viewBox="0 0 16 16" className="size-icon-sm text-fg-success" {...pop}>
<path d="M3.5 8.5l3 3 6-7" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
</motion.svg>
) : (
<motion.svg key="copy" viewBox="0 0 16 16" className="size-icon-sm" {...pop}>
<rect x="5" y="5" width="8.5" height="8.5" rx="2" fill="none" stroke="currentColor" strokeWidth="1.4" />
<path d="M11 5V4a1.5 1.5 0 00-1.5-1.5H4A1.5 1.5 0 002.5 4v5.5A1.5 1.5 0 004 11h1" fill="none" stroke="currentColor" strokeWidth="1.4" />
</motion.svg>
)}
</AnimatePresence>
</motion.button>
<span className="sr-only" aria-live="polite">
{copied ? "Code copied to clipboard" : ""}
</span>
</div>
{/* Height folds between a fixed number of rows and auto; rows keep their own size */}
<motion.div
className="relative overflow-hidden"
initial={false}
animate={{ height: open ? "auto" : maxLines * LINE + PAD_Y }}
transition={m.reduce ? { duration: 0 } : m.spring("layout")}
>
<pre
id={bodyId}
role="region"
aria-label={filename ?? (language ? `${language} code` : "Code")}
aria-busy={streaming}
tabIndex={0}
className="overflow-x-auto font-mono text-xs"
style={{ paddingBlock: PAD_Y }}
>
<code className="block w-max min-w-full">
{lines.map((line, i) => (
<CodeLine
key={i}
text={line}
pattern={pattern}
enter={streaming && !m.reduce}
caret={streaming && i === lines.length - 1}
/>
))}
</code>
</pre>
<AnimatePresence initial={false}>
{!open && (
<motion.span
aria-hidden
className="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-gradient-to-t from-[var(--card-bg)] to-transparent"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={m.tween("base")}
/>
)}
</AnimatePresence>
</motion.div>
<AnimatePresence initial={false}>
{collapsible && (
<motion.div key="toggle" className="overflow-hidden" {...m.collapse()}>
<button
type="button"
aria-expanded={open}
aria-controls={bodyId}
onClick={() => setExpanded(!open)}
className="transition-ui flex h-8 w-full items-center justify-center gap-1.5 border-t border-line-subtle text-xs text-fg-muted hover:bg-fill-faint hover:text-fg"
>
<span className="relative overflow-hidden">
<AnimatePresence mode="popLayout" initial={false}>
<motion.span key={String(open)} className="block" {...m.swap()}>
{open ? "Show less" : `Show ${hidden} more line${hidden === 1 ? "" : "s"}`}
</motion.span>
</AnimatePresence>
</span>
<motion.svg
aria-hidden
viewBox="0 0 16 16"
className="size-icon-sm"
animate={{ rotate: open ? 180 : 0 }}
transition={m.spring("micro")}
>
<path d="M4 6l4 4 4-4" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</motion.svg>
</button>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
/* ── Rows ────────────────────────────────────────────────── */
type CodeLineProps = { text: string; pattern: RegExp | null; enter: boolean; caret: boolean };
/** Memoized so only the row that's still growing re-renders while streaming. */
const CodeLine = memo(function CodeLine({ text, pattern, enter, caret }: CodeLineProps) {
const m = useMotion();
// Decided once at mount: rows that arrive mid-stream animate, rows already there never do
const [animateIn] = useState(enter);
const tokens = useMemo(() => (pattern ? tokenize(text, pattern) : [{ text }]), [text, pattern]);
return (
<motion.span
className="block overflow-hidden whitespace-pre px-3.5 text-fg-tertiary"
style={{ lineHeight: `${LINE}px`, height: animateIn ? undefined : LINE }}
initial={animateIn ? { height: 0, opacity: 0, filter: m.blur(Math.max(m.personality.blur, 3)) } : false}
animate={animateIn ? { height: LINE, opacity: 1, filter: m.blur(0) } : undefined}
transition={{ height: m.spring("layout"), default: m.tween("slow") }}
>
{tokens.map((token, i) =>
token.kind ? (
<span key={i} className={tone[token.kind]}>
{token.text}
</span>
) : (
token.text
),
)}
{/* Zero-width space keeps empty rows selectable and full height */}
{text === "" && !caret && ""}
{caret && <Caret />}
</motion.span>
);
});
function Caret() {
const m = useMotion();
return (
<motion.span
aria-hidden
className="ml-px inline-block h-[1.1em] w-[0.5ch] translate-y-[0.2em] rounded-caret bg-fg-secondary"
animate={m.reduce ? { opacity: 0.6 } : { opacity: [1, 0.15] }}
transition={m.reduce ? { duration: 0 } : { duration: 0.5 * m.scale, repeat: Infinity, repeatType: "reverse" }}
/>
);
}
/* ── Tinting ─────────────────────────────────────────────
One regex per line, no grammar. Monochrome on purpose:
brightness carries structure, and only strings get a hue. */
type TokenKind = "comment" | "string" | "keyword" | "number" | "call";
const tone: Record<TokenKind, string> = {
comment: "text-fg-muted italic",
string: "text-fg-success",
keyword: "text-fg",
number: "text-fg-secondary",
call: "text-fg-secondary",
};
const KEYWORDS = [
"const", "let", "var", "function", "return", "if", "else", "for", "while", "do", "switch", "case", "break",
"continue", "import", "from", "export", "default", "async", "await", "new", "class", "extends", "implements",
"type", "interface", "enum", "typeof", "keyof", "public", "private", "static", "readonly", "def", "in", "of",
"not", "and", "or", "true", "false", "null", "undefined", "None", "True", "False", "try", "catch", "finally",
"throw", "raise", "yield", "as", "with", "lambda", "pass", "elif", "self", "this", "fn", "pub", "use", "mut",
"struct", "impl", "match", "func", "package", "echo", "then", "fi",
].join("|");
const STRING = /"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`(?:[^`\\]|\\.)*`?/.source;
const NUMBER = /\d[\d_]*(?:\.\d+)?/.source;
const CALL = /[A-Za-z_$][\w$]*(?=\()/.source;
const build = (comment: string) =>
new RegExp(`(${comment})|(${STRING})|\\b(${KEYWORDS})\\b|\\b(${NUMBER})\\b|(${CALL})`, "g");
const SLASH = build(/\/\/.*|\/\*.*?\*\//.source);
const HASH = build(/#.*/.source);
const HASH_LANGUAGES = new Set(["py", "python", "sh", "bash", "zsh", "shell", "yaml", "yml", "toml", "rb", "ruby", "r", "dockerfile", "makefile"]);
function patternFor(language?: string) {
return language && HASH_LANGUAGES.has(language.toLowerCase()) ? HASH : SLASH;
}
function tokenize(line: string, pattern: RegExp) {
const kinds: TokenKind[] = ["comment", "string", "keyword", "number", "call"];
const out: { text: string; kind?: TokenKind }[] = [];
let last = 0;
// matchAll clones the regex, so the shared global pattern keeps no state
for (const match of line.matchAll(pattern)) {
const start = match.index ?? 0;
if (start > last) out.push({ text: line.slice(last, start) });
const group = match.findIndex((g, i) => i > 0 && g !== undefined);
out.push({ text: match[0], kind: kinds[group - 1] });
last = start + match[0].length;
}
if (last < line.length) out.push({ text: line.slice(last) });
return out;
}Motion notes
- Each new line grows from zero height while it fades in from a blur, so the card extends smoothly instead of jumping a row at a time. Lines already on screen never animate again.
- Every row has a fixed height, so the folded state is plain arithmetic and the expander animates between that height and auto on the layout spring, with no measuring.
- Code you just watched stream in is never collapsed under you. The fold only applies to blocks that arrive complete, and a streamed block offers “Show less” instead.
- The copy icon pops into a check, and a polite live region announces the copy. With reduced motion, rows appear at once, the fold snaps, and the caret holds still instead of blinking.
Installation
- 1
Install dependencies
Terminalnpm install motion clsx tailwind-merge - 2
Add the design tokens and motion system (once per project)
Copy
styles/tokens/*,lib/motion.tsxandlib/utils.tsfrom Get started. - 3
Add the components it uses
- 4
Paste the source into components/thinking-ui/code-block.tsx
Copy it from the Code tab, or use Copy prompt to let your coding agent do all of this.
Usage
Example
<CodeBlock
code={code}
language="ts"
filename="debounce.ts"
streaming={status === "streaming"}
maxLines={12}
/>Props
| Prop | Type | Default | Description |
|---|---|---|---|
| code | string | — | The code received so far. Pass the growing string while streaming. |
| language | string | — | Label shown in the header. Python, shell, YAML and similar use # comments when tinting. |
| filename | string | — | Shown in the header with a file icon. |
| streaming | boolean | false | Animates new lines in, shows a caret and a “Writing…” shimmer. Never collapses while true. |
| maxLines | number | 12 | Lines shown before the rest folds behind “Show N more lines”. |
| expanded | boolean | — | Controlled expanded state. Leave it out for uncontrolled use. |
| defaultExpanded | boolean | false | Start expanded when uncontrolled. |
| onExpandedChange | (expanded: boolean) => void | — | Called when the expander is pressed. |
| highlight | boolean | true | Lightweight, monochrome keyword, string and comment tinting. |
| onCopy | (code: string) => void | — | Called when the copy button is pressed. The code is also written to the clipboard. |
| className | string | — | Classes for the card. |