About
Starter cards, chips and follow up rows for a chat, each a real button that staggers in once.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Suggestions to your project and fits it to your theme.
Code
How Suggestions is used: the demo's code. The component's own source comes with a free account.
Usage.tsx
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import { Icon, IconNode, Suggestion, Suggestions, createIcon } from "@/components/ui/suggestions"
interface GhostState {
x: number
y: number
shown: boolean
down: boolean
}
/**
* A pointer that walks a demo through its clicks, so a preview shows what each control does.
* `stage` is the positioned box the pointer moves in; targets are found inside it. Sizes come
* from layout boxes, so a scaled FitFrame never throws the aim off.
*/
function useGhost(stage: React.RefObject<HTMLElement | null>) {
const [ghost, setGhost] = React.useState<GhostState>({ x: 0, y: 0, shown: false, down: false })
const find = React.useCallback(
(target: string | HTMLElement) =>
typeof target === "string"
? stage.current?.querySelector<HTMLElement>(target) ?? null
: target,
[stage],
)
const moveTo = React.useCallback(
(target: string | HTMLElement, dx = 0.5, dy = 0.6) => {
const root = stage.current
const el = find(target)
if (!root || !el) return null
const rr = root.getBoundingClientRect()
const scale = root.offsetWidth ? rr.width / root.offsetWidth : 1
const er = el.getBoundingClientRect()
const x = (er.left - rr.left + er.width * dx) / scale
const y = (er.top - rr.top + er.height * dy) / scale
// A hidden pointer fades in a short way off its first target instead of flying in from
// wherever it was last.
setGhost((g) => (g.shown ? { x, y, shown: true, down: false } : { x: x + 70, y: y + 46, shown: false, down: false }))
window.requestAnimationFrame(() =>
window.requestAnimationFrame(() => setGhost({ x, y, shown: true, down: false })),
)
return el
},
[stage, find],
)
const press = React.useCallback((down: boolean) => setGhost((g) => ({ ...g, down })), [])
const hide = React.useCallback(() => setGhost((g) => ({ ...g, shown: false, down: false })), [])
return { ghost, moveTo, press, hide, find }
}
type Step = "start" | "thread"
const WORD_MS = 46
const reducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches
const STOP = Symbol("stop")
/**
* Runs `script` in a loop with a `wait(ms)` that stops cleanly on unmount or once `active` turns
* false. Reduced motion never starts it.
*/
function useLoop(
script: (wait: (ms: number) => Promise<void>) => Promise<void>,
active = true,
) {
const ref = React.useRef(script)
ref.current = script
React.useEffect(() => {
if (!active || reducedMotion()) return
let alive = true
const timers = new Set<number>()
const wait = (ms: number) =>
new Promise<void>((resolve, reject) => {
const id = window.setTimeout(() => {
timers.delete(id)
if (alive) resolve()
else reject(STOP)
}, ms)
timers.add(id)
})
;(async () => {
try {
while (alive) await ref.current(wait)
} catch (error) {
if (error !== STOP) throw error
}
})()
return () => {
alive = false
for (const id of timers) window.clearTimeout(id)
}
}, [active])
}
const ASK = "Find what makes the runs page slow."
const REPLY =
"The runs query sorts 40,000 rows by created_at with no index, so every load reads the whole table. That is 1.6 of its 2 seconds."
const FOLLOW_UPS = [
"Add the index in a migration",
"Show me the query plan",
"What else runs on every load?",
]
const NEXT_REPLY =
"Added 0042_runs_created_at.sql. It builds the index concurrently, so the table stays writable, and the page now loads in 380 ms."
const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"
/**
* 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
* phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
* render white on dark pages. FitFrame fills the frame exactly instead.
*
* - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
* - "crop": the content stays at full size from the top and fades out at the bottom. For text
* that streams in, where a changing scale would make the page breathe.
*
* `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
* to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
* shrinks evenly on both sides.
*
* Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
* shorter than `hideBelow`, so a profile card shows the visual alone.
*/
function FitFrame({
children,
mode = "scale",
hideBelow = 360,
minWidth,
}: {
children: React.ReactNode
mode?: "scale" | "crop"
hideBelow?: number
minWidth?: string
}) {
const content = React.useRef<HTMLDivElement>(null)
const [cropped, setCropped] = React.useState(false)
React.useLayoutEffect(() => {
const el = content.current
if (!el) return
const measure = () => {
const vw = window.innerWidth
const vh = window.innerHeight
el.toggleAttribute("data-fit-small", vh < hideBelow)
// Layout sizes ignore the transform, so measuring never feeds back.
const w = Math.max(el.offsetWidth, el.scrollWidth)
const h = Math.max(el.offsetHeight, el.scrollHeight)
const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
el.style.transform = scale < 1 ? `scale(${scale})` : ""
setCropped(mode === "crop" && h > vh + 1)
}
measure()
const observer = new ResizeObserver(measure)
observer.observe(el)
// Content that changes inside a fixed width box (a headline that cycles words) never resizes
// the box itself, so changes below it measure again on the next frame.
let frame = 0
const mutations = new MutationObserver(() => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(measure)
})
mutations.observe(el, { subtree: true, childList: true, characterData: true })
window.addEventListener("resize", measure)
return () => {
observer.disconnect()
mutations.disconnect()
cancelAnimationFrame(frame)
window.removeEventListener("resize", measure)
}
}, [mode, hideBelow])
const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
return (
<div
className="flex w-full justify-center overflow-hidden"
style={{
height: "100dvh",
alignItems: mode === "crop" ? "flex-start" : "center",
maskImage: cropped ? fade : undefined,
WebkitMaskImage: cropped ? fade : undefined,
}}
>
<style>{FIT_CSS}</style>
<div
ref={content}
className="w-full shrink-0"
style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
>
{children}
</div>
</div>
)
}
const iconNode: IconNode = [
["path", {"d":"M4.63 18.66a9 9 0 1 1 14.74 0"}],
["path", {"d":"m12 13.5 3.75-3.75"}],
]
const GaugeIcon: Icon = /* @__PURE__ */ createIcon("gauge", iconNode)
const iconNode2: IconNode = [
["path", {"d":"M3.5 5.5a8.5 3 0 1 0 17 0 8.5 3 0 1 0-17 0"}],
["path", {"d":"M3.5 5.5v13a8.5 3 0 0 0 17 0v-13"}],
["path", {"d":"M3.5 12a8.5 3 0 0 0 17 0"}],
]
const DatabaseIcon: Icon = /* @__PURE__ */ createIcon("database", iconNode2)
const iconNode3: IconNode = [
["path", {"d":"m3 6.5 1.04 1.04a1 1 0 0 0 1.42 0L8.5 4.5"}],
["path", {"d":"m3 17.5 1.04 1.04a1 1 0 0 0 1.42 0L8.5 15.5"}],
["path", {"d":"M12.5 6h8"}],
["path", {"d":"M12.5 12h8"}],
["path", {"d":"M12.5 18h8"}],
]
const ListChecksIcon: Icon = /* @__PURE__ */ createIcon("list-checks", iconNode3)
const iconNode4: IconNode = [
["path", {"d":"M5.73 13.32 9.55 9.5a4 4 0 0 1 1.38-.9l3.62-1.42a1.75 1.75 0 0 1 2.27 2.27l-1.42 3.62a4 4 0 0 1-.9 1.38l-3.82 3.82a1.25 1.25 0 0 1-1.77 0l-3.18-3.18a1.25 1.25 0 0 1 0-1.77"}],
["path", {"d":"M7.67 11.38H4.22a1.25 1.25 0 0 0-1.07 1.89l.99 1.64"}],
["path", {"d":"M12.62 16.33v3.45a1.25 1.25 0 0 1-1.89 1.07l-1.64-.99"}],
["path", {"d":"M11.05 11.2a1.75 1.75 0 1 0 3.5 0 1.75 1.75 0 1 0-3.5 0"}],
["path", {"d":"m5.2 18.8-1.95 1.95"}],
]
const RocketIcon: Icon = /* @__PURE__ */ createIcon("rocket", iconNode4)
const STARTERS = [
{
title: "Speed up a page",
description: "Find what makes the runs page slow.",
icon: <GaugeIcon />,
},
{
title: "Plan a migration",
description: "Move sessions from Redis to Postgres.",
icon: <DatabaseIcon />,
},
{
title: "Write release notes",
description: "From the pull requests merged this week.",
icon: <ListChecksIcon />,
},
{
title: "Ship a fix",
description: "Branch, fix, test and open the pull request.",
icon: <RocketIcon />,
},
]
/* -------------------------------------------------------------------------------------------------
* Types and context
* -----------------------------------------------------------------------------------------------*/
type MessageRole = "user" | "assistant" | "system"
type MessageLayout = "auto" | "bubble" | "flat" | "compact"
type MessageState = "streaming" | "done" | "edited" | "error" | "stopped" | "queued"
/* -------------------------------------------------------------------------------------------------
* Message
* -----------------------------------------------------------------------------------------------*/
interface MessageProps extends React.ComponentProps<"div"> {
/** Who wrote it. Named `from` so the ARIA `role` attribute stays free. */
from: MessageRole
/**
* `auto` gives users a subtle bubble and assistants a flat, document-style block. `compact`
* is the dense log style for agent traces and side panels. Defaults to `auto`.
*/
layout?: MessageLayout
/** Lifecycle state. Defaults to `done`. */
state?: MessageState
/** Follows a message from the same author: tightens the gap and hides the avatar. */
grouped?: boolean
/** The newest message. Keeps its actions visible instead of revealing them on hover. */
latest?: boolean
/**
* Enter animation. Defaults to animating only messages that arrive after the conversation
* mounted, so restored history appears at once.
*/
animate?: boolean
/** Announce the text to screen readers when streaming finishes. Defaults to true. */
announce?: boolean
}
/** Scroll behavior for imperative calls. `smooth` falls back to instant under reduced motion. */
type ChatcnScrollBehavior = "smooth" | "instant"
/* -------------------------------------------------------------------------------------------------
* Context
* -----------------------------------------------------------------------------------------------*/
interface ConversationContextValue {
scrollRef: (element: HTMLElement | null) => void
contentRef: (element: HTMLElement | null) => void
spacerRef: (element: HTMLElement | null) => void
/** Within the threshold of the bottom. */
isAtBottom: boolean
/** Following new content. */
isSticky: boolean
/** More than one viewport from the bottom. */
isFar: boolean
/** Messages that arrived below while the reader was scrolled up. */
unread: number
scrollToBottom: (options?: { behavior?: ChatcnScrollBehavior }) => void
scrollToTurn: (element: HTMLElement, options?: { behavior?: ChatcnScrollBehavior }) => void
/** Read text to screen readers through the conversation's polite live region. */
announce: (text: string) => void
/** False during the first render, so restored history does not animate in. */
ready: boolean
}
const ConversationContext = React.createContext<ConversationContextValue | null>(null)
/** Scroll state and controls of the nearest `Conversation`. Returns null outside one. */
function useConversation() {
return React.useContext(ConversationContext)
}
interface MessageContextValue {
from: MessageRole
/** Resolved layout: `auto` becomes `bubble` for users and `flat` for everyone else. */
layout: Exclude<MessageLayout, "auto">
state: MessageState
/** The newest message: its actions stay visible. */
latest: boolean
}
const MessageContext = React.createContext<MessageContextValue | null>(null)
/**
* One turn in the conversation. Compose `MessageAvatar`, `MessageContent`, `MessageMeta`,
* `MessageStatus` and `MessageActions` inside it.
*/
function Message({
from,
layout: layoutProp = "auto",
state = "done",
grouped = false,
latest = false,
animate,
announce = true,
className,
children,
...props
}: MessageProps) {
const conversation = useConversation()
const layout: MessageContextValue["layout"] =
layoutProp === "auto" ? (from === "user" ? "bubble" : "flat") : layoutProp
const [enter] = React.useState(() => animate ?? conversation?.ready ?? false)
const ref = React.useRef<HTMLDivElement>(null)
// Screen readers hear the finished reply once, never token by token.
const previous = React.useRef(state)
React.useEffect(() => {
const was = previous.current
previous.current = state
if (!announce || was !== "streaming" || state === "streaming") return
const text = ref.current?.querySelector('[data-slot="message-content"]')?.textContent?.trim()
if (text) conversation?.announce(text)
}, [state, announce, conversation])
const value = React.useMemo(
() => ({ from, layout, state, latest }),
[from, layout, state, latest],
)
return (
<MessageContext.Provider value={value}>
<div
ref={ref}
data-slot="message"
data-role={from}
data-layout={layout}
data-message-state={state}
data-grouped={grouped ? "" : undefined}
data-latest={latest ? "" : undefined}
aria-busy={state === "streaming" || undefined}
className={cn(
"group/message relative flex min-w-0 flex-col",
layout === "compact" ? "gap-1" : "gap-2",
layout === "bubble" ? "items-end" : "items-start",
from === "system" && layout !== "compact" && "items-center text-center",
grouped && (layout === "compact" ? "-mt-2" : "-mt-4"),
// An avatar sits in the start gutter (the end gutter for bubbles).
layout === "bubble"
? "has-[>[data-slot=message-avatar]]:pe-9"
: "has-[>[data-slot=message-avatar]]:ps-9",
enter &&
(from === "user"
? "ease-(--chatcn-ease-out-soft) transition-[opacity,translate] duration-200 starting:translate-y-2 starting:opacity-0 motion-reduce:starting:translate-y-0"
: "ease-(--chatcn-ease-out-soft) transition-opacity duration-150 starting:opacity-0"),
className,
)}
{...props}
>
{children}
</div>
</MessageContext.Provider>
)
}
/** Role, layout and state of the nearest `Message`. Returns null outside one. */
function useMessage() {
return React.useContext(MessageContext)
}
/* -------------------------------------------------------------------------------------------------
* MessageContent
* -----------------------------------------------------------------------------------------------*/
/**
* The text of a message, capped at a 68ch measure. Plain text keeps its line breaks. Markdown
* renderers drop in as children and inherit the 15/24 prose size.
*/
function MessageContent({ className, children, ...props }: React.ComponentProps<"div">) {
const ctx = useMessage()
const layout = ctx?.layout ?? "flat"
const from = ctx?.from ?? "assistant"
const state = ctx?.state ?? "done"
const plain = typeof children === "string"
return (
<div
data-slot="message-content"
className={cn(
"text-(color:--chatcn-fg) min-w-0 [overflow-wrap:anywhere]",
// Bubbles fill their lines: pretty wrapping would leave a wide, half-empty bubble.
layout !== "bubble" && "text-pretty",
plain && "whitespace-pre-wrap",
layout === "bubble" &&
"text-[0.9375rem]/[1.5rem] tracking-[-0.006em] rounded-(--chatcn-radius-xl) bg-(color:--chatcn-fill) max-w-[80%] px-4 py-2.5 text-start",
layout === "flat" && "text-[0.9375rem]/[1.5rem] tracking-[-0.006em] w-full max-w-[68ch]",
layout === "compact" &&
(from === "user"
? "text-[0.875rem]/[1.25rem] tracking-[-0.003em] rounded-(--chatcn-radius-md) bg-(color:--chatcn-fill) max-w-full px-3 py-1.5"
: "text-[0.875rem]/[1.25rem] tracking-[-0.003em] w-full max-w-[68ch]"),
from === "system" && "text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-muted) max-w-[60ch]",
// Queued turns are not sent yet: an outline instead of a fill says "pending".
state === "queued" &&
from === "user" &&
"text-(color:--chatcn-fg-muted) border-(color:--chatcn-border-strong) border border-dashed bg-transparent",
state === "error" && from === "user" && "text-(color:--chatcn-fg-muted)",
className,
)}
{...props}
>
{children}
</div>
)
}
/** The pointer itself. Put it last inside the stage, which must be `relative`. */
function Ghost({ ghost }: { ghost: GhostState }) {
return (
<div
aria-hidden
className="pointer-events-none absolute top-0 left-0 z-20"
style={{
transform: `translate(${ghost.x}px, ${ghost.y}px)`,
opacity: ghost.shown ? 1 : 0,
// Hidden, it jumps; shown, it glides.
transition: ghost.shown
? "transform 620ms cubic-bezier(0.4, 0, 0.2, 1), opacity 220ms ease-out"
: "opacity 220ms ease-out",
}}
>
<svg
width="18"
height="20"
viewBox="0 0 18 20"
className="drop-shadow-[0_1px_2px_rgb(0_0_0/0.25)]"
style={{
transform: ghost.down ? "scale(0.86)" : "scale(1)",
transformOrigin: "2px 2px",
transition: "transform 120ms ease-out",
}}
>
<path
d="M2 1.5 L2 16 L5.9 12.4 L8.6 18.3 L11.2 17.1 L8.6 11.3 L13.9 11.1 Z"
className="fill-[oklch(0.2_0_0)] stroke-white dark:fill-white dark:stroke-[oklch(0.2_0_0)]"
strokeWidth="1.3"
strokeLinejoin="round"
/>
</svg>
</div>
)
}
/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
return (
<p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
{children}{" "}
<a
href={`https://chatcn.dev/docs/components/${slug}`}
target="_blank"
rel="noopener"
className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
>
chatcn.dev
</a>
</p>
)
}
/**
* A new chat with four starter cards. The pointer picks one, the answer streams, and three
* follow-ups stagger in under it as rows. The pointer picks the first, and the next answer
* streams. Loops. Click anything to stop the tour and pick yourself.
*/
export default function SuggestionsPreview() {
const stage = React.useRef<HTMLDivElement>(null)
const g = useGhost(stage)
const [touring, setTouring] = React.useState(true)
const [step, setStep] = React.useState<Step>("start")
const [round, setRound] = React.useState(0)
const [turns, setTurns] = React.useState<{ ask: string; reply: string }[]>([])
const [followUps, setFollowUps] = React.useState(false)
const stream = async (ask: string, reply: string, wait: (ms: number) => Promise<void>) => {
setTurns((t) => [...t, { ask, reply: "" }])
await wait(500)
const words = reply.split(" ")
for (let i = 1; i <= words.length; i += 1) {
const text = words.slice(0, i).join(" ")
setTurns((t) => t.map((turn, n) => (n === t.length - 1 ? { ...turn, reply: text } : turn)))
await wait(WORD_MS)
}
}
const press = async (target: string, wait: (ms: number) => Promise<void>) => {
if (!g.moveTo(target)) return false
await wait(720)
g.press(true)
await wait(140)
g.press(false)
await wait(160)
return true
}
useLoop(async (wait) => {
setStep("start")
setTurns([])
setFollowUps(false)
setRound((r) => r + 1)
await wait(1700)
if (!(await press('[data-demo="starters"] [data-slot="suggestion"]:nth-child(1)', wait))) return
g.hide()
setStep("thread")
await stream(ASK, REPLY, wait)
await wait(400)
setFollowUps(true)
await wait(1500)
if (!(await press('[data-demo="follow-ups"] [data-slot="suggestion"]:nth-child(1)', wait))) return
g.hide()
setFollowUps(false)
await stream(FOLLOW_UPS[0]!, NEXT_REPLY, wait)
await wait(2600)
}, touring)
// Picked by hand, once the tour has stopped.
const pickStarter = (prompt: string) => {
if (touring) return
setStep("thread")
setTurns([{ ask: prompt, reply: REPLY }])
setFollowUps(true)
}
const pickFollowUp = (prompt: string) => {
if (touring) return
setFollowUps(false)
setTurns((t) => [...t, { ask: prompt, reply: NEXT_REPLY }])
}
return (
<FitFrame minWidth="38rem">
<div className="flex w-full flex-col items-center justify-center gap-3 p-4">
<div
ref={stage}
className="relative w-full max-w-2xl"
onPointerDown={() => {
if (!touring) return
setTouring(false)
g.hide()
}}
>
<div className="bg-(color:--chatcn-bg) rounded-(--chatcn-radius-xl) shadow-(--chatcn-shadow-border) flex h-[23rem] w-full flex-col overflow-hidden">
{step === "start" ? (
<div
key={round}
className="flex flex-1 flex-col justify-center gap-5 px-8 transition-opacity duration-200 starting:opacity-0"
>
<h2 className="text-[1.5rem]/[2rem] tracking-[-0.022em] text-(color:--chatcn-fg) font-medium tracking-[-0.01em]">
What should we work on?
</h2>
<div data-demo="starters">
<Suggestions variant="cards" className="[&>[role=group]]:grid-cols-2">
{STARTERS.map((s) => (
<Suggestion
key={s.title}
icon={s.icon}
description={s.description}
value={s.description}
onSelect={pickStarter}
>
{s.title}
</Suggestion>
))}
</Suggestions>
</div>
</div>
) : (
// Newest at the bottom; older turns slide up under a soft top edge.
<div className="flex min-h-0 flex-1 flex-col justify-end gap-5 overflow-hidden px-7 pb-6 [mask-image:linear-gradient(to_bottom,transparent,black_48px)]">
{turns.map((turn) => (
<React.Fragment key={turn.ask}>
<Message from="user">
<MessageContent>{turn.ask}</MessageContent>
</Message>
{turn.reply ? (
<Message from="assistant" animate={false}>
<MessageContent>{turn.reply}</MessageContent>
</Message>
) : null}
</React.Fragment>
))}
{/* Under the first answer the rows keep their space before they arrive, so the
thread never jumps when they stagger in. */}
{followUps ? (
<div data-demo="follow-ups">
<Suggestions variant="rows" label="Follow-ups">
{FOLLOW_UPS.map((f) => (
<Suggestion key={f} onSelect={pickFollowUp}>
{f}
</Suggestion>
))}
</Suggestions>
</div>
) : turns.length === 1 ? (
<div aria-hidden className="h-[10rem] shrink-0" />
) : null}
</div>
)}
</div>
<Ghost ghost={g.ghost} />
</div>
<MoreOn slug="suggestions">Starter cards and follow-up rows that stagger in once. On</MoreOn>
</div>
</FitFrame>
)
}
















