# Code block

> Multi-line code in a bordered panel with an optional file name and language header and a copy button added by script; no highlighting.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/code-block`
- File: `src/components/haze/ui/code-block.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/code-block

## Use when
- Showing a file, a config or a short example in documentation
- A listing with a file name so readers know where the code lives
- Code that readers will copy whole

## Avoid when
- A single command people paste into a terminal; snippet is one line and smaller
- Code that needs syntax colors or line numbers; this component ships neither

## Alternatives
- [snippet](https://hazeui.com/ui/snippet.md)
- [kbd](https://hazeui.com/ui/kbd.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| code | `string` |  | yes | The source text. Rendered inside <pre><code>, so line breaks and indentation are kept. |
| filename | `string` |  | no | File name in the header bar. Also the aria-label of the code region. |
| lang | `string` |  | no | Small uppercase language label at the right of the header, for example "astro". |
| copyLabel | `string` | "Copy code" | no | Accessible name of the copy button. The button sits in the header, so it exists only when filename or lang is set. |
| copiedLabel | `string` | "Copied" | no | Text announced after a successful copy. |
| failedLabel | `string` | "Copy failed" | no | Text announced when the browser refuses the copy. |
| class | `string` |  | no | Extra classes on the outer panel. |

## Accessibility
- The <pre> is a focusable region named by the file name (or "Code"), so keyboard users can scroll lines that are wider than the box (WCAG 2.1.1).
- There is no syntax highlighting, so meaning never depends on token colors and the text keeps full contrast.
- The copy button is revealed by script, so without script the code is still selectable text and no dead button appears.
- After a copy, "Copied" or "Copy failed" is announced through a role="status" region, and the icon shows a check or a cross for 2 seconds.
- The language label is text in the header, not a class on the code, so it is read with the file name.
- Key Tab: Move to the copy button, then to the code region
- Key Enter / Space: Copy the code to the clipboard
- Key Arrow keys: Scroll the code region sideways or vertically while it has focus

## Agent prompts

### Install and use

Install the Haze UI component "Code block" with `npx shadcn@latest add @haze/code-block`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import CodeBlock from "@/components/haze/ui/code-block.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/code-block.md

### Customize with real content

Adapt the Haze code-block ui for our product. Replace the demo values of these props with our real content: code, filename, lang, copyLabel, copiedLabel, failedLabel, class. Keep the layout, the heading level rules and these accessibility details: The <pre> is a focusable region named by the file name (or "Code"), so keyboard users can scroll lines that are wider than the box (WCAG 2.1.1). There is no syntax highlighting, so meaning never depends on token colors and the text keeps full contrast. The copy button is revealed by script, so without script the code is still selectable text and no dead button appears. After a copy, "Copied" or "Copy failed" is announced through a role="status" region, and the icon shows a check or a cross for 2 seconds. The language label is text in the header, not a class on the code, so it is read with the file name. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using code-block, check it fits: use it when showing a file, a config or a short example in documentation; a listing with a file name so readers know where the code lives; code that readers will copy whole. Avoid it when a single command people paste into a terminal; snippet is one line and smaller; code that needs syntax colors or line numbers; this component ships neither. Alternatives: @haze/snippet, @haze/kbd.

## Example requests that should lead here
- Show this Astro component in a code block named waitlist-cta.astro
- Add a code block with a JSON config and a json label

## Source

```astro
---
import { Copy, Check, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  code: string;
  /** File name shown in the header bar; also names the scroll region. */
  filename?: string;
  /** Small language label in the header, for example "astro". */
  lang?: string;
  /** Accessible name of the copy button (shown in the header, so only when filename or lang is set). */
  copyLabel?: string;
  /** Text announced after a successful copy. */
  copiedLabel?: string;
  /** Text announced when the browser refuses the copy. */
  failedLabel?: string;
  class?: string;
}

const {
  code,
  filename,
  lang,
  copyLabel = "Copy code",
  copiedLabel = "Copied",
  failedLabel = "Copy failed",
  class: className,
} = Astro.props;
const hasHeader = Boolean(filename || lang);
---

<div
  data-haze-code-block
  data-copied-label={copiedLabel}
  data-failed-label={failedLabel}
  class={cn("group min-w-0 overflow-hidden rounded-xl border border-border bg-card", className)}
>
  {
    hasHeader && (
      <div class="flex min-h-11 items-center justify-between gap-2 border-b border-border bg-muted/40 py-1.5 pr-2 pl-4">
        <span class="min-w-0 truncate text-[0.8125rem]/5 font-medium tracking-[-0.01em] text-foreground">{filename}</span>
        <div class="flex shrink-0 items-center gap-2">
          {lang && <span class="font-mono text-xs/4 text-muted-foreground">{lang}</span>}
          <button
            type="button"
            hidden
            data-copy
            class="inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-90 active:duration-75"
          >
            <Copy class="size-4 group-data-[copied]:hidden group-data-[failed]:hidden" aria-hidden="true" />
            <Check class="hidden size-4 animate-pop text-success group-data-[copied]:block" aria-hidden="true" />
            <X class="hidden size-4 animate-pop text-destructive group-data-[failed]:block" aria-hidden="true" />
            <span class="sr-only">{copyLabel}</span>
          </button>
        </div>
      </div>
    )
  }
  <pre
    role="region"
    aria-label={filename ?? "Code"}
    tabindex="0"
    class="overflow-x-auto px-4 py-3.5 font-mono text-[0.8125rem]/6 text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"><code>{code}</code></pre>
  {hasHeader && <span role="status" class="sr-only" data-status></span>}
</div>

<script>
  // Enhancement: reveals the copy button and wires it up. Without script the code stays selectable text.
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    root.setAttribute("data-enhanced", "");
    const button = root.querySelector<HTMLButtonElement>("[data-copy]");
    const status = root.querySelector<HTMLElement>("[data-status]");
    const pre = root.querySelector("pre");
    if (!button || !pre) return;
    button.hidden = false;
    let timer: number | undefined;
    button.addEventListener("click", async () => {
      let ok = true;
      try {
        await navigator.clipboard.writeText(pre.textContent ?? "");
      } catch {
        ok = false;
      }
      root.removeAttribute("data-copied");
      root.removeAttribute("data-failed");
      root.setAttribute(ok ? "data-copied" : "data-failed", "");
      if (status) status.textContent = (ok ? root.dataset.copiedLabel : root.dataset.failedLabel) ?? "";
      window.clearTimeout(timer);
      timer = window.setTimeout(() => {
        root.removeAttribute("data-copied");
        root.removeAttribute("data-failed");
        if (status) status.textContent = "";
      }, 2000);
    });
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-code-block]").forEach(enhance);
  init();
  document.addEventListener("astro:page-load", init);
</script>
```
