# Code Block

A readable, copyable source-code surface with optional tokenization.

Code Block displays source, terminal output, logs, and diffs. Use the automatic API for a concise highlighted block or compose its parts when the header, actions, lines, and footer need application-specific controls.

```tsx
import { CodeBlock } from "@zentara-co/zenos-ui";

function CodeBlockExample() {
  return (
    <CodeBlock
      className="w-full max-w-xl"
      code={"const answer = 42;\nreturn answer;"}
      language="typescript"
      title="answer.ts"
    />
  );
}
```

## Import

```tsx
import {
  CodeBlock,
  CodeBlockActions,
  CodeBlockContent,
  CodeBlockCopyButton,
  CodeBlockFooter,
  CodeBlockHeader,
  CodeBlockLine,
  CodeBlockTitle,
} from "@zentara-co/zenos-ui";
```

## Composition

Use `CodeBlock.Header` for a title and persistent actions. `CodeBlock.Content` is keyboard-focusable and always reads left to right, while the header continues to follow the document direction.

```tsx
import { CodeBlock } from "@zentara-co/zenos-ui";

const codeBlockTerminalOutput = `$ pnpm build
> zenos build

✓ Compiled successfully
✓ Generated component documentation`;

function CodeBlockCompositionExample() {
  return (
    <CodeBlock className="w-full max-w-xl">
      <CodeBlock.Header>
        <CodeBlock.Title>Terminal</CodeBlock.Title>
        <CodeBlock.Actions>
          <CodeBlock.CopyButton value={codeBlockTerminalOutput} />
        </CodeBlock.Actions>
      </CodeBlock.Header>
      <CodeBlock.Content>{codeBlockTerminalOutput}</CodeBlock.Content>
      <CodeBlock.Footer className="justify-end text-xs text-text-subtle">
        Completed in 1.8s
      </CodeBlock.Footer>
    </CodeBlock>
  );
}
```

```tsx
<CodeBlock>
  <CodeBlock.Header>
    <CodeBlock.Title>Terminal</CodeBlock.Title>
    <CodeBlock.Actions>
      <CodeBlock.CopyButton value={output} />
    </CodeBlock.Actions>
  </CodeBlock.Header>
  <CodeBlock.Content>{output}</CodeBlock.Content>
  <CodeBlock.Footer>Completed</CodeBlock.Footer>
</CodeBlock>
```

Passing `code`, `language`, and the existing display props remains the shortest way to render tokenized source. Consumer code can migrate to composition only when it needs the additional slots.

## Actions and wrapping

Place `CodeBlock.Actions` directly under the root to float it at the logical top end. Floating actions appear on hover, keyboard focus, and touch devices. Wrapping is controlled so applications can connect it to any button or preference.

```tsx
import { Button, CodeBlock } from "@zentara-co/zenos-ui";
import { useState } from "react";

function CodeBlockActionsExample() {
  const [wrap, setWrap] = useState(false);
  const output =
    "Error: The generated response exceeded the available context window. Remove older messages or summarize the conversation before trying again.";

  return (
    <CodeBlock className="w-full max-w-xl" variant="destructive">
      <CodeBlock.Actions>
        <Button
          aria-pressed={wrap}
          className="h-7 min-h-7 px-2 text-xs"
          size="sm"
          variant="ghost"
          onClick={() => setWrap((current) => !current)}
        >
          Wrap
        </Button>
        <CodeBlock.CopyButton value={output} />
      </CodeBlock.Actions>
      <CodeBlock.Content className="pe-24" wrap={wrap}>
        {output}
      </CodeBlock.Content>
    </CodeBlock>
  );
}
```

## Line numbers and diffs

For plain string content, set `lineNumbers` and optionally `startLine` on `CodeBlock.Content`. For per-line emphasis, compose `CodeBlock.Line` with `variant="highlighted"`, `"added"`, or `"removed"`. Diff markers and line numbers are excluded from text selection.

```tsx
import { CodeBlock } from "@zentara-co/zenos-ui";

function CodeBlockDiffExample() {
  return (
    <CodeBlock className="w-full max-w-xl">
      <CodeBlock.Header>
        <CodeBlock.Title>components/greeting.tsx</CodeBlock.Title>
      </CodeBlock.Header>
      <CodeBlock.Content>
        <CodeBlock.Line lineNumber={12} variant="removed">
          {"return <p>Hello, {name}</p>;"}
        </CodeBlock.Line>
        <CodeBlock.Line lineNumber={13} variant="added">
          {'return <p className="text-sm">Hello, {name}!</p>;'}
        </CodeBlock.Line>
        <CodeBlock.Line lineNumber={14} variant="highlighted">
          {"// Keep the new greeting compact."}
        </CodeBlock.Line>
      </CodeBlock.Content>
    </CodeBlock>
  );
}
```

## Automatic line numbers and highlights

Use line numbers for source references and `highlightLines` to direct attention to a specific change.

```tsx
import { CodeBlock } from "@zentara-co/zenos-ui";

const codeBlockSample = `type Finding = {
  id: string;
  severity: "low" | "high";
};

const finding: Finding = {
  id: "F-1042",
  severity: "high",
};`;

function CodeBlockHighlightedExample() {
  return (
    <CodeBlock
      code={codeBlockSample}
      language="typescript"
      title="finding.ts"
      hasLineNumbers
      highlightLines={[6, 7, 8, 9]}
      width="100%"
    />
  );
}
```

