'use client'; import { useState, type ReactNode } from 'react'; interface CodeBlockProps { children: ReactNode; language?: string; filename?: string; showLineNumbers?: boolean; } /** * Code block component with syntax highlighting and copy button */ export function CodeBlock({ children, language, filename, showLineNumbers = false, }: CodeBlockProps) { const [copied, setCopied] = useState(false); // Extract text content from children const getCodeText = (): string => { if (typeof children === 'string') return children; if (typeof children === 'object' && children !== null) { // Handle pre > code structure from MDX const child = children as { props?: { children?: string } }; if (child.props?.children) { return typeof child.props.children === 'string' ? child.props.children : String(child.props.children); } } return String(children); }; const handleCopy = async () => { const code = getCodeText(); await navigator.clipboard.writeText(code); setCopied(true); setTimeout(() => setCopied(false), 2000); }; return (
{showLineNumbers && (
{getCodeText()
.split('\n')
.map((_, i) => (
{i + 1}
))}
)}
{children}