Code Snippet
A polished code block: rounded surface, optional window chrome, copy-on-hover, line numbers and token-driven highlighting. A small, dependency-free tokenizer covers TS/TSX, JSON, shell and CSS; plug in Shiki for every other language, in your theme's colors.
import { Button } from "@/components/ui/button"
import { ArrowRight } from "koala-icons"
export function CallToAction() {
// The label is the affordance; the icon just clarifies it.
return (
<Button>
Get started
<ArrowRight className="size-4" />
</Button>
)
}Installation#
Usage#
import { CodeSnippet } from "@/components/ui/code-snippet"
export function Example() {
return <CodeSnippet lang="tsx" code={`const x = 1`} />
}Languages#
Set lang to switch grammars. TS/TSX, shell (bash/sh), and CSS are highlighted; the language chip in the header reflects the choice.
# One-time setup (tokens + lib helpers)
npx koalaui-cli@latest init
# Add a component (its dependencies come along)
npx koalaui-cli@latest add button:root {
--radius: 1rem;
--primary: oklch(0.62 0.19 256);
--syntax-keyword: oklch(0.5 0.2 295);
}
.dark {
--primary: oklch(0.7 0.16 256);
}More languages#
For Python, Go, SQL, YAML and the two hundred other languages Shiki knows, put a CodeHighlighterProvider above your snippets. A highlighter answers in Koala's token types, not colors, so Shiki paints with the same syntax tokens and follows all four themes. Nothing in Code Snippet imports Shiki: without the provider, the bundle is as small as before.
from dataclasses import dataclass
@dataclass
class Usage:
input_tokens: int
output_tokens: int
def cost(self, rate: float = 3e-6) -> float:
# Output tokens cost five times as much.
return (self.input_tokens + 5 * self.output_tokens) * rateSELECT model, count(*) AS runs, avg(latency_ms) AS p50
FROM completions
WHERE created_at > now() - interval '7 days'
GROUP BY model
ORDER BY runs DESC;func stream(w http.ResponseWriter, tokens <-chan string) {
flusher := w.(http.Flusher)
for token := range tokens {
fmt.Fprintf(w, "data: %s\n\n", token)
flusher.Flush()
}
}model: claude-opus-5-5
max_tokens: 4096
tools:
- name: search_docs
description: Search the Koala UI docs
- name: run_testsInstall Shiki, add the adapter, and provide it once near the root of your app. Languages load the first time a snippet asks for one, on Shiki's JavaScript engine (no WASM).
npm install shikiimport { createCssVariablesTheme, createHighlighterCore, type HighlighterCore } from "shiki/core"
import { createJavaScriptRegexEngine } from "shiki/engine/javascript"
import { bundledLanguages } from "shiki/langs"
import type { CodeHighlighter, CodeToken, CodeTokenType } from "@/lib/code-highlighter"
const theme = createCssVariablesTheme({ name: "koala", variablePrefix: "--shiki-" })
const ROLE: Record<string, CodeTokenType> = {
"token-keyword": "keyword",
"token-string": "string",
"token-string-expression": "string",
"token-link": "string",
"token-comment": "comment",
"token-function": "function",
"token-constant": "number",
"token-parameter": "attribute",
"token-punctuation": "punctuation",
}
let core: Promise<HighlighterCore> | null = null
const loading = new Map<string, Promise<void>>()
function highlighter() {
core ??= createHighlighterCore({ themes: [theme], langs: [], engine: createJavaScriptRegexEngine() })
return core
}
export const shikiHighlighter: CodeHighlighter = async (code, lang) => {
const load = bundledLanguages[lang as keyof typeof bundledLanguages]
if (!load) return null
const shiki = await highlighter()
if (!shiki.getLoadedLanguages().includes(lang)) {
if (!loading.has(lang)) loading.set(lang, load().then((mod) => shiki.loadLanguage(mod.default)))
await loading.get(lang)
}
const { tokens } = shiki.codeToTokens(code, { lang, theme: "koala" })
return tokens.map((line) =>
line.map((token): CodeToken => {
const role = /--shiki-([\w-]+)/.exec(token.color ?? "")?.[1]
return { type: role ? ROLE[role] : undefined, value: token.content }
}),
)
}"use client"
import { CodeHighlighterProvider } from "@/lib/code-highlighter"
import { shikiHighlighter } from "@/lib/shiki-highlighter"
export function Providers({ children }: { children: React.ReactNode }) {
return <CodeHighlighterProvider highlighter={shikiHighlighter}>{children}</CodeHighlighterProvider>
}Window chrome#
A filename adds the header with a language chip; dots adds macOS-style window dots. With either, the snippet wears the inset look: the header sits on a tinted frame and the code is a sheet set 8px into it, its corners concentric with the frame's. Omit both for a chromeless block.
export function Button() {
return <button className="btn">Click me</button>
}export function Button() {
return <button className="btn">Click me</button>
}When the snippet is already a sheet inside another frame (a preview's Code tab), a second frame would double the chrome. Pass inset={false} and the header becomes a strip across the one surface instead.
export function Button() {
return <button className="btn">Click me</button>
}Terminal sessions#
In a shell snippet, start a line with $ and it reads as a session: the prompt dims, each line without one is the command's output, in muted ink with a leading ✓ kept green. The copy button copies only the commands, without their prompt, so what lands on the clipboard runs as pasted.
$ npx koalaui-cli@latest add button
✓ wrote components/ui/button/button.tsx
✓ wrote components/ui/button/index.ts
✓ added buttonLine numbers#
Set showLineNumbers to render a tabular-nums gutter, useful for longer listings or when referencing a specific line.
export function tokenize(code: string) {
const tokens = []
for (const line of code.split("\n")) {
tokens.push(line.trim())
}
return tokens
}Diff#
Show a change in context. startLine numbers the gutter from the excerpt's real position in the file, and diff marks lines as added or removed by that same number. A marked line takes a soft success or destructive band across the code plus a bar in the gutter, so the mark never rests on color alone, and a screen reader hears “Added” or “Removed” before it. The copy button still copies the plain code string.
export function buildResetLink(userId: string) {
const token = signResetToken({ uid: userId })
Removed: const baseUrl = "https://staging.example.com"
Added: const baseUrl = "https://example.com"
const url = new URL("/reset-password", baseUrl)
url.searchParams.set("token", token)
return url.toString()
}Split gutter and folds#
For a longer diff, showLineNumbers="split" numbers both sides of the change: a removed line keeps its old number, an added line gets only its new one. foldUnchanged folds the long runs between changes into a row that says how many lines it holds; click it and they open in place.
import { cookies } from "next/headers"
import { sign, verify } from "@/lib/auth/jwt"
import { db } from "@/lib/db"
const SESSION_COOKIE = "koala_session"
Removed: const SESSION_TTL = 60 * 60 * 24
Added: const SESSION_TTL = 60 * 60 * 24 * 7
Added: const REFRESH_WINDOW = 60 * 60 * 24
type SessionPayload = {
userId: string
export async function getSession() {
const token = (await cookies()).get(SESSION_COOKIE)?.value
if (!token) return null
Removed: return verify(token)
Added: const session = await verify<SessionPayload>(token)
Added: if (!session) return null
Added:
Added: const expiresIn = session.exp * 1000 - Date.now()
Added: if (expiresIn < REFRESH_WINDOW * 1000) {
Added: await createSession(session.userId, session.workspaceId)
Added: }
Added:
Added: return db.user.findUnique({ where: { id: session.userId } })
}Collapsible#
Long listings get noisy. Set collapsible to clamp the block to collapsedHeight (320px by default): the last lines dissolve into a bottom fade and a Show more toggle expands it to full height, animated. The toggle only appears once the content actually overflows the clamp, measured from the DOM, so short blocks are left untouched.
import * as React from "react"
import { tv } from "@/lib/tv"
import { Button } from "@/components/ui/button"
type Member = {
id: string
name: string
email: string
status: "Active" | "Invited" | "Suspended"
balance: number
}
const columns: ColumnDef<Member>[] = [
{
accessorKey: "name",
header: "Member",
cell: ({ row }) => (
<TableCellText primary={row.original.name} secondary={row.original.email} />
),
},
{
accessorKey: "status",
header: "Status",
cell: ({ getValue }) => <Badge size="sm">{getValue<string>()}</Badge>,
},
{
accessorKey: "balance",
header: "Balance",
meta: { numeric: true },
cell: ({ getValue }) => `$${getValue<number>()}`,
},
]
export function MembersTable({ data }: { data: Member[] }) {
return <DataTable columns={columns} data={data} />
}Density#
Like other Koala surfaces, Code Snippet honors density. compact (the default) suits dense app UI; comfortable opens up the padding for docs and marketing. Density retunes spacing only, never radius or color.
const theme = "moonlight"const theme = "moonlight"API reference#
CodeSnippet
A highlighted, copyable code block with a copy button on hover. Forwards native <div> props except children; accepts className, merged last onto the root.
| Prop | Type | Default | Description |
|---|---|---|---|
| code* | string | - | The source to render and copy. |
| lang | string | "tsx" | The language and the header chip. TSX, TS, JS, JSON, CSS and shell are built in; a shell listing with $ prompts reads as a session. Any other language needs a CodeHighlighterProvider, or reads as plain text; text is always plain. |
| filename | string | - | A filename chip in the header (and turns the header on). |
| dots | boolean | false | macOS-style window dots in the header (and turns the header on). |
| inset | boolean | true | With a header: a tinted frame with the code set 8px in as a sheet. false makes it a strip across one surface. |
| showLineNumbers | boolean | "split" | false | A tabular line-number gutter. "split" gives a diff two columns, the old number and the new one. |
| startLine | number | 1 | The first gutter number, for an excerpt (the new file's, when split); diff counts lines from it. |
| oldStartLine | number | startLine | The first line's number in the old file, for a split gutter. |
| diff | { added?: number[]; removed?: number[] } | - | Lines marked by their position from startLine: a tinted band and gutter bar, announced as Added or Removed. |
| foldUnchanged | boolean | number | false | Fold long runs of unchanged lines into a row that opens them in place. true keeps three lines of context beside each change. |
| collapsible | boolean | false | Clamps a long listing behind Show more / Show less, once it overflows. |
| collapsedHeight | number | 320 | The clamped height in px. |
| wrap | boolean | false | Folds long lines instead of scrolling sideways: for a prompt or prose, not shaped code. |
| density | "comfortable" | "compact" | "compact" | Padding only. Falls back to the nearest DensityProvider. |
| Data attribute | Description |
|---|---|
| data-diff | "added" or "removed" on a marked line and its gutter cell. |
CodeHighlighterProvider
From @/lib/code-highlighter. Every Code Snippet below it asks this highlighter first and falls back on its own grammar when the answer is null. Shell sessions keep the built-in reading.
| Prop | Type | Default | Description |
|---|---|---|---|
| highlighter* | (code: string, lang: string) => CodeToken[][] | null | Promise<CodeToken[][] | null> | - | Lines of { type?, value } tokens, where type is a Koala syntax role. While a block streams, finished lines keep their color between answers. |