## Sizes

The `sm`, `md`, and `lg` sizes change the code type scale and line height.

```tsx
import { CodeBlock, Stack } from "@zentara-co/zenos-ui";

function CodeBlockSizesExample() {
  return (
    <Stack gap="4" className="w-full">
      {(["sm", "md", "lg"] as const).map((size) => (
        <CodeBlock
          key={size}
          code={`const size = "${size}";`}
          language="typescript"
          title={`${size}.ts`}
          size={size}
          width="100%"
        />
      ))}
    </Stack>
  );
}
```

## Containers

`card` provides complete surface chrome. `section` removes the outer border and background for embedding in an existing surface.

```tsx
import { CodeBlock, Stack } from "@zentara-co/zenos-ui";

function CodeBlockContainersExample() {
  return (
    <Stack gap="6" className="w-full">
      <CodeBlock
        code={"pnpm add @zentara-co/zenos-ui"}
        language="bash"
        title="Card container"
        container="card"
        width="100%"
      />
      <CodeBlock
        code={"pnpm add @zentara-co/zenos-ui"}
        language="bash"
        title="Section container"
        container="section"
        width="100%"
      />
    </Stack>
  );
}
```

## Long content

Wrap long lines when horizontal scrolling would interrupt the surrounding layout. Collapsible blocks keep lengthy examples compact while preserving an accessible disclosure control.

```tsx
import { CodeBlock, Stack } from "@zentara-co/zenos-ui";

function CodeBlockLongContentExample() {
  const longCode = Array.from(
    { length: 12 },
    (_, index) => `const rule${index + 1} = evaluateControl("security-control-${index + 1}");`,
  ).join("\n");

  return (
    <Stack gap="4" className="w-full">
      <CodeBlock
        code={
          'const notification = "This long line wraps inside narrow containers instead of requiring horizontal scrolling.";'
        }
        language="typescript"
        title="wrapped.ts"
        isWrapped
        width="100%"
      />
      <CodeBlock
        code={longCode}
        language="typescript"
        title="controls.ts"
        hasLineNumbers
        isCollapsible
        collapsibleThreshold={10}
        maxHeight={240}
        width="100%"
      />
    </Stack>
  );
}
```

Use a `max-h-*` and `overflow-y-auto` class on composed `CodeBlock.Content` when a log needs a fixed height. Put a show-more control in `CodeBlock.Footer` when expanding content is more appropriate than an inner scrollbar.

## Destructive output

Set `variant="destructive"` on the root for failed commands, stack traces, or other error output. The treatment uses semantic danger tokens in both light and dark themes.

## RTL

The header and floating actions use logical positioning and follow the page direction. Code content always uses `dir="ltr"` so source, terminal output, and line gutters retain their expected reading order.

## Anatomy

```text
CodeBlock.Root
CodeBlock.Header
CodeBlock.Title
CodeBlock.Actions
CodeBlock.CopyButton
CodeBlock.Content
CodeBlock.Line
CodeBlock.Footer
```

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| code | string | — | Source rendered in the block. |
| children | ReactNode | — | Composable header, actions, content, lines, and footer. |
| variant | default \| destructive | default | Semantic surface treatment for ordinary or failed output. |
| language | string | plaintext | Language label and tokenizer hint. |
| title | string | — | Optional header title. |
| size | sm \| md \| lg | md | Code type scale. |
| hasLanguageLabel | boolean | true | Shows the normalized language name in the header. |
| hasLineNumbers | boolean | false | Shows line-number gutter. |
| hasCopyButton | boolean | true | Shows the copy action. |
| highlightLines | number[] | [] | One-based line numbers to emphasize. |
| onCopy | () => void | — | Runs after the source is copied successfully. |
| container | card \| section | card | Outer chrome. |
| Content lineNumbers / startLine | boolean / number | false / 1 | Numbers composed string content from the requested first line. |
| Content wrap | boolean | false | Wraps composed output instead of scrolling it horizontally. |
| Line variant | default \| highlighted \| added \| removed | default | Emphasizes a line or renders it as part of a diff. |
| isWrapped / isCollapsible | boolean | false | Long-line and long-snippet behavior. |
| collapsibleThreshold | number | 10 | Minimum line count before the collapse control appears. |
| maxHeight / width | number \| string / string | — | Constrains the scroll pane height and root width. |
| highlightMode | auto \| ranges \| spans | auto | Identifies how highlighting metadata is interpreted. |
| tokenizer | CodeBlockTokenizer | — | Optional syntax tokenizer. |

Unless narrowed above, each DOM-rendering part also accepts its underlying native or Base UI props, including className, style, aria-*, and data-*.

## Accessibility

Code is rendered with native `pre` and `code` elements. The scrollable content is keyboard-focusable, line numbers and diff markers are hidden from assistive technology, and copy controls announce both “Copy code” and their successful “Copied” state. Collapsible automatic blocks expose their expanded state with `aria-expanded`.

The composable behavior is informed by the [shadcn Code Block](https://ui.shadcn.com/docs/components/base/code-block) while retaining Zenos tokenization, semantic colors, sizing, and legacy convenience props.

Source: https://zenos-ui.pages.dev/components/code-block/