# Snippet

> One-line command in a mono field that scrolls sideways, with an optional prompt prefix and a copy button added by script.

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

## Use when
- An install or CLI command that readers will paste into a terminal
- A short token-like value such as a package name or a URL that people copy
- Docs and landing pages where one command is the main call to action

## Avoid when
- Several lines or a file; code-block shows multi-line code with a header
- Secrets that must not reach the clipboard history of a shared machine

## Alternatives
- [code-block](https://hazeui.com/ui/code-block.md)
- [kbd](https://hazeui.com/ui/kbd.md)
- [input-group](https://hazeui.com/ui/input-group.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| text | `string` |  | yes | The command. It is displayed as written and copied unchanged. |
| prefix | `string` |  | no | Leading marker such as "$". Hidden from screen readers and from selection, and not copied. |
| copyLabel | `string` | "Copy" | no | Accessible name of the copy button. |
| copiedLabel | `string` | "Copied" | no | Text announced after a successful copy. |
| failedLabel | `string` | "Copy failed" | no | Text announced when the browser refuses the copy, for example without clipboard permission. |
| class | `string` |  | no | Extra classes on the box. |

## Accessibility
- The copy button starts with the hidden attribute and script reveals it, so without script the command is still selectable text and no dead button appears.
- After a copy, copiedLabel (or failedLabel when the copy was refused) goes into a role="status" region, so screen reader users hear the result; the icon swap alone would be silent.
- The icon shows a check for 2 seconds on success and a cross on failure, then returns to the copy icon; the status text is cleared at the same time.
- The scrolling <code> is focusable, so a command longer than the box can be scrolled with the keyboard.
- Key Tab: Move to the command box, then to the copy button
- Key Enter / Space: Copy the command to the clipboard
- Key Arrow Left / Right: Scroll a long command while the command box has focus

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze snippet ui for our product. Replace the demo values of these props with our real content: text, prefix, copyLabel, copiedLabel, failedLabel, class. Keep the layout, the heading level rules and these accessibility details: The copy button starts with the hidden attribute and script reveals it, so without script the command is still selectable text and no dead button appears. After a copy, copiedLabel (or failedLabel when the copy was refused) goes into a role="status" region, so screen reader users hear the result; the icon swap alone would be silent. The icon shows a check for 2 seconds on success and a cross on failure, then returns to the copy icon; the status text is cleared at the same time. The scrolling <code> is focusable, so a command longer than the box can be scrolled with the keyboard. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using snippet, check it fits: use it when an install or cli command that readers will paste into a terminal; a short token-like value such as a package name or a url that people copy; docs and landing pages where one command is the main call to action. Avoid it when several lines or a file; code-block shows multi-line code with a header; secrets that must not reach the clipboard history of a shared machine. Alternatives: @haze/code-block, @haze/kbd, @haze/input-group.

## Example requests that should lead here
- Add an install command with a copy button under the hero text
- Show "npx shadcn@latest add @haze/button" with a $ prefix

## Source

```astro
---
import { Copy, Check, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  /** The command to show and copy. */
  text: string;
  /** Leading marker such as "$". Not selectable and hidden from screen readers. */
  prefix?: string;
  /** Accessible name of the copy button. */
  copyLabel?: string;
  /** Text announced after a successful copy. */
  copiedLabel?: string;
  /** Text announced when the browser refuses the copy. */
  failedLabel?: string;
  class?: string;
}

const {
  text,
  prefix,
  copyLabel = "Copy",
  copiedLabel = "Copied",
  failedLabel = "Copy failed",
  class: className,
} = Astro.props;
---

<div
  data-haze-snippet
  data-copied-label={copiedLabel}
  data-failed-label={failedLabel}
  class={cn(
    "group flex h-10 max-w-full min-w-0 items-center gap-2 rounded-lg border border-frame-input bg-field pr-1 pl-3 font-mono text-[0.8125rem]/5 text-foreground",
    className,
  )}
>
  {prefix && <span aria-hidden="true" class="text-muted-foreground select-none">{prefix}</span>}
  <code
    class="min-w-0 flex-1 overflow-x-auto rounded-sm whitespace-nowrap focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
    tabindex="0">{text}</code
  >
  <button
    type="button"
    hidden
    data-copy
    data-text={text}
    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>
  <span role="status" class="sr-only" data-status></span>
</div>

<script>
  // Enhancement: reveals the copy button and wires it up. Without script the command 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]");
    if (!button) return;
    button.hidden = false;
    let timer: number | undefined;
    button.addEventListener("click", async () => {
      let ok = true;
      try {
        await navigator.clipboard.writeText(button.dataset.text ?? "");
      } 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-snippet]").forEach(enhance);
  init();
  document.addEventListener("astro:page-load", init);
</script>
```
