Code Block
Code, terminal output, logs or a diff on a pencilled box, with a header, a copy button, line numbers and marked lines, and optional syntax highlighting in the ballpoint's pens.
$ pnpm build> ballpoint@0.0.0 build✓ Compiled successfully✓ Generating static pages (72/72)Route (app)┌ ○ /├ ○ /docs└ ● /docs/[name]import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockTitle } from "@/components/ui/code-block";
import { InkIcon } from "@/components/ui/ink-icons";
const output = `$ pnpm build
> ballpoint@0.0.0 build
✓ Compiled successfully
✓ Generating static pages (72/72)
Route (app)
┌ ○ /
├ ○ /docs
└ ● /docs/[name]`;
export default function CodeBlockDemo() {
return (
<CodeBlock seed="cb-demo" className="max-w-lg">
<CodeBlockHeader>
<CodeBlockTitle>
<InkIcon name="terminal" /> Terminal
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>
);
}Installation
pnpm dlx shadcn@latest add @ballpoint/ code-block"use client";
import { Children, isValidElement, type ComponentProps, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { penRadius, usePen, type Pen } from "@/hooks/use-ink-box";
import { InkOutline } from "@/lib/ink-outline";
import { CopyButton } from "@/components/ui/copy-button";
import { Separator } from "@/components/ui/separator";
/**
* Code, terminal output, logs or a diff on a pencilled box. A header can
* carry a title and buttons, lines can be numbered, and the lines of a diff
* are marked. `destructive` is for output that failed; `sm` for tool output.
*/
function CodeBlock({
className,
variant = "default",
size = "default",
children,
seed,
roughness,
passes,
radius,
corners,
draw,
weight,
speed,
...props
}: ComponentProps<"div"> & Pick<Pen, "roughness" | "passes" | "radius" | "corners" | "draw" | "weight" | "speed"> & { variant?: "default" | "destructive"; size?: "default" | "sm"; seed?: string | number }) {
const pen = usePen({ roughness, passes, radius, corners, draw, weight, speed });
return (
<div
data-slot="code-block"
data-variant={variant}
data-size={size}
style={{ borderRadius: penRadius(pen, 12) }}
className={cn(
"group/code-block relative isolate flex w-full min-w-0 flex-col overflow-hidden bg-ink-5/30 text-sm text-foreground data-[variant=destructive]:text-destructive data-[size=sm]:text-xs",
className,
)}
{...props}
>
<InkOutline pen={pen} seed={seed} estimate={[480, 120]} maxRadius={12} className={cn("text-ink-line", variant === "destructive" && "text-destructive")} />
{children}
</div>
);
}
/** A row above the code, ruled off from it, for a title and buttons. */
function CodeBlockHeader({ className, ...props }: ComponentProps<"div">) {
return (
<div data-slot="code-block-header" className={cn("relative flex items-center gap-2 px-3 py-2 group-data-[size=sm]/code-block:py-1.5", className)} {...props}>
{props.children}
<Separator className="absolute inset-x-2 bottom-0" />
</div>
);
}
/** A file name or a label. It truncates. */
function CodeBlockTitle({ className, ...props }: ComponentProps<"div">) {
return <div data-slot="code-block-title" className={cn("flex min-w-0 items-center gap-1.5 truncate text-base text-ink-2 [&_svg:not(.ink-sketch):not([class*='size-'])]:size-4", className)} {...props} />;
}
/** Buttons: at the end of a header, or floating in the corner when put straight in the block. */
function CodeBlockActions({ className, ...props }: ComponentProps<"div">) {
return <div data-slot="code-block-actions" className={cn("ml-auto flex items-center gap-1 [[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:right-2 [[data-slot=code-block]>&]:z-10", className)} {...props} />;
}
/** Copies `value` to the clipboard. */
function CodeBlockCopyButton({ value, className, ...props }: Omit<ComponentProps<typeof CopyButton>, "children" | "size" | "variant"> & { value: string | (() => string) }) {
return <CopyButton data-slot="code-block-copy-button" value={value} variant="ghost" size="icon-xs" aria-label="Copy code" className={className} {...props} />;
}
/**
* The code itself. A string is split into lines; give it CodeBlockLine
* children to mark some. `wrap` wraps long lines instead of scrolling them.
*/
function CodeBlockContent({
className,
children,
wrap = false,
lineNumbers = false,
startLine = 1,
tabIndex = 0,
...props
}: Omit<ComponentProps<"pre">, "children"> & { children?: ReactNode; wrap?: boolean; lineNumbers?: boolean; startLine?: number }) {
const lines =
typeof children === "string"
? children.replace(/\n$/, "").split("\n").map((line, i) => <CodeBlockLine key={i}>{line}</CodeBlockLine>)
: Children.toArray(children).map((child, i) => (isValidElement(child) ? child : <CodeBlockLine key={i}>{child}</CodeBlockLine>));
return (
<pre
data-slot="code-block-content"
data-numbers={lineNumbers ? "" : undefined}
tabIndex={tabIndex}
style={{ counterReset: `line ${startLine - 1}` }}
className={cn(
"relative min-w-0 overflow-auto px-3 py-3 font-mono leading-relaxed outline-none group-data-[size=sm]/code-block:py-2",
"focus-visible:outline-solid focus-visible:outline-[1.5px] focus-visible:-outline-offset-2 focus-visible:outline-ring",
wrap ? "whitespace-pre-wrap [overflow-wrap:anywhere]" : "whitespace-pre",
className,
)}
{...props}
>
<code className="grid">{lines}</code>
</pre>
);
}
/** One line. `added` and `removed` mark a diff with + and −; `highlighted` hatches it. */
function CodeBlockLine({ className, variant = "default", ...props }: ComponentProps<"span"> & { variant?: "default" | "added" | "removed" | "highlighted" }) {
return (
<span
data-slot="code-block-line"
data-variant={variant}
className={cn(
"relative block min-h-[1lh] [counter-increment:line] group-has-[[data-numbers]]/code-block:before:mr-4 group-has-[[data-numbers]]/code-block:before:inline-block group-has-[[data-numbers]]/code-block:before:min-w-6 group-has-[[data-numbers]]/code-block:before:text-right group-has-[[data-numbers]]/code-block:before:text-ink-4 group-has-[[data-numbers]]/code-block:before:content-[counter(line)]",
// Added and highlighted lines are hatched: fine pen lines, not a tint.
"data-[variant=added]:[background-image:repeating-linear-gradient(-50deg,color-mix(in_oklab,var(--ink)_14%,transparent)_0_1px,transparent_1px_5px)] data-[variant=highlighted]:[background-image:repeating-linear-gradient(-50deg,color-mix(in_oklab,var(--ink)_14%,transparent)_0_1px,transparent_1px_5px)]",
"data-[variant=added]:-mx-3 data-[variant=added]:px-3 data-[variant=highlighted]:-mx-3 data-[variant=highlighted]:px-3 data-[variant=removed]:-mx-3 data-[variant=removed]:px-3",
"data-[variant=removed]:text-destructive data-[variant=added]:after:absolute data-[variant=added]:after:left-0.5 data-[variant=added]:after:content-['+'] data-[variant=removed]:after:absolute data-[variant=removed]:after:left-0.5 data-[variant=removed]:after:content-['−']",
className,
)}
{...props}
/>
);
}
/** A row under the code, ruled off from it: a Show more button, say. */
function CodeBlockFooter({ className, ...props }: ComponentProps<"div">) {
return (
<div data-slot="code-block-footer" className={cn("relative flex items-center gap-2 px-3 py-2", className)} {...props}>
<Separator className="absolute inset-x-2 top-0" />
{props.children}
</div>
);
}
export { CodeBlock, CodeBlockHeader, CodeBlockTitle, CodeBlockActions, CodeBlockCopyButton, CodeBlockContent, CodeBlockLine, CodeBlockFooter };import { Fragment, type ReactNode } from "react";
// Code inked with the ballpoint's pens: keywords in the ink, strings and
// numbers a little lighter, names in red pen, and pencil for comments. The
// colours are CSS variables with the ink as their fallback, so a page can set
// --code-keyword, --code-string, --code-name, --code-comment and --code-plain
// to give each its own pen, and otherwise code follows the ink.
const pen = {
plain: "var(--code-plain, var(--ink))",
keyword: "var(--code-keyword, var(--ink))",
string: "var(--code-string, var(--ink-2))",
name: "var(--code-name, var(--pen-red))",
comment: "var(--code-comment, var(--ink-3))",
quiet: "var(--code-quiet, var(--ink-3))",
};
const ink = {
name: "ballpoint",
type: "light" as const,
colors: { "editor.foreground": pen.plain, "editor.background": "transparent" },
tokenColors: [
{ scope: ["comment", "punctuation.definition.comment"], settings: { foreground: pen.comment, fontStyle: "italic" } },
{ scope: ["keyword", "storage", "storage.type", "storage.modifier", "keyword.control", "variable.language", "constant.language"], settings: { foreground: pen.keyword, fontStyle: "bold" } },
{ scope: ["string", "punctuation.definition.string", "string.template", "string.quoted", "constant.numeric", "constant.other", "support.constant"], settings: { foreground: pen.string } },
{ scope: ["entity.name.function", "support.function", "entity.name.tag", "support.class.component", "entity.name.type", "entity.name.class", "support.type"], settings: { foreground: pen.name } },
{ scope: ["punctuation", "meta.brace", "keyword.operator", "punctuation.separator", "punctuation.terminator", "meta.tag.punctuation"], settings: { foreground: pen.quiet } },
],
};
/**
* Code as one node a line, ready for CodeBlockLine. Loads Shiki the first
* time it is called, so a page that never highlights never downloads it.
* Works in a Server Component too: `await highlightCode(code, "tsx")`.
*/
export async function highlightCode(code: string, language = "tsx"): Promise<ReactNode[]> {
const { codeToTokens } = await import("shiki");
const { tokens } = await codeToTokens(code, { lang: language as Parameters<typeof codeToTokens>[1]["lang"], theme: ink });
return tokens.map((line, i) => (
<Fragment key={i}>
{line.map((token, j) => {
const style = { color: token.color === pen.plain ? undefined : token.color, fontWeight: token.fontStyle && token.fontStyle & 2 ? 700 : undefined, fontStyle: token.fontStyle && token.fontStyle & 1 ? ("italic" as const) : undefined };
return style.color || style.fontWeight || style.fontStyle ? (
<span key={j} style={style}>
{token.content}
</span>
) : (
token.content
);
})}
</Fragment>
));
}"use client";
import { useEffect, useState, type ReactNode } from "react";
import { highlightCode } from "@/lib/highlight-code";
/**
* Code as one node a line, for CodeBlockLine. The plain lines come first and
* are swapped for the inked ones when the highlighter has loaded; if it can't
* highlight the language they stay plain.
*/
export function useHighlightedCode(code: string, language = "tsx"): ReactNode[] {
const key = `${language}\n${code}`;
const [done, setDone] = useState<{ key: string; lines: ReactNode[] } | null>(null);
useEffect(() => {
let current = true;
highlightCode(code, language)
.then((lines) => current && setDone({ key, lines }))
.catch(() => {});
return () => {
current = false;
};
}, [code, language, key]);
return done?.key === key ? done.lines : code.split("\n");
}Usage
import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockTitle } from "@/components/ui/code-block"
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>Terminal</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>Examples
Lines
Numbers, a diff with + and −, a highlighted line, and a block that wraps.
function Button({ variant }) { const pen = "plain" const pen = usePen({ roughness }) return <ButtonInk pen={pen} />}A long line of output that would run off the edge goes round onto the next line instead, because this block wraps.import { CodeBlock, CodeBlockContent, CodeBlockHeader, CodeBlockLine, CodeBlockTitle } from "@/components/ui/code-block";
export default function CodeBlockLines() {
return (
<div className="flex w-full max-w-lg flex-col gap-6">
<CodeBlock seed="cbl-a">
<CodeBlockHeader>
<CodeBlockTitle>button.tsx</CodeBlockTitle>
</CodeBlockHeader>
<CodeBlockContent lineNumbers startLine={12}>
<CodeBlockLine>{"function Button({ variant }) {"}</CodeBlockLine>
<CodeBlockLine variant="removed">{' const pen = "plain"'}</CodeBlockLine>
<CodeBlockLine variant="added">{" const pen = usePen({ roughness })"}</CodeBlockLine>
<CodeBlockLine variant="highlighted">{" return <ButtonInk pen={pen} />"}</CodeBlockLine>
<CodeBlockLine>{"}"}</CodeBlockLine>
</CodeBlockContent>
</CodeBlock>
<CodeBlock seed="cbl-b" size="sm">
<CodeBlockContent wrap>{"A long line of output that would run off the edge goes round onto the next line instead, because this block wraps."}</CodeBlockContent>
</CodeBlock>
</div>
);
}Highlighted
useHighlightedCode inks the lines; they appear plain until the highlighter has loaded.
import { Button } from "@/components/ui/button"export function Actions() { // Two buttons, one drawn lighter. return ( <> <Button>Book a call</Button> <Button variant="outline">Copy email</Button> </> )}"use client";
import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockLine, CodeBlockTitle } from "@/components/ui/code-block";
import { useHighlightedCode } from "@/hooks/use-highlighted-code";
const code = `import { Button } from "@/components/ui/button"
export function Actions() {
// Two buttons, one drawn lighter.
return (
<>
<Button>Book a call</Button>
<Button variant="outline">Copy email</Button>
</>
)
}`;
export default function CodeBlockHighlight() {
const lines = useHighlightedCode(code, "tsx");
return (
<CodeBlock seed="cbh" className="max-w-lg">
<CodeBlockHeader>
<CodeBlockTitle>actions.tsx</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent lineNumbers>
{lines.map((line, i) => (
<CodeBlockLine key={i}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
);
}Failed output
The destructive variant, with a footer.
Error: ENOENT: no such file or directory, open 'registry.json' at readFileSync (node:fs:441:20) at build (scripts/build-registry.ts:48:12)import { CodeBlock, CodeBlockContent, CodeBlockFooter, CodeBlockHeader, CodeBlockTitle } from "@/components/ui/code-block";
import { Button } from "@/components/ui/button";
const log = `Error: ENOENT: no such file or directory, open 'registry.json'
at readFileSync (node:fs:441:20)
at build (scripts/build-registry.ts:48:12)`;
export default function CodeBlockError() {
return (
<CodeBlock variant="destructive" seed="cbe" className="max-w-lg">
<CodeBlockHeader>
<CodeBlockTitle>Build failed</CodeBlockTitle>
</CodeBlockHeader>
<CodeBlockContent>{log}</CodeBlockContent>
<CodeBlockFooter>
<Button variant="outline" size="xs" seed="cbe-more">
Show the full log
</Button>
</CodeBlockFooter>
</CodeBlock>
);
}API reference
- CodeBlock variant / size
"default" | "destructive" / "default" | "sm"Failed output in red pen; a tighter block for tool output.
- CodeBlockContent lineNumbers / startLine / wrapdefault
false / 1 / false boolean / number / booleanNumber the lines from startLine; wrap long lines instead of scrolling them.
- CodeBlockLine variantdefault
"default" "default" | "added" | "removed" | "highlighted"Marks a diff with + and −, or hatches the line.
- CodeBlockCopyButton value
string | () => stringThe text to copy.
- useHighlightedCode(code, language)
ReactNode[]One node a line, for CodeBlockLine, inked in the ballpoint's pens. Needs the shiki package.
- highlightCode(code, language)
Promise<ReactNode[]>The same, awaited: it works in a Server Component.
- seed
string | numberPins the drawing.
Pen settings
The drawing also takes draw, roughness, passes, radius, corners, weight and speed, as props or from the nearest InkProvider. What each one does.