Copy button

A copy-to-clipboard button that swaps to a check for two seconds, plus a one-line CopySnippet for commands and IDs. Uses the Clipboard API with an execCommand fallback; when both are blocked (for example in a sandboxed iframe) it selects the text and asks for Ctrl+C or ⌘C instead of failing silently, and counts the user's own copy as success. Status is announced politely.

ButtonsComponentTailwind v4

Source

"use client";

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

export type CopyStatus = "idle" | "copied" | "manual";

// execCommand is deprecated, but it still copies inside iframes that block the async Clipboard API.
function legacyCopy(text: string) {
  if (typeof document === "undefined") return false;
  const previous = document.activeElement as HTMLElement | null;
  const area = document.createElement("textarea");
  area.value = text;
  area.setAttribute("readonly", "");
  area.style.cssText = "position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;pointer-events:none";
  document.body.appendChild(area);
  area.select();
  let ok = false;
  try {
    ok = document.execCommand("copy");
  } catch {
    ok = false;
  }
  area.remove();
  previous?.focus({ preventScroll: true });
  return ok;
}

function selectContents(element: HTMLElement) {
  if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
    element.focus({ preventScroll: true });
    element.select();
    return;
  }
  const selection = window.getSelection();
  if (!selection) return;
  const range = document.createRange();
  range.selectNodeContents(element);
  selection.removeAllRanges();
  selection.addRange(range);
}

/** Copies text with the Clipboard API, falls back to execCommand, and reports "manual" when both are blocked. Never throws. */
export function useCopyToClipboard(resetAfter = 2000) {
  const [status, setStatus] = useState<CopyStatus>("idle");
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);

  const settle = useCallback((next: CopyStatus, ms: number) => {
    clearTimeout(timer.current);
    setStatus(next);
    if (next !== "idle") timer.current = setTimeout(() => setStatus("idle"), ms);
  }, []);

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

  const copy = useCallback(async (text: string) => {
    let ok = false;
    try {
      if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
        // Some embedded contexts leave the promise pending forever; treat a slow answer as blocked.
        const timeout = new Promise<never>((_, reject) => setTimeout(() => reject(new Error("timeout")), 1200));
        await Promise.race([navigator.clipboard.writeText(text), timeout]);
        ok = true;
      }
    } catch {
      ok = false;
    }
    if (!ok) ok = legacyCopy(text);
    settle(ok ? "copied" : "manual", ok ? resetAfter : 10_000);
    return ok;
  }, [resetAfter, settle]);

  const reset = useCallback(() => settle("idle", 0), [settle]);
  const markCopied = useCallback(() => settle("copied", resetAfter), [resetAfter, settle]);
  return { status, copy, reset, markCopied };
}

function useCopyKeys() {
  const [keys, setKeys] = useState("Ctrl+C");
  useEffect(() => {
    if (/Mac|iPhone|iPad/i.test(navigator.platform || navigator.userAgent)) setKeys("⌘C");
  }, []);
  return keys;
}

export interface CopyButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "value"> {
  /** The text to copy. */
  value: string;
  /** Visible label. Without it the button is icon-only and uses aria-label (default "Copy"). */
  label?: string;
  copiedLabel?: string;
  /** Selected when clipboard access is blocked, so the user can press Ctrl+C. Without it a small field opens instead. */
  selectTarget?: RefObject<HTMLElement | null>;
  onCopied?: (value: string) => void;
  variant?: "ghost" | "outline";
  size?: "sm" | "md";
}

