# Copy Button

> Copies text to the clipboard and confirms success with an icon and a live message.

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

## Use when
- Users need to copy a share URL, command, or reference.
- The action needs immediate, accessible feedback.

## Avoid when
- The operation should open a share sheet with multiple destinations.

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

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| text | `string` |  | yes | Exact text written to the clipboard. |
| label | `string` | Copy | no | Visible button label. |
| copiedMessage | `string` |  | no | Status announced on success. |
| showText | `boolean` | false | no | Always show the source text. |
| class | `string` |  | no | Classes for the surrounding group. |

## Accessibility
- A live region confirms the write while the button retains focus.
- The text becomes selectable when clipboard access is unavailable.
- Key Enter / Space: Copy the text from the focused button.

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze copy-button ui for our product. Replace the demo values of these props with our real content: text, label, copiedMessage, showText, class. Keep the layout, the heading level rules and these accessibility details: A live region confirms the write while the button retains focus. The text becomes selectable when clipboard access is unavailable. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using copy-button, check it fits: use it when users need to copy a share url, command, or reference.; the action needs immediate, accessible feedback.. Avoid it when the operation should open a share sheet with multiple destinations.. Alternatives: @haze/snippet, @haze/code-block, @haze/stateful-button.

## Example requests that should lead here
- Add a button to copy a public share URL.
- Give a generated reference number a clipboard shortcut.

## Source

```astro
---
import { Check, Clipboard, CircleAlert } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";

interface Props {
  text: string;
  label?: string;
  copiedMessage?: string;
  showText?: boolean;
  class?: string;
}

const { text, label = "Copy", copiedMessage = "Copied to clipboard.", showText = false, class: className } = Astro.props;
---

<div data-haze-copy-button data-copied-message={copiedMessage} data-state="idle"
  class={cn("group grid min-w-0 max-w-full justify-items-start gap-2", className)}>
  <pre data-copy-text hidden={!showText} class="w-full min-w-0 rounded-lg border border-border bg-card px-3 py-2 font-mono text-[0.8125rem]/5 whitespace-pre-wrap wrap-anywhere text-card-foreground"><code>{text}</code></pre>
  <div class="flex min-w-0 flex-wrap items-center gap-2">
    <Button variant="secondary" size="sm" disabled data-copy-trigger class="max-w-full">
      <Clipboard aria-hidden="true" class="hidden group-data-[state=idle]:inline-block" />
      <Check aria-hidden="true" class="hidden animate-pop group-data-[state=copied]:inline-block" />
      <CircleAlert aria-hidden="true" class="hidden text-destructive group-data-[state=error]:inline-block" />
      <span class="min-w-0 whitespace-normal wrap-anywhere">{label}</span>
    </Button>
    <span data-copy-status aria-live="polite" aria-atomic="true" class="text-[0.8125rem]/5 text-muted-foreground"></span>
  </div>
  {!showText && <noscript><pre class="w-full min-w-0 font-mono text-[0.8125rem]/5 whitespace-pre-wrap wrap-anywhere"><code>{text}</code></pre></noscript>}
</div>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const trigger = root.querySelector<HTMLButtonElement>("[data-copy-trigger]");
    const source = root.querySelector<HTMLElement>("[data-copy-text]");
    const status = root.querySelector<HTMLElement>("[data-copy-status]");
    if (!trigger || !source || !status) return;
    let timeout: number | undefined;
    let pending = false;
    trigger.disabled = false;
    trigger.addEventListener("click", async () => {
      if (pending) return;
      pending = true;
      window.clearTimeout(timeout);
      try {
        await navigator.clipboard.writeText(source.textContent ?? "");
        root.dataset.state = "copied";
        status.textContent = root.dataset.copiedMessage ?? "Copied.";
        timeout = window.setTimeout(() => { root.dataset.state = "idle"; status.textContent = ""; }, 2000);
      } catch {
        source.hidden = false;
        root.dataset.state = "error";
        status.textContent = "Select and copy the text manually.";
      } finally {
        pending = false;
      }
    });
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-copy-button]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-copy-button-listener")) {
    document.documentElement.setAttribute("data-haze-copy-button-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
