Copy Button
Copies text to the clipboard with a drawn-tick icon morph, an optional swapping label, an error state and a screen-reader announcement.
Preview
terminal
$ pnpm dlx shadcn@latest add /r/copy-button.json// retry with backoff
await retry(sync, { tries: 3 });Publishable key
key_pub_8f2c41d9a7b3e605
Safe to ship in client code.
Copied to clipboard
Install
Add the editable source with the shadcn CLI. Your project also needs the shared theme tokens this component uses. Setup and requirements. The Pebble installer is not published yet.
npx shadcn@latest add https://pebbleui.com/r/copy-button.jsonProps
| Prop | Type | Default | Description |
|---|---|---|---|
| value | string | () => string | Promise<string> | — | Text to copy, read at click time. Required. |
| label | boolean | { idle?, copied?, error? } | false | Show a text label. true uses Copy / Copied / Failed. |
| variant | "ghost" | "secondary" | "outline" | "ghost" | Surface style. |
| size | "sm" | "md" | "md" | 28 or 32 px. |
| timeout | number | 2000 | How long the copied or error state shows, in ms. |
| status | "idle" | "copied" | "error" | — | Controlled status, e.g. for a static mock. |
| onCopy / onCopyError | (text) => void / (error) => void | — | Called after a successful or failed copy. |
| announce | { copied?, error? } | — | Screen reader messages for the live region. |
Build notes
- Clipboard: `navigator.clipboard.writeText`, read only in the click handler (SSR-safe). A missing API throws into the same error path. - Status machine `idle → copied | error → idle` with one timeout ref, cleared on every copy and on unmount. - Icon swap: `AnimatePresence mode="popLayout"` keyed on status; enter from scale 0.5 + 2 px blur, spring (stiffness 520, damping 28, mass 0.6). The tick is a `motion.path` animating `pathLength` 0 → 1 over ~240 ms on the enter curve after a 40 ms delay, so it draws after the sheets leave. Error adds `x: [0, -2, 2, -1, 0]` as a 320 ms tween (springs can't do multi keyframes). - Label swap: DESIGN text-swap (blur 2 px + fade + 5 px y, `popLayout`). All three labels sit invisible in one grid cell (`[grid-area:1/1]`) to reserve the widest width, so the button never changes size. - Colour: copied tints only the icon (`text-accent-strong`), error tints the whole button `text-danger-strong`. - Hover-reveal inside code (demo): `[@media(hover:hover)]:opacity-0` plus `group-hover`/`group-focus-within` to show; always visible on touch. <!-- PEBBLE-LICENSE -->
View source
registry/button/copy-button/copy-button.tsx
"use client";
/* PEBBLE-LICENSE
Built by Pebble. Component: copy-button.
First-party license: MIT
The following first-party terms apply only to original Pebble material.
MIT License
Copyright (c) 2026 Praxys Solutions LLC (Pebble)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
THIRD-PARTY NOTICES
These notices apply to identified upstream portions; Pebble terms do not replace or narrow their rights.
Upstream: https://raw.githubusercontent.com/WatermelonCorp/watermelon-platform/main/LICENSE
MIT License
Copyright (c) 2026 Watermelon Platform Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
END PEBBLE-LICENSE */
import * as React from "react";
import { AnimatePresence, motion, MotionConfig } from "motion/react";
import { cn } from "@/lib/utils";
export type CopyStatus = "idle" | "copied" | "error";
const variants = {
ghost:
"text-muted-foreground hover:bg-muted hover:text-foreground active:bg-muted/80 data-[status=copied]:text-foreground",
secondary:
"bg-card text-foreground ring-1 ring-hairline shadow-raised-xs inset-shadow-highlight hover:bg-muted/60 active:shadow-none active:inset-shadow-none",
outline: "text-foreground ring-1 ring-border hover:bg-muted active:bg-muted/80",
} as const;
const sizes = {
sm: { icon: "size-7 [&_svg]:size-3.5", label: "h-7 gap-1.5 px-2 text-xs [&_svg]:size-3.5" },
md: { icon: "size-8 [&_svg]:size-4", label: "h-8 gap-1.5 px-2.5 text-[13px] [&_svg]:size-4" },
} as const;
// Icon glyphs: two sheets (copy), a tick (copied) and a cross (error). Ours,
// 16 px at 1.5 stroke.
function CopyGlyph() {
return (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
<rect x="5.5" y="5.5" width="8" height="8" rx="2" />
<path d="M10.5 3.5A1.5 1.5 0 0 0 9 2.5H4A1.5 1.5 0 0 0 2.5 4v5A1.5 1.5 0 0 0 3.5 10.5" />
</svg>
);
}
function CheckGlyph() {
return (
<svg
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
{/* The tick draws itself in, left to right. */}
<motion.path
d="M3.5 8.5l3 3 6-7"
initial={{ pathLength: 0 }}
animate={{ pathLength: 1 }}
// ~--motion-base on the --motion-enter curve.
transition={{ duration: 0.24, ease: [0.22, 1, 0.36, 1], delay: 0.04 }}
/>
</svg>
);
}
function ErrorGlyph() {
return (
<svg
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
aria-hidden="true"
>
<circle cx="8" cy="8" r="5.5" />
<path d="M8 5.25v3.25M8 10.75v.01" />
</svg>
);
}
const glyphs = { idle: CopyGlyph, copied: CheckGlyph, error: ErrorGlyph };
export type CopyButtonProps = Omit<
React.ComponentProps<"button">,
"value" | "children" | "onCopy"
> & {
/** Text to copy, or a function returning it (sync or async). */
value: string | (() => string | Promise<string>);
/** Show a text label next to the icon. `true` uses "Copy" / "Copied" / "Failed". */
label?: boolean | { idle?: string; copied?: string; error?: string };
variant?: keyof typeof variants;
size?: keyof typeof sizes;
/** How long the copied or error state shows, in ms. */
timeout?: number;
/** Controlled status, e.g. to show a copied state in a static mock. */
status?: CopyStatus;
onCopy?: (text: string) => void;
onCopyError?: (error: unknown) => void;
/** Screen reader announcement after a copy. */
announce?: { copied?: string; error?: string };
};
export function CopyButton({
value,
label = false,
variant = "ghost",
size = "md",
timeout = 2000,
status: statusProp,
onCopy,
onCopyError,
announce,
className,
onClick,
type,
"aria-label": ariaLabel,
...props
}: CopyButtonProps) {
const [internal, setInternal] = React.useState<CopyStatus>("idle");
const status = statusProp ?? internal;
const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined);
React.useEffect(() => () => clearTimeout(timer.current), []);
const labels = {
idle: "Copy",
copied: "Copied",
error: "Failed",
...(typeof label === "object" ? label : {}),
};
const messages = {
copied: "Copied to clipboard",
error: "Couldn’t copy. Select the text and copy it manually.",
...announce,
};
function settle(next: CopyStatus) {
setInternal(next);
clearTimeout(timer.current);
timer.current = setTimeout(() => setInternal("idle"), timeout);
}
async function copy() {
try {
const text = typeof value === "function" ? await value() : value;
if (!navigator.clipboard?.writeText) throw new Error("Clipboard API unavailable");
await navigator.clipboard.writeText(text);
settle("copied");
onCopy?.(text);
} catch (error) {
settle("error");
onCopyError?.(error);
}
}
const Glyph = glyphs[status];
const showLabel = label !== false;
return (
<MotionConfig reducedMotion="user">
<button
type={type ?? "button"}
data-slot="copy-button"
data-status={status}
// Labelled buttons name themselves from the current label, so the
// outgoing text (still fading out) never joins the name.
aria-label={showLabel ? labels[status] : (ariaLabel ?? labels.idle)}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) void copy();
}}
className={cn(
"relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-md font-medium whitespace-nowrap select-none",
"transition-[background-color,box-shadow,color,transform] duration-(--motion-fast) ease-enter motion-reduce:transition-none",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none",
"active:scale-[0.94] motion-reduce:active:scale-100",
"disabled:pointer-events-none disabled:opacity-50",
// Success is ink with an ember tick; failure is danger text.
"data-[status=copied]:[&_[data-slot=copy-button-icon]]:text-accent-strong",
"data-[status=error]:text-danger-strong data-[status=error]:ring-danger/40",
variants[variant],
showLabel ? sizes[size].label : sizes[size].icon,
className,
)}
{...props}
>
<span data-slot="copy-button-icon" className="relative grid place-items-center">
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={status}
className="grid place-items-center"
initial={{ opacity: 0, scale: 0.5, filter: "blur(2px)" }}
animate={
status === "error"
? { opacity: 1, scale: 1, filter: "blur(0px)", x: [0, -2, 2, -1, 0] }
: { opacity: 1, scale: 1, filter: "blur(0px)" }
}
exit={{ opacity: 0, scale: 0.5, filter: "blur(2px)" }}
// A snappy spring for the swap; the error shake is keyframed
// over --motion-slow.
transition={{
type: "spring",
stiffness: 520,
damping: 28,
mass: 0.6,
x: { type: "tween", duration: 0.32, ease: "easeInOut" },
}}
>
<Glyph />
</motion.span>
</AnimatePresence>
</span>
{showLabel && (
// All three labels share one grid cell; the hidden ones reserve the
// widest width so the button never jumps when the text swaps.
<span className="grid">
{(["idle", "copied", "error"] as const).map((key) => (
<span
key={key}
aria-hidden="true"
className="invisible [grid-area:1/1]"
data-slot="copy-button-sizer"
>
{labels[key]}
</span>
))}
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={status}
className="[grid-area:1/1]"
initial={{ opacity: 0, y: 5, filter: "blur(2px)" }}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={{ opacity: 0, y: -5, filter: "blur(2px)" }}
// --motion-base on the --motion-enter curve.
transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
>
{labels[status]}
</motion.span>
</AnimatePresence>
</span>
)}
</button>
{/* Outside the button so it never joins the button's accessible name. */}
<span role="status" className="sr-only">
{status === "idle" ? "" : messages[status]}
</span>
</MotionConfig>
);
}
