# Copy button

A button that copies a link, an ID or a snippet and says so: the icon swaps to a check that draws itself and the label to Copied, at a width that never moves.

Tier: free. Type: component. Category: actions. Tags: motion.

## Install

```bash
npx shadcn@latest add @pixilui/copy-button
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/copy-button.tsx`.

## Preview

Live preview: https://pixilui.com/components/copy-button

Knobs:

- `show`: `styles`, `more`, `sizes`, `states`

Signature: The copy icon swaps deep to a check that draws itself while the word becomes Copied, and the button never changes width.

Styles: `quiet` (default), `lively`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: quiet https://pixilui.com/r/standalone/copy-button.tsx, lively https://pixilui.com/r/standalone/copy-button.lively.tsx.

## Code

`components/pixilui/copy-button.tsx`

```tsx
"use client";

import { forwardRef, useEffect, useRef, useState, type MouseEvent, type ReactNode } from "react";
import { Button, type ButtonProps, type ButtonSize, type ButtonVariant } from "./button";

/*
  Copy, then Copied. The button's own copy face does the motion (button.tsx, foundation.css
  section 7): the icon swaps deep to a check that draws itself, the word swaps on the same curve,
  and `reserve` holds the wider label so the width never moves.
*/

const RESET_MS = 1600;

export type CopyButtonProps = Omit<ButtonProps, "children" | "icon" | "copied" | "reserve" | "onCopy" | "aria-label" | "value"> & {
  /** What lands on the clipboard: a string, or a function that returns one when pressed. */
  value: string | (() => string | Promise<string>);
  /** The copy icon (Lucide Copy, say). The check that replaces it is the button's own. */
  icon: ReactNode;
  /** The label at rest. Leave it out for an icon-only button, and pass aria-label. */
  label?: string;
  /** The label while the copy shows. */
  copiedLabel?: string;
  /** Accessible name for the icon-only form ("Copy link"). Required when there is no label. */
  "aria-label"?: string;
  /** Visual weight, as on Button. secondary (the glass) is the default; secondary-2 suits a row of message actions. */
  variant?: ButtonVariant;
  /** Height, as on Button: xs 24, sm 28, md 32 (default), lg 36, xl 44. */
  size?: ButtonSize;
  /** How long Copied shows before the button returns, in ms. */
  resetAfter?: number;
  /** Runs after the value is on the clipboard, with what was copied. */
  onCopied?: (value: string) => void;
  /** Runs when the clipboard refuses (no permission, an insecure page). The button stays at rest. */
  onCopyError?: (error: Error) => void;
};

/** A button that copies a value and says so: the icon swaps to a drawn check and the label to Copied, at a width that never moves. */
export const CopyButton = forwardRef<HTMLButtonElement, CopyButtonProps>(function CopyButton(
  { value, icon, label, copiedLabel = "Copied", resetAfter = RESET_MS, onCopied, onCopyError, onClick, ...rest },
  ref,
) {
  const [copied, setCopied] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);

  const copy = async (event: MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented) return;
    try {
      const text = typeof value === "function" ? await value() : value;
      await navigator.clipboard.writeText(text);
      setCopied(true);
      clearTimeout(timer.current);
      timer.current = setTimeout(() => setCopied(false), resetAfter);
      onCopied?.(text);
    } catch (error) {
      onCopyError?.(error instanceof Error ? error : new Error(String(error)));
    }
  };

  const reserve = label ? [{ label, icon: true }, { label: copiedLabel, icon: true }] : undefined;
  const common = { ...rest, ref, icon, copied, reserve, "data-status": copied ? "copied" : "idle", onClick: (event: MouseEvent<HTMLButtonElement>) => void copy(event) };
  if (label) return <Button {...common}>{copied ? copiedLabel : label}</Button>;
  return <Button {...common} aria-label={rest["aria-label"] ?? "Copy"} />;
});
```

## Usage

When to use:

- Copying something a person pastes elsewhere: a share link, an API key's prefix, a run ID, a code block.
- Icon-only beside a value in a table row or under a message, with an aria-label.

When not to use:

- Copying a whole message among other message actions: use Message actions, which holds this copy with regenerate and feedback.
- Secrets shown once: pair the copy with a clear warning on the page, not a toast.

