dxbh-uiGitHub

Copy Button

Copies text to the clipboard. The icon morphs from copy to check with a blurred cross-fade, the button presses to 0.97, and screen readers hear a polite “Copied”.

Preview
npx shadcn@latest add @dxbh-ui/copy-button
Copied 0×

Install

npx shadcn@latest add @dxbh-ui/copy-button

Add the @dxbh-ui registry to components.json once:

{
  "registries": {
    "@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
  }
}

Usage

demo.tsx
"use client";

import { useState } from "react";
import { CopyButton } from "@/components/ui/copy-button/copy-button";

export default function CopyButtonDemo() {
  const [count, setCount] = useState(0);
  const command = "npx shadcn@latest add @dxbh-ui/copy-button";

  return (
    <div className="flex w-full max-w-md flex-col items-center gap-6">
      <div className="flex w-full items-center gap-2 rounded-lg border bg-background py-1.5 pr-1.5 pl-3 font-mono text-[13px]">
        <span className="truncate text-foreground">{command}</span>
        <CopyButton value={command} className="ml-auto" onCopy={() => setCount((n) => n + 1)} />
      </div>
      <div className="flex items-center gap-3">
        <CopyButton value="dxbh-ui" showLabel className="border" />
        <span className="text-xs text-muted-foreground tabular-nums">Copied {count}×</span>
      </div>
    </div>
  );
}

Props

PropTypeDefault
value*

Text to copy, or a function that returns it at click time.

string | (() => string | Promise<string>)—
onCopy

Called after the text reached the clipboard.

(value: string) => void—
onCopyError

Called when the clipboard write fails.

(error: unknown) => void—
timeout

How long the check mark stays, in ms.

number1600
label

Accessible name, and the visible text with showLabel.

string"Copy"
copiedLabel

Announced (and shown with showLabel) after copying.

string"Copied"
showLabel

Show the label next to the icon.

booleanfalse

Polish

  • Analytics coupling removed; an onCopy callback reports the copied text instead.
  • Icon swap is a cross-fade with 2px blur and scale 0.95 → 1, never from scale 0.
  • Press feedback at active:scale-[0.97] with the press duration token and the dxbh-ui ease-out curve.
  • Only transform, opacity and filter animate. Hover colour changes are instant.
  • Result announced through an aria-live status region; the accessible name stays stable.
  • Labelled variant stacks both labels in one grid cell so the width never jumps.
  • Reduced motion keeps the cross-fade and drops the scale and blur.
  • Falls back to execCommand when the async clipboard is unavailable.

Source

copy-button.tsx
"use client";

import { useEffect, useRef, useState, type ButtonHTMLAttributes, type MouseEvent } from "react";
import { Check, Copy } from "lucide-react";
import { cn } from "@/lib/utils";

export type CopyButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "value" | "onCopy" | "children"> & {
  /** Text to copy, or a function that returns it at click time. */
  value: string | (() => string | Promise<string>);
  /** Called after the text reached the clipboard. Hook analytics here. */
  onCopy?: (value: string) => void;
  /** Called when the clipboard refused the write. */
  onCopyError?: (error: unknown) => void;
  /** How long the check mark stays, in ms. */
  timeout?: number;
  /** Accessible name, and the visible text when `showLabel` is set. */
  label?: string;
  /** Announced (and shown with `showLabel`) after a successful copy. */
  copiedLabel?: string;
  /** Show the label next to the icon instead of an icon-only button. */
  showLabel?: boolean;
};

/** Write text to the clipboard, falling back to execCommand outside secure contexts. */
export async function writeClipboard(text: string): Promise<void> {
  if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
    await navigator.clipboard.writeText(text);
    return;
  }
  const area = document.createElement("textarea");
  area.value = text;
  area.setAttribute("readonly", "");
  area.style.position = "fixed";
  area.style.opacity = "0";
  document.body.appendChild(area);
  area.select();
  try {
    if (!document.execCommand("copy")) throw new Error("Copy command was rejected");
  } finally {
    area.remove();
  }
}

// Both states stay mounted and cross-fade with a touch of blur so the eye
// reads one icon morphing, not two swapping. Scale starts at 0.95, never 0.
const swap =
  "col-start-1 row-start-1 transition-[opacity,filter,transform] duration-(--duration-popover,180ms) ease-out motion-reduce:scale-100 motion-reduce:blur-none";
const shown = "scale-100 opacity-100 blur-none";
const hidden = "scale-95 opacity-0 blur-[2px]";

export function CopyButton({
  value,
  onCopy,
  onCopyError,
  timeout = 1600,
  label = "Copy",
  copiedLabel = "Copied",
  showLabel = false,
  className,
  onClick,
  type = "button",
  ...props
}: CopyButtonProps) {
  const [copied, setCopied] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);

  useEffect(() => () => clearTimeout(timer.current), []);

  const handleClick = async (event: MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented) return;
    try {
      const text = typeof value === "function" ? await value() : value;
      await writeClipboard(text);
      setCopied(true);
      // Copying again restarts the timer rather than stacking a second one.
      clearTimeout(timer.current);
      timer.current = setTimeout(() => setCopied(false), timeout);
      onCopy?.(text);
    } catch (error) {
      setCopied(false);
      onCopyError?.(error);
    }
  };

  return (
    <>
      <button
        type={type}
        // The name stays put while the visuals change; the status region below
        // announces the result instead.
        aria-label={label}
        data-copied={copied || undefined}
        onClick={handleClick}
        className={cn(
          "inline-flex shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-md text-sm font-medium text-muted-foreground outline-none select-none",
          "transition-transform duration-(--duration-press,120ms) ease-out active:scale-[0.97]",
          "hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50",
          "disabled:pointer-events-none disabled:opacity-50",
          showLabel ? "h-8 px-2.5" : "size-8",
          className,
        )}
        {...props}
      >
        <span aria-hidden="true" className="grid size-4 place-items-center [&>svg]:size-4">
          <Copy className={cn(swap, copied ? hidden : shown)} />
          <Check className={cn(swap, copied ? shown : hidden)} />
        </span>
        {showLabel ? (
          // Both labels share one grid cell so the button never changes width.
          <span aria-hidden="true" className="grid">
            <span className={cn(swap, copied ? hidden : shown)}>
              {label}
            </span>
            <span className={cn(swap, copied ? shown : hidden)}>
              {copiedLabel}
            </span>
          </span>
        ) : null}
      </button>
      <span role="status" aria-live="polite" className="sr-only">
        {copied ? copiedLabel : ""}
      </span>
    </>
  );
}

Extracted from anidub/apps/web/src/components/ui/copy-button.tsx at a950c62.