export function CopyButton({
  value, label, copiedLabel = "Copied", selectTarget, onCopied, variant = "ghost", size = "md",
  className, onClick, "aria-label": ariaLabel, ...props
}: CopyButtonProps) {
  const { status, copy, reset, markCopied } = useCopyToClipboard();
  const keys = useCopyKeys();
  const buttonRef = useRef<HTMLButtonElement>(null);
  const fieldRef = useRef<HTMLInputElement>(null);
  const usePopover = status === "manual" && !selectTarget;
  const copied = status === "copied";

  async function handleClick(event: MouseEvent<HTMLButtonElement>) {
    onClick?.(event);
    if (event.defaultPrevented) return;
    if (await copy(value)) onCopied?.(value);
    else if (selectTarget?.current) selectContents(selectTarget.current);
  }

  // The fallback field opens with its text selected, ready for the shortcut.
  useEffect(() => {
    if (!usePopover) return;
    fieldRef.current?.focus({ preventScroll: true });
    fieldRef.current?.select();
  }, [usePopover]);

  // While in manual mode, a real copy (shortcut or context menu) counts as success.
  useEffect(() => {
    if (status !== "manual") return;
    function handleCopy() {
      const fromField = document.activeElement === fieldRef.current;
      markCopied();
      onCopied?.(value);
      if (fromField) buttonRef.current?.focus({ preventScroll: true });
    }
    document.addEventListener("copy", handleCopy);
    return () => document.removeEventListener("copy", handleCopy);
  }, [status, markCopied, onCopied, value]);

  function closeField(event: KeyboardEvent<HTMLInputElement>) {
    if (event.key !== "Escape") return;
    event.preventDefault();
    reset();
    buttonRef.current?.focus({ preventScroll: true });
  }

  const message = copied ? copiedLabel : status === "manual" ? `Copy blocked. Press ${keys} to copy.` : "";
  const iconOnly = !label;

  return (
    <span className="relative inline-flex">
      <button
        ref={buttonRef}
        type="button"
        aria-label={iconOnly ? ariaLabel ?? "Copy" : ariaLabel}
        data-status={status}
        onClick={handleClick}
        className={cn(
          "inline-flex shrink-0 items-center justify-center gap-1.5 rounded-md font-medium outline-hidden",
          "transition-[color,background-color,border-color,box-shadow] duration-150",
          "focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50",
          variant === "ghost" && "hover:bg-accent",
          variant === "outline" && "border border-border bg-background shadow-xs hover:bg-accent dark:border-input dark:bg-input/20 dark:hover:bg-input/40",
          copied
            ? "text-emerald-600 dark:text-emerald-400"
            : variant === "ghost" ? "text-muted-foreground hover:text-foreground" : "text-foreground",
          size === "sm" ? "h-7 text-xs" : "h-8 text-[13px]",
          iconOnly ? (size === "sm" ? "w-7" : "w-8") : "px-2.5",
          className,
        )}
        {...props}
      >
        <span aria-hidden="true" className="relative grid size-4 place-items-center">
          <Copy className={cn("col-start-1 row-start-1 size-3.5 transition-opacity duration-200 motion-safe:transition-[opacity,scale]", copied ? "scale-50 opacity-0" : "scale-100 opacity-100")} />
          <Check className={cn("col-start-1 row-start-1 size-4 transition-opacity duration-200 motion-safe:transition-[opacity,scale]", copied ? "scale-100 opacity-100" : "scale-50 opacity-0")} />
        </span>
        {label && <span>{copied ? copiedLabel : label}</span>}
      </button>

      {/* Polite announcement for copied and blocked states. */}
      <span role="status" className="sr-only">{message}</span>

      {status === "manual" && selectTarget && (
        <span
          aria-hidden="true"
          className="pointer-events-none absolute bottom-full right-0 z-20 mb-2 whitespace-nowrap rounded-md bg-foreground px-2 py-1 font-sans text-xs font-medium text-background shadow-md"
        >
          Press {keys} to copy
        </span>
      )}

      {usePopover && (
        <span className="absolute right-0 top-full z-20 mt-2 flex w-64 max-w-[calc(100vw-2rem)] flex-col gap-2 rounded-lg border border-border bg-popover p-2.5 text-left font-sans font-normal text-popover-foreground shadow-lg">
          <input
            ref={fieldRef}
            readOnly
            value={value}
            aria-label="Text to copy"
            onKeyDown={closeField}
            onBlur={(event) => {
              if (event.relatedTarget !== buttonRef.current) reset();
            }}
            className="h-8 w-full rounded-md border border-input bg-background px-2 font-mono text-xs text-foreground outline-hidden focus-visible:ring-[3px] focus-visible:ring-ring/50"
          />
          <span className="px-0.5 text-xs text-muted-foreground">Press {keys} to copy</span>
        </span>
      )}
    </span>
  );
}

export interface CopySnippetProps {
  /** The text shown and copied, such as a shell command or an ID. */
  value: string;
  /** Shown before the value and not copied, such as "$". */
  prefix?: string;
  className?: string;
  onCopied?: (value: string) => void;
}

/** A one-line code snippet with a copy button. If the clipboard is blocked, the snippet text is selected instead. */
export function CopySnippet({ value, prefix, className, onCopied }: CopySnippetProps) {
  const codeRef = useRef<HTMLElement>(null);
  return (
    <div className={cn("flex min-w-0 items-center gap-2 rounded-lg border border-border bg-muted/50 py-1 pl-3.5 pr-1 dark:bg-muted/30", className)}>
      {prefix && <span aria-hidden="true" className="select-none font-mono text-[13px] text-muted-foreground">{prefix}</span>}
      <code
        ref={codeRef}
        className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap py-1.5 font-mono text-[13px] text-foreground [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
      >
        {value}
      </code>
      <CopyButton value={value} selectTarget={codeRef} onCopied={onCopied} aria-label={`Copy ${prefix ? "command" : "text"}`} />
    </div>
  );
}