# Code tabs

> Tabbed command and code switcher for package managers or languages with keyboard arrow navigation and one-click copy.

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

## Use when
- CLI install commands across pnpm, npm, yarn, and bun
- SDK snippets switching between TypeScript, cURL, and Python

## Avoid when
- A single static file snippet needs no tabs; use code-block or snippet

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

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Base DOM id for tablist and tabpanels. |
| tabs | `TabItem[]` |  | no | Tab items with id, label, and code string. |
| showPrompt | `boolean` | true | no | Prepends a visual '$ ' prompt stripped automatically when copied. |
| class | `string` |  | no | Extra classes. |

## Accessibility
- Implements ARIA tablist/tab/tabpanel linkage via aria-controls and aria-labelledby.
- Clipboard result is announced through an aria-live status region.
- Key ArrowLeft / ArrowRight: Move between package manager or language tabs.

## Agent prompts

### Install and use

Install the Haze UI component "Code tabs" with `npx shadcn@latest add @haze/code-tabs`. 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 CodeTabs from "@/components/haze/ui/code-tabs.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-tabs.md

### Customize with real content

Adapt the Haze code-tabs ui for our product. Replace the demo values of these props with our real content: id, tabs, showPrompt, class. Keep the layout, the heading level rules and these accessibility details: Implements ARIA tablist/tab/tabpanel linkage via aria-controls and aria-labelledby. Clipboard result is announced through an aria-live status region. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using code-tabs, check it fits: use it when cli install commands across pnpm, npm, yarn, and bun; sdk snippets switching between typescript, curl, and python. Avoid it when a single static file snippet needs no tabs; use code-block or snippet. Alternatives: @haze/code-block, @haze/snippet, @haze/tabs.

## Example requests that should lead here
- Add a package manager install block switching between pnpm, npm, yarn, and bun with a copy button

## Source

```astro
---
import { Check, Copy, Terminal, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface TabItem {
  id: string;
  label: string;
  code: string;
  lang?: string;
}

interface Props {
  id: string;
  tabs?: TabItem[];
  showPrompt?: boolean;
  copyLabel?: string;
  class?: string;
}

const {
  id,
  tabs = [
    { id: "pnpm", label: "pnpm", code: "pnpm dlx shadcn@latest add @haze/button" },
    { id: "npm", label: "npm", code: "npx shadcn@latest add @haze/button" },
    { id: "yarn", label: "yarn", code: "yarn dlx shadcn@latest add @haze/button" },
    { id: "bun", label: "bun", code: "bunx --bun shadcn@latest add @haze/button" },
  ],
  showPrompt = true,
  copyLabel = "Copy command",
  class: className,
} = Astro.props;
---

<div
  id={id}
  data-haze-code-tabs
  class={cn("group min-w-0 overflow-hidden rounded-xl border border-border bg-card text-card-foreground", className)}
>
  <div class="flex min-h-11 flex-wrap items-center justify-between gap-2 border-b border-border bg-muted/40 py-1.5 pr-2 pl-4">
    <div class="flex min-w-0 items-center gap-2">
      <Terminal class="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
      <div role="tablist" aria-label="Install or language tabs" class="relative isolate inline-flex flex-wrap gap-1 rounded-lg bg-muted p-1 text-xs">
        {
          tabs.map((t, index) => (
            <button
              type="button"
              role="tab"
              id={`${id}-tab-${t.id}`}
              aria-controls={`${id}-panel-${t.id}`}
              aria-selected={index === 0 ? "true" : "false"}
              data-ct-tab={t.id}
              class="inline-flex h-6 cursor-pointer items-center rounded-md px-2.5 font-mono text-xs font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground aria-selected:bg-card aria-selected:text-foreground aria-selected:shadow-key focus-visible:outline-2 focus-visible:outline-ring"
            >
              {t.label}
            </button>
          ))
        }
      </div>
    </div>

    <button
      type="button"
      data-ct-copy
      aria-label={copyLabel}
      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 data-ct-ico="idle" class="size-3.5" aria-hidden="true" />
      <Check data-ct-ico="ok" class="hidden size-3.5 animate-pop text-success" aria-hidden="true" />
      <X data-ct-ico="err" class="hidden size-3.5 animate-pop text-destructive" aria-hidden="true" />
    </button>
  </div>

  <div>
    {
      tabs.map((t, index) => (
        <pre
          id={`${id}-panel-${t.id}`}
          role="tabpanel"
          aria-labelledby={`${id}-tab-${t.id}`}
          hidden={index !== 0}
          data-ct-panel={t.id}
          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>{showPrompt ? `$ ${t.code}` : t.code}</code></pre>
      ))
    }
  </div>
  <span role="status" data-ct-status class="sr-only"></span>
</div>

<script>
  function initCodeTabs() {
    document.querySelectorAll<HTMLElement>("[data-haze-code-tabs]:not([data-enhanced])").forEach((root) => {
      root.setAttribute("data-enhanced", "");
      const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-ct-tab]"));
      const panels = Array.from(root.querySelectorAll<HTMLElement>("[data-ct-panel]"));
      const copyBtn = root.querySelector<HTMLButtonElement>("[data-ct-copy]");
      const status = root.querySelector<HTMLElement>("[data-ct-status]");
      let activeId = tabs[0]?.dataset.ctTab ?? "";

      const select = (nextId: string) => {
        activeId = nextId;
        tabs.forEach((t) => t.setAttribute("aria-selected", String(t.dataset.ctTab === nextId)));
        panels.forEach((p) => {
          p.hidden = p.dataset.ctPanel !== nextId;
        });
      };

      tabs.forEach((t, i) => {
        t.addEventListener("click", () => select(t.dataset.ctTab ?? ""));
        t.addEventListener("keydown", (ev) => {
          const nextIdx =
            ev.key === "ArrowRight" ? (i + 1) % tabs.length : ev.key === "ArrowLeft" ? (i - 1 + tabs.length) % tabs.length : -1;
          if (nextIdx >= 0) {
            ev.preventDefault();
            const target = tabs[nextIdx];
            select(target.dataset.ctTab ?? "");
            target.focus();
          }
        });
      });

      let timer = 0;
      copyBtn?.addEventListener("click", async () => {
        const panel = panels.find((p) => p.dataset.ctPanel === activeId);
        const raw = (panel?.textContent ?? "").replace(/^\$\s*/, "");
        let ok = true;
        try {
          await navigator.clipboard.writeText(raw);
        } catch {
          ok = false;
        }
        root.querySelector('[data-ct-ico="idle"]')?.classList.add("hidden");
        root.querySelector(`[data-ct-ico="${ok ? "ok" : "err"}"]`)?.classList.remove("hidden");
        if (status) status.textContent = ok ? "Copied to clipboard" : "Copy failed";
        window.clearTimeout(timer);
        timer = window.setTimeout(() => {
          root.querySelector('[data-ct-ico="idle"]')?.classList.remove("hidden");
          root.querySelector('[data-ct-ico="ok"]')?.classList.add("hidden");
          root.querySelector('[data-ct-ico="err"]')?.classList.add("hidden");
        }, 1800);
      });
    });
  }

  initCodeTabs();
  if (!document.documentElement.hasAttribute("data-haze-code-tabs-listener")) {
    document.documentElement.setAttribute("data-haze-code-tabs-listener", "");
    document.addEventListener("astro:page-load", initCodeTabs);
  }
</script>
```
