Code Block
Code, terminal output, logs, and diffs, with line numbers and a copy button.
import { App, Button, signal } from "@implementjs/core";
const app = App({ target: document.body });
function Counter() { const count = signal(0);
return Button({ onClick: () => count.increment() }, "Count: ", count);}
app.render(Counter());import { Div, Dynamic, ForEach } from "@implementjs/core";
import { FileCodeIcon } from "@implementjs/lucide";
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/lib/components/ui/code-block";
import { highlightedCode } from "@/lib/components/ui/highlighted-code";
const code = `import { App, Button, signal } from "@implementjs/core";
const app = App({ target: document.body });
function Counter() {
const count = signal(0);
return Button({ onClick: () => count.increment() }, "Count: ", count);
}
app.render(Counter());`;
export default function CodeBlockDemo() {
const lines = highlightedCode(code, "ts");
return Div(
{ class: "w-full max-w-lg" },
CodeBlock(
CodeBlockHeader(
CodeBlockTitle(FileCodeIcon(), "src/main.ts"),
CodeBlockActions(CodeBlockCopyButton({ value: code })),
),
CodeBlockContent(
{ lineNumbers: true },
ForEach(
lines,
(_, index) => index,
(line) => CodeBlockLine(Dynamic(line)),
),
),
),
);
}Installation
npx jsrepo add @implementjs/ui/code-block
jsrepo pulls button along with it, for the copy button. Syntax highlighting is a separate item, so a block that only ever shows plain output does not ship a grammar:
npx jsrepo add @implementjs/ui/highlighted-code
That one installs shiki.
Copy the file below to src/lib/components/ui/code-block.ts. It imports cn from @implementjs/cn, and button from the same directory — copy those in beside it too. Then, on top of @implementjs/core and @implementjs/primitives:
npm install tailwind-variants @implementjs/lucide
import {
Code,
derived,
Div,
ForEach,
If,
ImplementLifecycle,
isReadable,
Pre,
signal,
Span,
type Child,
type ElementProps,
type PrimitiveChild,
type Readable,
} from "@implementjs/core";
import { CheckIcon, CopyIcon } from "@implementjs/lucide";
import { createComponent, mergeProps } from "@implementjs/primitives";
import { tv, type VariantProps } from "tailwind-variants";
import { Button, type ButtonProps } from "./button";
import { cn } from "@implementjs/cn";
export const codeBlockVariants = tv({
base: "group/code-block relative flex w-full min-w-0 flex-col overflow-hidden rounded-lg text-sm has-[>[data-slot=code-block-content]:focus-visible]:ring-[3px] has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/50 data-[size=sm]:text-xs",
variants: {
variant: {
default:
"border border-input text-foreground has-[>[data-slot=code-block-content]:focus-visible]:border-ring dark:bg-input/30",
destructive: "border border-destructive/30 text-destructive dark:border-destructive/40",
},
},
defaultVariants: { variant: "default" },
});
export const codeBlockLineVariants = tv({
base: [
"relative -mx-4 block min-h-lh px-4 group-data-[size=sm]/code-block:-mx-3 group-data-[size=sm]/code-block:px-3",
// the line number, and the + or − a diff line puts in the gutter
"before:min-w-6 before:text-end before:text-muted-foreground after:absolute after:start-1 after:top-0 after:text-muted-foreground after:select-none",
"in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:gap-x-3 in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']",
],
variants: {
variant: {
default: "",
added: "bg-muted after:content-['+']",
removed: "bg-destructive/10 after:text-destructive after:content-['−']",
highlighted: "bg-muted",
},
},
defaultVariants: { variant: "default" },
});
export type CodeBlockVariant = VariantProps<typeof codeBlockVariants>["variant"];
export type CodeBlockLineVariant = VariantProps<typeof codeBlockLineVariants>["variant"];
export type CodeBlockProps = ElementProps<"div"> &
VariantProps<typeof codeBlockVariants> & {
/** `sm` tightens the padding and type, for tool output inside a `Trace`. */
size?: "default" | "sm";
};
export type CodeBlockHeaderProps = ElementProps<"div">;
export type CodeBlockTitleProps = ElementProps<"div">;
export type CodeBlockActionsProps = ElementProps<"div">;
export type CodeBlockCopyButtonProps = Omit<ButtonProps, "value"> & {
/** The text written to the clipboard. Pass a readable when the code streams in. */
value: string | Readable<string>;
};
export type CodeBlockContentProps = ElementProps<"pre"> & {
/** Wrap long lines instead of scrolling sideways. */
wrap?: boolean;
/**
* Number the lines. Code passed as text is split into `CodeBlockLine`s for
* you; pass lines of your own to mark some of them as a diff.
*/
lineNumbers?: boolean;
/** The number the first line gets. */
startLine?: number;
};
export type CodeBlockLineProps = ElementProps<"span"> & VariantProps<typeof codeBlockLineVariants>;
export type CodeBlockFooterProps = ElementProps<"div">;
/**
* Code, terminal output, logs, or a diff, in a bordered panel. Put a
* `CodeBlockContent` in it, and a header, footer, or actions around that.
*/
export const CodeBlock = createComponent(function CodeBlock(
{ class: className, variant = "default", size = "default", ...props }: CodeBlockProps,
...children: Child[]
) {
return Div(
{
...props,
"data-slot": "code-block",
"data-variant": variant,
"data-size": size,
class: cn(codeBlockVariants({ variant }), className),
},
...children,
);
});
/** A row above the code for a title, and actions pushed to the end of it. */
export const CodeBlockHeader = createComponent(function CodeBlockHeader(
{ class: className, ...props }: CodeBlockHeaderProps,
...children: Child[]
) {
return Div(
{
...props,
"data-slot": "code-block-header",
class: cn(
"flex min-w-0 shrink-0 items-center gap-2 px-4 pt-4 text-muted-foreground group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pt-3 group-data-[variant=destructive]/code-block:text-destructive *:has-[>[data-slot=code-block-title]]:min-w-0",
className,
),
},
...children,
);
});
/** The file name or command the code belongs to. An icon in front of it is sized for you. */
export const CodeBlockTitle = createComponent(function CodeBlockTitle(
{ class: className, ...props }: CodeBlockTitleProps,
...children: Child[]
) {
return Div(
{
...props,
"data-slot": "code-block-title",
class: cn(
"min-w-0 truncate font-sans text-sm font-medium text-foreground group-data-[size=sm]/code-block:text-xs group-data-[variant=destructive]/code-block:text-destructive",
"[&_svg]:pointer-events-none [&_svg]:inline-block [&_svg]:align-middle [&_svg:not([class*='size-'])]:size-4 group-data-[size=sm]/code-block:[&_svg:not([class*='size-'])]:size-3.5 *:[svg]:me-1.5",
className,
),
},
...children,
);
});
/**
* Buttons for the code: copy, expand, download. In a header they sit at its
* end; placed straight in the `CodeBlock` they float over the top corner and
* show on hover or focus (always, on a touch screen).
*/
export const CodeBlockActions = createComponent(function CodeBlockActions(
{ class: className, ...props }: CodeBlockActionsProps,
...children: Child[]
) {
return Div(
{
...props,
"data-slot": "code-block-actions",
class: cn(
"-my-1 ms-auto -me-1.5 flex shrink-0 items-center gap-1",
"[[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:end-3 [[data-slot=code-block]>&]:top-3 [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:m-0",
"[[data-slot=code-block]>&]:opacity-0 [[data-slot=code-block]>&]:transition-opacity [[data-slot=code-block]>&]:group-focus-within/code-block:opacity-100 [[data-slot=code-block]>&]:group-hover/code-block:opacity-100 [[data-slot=code-block]>&]:pointer-coarse:opacity-100",
"group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:end-2 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:top-2",
"[[data-slot=code-block]>&]:*:[button]:bg-background [[data-slot=code-block]>&]:*:[button]:ring-1 [[data-slot=code-block]>&]:*:[button]:ring-foreground/10",
className,
),
},
...children,
);
});
/** How long the check stays up after a copy, in milliseconds. */
const COPIED_FOR = 2000;
/**
* Copies `value` to the clipboard, then shows a check for two seconds. The
* change is announced to screen readers as well as drawn.
*/
export const CodeBlockCopyButton = createComponent(function CodeBlockCopyButton({
value,
variant = "ghost",
size = "icon-xs",
onClick,
...props
}: CodeBlockCopyButtonProps) {
const copied = signal(false);
let timeout: ReturnType<typeof setTimeout> | undefined;
return ImplementLifecycle(
{ onUnmount: () => clearTimeout(timeout) },
Button(
{
...props,
variant,
size,
"data-copied": copied.bind((value) => value || undefined),
"aria-label": copied.bind((value) => (value ? "Copied" : "Copy")),
onClick(event) {
const click = isReadable<typeof onClick>(onClick) ? onClick.get() : onClick;
if (typeof click === "function") click.call(this, event);
const text = isReadable(value) ? value.get() : value;
navigator.clipboard
.writeText(text)
.then(() => {
copied.set(true);
clearTimeout(timeout);
timeout = setTimeout(() => copied.set(false), COPIED_FOR);
})
.catch(() => {});
},
},
If(copied, CheckIcon()).Else(CopyIcon()),
),
Span(
{ "aria-live": "polite", class: "sr-only" },
copied.bind((value) => (value ? "Copied" : "")),
),
);
});
/** Splits code into lines, dropping the one empty line a trailing newline would add. */
function splitLines(code: string): string[] {
return code.replace(/\n$/, "").split("\n");
}
/** The children as one string, when every one of them is plain text — `null` when any is not. */
function plainText(children: Child[]): string | null {
let text = "";
for (const child of children) {
if (typeof child === "string" || typeof child === "number") text += child;
else if (child !== null && child !== undefined && child !== false) return null;
}
return text;
}
/**
* The code itself, in a `Pre` that scrolls sideways (or wraps, with `wrap`)
* and fades its edges as it does. It is focusable, so the keyboard can scroll
* it too.
*
* With `lineNumbers`, code passed as text — a string, or a readable one that
* grows as it streams — is split into numbered lines.
*/
export const CodeBlockContent = createComponent(function CodeBlockContent(
{
class: className,
style,
wrap = false,
lineNumbers = false,
startLine = 1,
...props
}: CodeBlockContentProps,
...children: Child[]
) {
let lines: Child[] = children;
if (lineNumbers) {
const text = plainText(children);
const [only] = children;
if (text !== null) {
lines = splitLines(text).map((line) => CodeBlockLine(line));
} else if (children.length === 1 && isReadable<PrimitiveChild>(only)) {
const split = derived([only], (code) => splitLines(String(code ?? "")));
lines = [
ForEach(
split,
(_, index) => index,
(line) => CodeBlockLine(line),
),
];
}
}
return Pre(
mergeProps(
{
...props,
"data-slot": "code-block-content",
"data-wrap": wrap || undefined,
"data-numbered": lineNumbers || undefined,
dir: "ltr" as const,
tabIndex: 0,
style: { counterReset: `line ${startLine - 1}` },
class: cn(
"min-h-0 min-w-0 scroll-fade-x scrollbar-thin overflow-auto px-4 py-4 text-start font-mono leading-relaxed outline-none",
"group-has-data-[slot=code-block-footer]/code-block:pb-2 group-has-data-[slot=code-block-header]/code-block:pt-2",
"group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:py-3 group-data-[size=sm]/code-block:group-has-data-[slot=code-block-header]/code-block:pt-1.5",
"data-wrap:scroll-fade-y data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap",
className,
),
},
{ style },
),
Code(
{
"data-slot": "code-block-code",
class:
"grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0",
},
...lines,
),
);
});
/**
* One line of code. Use these yourself to mark lines `added`, `removed`, or
* `highlighted`, or to render the lines `highlightedCode` hands back.
*/
export const CodeBlockLine = createComponent(function CodeBlockLine(
{ class: className, variant = "default", ...props }: CodeBlockLineProps,
...children: Child[]
) {
// an empty line holds a newline, so copying a selection keeps blank lines
const empty = children.every((child) => child === "" || child === null || child === undefined);
const content: Child[] = empty
? ["\n"]
: children.map((child) =>
isReadable<PrimitiveChild>(child)
? child.bind((value) =>
value === "" || value === null || value === undefined ? "\n" : String(value),
)
: child,
);
return Span(
{
...props,
"data-slot": "code-block-line",
"data-variant": variant,
class: cn(codeBlockLineVariants({ variant }), className),
},
Span({ "data-slot": "code-block-line-content", class: "min-w-0" }, ...content),
);
});
/** A row under the code, for a caption, a status, or more actions. */
export const CodeBlockFooter = createComponent(function CodeBlockFooter(
{ class: className, ...props }: CodeBlockFooterProps,
...children: Child[]
) {
return Div(
{
...props,
"data-slot": "code-block-footer",
class: cn(
"flex min-w-0 shrink-0 items-center gap-2 px-4 pb-4 text-muted-foreground group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pb-3",
className,
),
},
...children,
);
});For syntax highlighting, copy this one to src/lib/components/ui/highlighted-code.ts, and install shiki:
npm install shiki
import {
derived,
Fragment,
isReadable,
signal,
Span,
type Child,
type Readable,
} from "@implementjs/core";
import {
createHighlighterCore,
type GrammarState,
type HighlighterCore,
type ThemedToken,
} from "shiki/core";
import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
// Add the languages you need. Each one loads the first time it is used.
const languages = {
bash: () => import("shiki/langs/shellscript.mjs"),
css: () => import("shiki/langs/css.mjs"),
diff: () => import("shiki/langs/diff.mjs"),
html: () => import("shiki/langs/html.mjs"),
javascript: () => import("shiki/langs/javascript.mjs"),
json: () => import("shiki/langs/json.mjs"),
jsx: () => import("shiki/langs/jsx.mjs"),
markdown: () => import("shiki/langs/markdown.mjs"),
python: () => import("shiki/langs/python.mjs"),
sql: () => import("shiki/langs/sql.mjs"),
tsx: () => import("shiki/langs/tsx.mjs"),
typescript: () => import("shiki/langs/typescript.mjs"),
yaml: () => import("shiki/langs/yaml.mjs"),
};
type Language = keyof typeof languages | "ansi";
const aliases: Record<string, keyof typeof languages> = {
js: "javascript",
md: "markdown",
py: "python",
sh: "bash",
shell: "bash",
shellscript: "bash",
ts: "typescript",
yml: "yaml",
zsh: "bash",
};
let shiki: Promise<HighlighterCore> | undefined;
function getShiki(): Promise<HighlighterCore> {
shiki ??= createHighlighterCore({
themes: [import("shiki/themes/github-light.mjs"), import("shiki/themes/github-dark.mjs")],
langs: [],
engine: createJavaScriptRegexEngine({ forgiving: true }),
});
return shiki;
}
function isListed(name: string): name is keyof typeof languages {
return Object.hasOwn(languages, name);
}
function resolveLanguage(language: string): Language | null {
const name = language.toLowerCase();
if (name === "ansi" || isListed(name)) return name;
return aliases[name] ?? null;
}
/** One rendered line per line of code, and the grammar state after the last one. */
export type HighlightResult = { lines: Child[]; state: GrammarState | undefined };
export type Highlighter = {
/**
* Highlights `code`, one child per line. Pass the `state` a previous call
* returned to carry on from where that code left off.
*/
highlight(code: string, state?: GrammarState): HighlightResult;
};
/** The inline style shiki gives a token: its color in each theme, as custom properties. */
function tokenStyle(token: ThemedToken): string {
return Object.entries(token.htmlStyle ?? {})
.map(([property, value]) => `${property}:${value}`)
.join(";");
}
/** A line of tokens as spans. An empty line holds a newline, so copying a selection keeps it. */
function renderLine(tokens: ThemedToken[]): Child {
if (tokens.length === 0) return "\n";
return Fragment(
...tokens.map((token) =>
Span(
{
style: tokenStyle(token),
class: "text-(--shiki-light) dark:text-(--shiki-dark)",
},
token.content,
),
),
);
}
/**
* Loads a language and returns a highlighter for it, or `null` for one that is
* not listed above.
*/
export async function loadHighlighter(language: string): Promise<Highlighter | null> {
const lang = resolveLanguage(language);
if (!lang) return null;
const core = await getShiki();
if (lang !== "ansi" && !core.getLoadedLanguages().includes(lang)) {
await core.loadLanguage(languages[lang]);
}
return {
highlight(code, state) {
const tokenize = (text: string) =>
core.codeToTokens(text, {
lang,
themes: { light: "github-light", dark: "github-dark" },
defaultColor: false,
grammarState: state,
}).tokens;
// ANSI has no grammar state, so each line is tokenized on its own and
// gets the same colors whether it arrives in one piece or streams.
const tokens =
lang === "ansi" ? code.split("\n").flatMap((line) => tokenize(line)) : tokenize(code);
return { lines: tokens.map(renderLine), state: core.getLastGrammarState(tokens) };
},
};
}
/** Highlights code once, one child per line — `null` for a language that is not listed. */
export async function highlightCode(code: string, language: string): Promise<Child[] | null> {
const highlighter = await loadHighlighter(language);
return highlighter ? highlighter.highlight(code).lines : null;
}
/**
* Highlighters by the name they were asked for, once loaded: `null` for a
* language that is not listed, so it is not asked for again.
*/
const loaded = new Map<string, Highlighter | null>();
const loading = new Set<string>();
/** Bumped as each language finishes loading, so whatever was waiting on it re-reads. */
const loads = signal(0);
/** The highlighter for a language when it is ready, starting the load the first time it is asked for. */
function highlighterFor(language: string): Highlighter | null {
const ready = loaded.get(language);
if (ready !== undefined) return ready;
// the server renders the plain lines; the client highlights them once it
// has the grammar, so the markup it hydrates is the markup that was sent
if (typeof window === "undefined" || loading.has(language)) return null;
loading.add(language);
void loadHighlighter(language)
.catch(() => null)
.then((highlighter) => {
loaded.set(language, highlighter);
loading.delete(language);
loads.set(loads.get() + 1);
});
return null;
}
function toReadable(value: string | Readable<string>): Readable<string> {
return isReadable(value) ? value : signal(value);
}
/**
* The lines of `code`, highlighted for `language`: one child each, to put in
* a `CodeBlockLine`. Until the grammar has loaded — and on the server — they
* are the plain lines.
*
* Pass a readable for code that streams in. Lines that are complete are
* tokenized once, carrying the grammar state forward, so only the last line,
* the one still being written, is tokenized again on each change.
*
* ```ts
* const lines = highlightedCode(code, "ts");
*
* CodeBlockContent(
* { lineNumbers: true },
* ForEach(lines, (_, index) => index, (line) => CodeBlockLine(Dynamic(line))),
* );
* ```
*/
export function highlightedCode(
code: string | Readable<string>,
language: string | Readable<string>,
): Readable<Child[]> {
// the complete lines, highlighted, and where the grammar stood after them
let done: {
highlighter: Highlighter | null;
text: string;
lines: Child[];
state: GrammarState | undefined;
} = { highlighter: null, text: "", lines: [], state: undefined };
return derived([toReadable(code), toReadable(language), loads], (value, lang) => {
// a trailing newline would render as an extra empty line
const text = value.endsWith("\n") ? value.slice(0, -1) : value;
const highlighter = highlighterFor(lang);
if (!highlighter) return text.split("\n").map((line) => line || "\n");
// anything but more of the same code starts over
if (done.highlighter !== highlighter || !text.startsWith(done.text)) {
done = { highlighter, text: "", lines: [], state: undefined };
}
const end = text.lastIndexOf("\n") + 1;
if (end > done.text.length) {
const result = highlighter.highlight(text.slice(done.text.length, end - 1), done.state);
done = {
highlighter,
text: text.slice(0, end),
lines: [...done.lines, ...result.lines],
state: result.state,
};
}
// the last line is still being written, so it is tokenized on every change
const tail = highlighter.highlight(text.slice(end), done.state).lines[0] ?? "\n";
return [...done.lines, tail];
});
}Then add the scroll fade to your stylesheet.
Usage
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle,
} from "@/lib/components/ui/code-block";
CodeBlock(
CodeBlockHeader(
CodeBlockTitle(TerminalIcon(), "Terminal"),
CodeBlockActions(CodeBlockCopyButton({ value: "pnpm dev" })),
),
CodeBlockContent("pnpm dev"),
);
CodeBlock
├── CodeBlockHeader
│ ├── CodeBlockTitle
│ └── CodeBlockActions
│ └── CodeBlockCopyButton
├── CodeBlockContent
│ └── CodeBlockLine
└── CodeBlockFooter
Every part but CodeBlockContent is optional. Put CodeBlockActions straight in the CodeBlock, with no header, and it floats over the top corner instead, showing on hover or focus — and always on a touch screen, where there is no hover to show it.
Line numbers
lineNumbers numbers the lines, and startLine says what the first one is called — for an excerpt from the middle of a file. Code passed as text is split into lines for you. To mark lines of a diff, pass the lines yourself: a CodeBlockLine takes added, removed, or highlighted.
function Counter() { let count = 0; const count = signal(0);
return Button({ onClick: () => count.increment() }, "Count: ", count);}import { Div } from "@implementjs/core";
import { CodeBlock, CodeBlockContent, CodeBlockLine } from "@/lib/components/ui/code-block";
export default function CodeBlockDiffDemo() {
return Div(
{ class: "w-full max-w-lg" },
CodeBlock(
CodeBlockContent(
{ lineNumbers: true, startLine: 12 },
CodeBlockLine("function Counter() {"),
CodeBlockLine({ variant: "removed" }, "\tlet count = 0;"),
CodeBlockLine({ variant: "added" }, "\tconst count = signal(0);"),
CodeBlockLine(""),
CodeBlockLine(
{ variant: "highlighted" },
'\treturn Button({ onClick: () => count.increment() }, "Count: ", count);',
),
CodeBlockLine("}"),
),
),
);
}CodeBlockContent(
{ lineNumbers: true, startLine: 12 },
CodeBlockLine("function Counter() {"),
CodeBlockLine({ variant: "removed" }, "\tlet count = 0;"),
CodeBlockLine({ variant: "added" }, "\tconst count = signal(0);"),
CodeBlockLine("}"),
);
The numbers and the + and − are drawn by CSS, so selecting the code and copying it copies the code alone.
Streaming
Pass a readable string as the only child, and the block follows it as it grows — a terminal while the command runs, or an answer as a model writes it. With lineNumbers, each new line becomes a CodeBlockLine as it arrives, and the ones already there are left alone.
import { Div, ImplementLifecycle, signal } from "@implementjs/core";
import { RotateCcwIcon, TerminalIcon } from "@implementjs/lucide";
import { Button } from "@/lib/components/ui/button";
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle,
} from "@/lib/components/ui/code-block";
const output = `$ pnpm build
packages/core build: ✔ Build complete in 812ms
packages/primitives build: ✔ Build complete in 1204ms
packages/kit build: ✔ Build complete in 1532ms
apps/docs build: ✓ 2318 modules transformed.
apps/docs build: ✓ built in 9.41s`;
export default function CodeBlockStreamingDemo() {
// the output so far: a readable string the block follows as it grows
const log = signal("");
let timer: ReturnType<typeof setInterval> | undefined;
function run() {
clearInterval(timer);
log.set("");
const lines = output.split("\n");
let next = 0;
timer = setInterval(() => {
log.set(lines.slice(0, ++next).join("\n"));
if (next === lines.length) clearInterval(timer);
}, 400);
}
return ImplementLifecycle(
{
onMount() {
run();
return () => clearInterval(timer);
},
},
Div(
{ class: "w-full max-w-lg" },
CodeBlock(
CodeBlockHeader(
CodeBlockTitle(TerminalIcon(), "Terminal"),
CodeBlockActions(
Button(
{ variant: "ghost", size: "icon-xs", "aria-label": "Run again", onClick: run },
RotateCcwIcon(),
),
CodeBlockCopyButton({ value: log }),
),
),
CodeBlockContent({ lineNumbers: true, class: "h-48" }, log),
),
),
);
}const log = signal("");
CodeBlock(
CodeBlockHeader(
CodeBlockTitle(TerminalIcon(), "Terminal"),
CodeBlockActions(CodeBlockCopyButton({ value: log })),
),
CodeBlockContent({ lineNumbers: true }, log),
);
CodeBlockCopyButton takes the same readable, so it copies what is there when it is pressed.
Syntax highlighting
highlightedCode turns code into highlighted lines with Shiki, one child per line, to put in CodeBlockLines. It hands back a readable: the plain lines first — on the server, and until the grammar arrives — then the highlighted ones.
import { highlightedCode } from "@/lib/components/ui/highlighted-code";
const lines = highlightedCode(code, "ts");
CodeBlockContent(
{ lineNumbers: true },
ForEach(
lines,
(_, index) => index,
(line) => CodeBlockLine(Dynamic(line)),
),
);
Both arguments take a readable. Code that streams in is highlighted as it goes: a line is tokenized once it is complete, carrying the grammar's state on to the next, so only the line still being written is tokenized again on each change.
Each language loads the first time it is asked for. The list at the top of highlighted-code.ts ships with bash, css, diff, html, javascript, json, jsx, markdown, python, sql, tsx, typescript, and yaml, plus aliases like ts, js, sh, and yml — add to it what you need. A language that is not on it renders plain. ansi colors terminal output by its escape codes.
The tokens carry both themes' colors, github-light and github-dark, as custom properties, and the dark: variant picks one — so a highlighted block follows your color mode with no second pass.
For code that is not going to change, highlightCode(code, language) is the one-shot version: a promise of the lines, or null for a language that is not listed.
Wrapping
wrap wraps long lines rather than scrolling sideways — for logs and prose-like output, where reading a line matters more than its shape.
Inside a trace
size: "sm" tightens the padding and the type, for tool output under a trace step. Pair it with the destructive variant for a step that failed:
TraceCollapsibleContent(
CodeBlock(
{ size: "sm", variant: "destructive" },
CodeBlockContent({ wrap: true, class: "max-h-64" }, stderr),
),
);
Scroll fade
A block that scrolls fades its edges where there is more to scroll to, and only there — left and right as it scrolls sideways, top and bottom once it wraps. Add scroll-fade-y to a block you cap with max-h-* that does not wrap, and all four edges fade.
These are Tailwind utilities rather than classes the component carries, so paste them into your stylesheet beside the rest. In a browser without scroll-driven animations the edges stay sharp; without the utilities at all, nothing fades.
/* A thin scrollbar, for panels that scroll but should not be framed by one —
the code block's horizontal overflow. */
@utility scrollbar-thin {
scrollbar-width: thin;
}
/* scroll-fade: a scroller fades its edges where there is more to scroll to,
and only there. The code block uses the inline pair, and the block pair once
it wraps. Ported from shadcn's `shadcn/tailwind.css`. */
@property --scroll-fade-t {
syntax: "<length-percentage>";
inherits: false;
initial-value: 0px;
}
@property --scroll-fade-b {
syntax: "<length-percentage>";
inherits: false;
initial-value: 0px;
}
@property --scroll-fade-s {
syntax: "<length-percentage>";
inherits: false;
initial-value: 0px;
}
@property --scroll-fade-e {
syntax: "<length-percentage>";
inherits: false;
initial-value: 0px;
}
@theme inline {
@keyframes scroll-fade-reveal-t {
from {
--scroll-fade-t: 0px;
}
to {
--scroll-fade-t: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
}
}
@keyframes scroll-fade-reveal-b {
from {
--scroll-fade-b: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
}
to {
--scroll-fade-b: 0px;
}
}
@keyframes scroll-fade-reveal-s {
from {
--scroll-fade-s: 0px;
}
to {
--scroll-fade-s: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
}
}
@keyframes scroll-fade-reveal-e {
from {
--scroll-fade-e: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
}
to {
--scroll-fade-e: 0px;
}
}
}
@utility scroll-fade-x {
--scroll-fade-inline: linear-gradient(
to right,
transparent 0,
#000 var(--scroll-fade-s, 0px),
#000 calc(100% - var(--scroll-fade-e, 0px)),
transparent 100%
);
&:where([dir="rtl"], [dir="rtl"] *) {
--scroll-fade-inline: linear-gradient(
to left,
transparent 0,
#000 var(--scroll-fade-s, 0px),
#000 calc(100% - var(--scroll-fade-e, 0px)),
transparent 100%
);
}
mask-image: var(--scroll-fade-inline);
mask-repeat: no-repeat;
@supports (animation-timeline: scroll()) {
animation:
scroll-fade-reveal-s 1ms ease-in-out,
scroll-fade-reveal-e 1ms ease-in-out;
animation-timeline: scroll(self inline), scroll(self inline);
animation-range:
0 var(--scroll-fade-reveal, calc(var(--spacing) * 24)),
calc(100% - var(--scroll-fade-reveal, calc(var(--spacing) * 24))) 100%;
animation-fill-mode: both;
}
}
/* With both, the two masks intersect: `scroll-fade-x scroll-fade-y` fades all
four edges. */
@utility scroll-fade-y {
--scroll-fade-block: linear-gradient(
to bottom,
transparent 0,
#000 var(--scroll-fade-t, 0px),
#000 calc(100% - var(--scroll-fade-b, 0px)),
transparent 100%
);
mask-image: var(--scroll-fade-inline, linear-gradient(#000, #000)), var(--scroll-fade-block);
mask-composite: intersect;
mask-repeat: no-repeat;
@supports (animation-timeline: scroll()) {
animation:
scroll-fade-reveal-s 1ms ease-in-out,
scroll-fade-reveal-e 1ms ease-in-out,
scroll-fade-reveal-t 1ms ease-in-out,
scroll-fade-reveal-b 1ms ease-in-out;
animation-timeline: scroll(self inline), scroll(self inline), scroll(self y), scroll(self y);
animation-range:
0 var(--scroll-fade-reveal, calc(var(--spacing) * 24)),
calc(100% - var(--scroll-fade-reveal, calc(var(--spacing) * 24))) 100%,
0 var(--scroll-fade-reveal, calc(var(--spacing) * 24)),
calc(100% - var(--scroll-fade-reveal, calc(var(--spacing) * 24))) 100%;
animation-fill-mode: both;
}
}
Accessibility
- The
Preis focusable, so a keyboard can scroll it, and the block draws a focus ring while it has focus. - The copy button is labelled "Copy", then "Copied" — and the change is announced through a live region, since the icon swap alone says nothing to a screen reader.
- The code is always laid out left to right, even on a right-to-left page.
API Reference
CodeBlock
The bordered panel. It shows a focus ring while the code inside it has focus. Renders a Div; extra props are forwarded onto it.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | "default" | "destructive" | "default" | destructive is for a failure — an error log, a stack trace. Also set as data-variant. |
size | "default" | "sm" | "default" | sm tightens the padding and the type, for tool output inside a Trace. Also set as data-size. |
CodeBlockHeader
A row above the code for a title and actions. Renders a Div; extra props are forwarded onto it.
CodeBlockTitle
The file name or command. Truncates, and sizes an svg in front of it. Renders a Div; extra props are forwarded onto it.
CodeBlockActions
Buttons for the code. In a header they sit at its end; as a direct child of CodeBlock they float over the top corner and show on hover or focus — always, on a touch screen. Renders a Div; extra props are forwarded onto it.
CodeBlockCopyButton
Copies value, then shows a check for two seconds and announces the copy to screen readers. Every other prop is the Button's. Renders a Button; extra props are forwarded onto it.
| Prop | Type | Default | Description |
|---|---|---|---|
value* | string | Readable<string> | — | The text written to the clipboard. Pass a readable for code that streams in. |
variant | "default" | "destructive" | "outline" | "secondary" | "ghost" | "link" | "ghost" | Which button style the part renders with. Also set as data-variant. |
size | "default" | "xs" | "sm" | "lg" | "icon" | "icon-xs" | "icon-sm" | "icon-lg" | "icon-xs" | The button's height and padding scale. Also set as data-size. |
CodeBlockContent
The code, in a focusable Pre that scrolls sideways and fades its edges where there is more to see. Its children land in a Code inside it. Renders a Pre; extra props are forwarded onto it.
| Prop | Type | Default | Description |
|---|---|---|---|
wrap | boolean | false | Wrap long lines instead of scrolling sideways. Also set as data-wrap. |
lineNumbers | boolean | false | Number the lines. Text passed as the only child — a string, or a readable one — is split into CodeBlockLines for you. Also set as data-numbered. |
startLine | number | 1 | The number the first line gets. |
CodeBlockLine
One line of code. An empty line holds a newline, so copying a selection keeps it. Renders a Span; extra props are forwarded onto it.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | "default" | "added" | "removed" | "highlighted" | "default" | added and removed mark a diff line with a tint and a + or − in the gutter; highlighted only tints it. Also set as data-variant. |
CodeBlockFooter
A row under the code, for a caption, a status, or more actions. Renders a Div; extra props are forwarded onto it.