Copy button
FreeA button that copies a link, an ID or a snippet and says so: the icon swaps to a check that draws itself and the label to Copied, at a width that never moves.
npx shadcn@latest add @pixilui/copy-buttonPreview
The copy icon swaps to a check that draws itself; the width holds.
Show
import type { ReactNode } from "react";
import { IconCopyCheck } from "@/components/pixilui/icons/copy-check";
import { IconCopyLink } from "@/components/pixilui/icons/copy-link";
import { CopyButton } from "@/components/pixilui/copy-button";
// The item page's one row, Show: Styles, More styles, Icons and sizes, States (the button pages' layout).
export const knobs = {
show: ["styles", "more", "sizes", "states"],
} as const;
const Row = ({ children }: { children: ReactNode }) => <div className="flex flex-wrap items-center justify-center gap-2.5">{children}</div>;
const Cap = ({ children }: { children: ReactNode }) => <p className="-mt-2 text-center text-caption text-muted">{children}</p>;
function Shown({ show }: { show: string }) {
if (show === "more")
return (
<>
<Row>
<CopyButton variant="tinted" icon={<IconCopyLink />} label="Copy share link" value="https://northwind.co/share/q3-renewals" />
<CopyButton variant="soft" icon={<IconCopyCheck />} label="Copy prompt" value="Summarize ticket 2291 in three lines." />
</Row>
<Cap>Tinted, Soft</Cap>
</>
);
if (show === "sizes")
return (
<>
<Row>
<span className="flex items-center gap-1.5 text-body text-secondary">
<span className="font-mono text-mono">run_8f2c41</span>
<CopyButton variant="secondary-2" size="sm" aria-label="Copy run ID" icon={<IconCopyCheck />} value="run_8f2c41" />
</span>
<span className="flex items-center gap-1.5 text-body text-secondary">
<span className="font-mono text-mono">pk_live_51Hq</span>
<CopyButton variant="secondary-2" size="sm" aria-label="Copy key prefix" icon={<IconCopyCheck />} value="pk_live_51Hq" />
</span>
</Row>
<Cap>Icon-only, beside the value it copies</Cap>
<Row>
{(["sm", "md", "lg"] as const).map((size) => (
<CopyButton key={size} size={size} icon={<IconCopyLink />} label="Copy link" value="https://northwind.co/share/q3-renewals" />
))}
</Row>
<Cap>28, 32 (default), 36</Cap>
</>
);
if (show === "states")
return (
<>
<Row>
<CopyButton icon={<IconCopyLink />} label="Copy link" value="https://northwind.co/share/q3-renewals" resetAfter={3000} />
<CopyButton icon={<IconCopyCheck />} label="Copy API key" value="sk_live_redacted" aria-disabled="true" />
</Row>
<Cap>Press Copy link: the check draws and Copied holds for 3 seconds. Disabled stays focusable.</Cap>
</>
);
return (
<>
<Row>
<CopyButton size="lg" icon={<IconCopyLink />} label="Copy link" value="https://northwind.co/share/q3-renewals" />
<CopyButton variant="primary" size="lg" icon={<IconCopyLink />} label="Copy invite link" value="https://northwind.co/join/7Kq2" />
<CopyButton variant="secondary-2" size="lg" icon={<IconCopyCheck />} label="Copy" value="Refunds over $500 need a second approval." />
</Row>
<Cap>Secondary (the glass), Primary, Secondary 2</Cap>
</>
);
}
export default function CopyButtonDemo({ show = "styles" }: KnobValues<typeof knobs>) {
return (
<div key={show} className="grid justify-items-center gap-4.5" aria-live="polite">
<Shown show={show} />
</div>
);
}When to use
Use it when
- Copying something a person pastes elsewhere: a share link, an API key's prefix, a run ID, a code block.
- Icon-only beside a value in a table row or under a message, with an aria-label.
Use something else when
- Copying a whole message among other message actions: use Message actions, which holds this copy with regenerate and feedback.
- Secrets shown once: pair the copy with a clear warning on the page, not a toast.
Installation
Terminal
npx shadcn@latest add @pixilui/copy-buttonAdds copy-button.tsx with button.tsx, and installs clsx and tailwind-merge. First PixilUI item in this app? Add the registry once, as in Installation.
components/pixilui/copy-button.tsx
"use client";
import { forwardRef, useEffect, useRef, useState, type MouseEvent, type ReactNode } from "react";
import { Button, type ButtonProps, type ButtonSize, type ButtonVariant } from "./button";
/*
Copy, then Copied. The button's own copy face does the motion (button.tsx, foundation.css
section 7): the icon swaps deep to a check that draws itself, the word swaps on the same curve,
and `reserve` holds the wider label so the width never moves.
*/
const RESET_MS = 1600;
export type CopyButtonProps = Omit<ButtonProps, "children" | "icon" | "copied" | "reserve" | "onCopy" | "aria-label" | "value"> & {
/** What lands on the clipboard: a string, or a function that returns one when pressed. */
value: string | (() => string | Promise<string>);
/** The copy icon (Lucide Copy, say). The check that replaces it is the button's own. */
icon: ReactNode;
/** The label at rest. Leave it out for an icon-only button, and pass aria-label. */
label?: string;
/** The label while the copy shows. */
copiedLabel?: string;
/** Accessible name for the icon-only form ("Copy link"). Required when there is no label. */
"aria-label"?: string;
/** Visual weight, as on Button. secondary (the glass) is the default; secondary-2 suits a row of message actions. */
variant?: ButtonVariant;
/** Height, as on Button: xs 24, sm 28, md 32 (default), lg 36, xl 44. */
size?: ButtonSize;
/** How long Copied shows before the button returns, in ms. */
resetAfter?: number;
/** Runs after the value is on the clipboard, with what was copied. */
onCopied?: (value: string) => void;
/** Runs when the clipboard refuses (no permission, an insecure page). The button stays at rest. */
onCopyError?: (error: Error) => void;
};
/** A button that copies a value and says so: the icon swaps to a drawn check and the label to Copied, at a width that never moves. */
export const CopyButton = forwardRef<HTMLButtonElement, CopyButtonProps>(function CopyButton(
{ value, icon, label, copiedLabel = "Copied", resetAfter = RESET_MS, onCopied, onCopyError, onClick, ...rest },
ref,
) {
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
const copy = async (event: MouseEvent<HTMLButtonElement>) => {
onClick?.(event);
if (event.defaultPrevented) return;
try {
const text = typeof value === "function" ? await value() : value;
await navigator.clipboard.writeText(text);
setCopied(true);
clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(false), resetAfter);
onCopied?.(text);
} catch (error) {
onCopyError?.(error instanceof Error ? error : new Error(String(error)));
}
};
const reserve = label ? [{ label, icon: true }, { label: copiedLabel, icon: true }] : undefined;
const common = { ...rest, ref, icon, copied, reserve, "data-status": copied ? "copied" : "idle", onClick: (event: MouseEvent<HTMLButtonElement>) => void copy(event) };
if (label) return <Button {...common}>{copied ? copiedLabel : label}</Button>;
return <Button {...common} aria-label={rest["aria-label"] ?? "Copy"} />;
});
It uses Button: add it the same way. Then npm i clsx tailwind-merge, and add the foundation once per app, as in Installation.
Usage
example.tsx
import { CopyButton } from "@/components/pixilui/copy-button";
<CopyButton
value={value}
icon={icon}
onCopied={onCopied}
onCopyError={onCopyError}
/>Never wider than its container. Icon-only sizes keep a 40px hit area on desktop and 44 on touch.
API reference
PropTypeDefault
valueRequiredstring | (() => string | Promise<string>)–What lands on the clipboard: a string, or a function that returns one when pressed.iconRequiredReactNode–The copy icon (Lucide Copy, say). The check that replaces it is the button's own.variantButtonVariant–Visual weight, as on Button. secondary (the glass) is the default; secondary-2 suits a row of message actions.sizeButtonSize–Height, as on Button: xs 24, sm 28, md 32 (default), lg 36, xl 44.labelstring–The label at rest. Leave it out for an icon-only button, and pass aria-label.copiedLabelstring"Copied"The label while the copy shows.resetAfternumberRESET_MSHow long Copied shows before the button returns, in ms.onCopied(value: string) => void–Runs after the value is on the clipboard, with what was copied.onCopyError(error: Error) => void–Runs when the clipboard refuses (no permission, an insecure page). The button stays at rest.aria-labelstring–Accessible name for the icon-only form ("Copy link"). Required when there is no label.Keyboard
TabMoves focus to the button.
EnterCopies the value; focus stays on the button while Copied shows.
SpaceCopies the value on release.
Accessibility
- A native button. The label changes to Copied, so screen readers hear the result when they read the button again.
- Icon-only needs aria-label ("Copy run ID"); it defaults to Copy.
- The check is aria-hidden; the swapped label carries the meaning.
- data-status is copied or idle, for styling and tests.
Motion
- The copy icon swaps deep (scale .3 with a 3px blur) to a check that draws itself in 260ms.
- The word swaps on the same curve; reserve holds the wider of Copy link and Copied, so the width never moves.
- Copied returns to rest after 1600ms (resetAfter).
- Reduced motion: the icon and the word change at once, with no draw.