```tsx
import type { ReactNode } from "react";
import { IconCopyCheck } from "@/components/pixilui/icons/copy-check";
import { IconCopyLink } from "@/components/pixilui/icons/copy-link";
import { CopyButton } from "@/components/pixilui/copy-button";

// The item page's one row, Show: Styles, More styles, Icons and sizes, States (the button pages' layout).
export const knobs = {
  show: ["styles", "more", "sizes", "states"],
} as const;

const Row = ({ children }: { children: ReactNode }) => <div className="flex flex-wrap items-center justify-center gap-2.5">{children}</div>;
const Cap = ({ children }: { children: ReactNode }) => <p className="-mt-2 text-center text-caption text-muted">{children}</p>;

function Shown({ show }: { show: string }) {
  if (show === "more")
    return (
      <>
        <Row>
          <CopyButton variant="tinted" icon={<IconCopyLink />} label="Copy share link" value="https://northwind.co/share/q3-renewals" />
          <CopyButton variant="soft" icon={<IconCopyCheck />} label="Copy prompt" value="Summarize ticket 2291 in three lines." />
        </Row>
        <Cap>Tinted, Soft</Cap>
      </>
    );
  if (show === "sizes")
    return (
      <>
        <Row>
          <span className="flex items-center gap-1.5 text-body text-secondary">
            <span className="font-mono text-mono">run_8f2c41</span>
            <CopyButton variant="secondary-2" size="sm" aria-label="Copy run ID" icon={<IconCopyCheck />} value="run_8f2c41" />
          </span>
          <span className="flex items-center gap-1.5 text-body text-secondary">
            <span className="font-mono text-mono">pk_live_51Hq</span>
            <CopyButton variant="secondary-2" size="sm" aria-label="Copy key prefix" icon={<IconCopyCheck />} value="pk_live_51Hq" />
          </span>
        </Row>
        <Cap>Icon-only, beside the value it copies</Cap>
        <Row>
          {(["sm", "md", "lg"] as const).map((size) => (
            <CopyButton key={size} size={size} icon={<IconCopyLink />} label="Copy link" value="https://northwind.co/share/q3-renewals" />
          ))}
        </Row>
        <Cap>28, 32 (default), 36</Cap>
      </>
    );
  if (show === "states")
    return (
      <>
        <Row>
          <CopyButton icon={<IconCopyLink />} label="Copy link" value="https://northwind.co/share/q3-renewals" resetAfter={3000} />
          <CopyButton icon={<IconCopyCheck />} label="Copy API key" value="sk_live_redacted" aria-disabled="true" />
        </Row>
        <Cap>Press Copy link: the check draws and Copied holds for 3 seconds. Disabled stays focusable.</Cap>
      </>
    );
  return (
    <>
      <Row>
        <CopyButton size="lg" icon={<IconCopyLink />} label="Copy link" value="https://northwind.co/share/q3-renewals" />
        <CopyButton variant="primary" size="lg" icon={<IconCopyLink />} label="Copy invite link" value="https://northwind.co/join/7Kq2" />
        <CopyButton variant="secondary-2" size="lg" icon={<IconCopyCheck />} label="Copy" value="Refunds over $500 need a second approval." />
      </Row>
      <Cap>Secondary (the glass), Primary, Secondary 2</Cap>
    </>
  );
}

export default function CopyButtonDemo({ show = "styles" }: KnobValues<typeof knobs>) {
  return (
    <div key={show} className="grid justify-items-center gap-4.5" aria-live="polite">
      <Shown show={show} />
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `variant` | `ButtonVariant` |  | Visual weight, as on Button. secondary (the glass) is the default; secondary-2 suits a row of message actions. |
| `size` | `ButtonSize` |  | Height, as on Button: xs 24, sm 28, md 32 (default), lg 36, xl 44. |
| `value` (required) | `string \| (() => string \| Promise<string>)` |  | What lands on the clipboard: a string, or a function that returns one when pressed. |
| `icon` (required) | `ReactNode` |  | The copy icon (Lucide Copy, say). The check that replaces it is the button's own. |
| `label` | `string` |  | The label at rest. Leave it out for an icon-only button, and pass aria-label. |
| `copiedLabel` | `string` | `"Copied"` | The label while the copy shows. |
| `aria-label` | `string` |  | Accessible name for the icon-only form ("Copy link"). Required when there is no label. |
| `resetAfter` | `number` | `RESET_MS` | How long Copied shows before the button returns, in ms. |
| `onCopied` | `(value: string) => void` |  | Runs after the value is on the clipboard, with what was copied. |
| `onCopyError` | `(error: Error) => void` |  | Runs when the clipboard refuses (no permission, an insecure page). The button stays at rest. |

## Keyboard

- `Tab`: Moves focus to the button.
- `Enter`: Copies the value; focus stays on the button while Copied shows.
- `Space`: Copies the value on release.

## Accessibility

- A native button. The label changes to Copied, so screen readers hear the result when they read the button again.
- Icon-only needs aria-label ("Copy run ID"); it defaults to Copy.
- The check is aria-hidden; the swapped label carries the meaning.
- data-status is copied or idle, for styling and tests.

## Motion

- The copy icon swaps deep (scale .3 with a 3px blur) to a check that draws itself in 260ms.
- The word swaps on the same curve; reserve holds the wider of Copy link and Copied, so the width never moves.
- Copied returns to rest after 1600ms (resetAfter).
- Reduced motion: the icon and the word change at once, with no draw.

## Responsive

- Never wider than its container. Icon-only sizes keep a 40px hit area on desktop and 44 on touch.

## Performance

- The clipboard is touched only on press. One timer, cleared on unmount.

## Notes for AI

- Pass value as a string, or a function that returns one (async is fine) when the text is built on press.
- Pass the copy icon as icon (Lucide Copy); never import an icon library inside the component. The check is the button's own.
- For icon-only, leave out label and pass aria-label. Use variant="secondary-2" size="sm" beside values in rows.
- onCopied runs after the clipboard write; onCopyError runs when the browser refuses, and the button stays at rest.

## Related

- [Button](https://pixilui.com/components/button/markdown): The PixilUI button in four main styles and four more, five sizes from 24 to 44, with icons, loading, disabled, a count and a shortcut.
- [Action button](https://pixilui.com/components/action-button/markdown): Buttons that show their own work, so the page needs no toast: Save to Saving to Saved, Upload that fills its own glass, and Generate that becomes its own Stop with the elapsed time.
- [Message actions](https://pixilui.com/components/message-actions/markdown): The row under an assistant's answer: copy, regenerate, good and bad feedback and more, as quiet icon buttons with tooltips, where copy draws a check and feedback fills its glyph.
