Skip to content
Shaken UI
Sign in

Code Block

Save

A code block with a filename tab, line numbers, highlighted lines, a copy button, and a wrap toggle, with optional dependency-free coloring for JS, TS, JSON, and shell.

Category
Data display
Version
0.1.1
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Code Block preview
app/api/runs/route.ts
import { createRun } from "@/lib/agent";​// Starts a run and streams its events back to the client.export async function POST(request: Request) {  const { prompt, tools } = await request.json();  const run = await createRun({ prompt, tools, maxSteps: 12 });​  return new Response(run.toEventStream(), {    headers: { "content-type": "text/event-stream" },  });}
bash
pnpm dlx @shakenui/cli add code-block

Installation

npx @shakenui/cli add code-block

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add code-block --dry-run

Usage

code-block-example.tsx
import { CodeBlock } from "@/components/shaken/ui/code-block";

const route = `import { createRun } from "@/lib/agent";

// Starts a run and streams its events back to the client.
export async function POST(request: Request) {
  const { prompt, tools } = await request.json();
  const run = await createRun({ prompt, tools, maxSteps: 12 });

  return new Response(run.toEventStream(), {
    headers: { "content-type": "text/event-stream" },
  });
}`;

export default function CodeBlockExample() {
  return (
    <div className="grid w-full max-w-2xl gap-4">
      <CodeBlock filename="app/api/runs/route.ts" language="ts" code={route} highlightLines="6-8" />
      <CodeBlock language="bash" code="pnpm dlx @shakenui/cli add code-block" lineNumbers={false} wrapToggle={false} />
    </div>
  );
}

API

PropTypeDefaultDescription
codestring—The source; also what Copy copies.
language"ts" | "tsx" | "js" | "jsx" | "json" | "bash" | "text""text"Enables the built-in coloring.
filenamestring—Shown as the header tab. Without it the header shows the language.
tokens{ content, className?, color? }[][]—Pre-tokenized lines from your own highlighter; overrides the built-in coloring.
highlightbooleantrueBuilt-in token coloring.
lineNumbersbooleantrueLine number gutter.
highlightLinesstring | number[]—Lines to emphasize, such as "3,7-9".
startLinenumber1First line number for excerpts.
defaultWrap / wrapToggleboolean / booleanfalse / trueInitial wrap and whether the toggle shows.
copyablebooleantrueShows the copy button.
maxHeightstring—Caps the height; the code scrolls inside.
actionsReactNode—Extra header content before the buttons.

Accessibility

  • The code area is a focusable pre with an accessible name ("Code: app/api/runs/route.ts") so keyboard users can scroll long lines.
  • Copy and Wrap are labelled icon buttons; Wrap is a toggle with aria-pressed.
  • A polite live region announces "Copied to clipboard", and the icon swaps to a check for 1.8 seconds.
  • Line numbers are aria-hidden and not selectable, so selections and screen readers get only the code.
  • The tokenizer colors are a reading aid; text keeps AA contrast in both themes.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/code-block.tsxcode-block
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/code-block/0.1.1.json.

ui/code-block.tsxShow
ui/code-block.tsx
"use client";

import { type ComponentProps, type CSSProperties, type ReactNode, useEffect, useMemo, useRef, useState } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

/** One run of text in a line. Shape matches what most highlighters emit (`content` plus a `color`). */
export interface CodeToken {
  content: string;
  /** Classes for the run, for example `"text-emerald-700 dark:text-emerald-400"`. */
  className?: string;
  /** A CSS color, as emitted by highlighters such as Shiki. */
  color?: string;
}

export type CodeLanguage = "ts" | "tsx" | "js" | "jsx" | "json" | "bash" | "text";

type TokenKind = "plain" | "keyword" | "string" | "number" | "comment" | "function" | "type" | "property" | "punctuation";

// A restrained scheme: structure in ink, literals in two meaning hues, comments recede.
const tokenClass: Record<TokenKind, string | undefined> = {
  plain: undefined,
  keyword: "text-zinc-950 font-medium dark:text-white",
  string: "text-emerald-700 dark:text-emerald-400",
  number: "text-sky-700 dark:text-sky-400",
  comment: "text-zinc-400 italic dark:text-zinc-500",
  function: "text-zinc-950 dark:text-white",
  type: "text-amber-700 dark:text-amber-300",
  property: "text-sky-700 dark:text-sky-400",
  punctuation: "text-zinc-400 dark:text-zinc-500",
};

