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.

call-to-action.tsxTSX
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#

# One-time setup (tokens + lib helpers)npx koalaui-cli@latest init# Add this component (its dependencies come along)npx koalaui-cli@latest add code-snippet

Usage#

usage.tsxTSX
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.

install.shBash
# One-time setup (tokens + lib helpers)npx koalaui-cli@latest init# Add a component (its dependencies come along)npx koalaui-cli@latest add button
globals.cssCSS
: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.

usage.pyPython
from dataclasses import dataclass@dataclassclass 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) * rate
weekly-runs.sqlSQL
SELECT model, count(*) AS runs, avg(latency_ms) AS p50FROM completionsWHERE created_at > now() - interval '7 days'GROUP BY modelORDER BY runs DESC;
stream.goGo
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()	}}
agent.yamlYAML
model: claude-opus-5-5max_tokens: 4096tools:  - name: search_docs    description: Search the Koala UI docs  - name: run_tests

Install 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 shiki
lib/shiki-highlighter.tsTS
import { 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 = nullconst 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 }    }),  )}
app/providers.tsxTSX
"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.

button.tsxTSX
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.

button.tsxTSX
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.

TerminalBash
$ npx koalaui-cli@latest add button✓ wrote components/ui/button/button.tsx✓ wrote components/ui/button/index.ts✓ added button

Line numbers#

Set showLineNumbers to render a tabular-nums gutter, useful for longer listings or when referencing a specific line.

tokenize.tsTSX
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.

auth/reset.tsTS
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.

auth/session.tsTS
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 * 24Added: const SESSION_TTL = 60 * 60 * 24 * 7Added: const REFRESH_WINDOW = 60 * 60 * 24type SessionPayload = {  userId: stringexport async function getSession() {  const token = (await cookies()).get(SESSION_COOKIE)?.value  if (!token) return nullRemoved:   return verify(token)Added:   const session = await verify<SessionPayload>(token)Added:   if (!session) return nullAdded: 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.

members-table.tsxTSX
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.

comfortable.tsxTSX
const theme = "moonlight"
compact.tsxTSX
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.

PropTypeDefaultDescription
code*string-The source to render and copy.
langstring"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.
filenamestring-A filename chip in the header (and turns the header on).
dotsbooleanfalsemacOS-style window dots in the header (and turns the header on).
insetbooleantrueWith a header: a tinted frame with the code set 8px in as a sheet. false makes it a strip across one surface.
showLineNumbersboolean | "split"falseA tabular line-number gutter. "split" gives a diff two columns, the old number and the new one.
startLinenumber1The first gutter number, for an excerpt (the new file's, when split); diff counts lines from it.
oldStartLinenumberstartLineThe 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.
foldUnchangedboolean | numberfalseFold long runs of unchanged lines into a row that opens them in place. true keeps three lines of context beside each change.
collapsiblebooleanfalseClamps a long listing behind Show more / Show less, once it overflows.
collapsedHeightnumber320The clamped height in px.
wrapbooleanfalseFolds 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 attributeDescription
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.

PropTypeDefaultDescription
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.

FAQ#

Out of the box, a small dependency-free tokenizer highlights TS/TSX, JS, JSON, shell and CSS. Any other language reads as plain text until you provide a highlighter: with the Shiki adapter above, every language Shiki bundles is highlighted in your theme's syntax colors.