feat: copy button
This commit is contained in:
1 parent
da99471ca5
commit
ed2c47aab2
4 files changed
+91
-25
No files matched your search
@@ -0,0 +1,45 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
export function CopyButton({ code }: { code?: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleCopy = async (e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
// Falls kein expliziter Code übergeben wird, suchen wir den Text im Elternelement (Codeblock)
|
||||
let textToCopy = code;
|
||||
if (!textToCopy) {
|
||||
const parent = e.currentTarget.closest('figure');
|
||||
const codeElement = parent?.querySelector('code');
|
||||
textToCopy = codeElement?.textContent || '';
|
||||
}
|
||||
|
||||
if (textToCopy) {
|
||||
await navigator.clipboard.writeText(textToCopy);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
className="absolute top-2.5 right-3 p-1.5 rounded-md bg-zinc-900 border border-zinc-800 text-zinc-400 hover:text-white hover:bg-zinc-800 transition-colors z-20"
|
||||
aria-label="Code kopieren"
|
||||
>
|
||||
{copied ? (
|
||||
// Check Icon (Erfolg)
|
||||
<svg className="w-4 h-4 text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : (
|
||||
// Clipboard Icon
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user