const jsKeywords = new Set(
  (
    "as async await break case catch class const continue debugger default delete do else enum export extends finally for from function " +
    "get if implements import in instanceof interface let new of package private protected public readonly return satisfies set static " +
    "super switch this throw try type typeof var void while with yield keyof declare namespace abstract"
  ).split(" "),
);
const literals = new Set(["true", "false", "null", "undefined", "NaN", "Infinity"]);

type Piece = { kind: TokenKind; text: string };

function tokenizeScript(code: string, language: CodeLanguage): Piece[] {
  const out: Piece[] = [];
  const json = language === "json";
  const bash = language === "bash";
  const pattern = bash
    ? /(#[^\n]*)|("(?:\\.|[^"\\])*"|'[^']*')|(\$\{?[A-Za-z_][\w]*\}?)|(--?[A-Za-z][\w-]*)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][\w./-]*)|(\s+)|(.)/g
    : /(\/\/[^\n]*|\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|(\b(?:0x[\da-fA-F]+|\d[\d_]*(?:\.\d+)?(?:e[+-]?\d+)?n?)\b)|([A-Za-z_$][\w$]*)|(\s+)|([{}()[\];,.:<>=+\-*/!?&|%^~@])|(.)/g;
  let match: RegExpExecArray | null;
  let lineStart = true;
  while ((match = pattern.exec(code))) {
    const text = match[0];
    if (bash) {
      const [, comment, str, variable, flag, num, word] = match;
      if (comment) out.push({ kind: "comment", text });
      else if (str) out.push({ kind: "string", text });
      else if (variable) out.push({ kind: "property", text });
      else if (flag) out.push({ kind: "type", text });
      else if (num) out.push({ kind: "number", text });
      else if (word) out.push({ kind: lineStart ? "function" : "plain", text });
      else out.push({ kind: "plain", text });
      if (text.includes("\n")) lineStart = true;
      else if (!/^\s+$/.test(text)) lineStart = text === "|" || text === "&" || text === ";";
      continue;
    }
    const [, comment, str, num, ident, , punct] = match;
    if (comment) out.push({ kind: "comment", text });
    else if (str) {
      // In JSON, a string followed by a colon is a key.
      const rest = code.slice(pattern.lastIndex);
      out.push({ kind: json && /^\s*:/.test(rest) ? "property" : "string", text });
    } else if (num) out.push({ kind: "number", text });
    else if (ident) {
      const rest = code.slice(pattern.lastIndex);
      // A reverse search instead of findLast, which needs an ES2023 lib some projects do not target.
      const previous = [...out].reverse().find((piece) => !/^\s+$/.test(piece.text));
      if (literals.has(ident)) out.push({ kind: "number", text });
      else if (!json && jsKeywords.has(ident) && previous?.text !== ".") out.push({ kind: "keyword", text });
      else if (/^\s*\(/.test(rest) || /^\s*=\s*(?:async\s*)?\(/.test(rest)) out.push({ kind: "function", text });
      else if (/^[A-Z]/.test(ident)) out.push({ kind: "type", text });
      // Object keys and member access; a parameter's type annotation (after "(") stays plain.
      else if (previous?.text === "." || (/^\??:(?!:)/.test(rest.trimStart()) && previous?.text !== "(" && previous?.text !== "<"))
        out.push({ kind: "property", text });
      else out.push({ kind: "plain", text });
    } else if (punct) out.push({ kind: "punctuation", text });
    else out.push({ kind: "plain", text });
  }
  return out;
}

/**
 * A tiny, dependency-free highlighter for JavaScript, TypeScript, JSX, JSON, and shell. It colors
 * keywords, strings, numbers, comments, types, and properties; it does not parse, so treat it as
 * a reading aid. For full grammars, pass pre-tokenized `tokens` from a highlighter of your choice.
 */
export function tokenize(code: string, language: CodeLanguage): CodeToken[][] {
  const lines: CodeToken[][] = [[]];
  const pieces = language === "text" ? [{ kind: "plain" as const, text: code }] : tokenizeScript(code, language);
  for (const piece of pieces) {
    const parts = piece.text.split("\n");
    parts.forEach((part, index) => {
      if (index > 0) lines.push([]);
      if (part) lines[lines.length - 1]!.push({ content: part, className: tokenClass[piece.kind] });
    });
  }
  return lines;
}

/** Parses `"1,4-6"` or `[1, 4, 5, 6]` into a set of 1-based line numbers. */
function parseLines(input: string | number[] | undefined) {
  const set = new Set<number>();
  if (!input) return set;
  if (Array.isArray(input)) input.forEach((line) => set.add(line));
  else
    for (const part of input.split(",")) {
      const [start, end] = part.split("-").map((value) => Number.parseInt(value.trim(), 10));
      if (start === undefined || Number.isNaN(start)) continue;
      for (let line = start; line <= (end && !Number.isNaN(end) ? end : start); line++) set.add(line);
    }
  return set;
}

async function copyText(text: string) {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    const area = document.createElement("textarea");
    area.value = text;
    area.setAttribute("readonly", "");
    area.style.position = "fixed";
    area.style.opacity = "0";
    document.body.appendChild(area);
    area.select();
    const ok = document.execCommand("copy");
    area.remove();
    return ok;
  }
}

export interface CodeBlockProps extends Omit<ComponentProps<"figure">, "children"> {
  /** The source text. Also what the copy button copies. */
  code: string;
  /** Turns on the built-in coloring for js, jsx, ts, tsx, json, and bash. */
  language?: CodeLanguage;
  /** Shown as a tab in the header. Without it, the header shows the language. */
  filename?: string;
  /** Pre-tokenized lines from your own highlighter. Overrides the built-in coloring. */
  tokens?: CodeToken[][];
  /** Colors tokens with the built-in highlighter. Off renders plain text. */
  highlight?: boolean;
  lineNumbers?: boolean;
  /** Lines to emphasize, 1-based: `"3,7-9"` or `[3, 7, 8, 9]`. */
  highlightLines?: string | number[];
  /** First line number, for excerpts from the middle of a file. */
  startLine?: number;
  /** Initial wrap state. Long lines scroll sideways when off. */
  defaultWrap?: boolean;
  /** Shows the wrap toggle in the header. */
  wrapToggle?: boolean;
  /** Shows the copy button. */
  copyable?: boolean;
  /** Caps the height; the code scrolls inside. Any CSS length, for example `"20rem"`. */
  maxHeight?: string;
  /** Extra header content, placed before the buttons. */
  actions?: ReactNode;
}

/**
 * A code block with a filename tab, line numbers, emphasized lines, a copy button, and a wrap
 * toggle. Highlighting is optional and has no dependency.
 */
export function CodeBlock({
  code,
  language = "text",
  filename,
  tokens,
  highlight = true,
  lineNumbers = true,
  highlightLines,
  startLine = 1,
  defaultWrap = false,
  wrapToggle = true,
  copyable = true,
  maxHeight,
  actions,
  className,
  ...props
}: CodeBlockProps) {
  const [wrap, setWrap] = useState(defaultWrap);
  const [copied, setCopied] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  const trimmed = code.replace(/\n$/, "");
  const lines = useMemo<CodeToken[][]>(
    () => tokens ?? (highlight ? tokenize(trimmed, language) : trimmed.split("\n").map((line) => (line ? [{ content: line }] : []))),
    [tokens, highlight, trimmed, language],
  );
  const marked = useMemo(() => parseLines(highlightLines), [highlightLines]);
  const gutter = String(startLine + lines.length - 1).length;

  useEffect(() => () => clearTimeout(timer.current), []);

  async function onCopy() {
    const ok = await copyText(trimmed);
    if (!ok) return;
    setCopied(true);
    clearTimeout(timer.current);
    timer.current = setTimeout(() => setCopied(false), 1800);
  }

  const label = filename ?? (language === "text" ? "Code" : language);

  return (
    <figure
      data-slot="code-block"
      className={cx(
        "group/code m-0 grid min-w-0 overflow-hidden rounded-xl border text-sm",
        "border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
        className,
      )}
      {...props}
    >
      <figcaption className="flex h-10 items-center gap-2 border-b border-zinc-950/[0.07] ps-3 pe-1.5 dark:border-white/[0.08]">
        <span className="flex min-w-0 items-center gap-2 font-mono text-xs text-zinc-600 dark:text-zinc-400">
          {filename ? <FileGlyph /> : null}
          <span className="truncate">{label}</span>
        </span>
        <span className="ms-auto flex items-center gap-0.5">
          {actions}
          {wrapToggle ? (
            <HeaderButton label="Wrap lines" pressed={wrap} onClick={() => setWrap((value) => !value)}>
              <svg aria-hidden="true" viewBox="0 0 16 16" fill="none">
                <path d="M2.5 4h11M2.5 8h9a2 2 0 0 1 0 4H8.5m0 0 1.5-1.5M8.5 12l1.5 1.5M2.5 12h3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </HeaderButton>
          ) : null}
          {copyable ? (
            <HeaderButton label={copied ? "Copied" : "Copy code"} onClick={onCopy}>
              <span className="relative size-4">
                <svg
                  aria-hidden="true"
                  viewBox="0 0 16 16"
                  fill="none"
                  className={cx(
                    "absolute inset-0 transition-[opacity,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
                    copied ? "scale-90 opacity-0" : "scale-100 opacity-100",
                  )}
                >
                  <rect x="5.25" y="5.25" width="8" height="8" rx="1.75" stroke="currentColor" strokeWidth="1.5" />
                  <path d="M10.75 3.25A1.5 1.5 0 0 0 9.25 2.5h-5a1.75 1.75 0 0 0-1.75 1.75v5a1.5 1.5 0 0 0 .75 1.3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                </svg>
                <svg
                  aria-hidden="true"
                  viewBox="0 0 16 16"
                  fill="none"
                  className={cx(
                    "absolute inset-0 text-emerald-600 transition-[opacity,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none dark:text-emerald-400",
                    copied ? "scale-100 opacity-100" : "scale-90 opacity-0",
                  )}
                >
                  <path d="M3.5 8.5 6.5 11.5 12.5 4.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </span>
            </HeaderButton>
          ) : null}
          <span aria-live="polite" className="sr-only">
            {copied ? "Copied to clipboard" : ""}
          </span>
        </span>
      </figcaption>
      <pre
        tabIndex={0}
        aria-label={filename ? `Code: ${filename}` : "Code"}
        style={{ maxHeight } as CSSProperties}
        className={cx(
          "m-0 overflow-auto py-3 font-mono text-[13px] leading-6 text-zinc-700 dark:text-zinc-300",
          "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
          "[scrollbar-width:thin]",
        )}
      >
        <code className={cx("grid", wrap ? "min-w-0" : "w-max min-w-full")}>
          {lines.map((line, index) => {
            const number = startLine + index;
            const emphasized = marked.has(number);
            return (
              <span
                key={index}
                data-highlighted={emphasized || undefined}
                className={cx(
                  "flex pe-4",
                  lineNumbers ? "ps-0" : "ps-4",
                  emphasized &&
                    "bg-zinc-950/[0.04] shadow-[inset_2px_0_0_rgb(9_9_11/0.35)] dark:bg-white/[0.06] dark:shadow-[inset_2px_0_0_rgb(255_255_255/0.45)]",
                )}
              >
                {lineNumbers ? (
                  <span
                    aria-hidden="true"
                    style={{ width: `${gutter + 3}ch` } as CSSProperties}
                    className={cx(
                      "shrink-0 pe-4 text-right tabular-nums select-none",
                      emphasized ? "text-zinc-600 dark:text-zinc-400" : "text-zinc-400 dark:text-zinc-600",
                    )}
                  >
                    {number}
                  </span>
                ) : null}
                <span className={cx("min-w-0", wrap ? "break-words whitespace-pre-wrap" : "whitespace-pre")}>
                  {line.length === 0
                    ? "\u200b"
                    : line.map((token, tokenIndex) => (
                        <span key={tokenIndex} className={token.className} style={token.color ? { color: token.color } : undefined}>
                          {token.content}
                        </span>
                      ))}
                </span>
              </span>
            );
          })}
        </code>
      </pre>
    </figure>
  );
}

function HeaderButton({
  label,
  pressed,
  onClick,
  children,
}: {
  label: string;
  pressed?: boolean;
  onClick: () => void;
  children: ReactNode;
}) {
  return (
    <button
      type="button"
      aria-label={label}
      title={label}
      aria-pressed={pressed}
      onClick={onClick}
      className={cx(
        "inline-flex size-7 items-center justify-center rounded-md text-zinc-500 [&_svg]:size-4",
        "transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none",
        "hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
        "aria-pressed:bg-zinc-950/[0.06] aria-pressed:text-zinc-950 dark:aria-pressed:bg-white/[0.09] dark:aria-pressed:text-white",
        "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500",
      )}
    >
      {children}
    </button>
  );
}

function FileGlyph() {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-3.5 shrink-0 text-zinc-400 dark:text-zinc-500">
      <path d="M4 1.75h5.25L12.5 5v8.25c0 .55-.45 1-1 1H4c-.55 0-1-.45-1-1V2.75c0-.55.45-1 1-1Z" stroke="currentColor" strokeWidth="1.25" strokeLinejoin="round" />
      <path d="M9 1.75V5.25h3.5" stroke="currentColor" strokeWidth="1.25" strokeLinejoin="round" />
    </svg>
  );
}