Code Block
React code blocks built with the CodeBlock components and Shiki on the server, with folder tab headers, copy buttons, line numbers, marked lines and text, file tabs, remembered package managers, files loaded on demand, collapsed code, and a browser playground.
Examples
import { useState } from "react";
export function Counter() {
const [count, setCount] = useState(0);
return (
<button type="button" onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}npm install @ariakit/reactexport function formatPrice(amount: number, currency = "USD") {
const format = new Intl.NumberFormat("en-US", {
style: "currency",
currency,
});
return format.format(amount);
}import { useEffect, useState } from "react";
/** Returns the value after it stops changing for `delay` milliseconds. */
export function useDebouncedValue<T>(value: T, delay = 300) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timeout = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timeout);
}, [value, delay]);
return debouncedValue;
}import { useState } from "react";
export function Disclosure({ title, children }) {
const [open, setOpen] = useState(false);
return (
<section>
<button aria-expanded={open} onClick={() => setOpen(!open)}>
{title}
</button>
{open && <div>{children}</div>}
</section>
);
}import type { User } from "./types.ts";
// Loads one page of users. The signal cancels the request when the page
// changes before it ends.
export async function fetchUsers(page: number, signal?: AbortSignal) {
const params = new URLSearchParams({ page: String(page), limit: "20" });
const response = await fetch(`/api/users?${params}`, { signal });
if (!response.ok) {
throw new Error(`Couldn't load page ${page} of users: ${response.status} ${response.statusText}`);
}
const users: User[] = await response.json();
return users.map((user) => ({ ...user, name: user.name.trim() }));
}import "./toggle.css";
import { useToggle } from "./use-toggle.ts";
export function Toggle({ children }) {
const { open, toggle } = useToggle();
return (
<div className="toggle">
<button aria-expanded={open} onClick={toggle}>
{open ? "Hide details" : "Show details"}
</button>
{open && <div className="toggle-content">{children}</div>}
</div>
);
}import { useCallback, useState } from "react";
export function useToggle(initialOpen = false) {
const [open, setOpen] = useState(initialOpen);
const toggle = useCallback(() => setOpen((open) => !open), []);
return { open, toggle };
}.toggle {
display: grid;
gap: 0.5rem;
}
.toggle button {
justify-self: start;
padding: 0.5rem 0.875rem;
border: 1px solid oklch(0.8 0.02 255);
border-radius: 0.5rem;
font: inherit;
}
.toggle-content {
padding: 0.75rem;
border-radius: 0.5rem;
background: oklch(0.97 0.01 255);
}import { TodoForm } from "./todo-form.tsx";
import { TodoList } from "./todo-list.tsx";
import { useTodos } from "./use-todos.ts";
import "./todos.css";
export function TodoApp() {
const { todos, addTodo, toggleTodo } = useTodos();
return (
<main className="todo-app">
<TodoForm onAdd={addTodo} />
<TodoList todos={todos} onToggle={toggleTodo} />
</main>
);
}import { useState } from "react";
export function TodoForm({ onAdd }) {
const [title, setTitle] = useState("");
return (
<form
onSubmit={(event) => {
event.preventDefault();
onAdd(title);
setTitle("");
}}
>
<input
aria-label="New task"
value={title}
onChange={(event) => setTitle(event.target.value)}
/>
<button type="submit">Add</button>
</form>
);
}import { TodoItem } from "./todo-item.tsx";
export function TodoList({ todos, onToggle }) {
return (
<ul className="todo-list">
{todos.map((todo) => (
<TodoItem key={todo.id} todo={todo} onToggle={onToggle} />
))}
</ul>
);
}export function TodoItem({ todo, onToggle }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
{todo.title}
</label>
</li>
);
}import { useState } from "react";
import type { Todo } from "./types.ts";
export function useTodos(initialTodos: Todo[] = []) {
const [todos, setTodos] = useState(initialTodos);
const addTodo = (title: string) => {
const todo = { id: crypto.randomUUID(), title, done: false };
setTodos((todos) => [...todos, todo]);
};
const toggleTodo = (id: string) => {
setTodos((todos) =>
todos.map((todo) => (todo.id === id ? { ...todo, done: !todo.done } : todo)),
);
};
return { todos, addTodo, toggleTodo };
}export interface Todo {
id: string;
title: string;
done: boolean;
}.todo-app {
display: grid;
gap: 1rem;
}
.todo-list {
display: grid;
gap: 0.5rem;
padding: 0;
list-style: none;
}[
{ "id": "1", "title": "Water the plants", "done": true },
{ "id": "2", "title": "Call the bank", "done": false }
]import "./toggle.css";
import { useToggle } from "./use-toggle.ts";
export function Toggle({ children }) {
const { open, toggle } = useToggle();
return (
<div className="toggle">
<button aria-expanded={open} onClick={toggle}>
{open ? "Hide details" : "Show details"}
</button>
{open && <div className="toggle-content">{children}</div>}
</div>
);
}import { useEffect, useState } from "react";
interface User {
id: string;
name: string;
email: string;
}
type State =
| { status: "loading" }
| { status: "loaded"; users: User[] }
| { status: "failed"; error: Error };
export function useUsers(teamId: string) {
const [state, setState] = useState<State>({ status: "loading" });
useEffect(() => {
const controller = new AbortController();
setState({ status: "loading" });
fetch(`/api/teams/${teamId}/users`, { signal: controller.signal })
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
})
.then((users: User[]) => setState({ status: "loaded", users }))
.catch((error: Error) => {
if (controller.signal.aborted) return;
setState({ status: "failed", error });
});
return () => controller.abort();
}, [teamId]);
return state;
}{
"name": "pricing-page",
"version": "1.4.0",
"private": true,
"description": "A pricing page with three plans, a monthly or yearly switch, and a table that compares the features of each plan side by side.",
"keywords": ["pricing", "plans", "billing", "comparison table", "subscription", "checkout"],
"scripts": {
"dev": "astro dev --host",
"build": "astro check && astro build",
"test": "vitest run --coverage --reporter=verbose --exclude \"**/fixtures/**\"",
"lint": "oxlint --deny-warnings src && prettier --check \"src/**/*.{ts,tsx,astro,css,json,md}\""
},
"dependencies": {
"@ariakit/react": "^0.4.0",
"astro": "^7.4.0"
}
}export function Greeting({ name }) {
return <p>Hello, {name}!</p>;
}export function Greeting({ name }) {
return <p>Hello, {name}!</p>;
}Overview
These examples build code blocks with the Ariakit UI CodeBlock components and syntax highlighting from Shiki. Shiki runs on the server or at build time, so the browser gets finished HTML and never loads the highlighter. Each example has a server file, index.server.ts, next to the component. Its load function highlights the code, and the result becomes props of the component.
The gallery starts with a block and a copy button, without a header, and a one-line command. Then it adds a file name in a header, line numbers, and marked lines and text, with and without line numbers. The next examples put several files in tabs, more tabs than fit in the block, and code blocks in a documentation page with install commands that remember the package manager. The last examples load files only when they show, collapse long code, wrap long lines, and highlight code that people type.
Components
highlight from @ariakit/ui/utils/highlight.server returns the html of the lines and the text to copy. Import it only in server code, such as a server file, a Next.js server component, a loader, or Astro frontmatter. A module that the browser loads must not import it, or Shiki goes to the browser too. A type import is safe, because it leaves no code. The helper uses the JavaScript regex engine and the GitHub light and dark themes. To support another language, add its grammar to the helper.
Its options mark lines and text, so the source stays plain code. lines takes one-based line numbers. words takes text: a string marks each occurrence, and a tuple such as ["open", 0, 2] marks only the first and the third. A mark can span tokens and lines. A mark in one token takes the color of the token, and a mark across tokens gets the color of the line.
CodeBlock has the geometry of tabs. Its title prop renders a CodeBlockHeader with a CodeBlockTitle, which looks like a selected folder tab but isn’t a tab. A static block like this has no frame of its own and a transparent strip, so only the title and the code show edges. CodeBlockCode renders the html in a scroll area, half a step lighter than the page, like a tab panel. Its copy prop renders a CodeBlockCopy in the top end corner of the code, at the end of the first line, in a frame that covers the code. Pass the text of highlight for a button whose label names the title, such as “Copy counter.tsx”, or “Copy code” without a title. Props such as label replace it, and a label function takes the title, such as for another language.
Token colors come from the light and the dark theme. Each token takes the theme that matches its layer, and its color adapts to the background, so tokens keep enough contrast on any layer, such as a brand-colored callout. Marked lines are layers too, with a bar at the start in the brand color. Adaptive dotted edges in the brand color also mark the top and the bottom of each run of marked lines. Like other adaptive edges, they show only when contrast increases, such as with prefers-contrast: more, and they grow stronger with it. The $lineNumbers, $wrap, and $prompt props of CodeBlockCode add line numbers, wrap long lines, and show a prompt sign before each command. Line numbers stay in view while the code scrolls sideways. Numbers and signs come from CSS, so they are not selected or copied.
A block fits in the scroll area around it, up to 60rem: the screen below the sticky bars of an app shell, or a dialog or a popover. Another scroll area can publish the height that its content can use in --scrollport-height, and the space that its sticky bars cover in --scrollport-start and --scrollport-end. The header and the collapse button keep their height, and long code scrolls down inside. $maxHeight on CodeBlock sets another limit, and false shows all lines. A block whose code wraps has no limit, because wrapped code is not a tab stop.
The maxLines prop of CodeBlock collapses longer code to its first lines and fades out the last ones. A click on the collapsed code, or on the expand button over it, shows all lines. A collapse button under the code shows fewer lines again. The expand and collapse props take a label, props, or an element, like the copy prop of the code. The label of the expand button can be a function of the line count, such as for another language. expanded, defaultExpanded, and setExpanded share the state with the page. With file tabs, the block keeps one state for all files, and a shorter file shows all lines.
For file tabs, pass defaultSelectedId or selectedId to CodeBlock, which then shares the tab state. Put a CodeBlockTabList with a CodeBlockTab for each file as the first child, and then a CodeBlockPanel for each file. The code in each panel is the scroll area of its file. The copy prop of the panel renders a copy button over the code while the panel shows, and the label names the tab, such as “Copy toggle.css”. The separator prop of CodeBlockTab puts a CodeBlockTabSeparator pipe before the tab, so separator={!!index} separates each tab from the one before it. Like TabList, a strip that overflows scrolls sideways, fades its tabs at the ends, and shows “Previous tabs” and “Next tabs” buttons with a fine pointer. When the tabs are views of the same code, such as the commands of each package manager, one CodeBlockPanel with the single prop can follow the selected tab. File tabs have the text size of a title, and more padding, so they are easier to press.
The install commands of the documentation page keep the package manager with useLocalStorageState from use-local-storage-state. Every hook with the same key shares the value, so a tab in one block selects it in the other blocks, and in other browser tabs. The server and the first render show npm, so hydration matches the page, and the saved choice applies right after it.
The icon prop of CodeBlockTab and CodeBlockTitle puts an icon before the file name, and screen readers skip it. The examples keep a few icons in file-icons.ts: the file type icons of the Seti theme of VS Code, and the logos of package managers, which Seti doesn’t have, from vscode-icons. A server file picks the icon of each file, so only the icons in use reach the page. The colored parts use ak-text, which adapts the color to the layer behind them, so each icon keeps its contrast on any tab and in both color schemes.
Files on demand
A server file can export lazyFiles, a record of sources by file name. At build time, a route in the app highlights each file and writes the result to a JSON file. The load function receives getFileUrl, which returns the URL of each JSON file, and sends only the names, URLs, and line counts with the page. The example loads each file with TanStack Query. The panel of the selected tab reads its file with useSuspenseQuery, and a file never goes stale or leaves the cache, so it loads once. The example keeps its QueryClient in its state, so a new mount, such as a reload of the preview, loads the files again. An app usually has one client at its root instead. A failed request doesn’t try again by itself, and a button starts a new one. A pointer over a tab starts the request earlier with prefetchQuery, in an event handler. A local server answers at once, so a checkbox adds a delay before each request, and the skeleton lines show long enough to see.
While a file loads, a Suspense boundary shows its fallback: a panel with a CodeBlockSkeleton and aria-busy, and a status message in the block. CodeBlockSkeleton renders skeleton lines in the shapes and the colors of highlighted code. Its lines prop takes the line count of the file, so the panel has its final height, and the buttons stay in place when the file arrives. With $lineNumbers, a bar takes the place of each line number. The copy button of that panel is disabled, because Safari rejects a copy that waits for a request. When a request fails, an error boundary shows a button that tries again.
In another app, use a route that is static at build time, such as an Astro endpoint with getStaticPaths or a Next.js route handler forced to be static. Code that exists only at run time, such as code from a database, needs a route that highlights each request, and Shiki then goes into the server bundle.
Accessibility
A scroll area is a tab stop, so keyboard users can scroll long lines in every browser, including Safari. The title names it, so screen readers announce the file name when the area takes focus. A block without a title needs an aria-label on CodeBlockCode, which then becomes a named region too. With $wrap, lines don’t scroll, and the code is not a tab stop. A file tab names its panel and the scroll area of its code.
Each copy button needs its own name when the page has more than one. The default label names the title of the block or the tab of the panel, such as “Copy counter.tsx” or “Copy toggle.css”. A block without either, such as two install commands that share a package manager, needs a label of its own, such as the command. The copy button of a file that is still loading is disabled.
Collapsed code is inert, so the tab order and screen readers skip it. The expand button is the way in: it moves the focus to the code. The collapse button comes after the code and its copy button in the tab order, and it moves the focus back to the expand button. Both buttons set aria-expanded and aria-controls.
Marks are visual only. When a mark matters, say it in the text next to the block too, such as “The Disclosure on line 6 is a button”.