Buttons & Actionsv0.1.0
Copy Button
Copy icon cross-fades into a check with a soft blur.
Installation
CLI
npx shadcn@latest add https://hantui-theta.vercel.app/r/copy-button.jsonManual
Install the dependencies
npm install clsx lucide-react motion tailwind-mergeAdd the shared helpers
Components use
cn()fromlib/utils.tsand the motion tokens below. See Installation if you have not set them up yet.lib/clipboard.ts"use client"; import { useCallback, useEffect, useRef, useState } from "react"; /** * Writes text to the clipboard. Uses the async Clipboard API where it exists and falls back to a * hidden textarea with `document.execCommand("copy")` in non-secure contexts (plain HTTP, some * embedded webviews). Call it from an event handler only. Rejects when the copy is refused. */ export async function writeClipboard(text: string): Promise<void> { if (navigator.clipboard?.writeText) { await navigator.clipboard.writeText(text); return; } const textarea = document.createElement("textarea"); textarea.value = text; textarea.setAttribute("readonly", ""); textarea.style.position = "fixed"; textarea.style.opacity = "0"; document.body.appendChild(textarea); textarea.select(); const ok = document.execCommand("copy"); textarea.remove(); if (!ok) throw new Error("Copy command was rejected"); } export interface UseCopyOptions { /** Milliseconds before `copied` returns to false. @default 2000 */ resetAfter?: number; /** Called with the copied text after a successful copy. */ onCopy?: (text: string) => void; } export interface UseCopyResult { /** True from a successful copy until `resetAfter` has passed. */ copied: boolean; /** Copies the text. Resolves to false when the browser refuses. Call it from an event handler. */ copy: () => Promise<boolean>; /** Returns to the idle state right away. */ reset: () => void; } /** Copy-to-clipboard state for buttons: `copied` flips to true after a successful copy and resets on a timer. */ export function useCopy(text: string, { resetAfter = 2000, onCopy }: UseCopyOptions = {}): UseCopyResult { const [copied, setCopied] = useState(false); const timer = useRef<number | undefined>(undefined); const mounted = useRef(true); const latest = useRef({ text, resetAfter, onCopy }); useEffect(() => { latest.current = { text, resetAfter, onCopy }; }); useEffect(() => { mounted.current = true; return () => { mounted.current = false; window.clearTimeout(timer.current); }; }, []); const reset = useCallback(() => { window.clearTimeout(timer.current); setCopied(false); }, []); const copy = useCallback(async () => { const current = latest.current; try { await writeClipboard(current.text); } catch { return false; } if (!mounted.current) return true; setCopied(true); current.onCopy?.(current.text); window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setCopied(false), current.resetAfter); return true; }, []); return { copied, copy, reset }; }lib/motion.tsimport type { Transition, Variants } from "motion/react"; /** Durations in seconds. */ export const duration = { instant: 0.1, quick: 0.18, base: 0.28, slow: 0.45, } as const; /** Cubic-bezier curves. */ export const ease = { /** Entering, UI response. */ out: [0.22, 1, 0.36, 1], /** Moving on screen. */ inOut: [0.65, 0, 0.35, 1], /** Sheets and the mobile menu. */ drawer: [0.32, 0.72, 0, 1], } as const; /** Everyday UI: presses, icon swaps, popovers and modals. Exits run at `exitFactor` of the enter. */ export const ui = { press: { scale: 0.96, duration: 0.12 }, icon: { type: "spring", duration: 0.3, bounce: 0 }, popover: { duration: 0.18, ease: ease.out }, modal: { duration: 0.24, ease: ease.out }, exitFactor: 0.6, } as const; /** Once-per-visit motion on the landing page: hero letters, the reel and the afterimage. */ export const kinetic = { heroLetter: { duration: 0.6, ease: ease.out }, /** Delay per letter, eased so the wave slows toward the end. */ heroStep: 0.035, reelSwap: { type: "spring", duration: 0.5, bounce: 0.1 }, /** Two afterimages: lag in seconds and opacity of each. */ ghost: { lag: [0.04, 0.09], opacity: [0.14, 0.06] }, } as const; /** Spring presets. */ export const spring = { snappy: { type: "spring", stiffness: 500, damping: 30 }, smooth: { type: "spring", stiffness: 260, damping: 26 }, bouncy: { type: "spring", stiffness: 300, damping: 15 }, } as const satisfies Record<string, Transition>; /** Stagger between siblings, in seconds (0.03–0.06). */ export const stagger = { tight: 0.03, base: 0.045, loose: 0.06, } as const; /** Blur + fade + y-offset. Falls back to a plain fade under reduced motion. */ export function enterVariants(reduceMotion?: boolean | null, y = 8): Variants { if (reduceMotion) { return { hidden: { opacity: 0 }, visible: { opacity: 1, transition: { duration: duration.base } }, exit: { opacity: 0, transition: { duration: duration.quick } }, }; } return { hidden: { opacity: 0, y, filter: "blur(4px)" }, visible: { opacity: 1, y: 0, filter: "blur(0px)", transition: { duration: duration.base, ease: ease.out }, }, exit: { opacity: 0, y: -y / 2, filter: "blur(4px)", transition: { duration: duration.quick, ease: ease.out }, }, }; } /** Scale 0.96 → 1 for popovers, menus and dialogs. */ export function overlayVariants(reduceMotion?: boolean | null): Variants { if (reduceMotion) { return { hidden: { opacity: 0 }, visible: { opacity: 1, transition: { duration: duration.quick } }, exit: { opacity: 0, transition: { duration: duration.instant } }, }; } return { hidden: { opacity: 0, scale: 0.96, filter: "blur(2px)" }, visible: { opacity: 1, scale: 1, filter: "blur(0px)", transition: { duration: duration.quick, ease: ease.out }, }, exit: { opacity: 0, scale: 0.96, filter: "blur(2px)", transition: { duration: duration.instant + 0.02, ease: ease.out }, }, }; } /** Parent variants that stagger their children in. */ export function staggerVariants(gap: number = stagger.base, delayChildren = 0): Variants { return { hidden: {}, visible: { transition: { staggerChildren: gap, delayChildren } }, exit: { transition: { staggerChildren: gap / 2, staggerDirection: -1 } }, }; }Add the theme tokens
This component uses --success, which shadcn does not define by default. Add it to your global CSS:
app/globals.css:root { --success: #15803d; } .dark { --success: #4ade80; } @theme inline { --color-success: var(--success); }Copy the source
components/ui/copy-button/copy-button.tsx"use client"; import type { ComponentProps, MouseEvent } from "react"; import { AnimatePresence, motion, useReducedMotion, type Variants } from "motion/react"; import { Check, Copy } from "lucide-react"; import { cn } from "@/lib/utils"; import { useCopy } from "@/lib/clipboard"; import { duration, ease } from "@/lib/motion"; export interface CopyButtonProps extends Omit<ComponentProps<"button">, "value" | "children" | "onCopy"> { /** Text written to the clipboard. */ value: string; /** Visible label. Omit it for an icon-only button. */ label?: string; /** Label shown after a successful copy. @default "Copied" */ copiedLabel?: string; /** Milliseconds before the button returns to its idle state. @default 2000 */ timeout?: number; /** Visual style. @default "outline" */ variant?: "outline" | "ghost" | "solid"; /** Button size. Small buttons keep a 40px hit area. @default "md" */ size?: "sm" | "md"; /** Called with the copied text after a successful copy. */ onCopied?: (value: string) => void; } const variantClasses = { outline: "border border-border bg-background text-foreground shadow-xs hover:bg-accent", ghost: "text-muted-foreground hover:bg-accent hover:text-foreground", solid: "bg-foreground text-background hover:bg-foreground/85", } as const; const sizeClasses = { sm: { base: "h-8 gap-1.5 rounded-md px-2.5 text-[13px]", icon: "size-8 rounded-md" }, md: { base: "h-10 gap-2 rounded-md px-3.5 text-sm", icon: "size-10 rounded-md" }, } as const; export function CopyButton({ value, label, copiedLabel = "Copied", timeout = 2000, variant = "outline", size = "md", onCopied, onClick, className, type = "button", "aria-label": ariaLabel, ...props }: CopyButtonProps) { const { copied, copy } = useCopy(value, { resetAfter: timeout, onCopy: onCopied }); const reduceMotion = useReducedMotion(); function handleClick(event: MouseEvent<HTMLButtonElement>) { onClick?.(event); if (event.defaultPrevented) return; void copy(); } const swap: Variants = reduceMotion ? { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } } : { initial: { opacity: 0, scale: 0.6, filter: "blur(4px)" }, animate: { opacity: 1, scale: 1, filter: "blur(0px)" }, exit: { opacity: 0, scale: 0.6, filter: "blur(4px)" }, }; const labelSwap: Variants = reduceMotion ? swap : { initial: { opacity: 0, y: 6, filter: "blur(3px)" }, animate: { opacity: 1, y: 0, filter: "blur(0px)" }, exit: { opacity: 0, y: -6, filter: "blur(3px)" }, }; const transition = { duration: duration.quick, ease: ease.out }; const iconOnly = !label; return ( <> <button type={type} aria-label={ariaLabel ?? (iconOnly ? "Copy to clipboard" : undefined)} onClick={handleClick} className={cn( "relative inline-flex shrink-0 cursor-pointer select-none items-center justify-center font-medium whitespace-nowrap outline-none", "transition-[background-color,border-color,color,box-shadow,transform] duration-150 active:scale-[0.96]", "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background", "disabled:pointer-events-none disabled:opacity-50", size === "sm" && "after:absolute after:-inset-1 after:content-['']", variantClasses[variant], iconOnly ? sizeClasses[size].icon : sizeClasses[size].base, className, )} {...props} > <span className="grid size-4 place-items-center *:[grid-area:1/1]" aria-hidden="true"> <AnimatePresence initial={false}> {copied ? ( <motion.span key="check" variants={swap} initial="initial" animate="animate" exit="exit" transition={transition} className={cn(variant !== "solid" && "text-success")} > <Check className="size-4" strokeWidth={2.25} /> </motion.span> ) : ( <motion.span key="copy" variants={swap} initial="initial" animate="animate" exit="exit" transition={transition} > <Copy className="size-4" strokeWidth={2} /> </motion.span> )} </AnimatePresence> </span> {label ? ( // Both labels sit in one grid cell so the button keeps the wider width // and never animates its size. <span className="grid *:[grid-area:1/1]"> <span className="invisible" aria-hidden="true"> {label} </span> <span className="invisible" aria-hidden="true"> {copiedLabel} </span> <AnimatePresence initial={false}> <motion.span key={copied ? "copied" : "idle"} variants={labelSwap} initial="initial" animate="animate" exit="exit" transition={transition} className="text-left" > {copied ? copiedLabel : label} </motion.span> </AnimatePresence> </span> ) : null} </button> <span role="status" className="sr-only"> {copied ? "Copied to clipboard" : ""} </span> </> ); }
Usage
import { CopyButton } from "@/components/ui/copy-button/copy-button";
export function InviteLink() {
return <CopyButton value="https://example.com/invite" label="Copy link" />;
}API reference
| Prop | Type | Default | Description |
|---|---|---|---|
value* | string | – | Text written to the clipboard. |
label | string | – | Visible label. Omit it for an icon-only button. |
copiedLabel | string | "Copied" | Label shown after a successful copy. |
timeout | number | 2000 | Milliseconds before the button returns to its idle state. |
variant | "outline" | "ghost" | "solid" | "outline" | Visual style. |
size | "sm" | "md" | "md" | Button size. Small buttons keep a 40px hit area. |
onCopied | (value: string) => void | – | Called with the copied text after a successful copy. |
Also accepts every native <button> attribute, including ref and className.
- Falls back to document.execCommand("copy") where the async Clipboard API is unavailable, such as plain-HTTP origins.
Accessibility
- Renders a native button, so it is reachable with Tab and activates with Enter or Space.
- Icon-only buttons get an accessible name of "Copy to clipboard" unless you pass aria-label.
- A polite status region announces "Copied to clipboard" after each successful copy.
- Both labels share one grid cell, so the button never changes size or shifts nearby content.
- With reduced motion enabled, the icon and label swap with a plain cross-fade.