Copy button
Press it and the copy mark lifts away while a check draws itself in, then it settles back. Screen readers hear Copied.
npx shadcn@latest add https://captain-ui.vercel.app/r/copy-button.json$ npx shadcn@latest add https://captain-ui.vercel.app/r/copy-button.jsonFix checkout race in the webhook handler
Commit 4f1c9e2 on fix/checkout-race
"use client";
// Captain UI · Copy button, MIT. The copy mark lifts away and a check draws itself in; screen readers hear "Copied".
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useEffect, useRef, useState } from "react";
import { EASE, cx } from "@/registry/captain/ui/captain";
import { Icon } from "@/registry/captain/ui/icons";
type CopyButtonProps = {
/** The text to copy, or a function that returns it at the moment of the click. */
value: string | (() => string | Promise<string>);
/** Shows a text label next to the icon. Without it the button is icon only and uses `aria-label`. */
label?: string;
/** Label after a successful copy. */
copiedLabel?: string;
/** Accessible name for the icon-only button. */
"aria-label"?: string;
onCopy?: (text: string) => void;
/** How long the check stays, in ms. */
timeout?: number;
size?: "sm" | "md";
className?: string;
};
type State = "idle" | "copied" | "failed";
async function write(text: string) {
if (navigator.clipboard && window.isSecureContext) {
try {
return await navigator.clipboard.writeText(text);
} catch {
// Permission refused or the document lost focus: 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();
const ok = document.execCommand("copy");
ta.remove();
if (!ok) throw new Error("copy failed");
}
const SWAP = { duration: 0.18, ease: EASE } as const;
export function CopyButton({ value, label, copiedLabel = "Copied", onCopy, timeout = 1600, size = "md", className, ...rest }: CopyButtonProps) {
const [state, setState] = useState<State>("idle");
const [said, setSaid] = useState("");
const reduce = useReducedMotion();
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
const copy = async () => {
clearTimeout(timer.current);
try {
const text = typeof value === "function" ? await value() : value;
await write(text);
setState("copied");
setSaid(copiedLabel);
onCopy?.(text);
} catch {
setState("failed");
setSaid("Copy failed");
}
timer.current = setTimeout(() => {
setState("idle");
setSaid("");
}, timeout);
};
const box = size === "sm" ? "h-8 min-w-8" : "h-9 min-w-9";
const icon = size === "sm" ? 15 : 16;
const mark = state === "idle" ? "copy" : state;
const from = reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: "blur(2px)" };
const to = { opacity: 1, scale: 1, filter: "blur(0px)" };
return (
<>
<button
type="button"
onClick={copy}
aria-label={label ? undefined : (rest["aria-label"] ?? "Copy")}
className={cx(
"pressable relative inline-flex shrink-0 items-center justify-center gap-1.5 rounded-inner text-[13px] font-medium text-ink-2 transition-colors duration-150 before:absolute before:-inset-1 before:content-[''] hover:bg-hover hover:text-ink focus-visible:bg-hover focus-visible:text-ink",
box,
label ? "px-2.5" : "",
state === "copied" && "text-ink",
className,
)}
>
<span className="relative grid place-items-center" style={{ width: icon, height: icon }}>
<AnimatePresence initial={false} mode="popLayout">
{mark === "copy" ? (
<motion.span key="copy" className="grid place-items-center" initial={from} animate={to} exit={from} transition={SWAP}>
<Icon name="copy" size={icon} />
</motion.span>
) : mark === "copied" ? (
<motion.svg
key="check"
width={icon}
height={icon}
viewBox="0 0 24 24"
aria-hidden="true"
initial={{ opacity: 0, scale: reduce ? 1 : 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: reduce ? 1 : 0.8 }}
transition={SWAP}
>
<motion.path
d="M5.5 12.75 9.75 17 18.5 7.5"
fill="none"
stroke="currentColor"
strokeWidth={1.75}
strokeLinecap="round"
strokeLinejoin="round"
initial={{ pathLength: reduce ? 1 : 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 0.28, ease: EASE, delay: reduce ? 0 : 0.05 }}
/>
</motion.svg>
) : (
<motion.span key="x" className="grid place-items-center text-danger" initial={from} animate={to} exit={from} transition={SWAP}>
<Icon name="x" size={icon} />
</motion.span>
)}
</AnimatePresence>
</span>
{label ? (
<span className="relative grid">
{/* Both labels sit in one cell so the button never changes width. */}
<span className={cx("col-start-1 row-start-1 transition-opacity duration-150", state !== "idle" && "opacity-0")}>{label}</span>
<span aria-hidden="true" className={cx("col-start-1 row-start-1 transition-opacity duration-150", state === "idle" && "opacity-0")}>
{state === "failed" ? "Failed" : copiedLabel}
</span>
</span>
) : null}
</button>
<span role="status" className="sr-only">
{said}
</span>
</>
);
}Usage
import { CopyButton } from "@/components/ui/copy-button"
<CopyButton value={command} aria-label="Copy install command" />Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| value | string | () => string | Promise<string> | What to copy. A function runs at click time, so it can read the latest text. | |
| label | string | Optional visible label. The button keeps its width when it changes to Copied. | |
| copiedLabel | string | "Copied" | Shown and announced after a copy. |
| aria-label | string | "Copy" | Name for the icon-only button. Say what it copies. |
| onCopy | (text: string) => void | Called after a successful copy. | |
| timeout | number | 1600 | How long the check stays, in ms. |
| size | "sm" | "md" | "md" | 32 or 36px. The hit area is always 44px. |
Keyboard
- Enter
- Copy
- Space
- Copy
Accessibility
- A real button. Icon-only buttons need an aria-label that says what is copied.
- A polite status region announces Copied, or Copy failed when the clipboard refuses.
- Reduced motion swaps the morph and the stroke draw for a plain crossfade.