"use client";
import { useState, useCallback } from "react";
const CopyIcon = () => (
);
const CheckIcon = () => (
);
type CopyableProps = {
text: string;
children: React.ReactNode;
className?: string;
style?: React.CSSProperties;
};
export function Copyable({ text, children, className, style }: CopyableProps) {
const [copied, setCopied] = useState(false);
const handleClick = useCallback(async () => {
const fallbackCopy = () => {
const ta = document.createElement("textarea");
ta.value = text;
ta.style.position = "fixed";
ta.style.left = "-9999px";
ta.style.top = "0";
ta.setAttribute("readonly", "");
document.body.appendChild(ta);
ta.select();
ta.setSelectionRange(0, text.length);
try {
document.execCommand("copy");
} finally {
document.body.removeChild(ta);
}
};
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
} else {
fallbackCopy();
}
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
try {
fallbackCopy();
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
/* ignore */
}
}
}, [text]);
return (
e.key === "Enter" && handleClick()}
className={className}
style={{
cursor: "pointer",
userSelect: "none",
display: "inline-flex",
alignItems: "center",
gap: "0.35rem",
...style,
}}
title={copied ? "已复制" : "点击复制"}
>
{children}
{copied ? : }
);
}