Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | 105x 105x 123x 123x 123x 123x 1x 1x 1x 1x 123x | import { Check, Copy } from "lucide-react";
import React, { useCallback, useEffect, useRef, useState } from "react";
/**
* Copy-to-clipboard control with a transient "Copied" acknowledgement.
*
* Nine pages hand-rolled this. Two shapes were in use and both are kept:
* `button`, a bordered control that sits in a card header, and `bare`, an
* icon-only affordance that sits inline next to the value it copies.
*
* Every copy also set a `setTimeout` it never cleared, so unmounting inside
* the acknowledgement window queued a state update on a dead component. The
* timer is tracked and cleared here, so no call site has to think about it.
*/
export interface CopyButtonProps {
value: string;
/** Text beside the icon. Omit for an icon-only control. */
label?: string;
/** Replaces `label` while the acknowledgement shows. */
copiedLabel?: string;
variant?: "button" | "bare";
/** Native tooltip, e.g. "Copy model ID". */
title?: string;
/** How long the acknowledgement stays up, in ms. */
duration?: number;
className?: string;
}
const VARIANTS: Record<NonNullable<CopyButtonProps["variant"]>, string> = {
button:
"flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors",
bare: "flex items-center gap-1 text-xs text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors",
};
export const CopyButton: React.FC<CopyButtonProps> = ({
value,
label,
copiedLabel = "Copied",
variant = "button",
title,
duration = 2000,
className = "",
}) => {
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => () => clearTimeout(timer.current), []);
const copy = useCallback(() => {
void navigator.clipboard.writeText(value).then(() => {
setCopied(true);
clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(false), duration);
});
}, [value, duration]);
return (
<button
type="button"
onClick={copy}
title={title}
aria-label={title ?? label ?? "Copy"}
className={`${VARIANTS[variant]} ${className}`.trim()}
>
{copied ? (
<Check className="size-3 text-emerald-500" />
) : (
<Copy className="size-3" />
)}
{label !== undefined && (copied ? copiedLabel : label)}
</button>
);
};
export default CopyButton;
|