diff --git a/src/components/mdx/code-block-with-copy.tsx b/src/components/mdx/code-block-with-copy.tsx new file mode 100644 index 0000000..5f23281 --- /dev/null +++ b/src/components/mdx/code-block-with-copy.tsx @@ -0,0 +1,73 @@ +"use client"; + +import { useRef, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { CheckIcon, CopyIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; + +interface CodeBlockWithCopyProps { + children: React.ReactNode; +} + +export function CodeBlockWithCopy({ + children, + ...props +}: CodeBlockWithCopyProps) { + const preRef = useRef(null); + const [copied, setCopied] = useState(false); + const [hovered, setHovered] = useState(false); + + const handleCopy = async () => { + const code = preRef.current?.textContent; + if (code) { + try { + await navigator.clipboard.writeText(code); + setCopied(true); + setTimeout(() => setCopied(false), 1500); + } catch (err) { + console.error("Failed to copy text: ", err); + } + } + }; + + return ( +
setHovered(true)} + onMouseLeave={() => setHovered(false)} + > + +
+        {children}
+      
+
+ ); +}