Skip to content
Atoms

Copy button

Click to copy, see the check.

Installation

  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/ and the colour tokens go into your CSS.

    $ pnpm dlx asta-ui@latest add copy-button

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/copy-button.json

  2. Or install the package

    Don’t want the file? Import from asta-ui/copy-button and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui
    import { ClipboardButton } from "asta-ui/copy-button";
  3. Or copy it by hand

    Copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { useEffect, useRef, useState, type ButtonHTMLAttributes } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    const EASE = "ease-[cubic-bezier(.16,1,.3,1)]";
    
    export interface ClipboardButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "value" | "onCopy" | "children"> {
      /** Text to copy, or a function that returns it at click time. */
      value: string | (() => string);
      /** Visible label. Leave it out for an icon-only button. */
      label?: string;
      /** Label while the check shows. */
      copiedLabel?: string;
      /** How long the check stays, in ms. */
      timeout?: number;
      onCopy?: (text: string) => void;
      variant?: "ghost" | "outline" | "soft";
      size?: "sm" | "md";
    }
    
    async function writeText(text: string) {
      try {
        await navigator.clipboard.writeText(text);
        return true;
      } catch {
        // Older browsers and non-secure pages: fall back to a hidden textarea.
        const ta = document.createElement("textarea");
        ta.value = text;
        ta.setAttribute("readonly", "");
        ta.style.cssText = "position:fixed;opacity:0;pointer-events:none";
        document.body.appendChild(ta);
        ta.select();
        let ok = false;
        try {
          ok = document.execCommand("copy");
        } catch {}
        ta.remove();
        return ok;
      }
    }
    
    const VARIANT = {
      ghost: "text-mute hover:bg-paper-2 hover:text-ink",
      outline: "text-ink-2 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_14%,transparent)] hover:text-ink hover:shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_26%,transparent)]",
      soft: "bg-paper-2 text-ink-2 hover:text-ink",
    };
    
    /**
     * Copies text on click. The copy icon turns and fades as a check draws itself in, the label rolls to
     * "Copied", and both settle back after a moment. Screen readers hear the result.
     */
    export function ClipboardButton({ value, label, copiedLabel = "Copied", timeout = 1600, onCopy, variant = "ghost", size = "md", className, onClick, ...rest }: ClipboardButtonProps) {
      const [state, setState] = useState<"idle" | "copied" | "failed">("idle");
      const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
    
      useEffect(() => () => clearTimeout(timer.current), []);
    
      const copy = async () => {
        const text = typeof value === "function" ? value() : value;
        const ok = await writeText(text);
        setState(ok ? "copied" : "failed");
        if (ok) onCopy?.(text);
        clearTimeout(timer.current);
        timer.current = setTimeout(() => setState("idle"), timeout);
      };
    
      const done = state === "copied";
      const icon = size === "md" ? "h-4 w-4" : "h-3.5 w-3.5";
      const said = done ? copiedLabel : state === "failed" ? "Couldn't copy" : label;
    
      return (
        <>
        <button
          type="button"
          {...rest}
          aria-label={label ? undefined : (rest["aria-label"] ?? "Copy")}
          data-state={state}
          onClick={(e) => {
            onClick?.(e);
            if (!e.defaultPrevented) copy();
          }}
          className={cx(
            "inline-flex shrink-0 select-none items-center justify-center gap-1.5 rounded-lg font-medium outline-none transition-[color,background-color,box-shadow,transform] duration-200 focus-visible:ring-2 focus-visible:ring-brand/50 active:scale-[.96] disabled:pointer-events-none disabled:opacity-40",
            size === "md" ? "h-9 text-[13px]" : "h-7 text-[12.5px]",
            label ? (size === "md" ? "px-3" : "px-2.5") : size === "md" ? "w-9" : "w-7",
            VARIANT[variant],
            className,
          )}
        >
          <span className={cx("relative flex items-center justify-center", icon)} aria-hidden>
            <svg
              viewBox="0 0 24 24"
              className={cx("absolute inset-0 transition-[opacity,transform] duration-300 motion-reduce:transition-none", EASE, done ? "rotate-[-30deg] scale-50 opacity-0" : "scale-100 opacity-100")}
              fill="none"
              stroke="currentColor"
              strokeWidth="2.25" strokeLinecap="round"
              strokeLinejoin="round"
            >
              <rect x="8.5" y="8.5" width="11" height="11" rx="2" />
              <path d="M15.5 8.5V6.5a2 2 0 0 0-2-2h-7a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h2" strokeLinecap="round" />
            </svg>
            <svg
              viewBox="0 0 24 24"
              className={cx("absolute inset-0 text-brand transition-[opacity,transform] duration-300 motion-reduce:transition-none", EASE, done ? "scale-100 opacity-100" : "scale-75 opacity-0")}
              fill="none"
              stroke="currentColor"
              strokeWidth="2.85"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path
                d="m5 12.5 4.5 4.5L19 7.5"
                pathLength={1}
                strokeDasharray={1}
                strokeDashoffset={done ? 0 : 1}
                className={cx("transition-[stroke-dashoffset] motion-reduce:transition-none", EASE, done ? "delay-75 duration-[420ms]" : "duration-150")}
              />
            </svg>
          </span>
          {label && (
            <span className="relative grid overflow-hidden" aria-hidden>
              {/* Both labels share one cell so the width never jumps. */}
              <span className={cx("col-start-1 row-start-1 transition-[opacity,transform] duration-300 motion-reduce:transition-none", EASE, state === "idle" ? "translate-y-0 opacity-100" : "-translate-y-full opacity-0")}>{label}</span>
              <span className={cx("col-start-1 row-start-1 transition-[opacity,transform] duration-300 motion-reduce:transition-none", EASE, state === "idle" ? "translate-y-full opacity-0" : "translate-y-0 opacity-100")}>
                {state === "failed" ? "Couldn't copy" : copiedLabel}
              </span>
            </span>
          )}
          {label && <span className="sr-only">{label}</span>}
        </button>
        {/* Outside the button so the announcement doesn't become part of its name. */}
        <span className="sr-only" role="status" aria-live="polite">
          {state === "idle" ? "" : said}
        </span>
        </>
      );
    }
    
    export default ClipboardButton;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Copy button component to my project.
    
    Click to copy, see the check.
    It includes: ClipboardButton, icon only, label, copied state, ghost, outline, soft.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add copy-button --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/copy-button.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { ClipboardButton } from "@/components/astabyte/copy-button";
    ```
    
    Usage example and props: https://ui.astabyte.com/copy-button
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <!-- Needs asta.js (Clipboard API, secure context only). -->
    <div style="display:flex;flex-wrap:wrap;align-items:flex-start;gap:24px">
    <button type="button" class="asta-copy-button asta-copy-button-outline asta-copy-button-text" data-asta-copy="npm i asta-ui" data-timeout="1600" data-state="idle" data-copied="Copied">
    <span class="asta-copy-button-icons" aria-hidden="true"><svg viewBox="0 0 16 16" class="asta-copy-button-copy" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"><rect x="5.25" y="5.25" width="8" height="8" rx="2"></rect><path d="M10.75 3.5V3.75A1.75 1.75 0 0 0 9 2H4A2 2 0 0 0 2 4v5a1.75 1.75 0 0 0 1.75 1.75H4" stroke-linecap="round"></path></svg><svg viewBox="0 0 16 16" class="asta-copy-button-done" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="m3.5 8.5 3 3 6-7" pathLength="1" class="asta-copy-tick"></path></svg></span>
    <span class="asta-copy-button-labels" aria-hidden="true"><span class="asta-copy-button-idle">Copy</span><span class="asta-copy-button-copied"><span class="asta-copy-button-ok">Copied</span><span class="asta-copy-button-fail">Couldn't copy</span></span></span><span class="asta-sr-only">Copy</span></button>
    <span class="asta-sr-only" role="status" aria-live="polite" data-asta-copy-status></span>
    <button type="button" class="asta-copy-button" data-asta-copy="0x1234" data-timeout="1600" data-state="idle" data-copied="Copied" aria-label="Copy">
    <span class="asta-copy-button-icons" aria-hidden="true"><svg viewBox="0 0 16 16" class="asta-copy-button-copy" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"><rect x="5.25" y="5.25" width="8" height="8" rx="2"></rect><path d="M10.75 3.5V3.75A1.75 1.75 0 0 0 9 2H4A2 2 0 0 0 2 4v5a1.75 1.75 0 0 0 1.75 1.75H4" stroke-linecap="round"></path></svg><svg viewBox="0 0 16 16" class="asta-copy-button-done" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="m3.5 8.5 3 3 6-7" pathLength="1" class="asta-copy-tick"></path></svg></span></button>
    <span class="asta-sr-only" role="status" aria-live="polite" data-asta-copy-status></span>
    <button type="button" class="asta-copy-button asta-copy-button-soft asta-copy-button-sm asta-copy-button-text" data-asta-copy="astabyte" data-timeout="1600" data-state="copied" data-copied="Copied">
    <span class="asta-copy-button-icons" aria-hidden="true"><svg viewBox="0 0 16 16" class="asta-copy-button-copy" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"><rect x="5.25" y="5.25" width="8" height="8" rx="2"></rect><path d="M10.75 3.5V3.75A1.75 1.75 0 0 0 9 2H4A2 2 0 0 0 2 4v5a1.75 1.75 0 0 0 1.75 1.75H4" stroke-linecap="round"></path></svg><svg viewBox="0 0 16 16" class="asta-copy-button-done" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="m3.5 8.5 3 3 6-7" pathLength="1" class="asta-copy-tick"></path></svg></span>
    <span class="asta-copy-button-labels" aria-hidden="true"><span class="asta-copy-button-idle">Copy</span><span class="asta-copy-button-copied"><span class="asta-copy-button-ok">Copied</span><span class="asta-copy-button-fail">Couldn't copy</span></span></span><span class="asta-sr-only">Copy</span></button>
    <span class="asta-sr-only" role="status" aria-live="polite" data-asta-copy-status></span>
    </div>

Usage

The demo above, as code.

"use client";

import { ClipboardButton } from "@/components/astabyte/copy-button";

const KEY = "nw_live_8f2k4q9xm3t7v1p6";
const INVITE = "https://app.astabyte.com/join/7f3k-q9xm";

export default function CopyButtonDemo() {
  return (
    <div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
      <div className="flex w-full max-w-sm flex-col gap-6">
        <div className="rounded-xl bg-paper-2 p-4 pl-5">
          <p className="text-[12px] text-mute">Secret key</p>
          <div className="mt-1 flex items-center justify-between gap-3">
            <code className="truncate font-mono text-[13px] text-ink">{KEY.slice(0, 12)}••••••••</code>
            <ClipboardButton value={KEY} aria-label="Copy secret key" />
          </div>
        </div>

        <div className="flex items-center justify-between gap-3 px-1">
          <code className="truncate font-mono text-[13px] text-ink-2">bunx asta-ui@latest add copy-button</code>
          <ClipboardButton value="bunx asta-ui@latest add copy-button" size="sm" variant="soft" aria-label="Copy command" />
        </div>

        <div className="flex items-center justify-between gap-3 px-1">
          <div className="min-w-0">
            <p className="text-[13.5px] font-medium tracking-[-0.01em] text-ink">Invite link</p>
            <p className="truncate text-[12.5px] text-mute">{INVITE}</p>
          </div>
          <ClipboardButton value={INVITE} label="Copy link" copiedLabel="Link copied" variant="outline" />
        </div>

        <p className="text-center text-[12.5px] text-mute">The check shows for a moment, then the button settles back.</p>
      </div>
    </div>
  );
}