implement
Code Block

Code Block

Code, terminal output, logs, and diffs, with line numbers and a copy button.

src/main.ts
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.

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.

Terminal

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 Pre is 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.

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

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

PropTypeDefaultDescription
wrapbooleanfalseWrap long lines instead of scrolling sideways. Also set as data-wrap.
lineNumbersbooleanfalseNumber 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.
startLinenumber1The 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.

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