API snippetPro
A code sample with language tabs and copy, and a response pane that streams the JSON reply when Run is pressed, with its status, latency and size.
On this page
Installation
Usage
import { ApiSnippet } from "@/components/ui/chatcn/pro/api-snippet"
<ApiSnippet samples={samples} endpoint="POST /v1/answers" response={{ status: 200, body: reply }} />Each sample is { id, label, language, code }, highlighted by the free code block. response is either a scripted reply ({ status, body, latencyMs?, hint? }) that arrives after delay, or a function that makes a real call, for example with a rate limited demo key, and resolves with the reply. Either way the body streams into the pane in chunks, then the status line shows the code, the latency and the size. A non 2xx status reads as an error and shows hint under the body: say how to get past it.
Run becomes Stop in the same footprint while the reply is on its way. Waiting shows only after 300 ms, then for at least 400 ms, so a fast reply never flashes a loader.
Every section is full width with a 16 px gutter on phones and 32 px from 768 px, content capped at 1200 px. Layout follows the section's own width through a container query, not the viewport, so a section in a narrow column lays out like a phone.
Examples
Live call, waiting and errors
A real promise behind Run: a slow reply that shows the waiting state, then a rate limit that says how to get past it.
Props
| Prop | Type | Notes |
|---|---|---|
title | ReactNode | Optional section headline, an h2 |
description | ReactNode | The paragraph beside the headline |
samples | { id, label, language, code }[] | Required. The first is the default |
language, defaultLanguage, onLanguageChange | string | Controlled or not |
response | ApiSnippetResponse | (sample) => Promise<ApiSnippetResponse> | Required. Scripted or real |
delay | number | Ms before a scripted reply. Default 650 |
chunkSize, chunkMs | number | Streaming pace. Default 14 characters every 28 ms |
endpoint | string | Request line in the response header |
emptyText | ReactNode | The empty pane |
height | number | Code and response height. Default 340 |
onRun | (sample) => void | Each time Run is pressed |
Keyboard
| Key | Action |
|---|---|
Cmd+Enter / Ctrl+Enter | Runs, or stops, from any control inside |
ArrowLeft / ArrowRight | Moves between language tabs |
Tab | Reaches the tabs, Run, Copy code and the code |
Accessibility
- Language tabs are a Base UI tab list named Language.
- A polite live region says the result once, for example
Response 200 OK, 812 milliseconds. Chunks are never announced. - Status uses an icon and the status text, never color alone.
Motion
- The reply appends chunk by chunk with no per character effects.
- Run and Stop swap labels with a short morph; the status line fades in over 150 ms.