'use client' import { useTranslations } from "next-intl"; import React from "react"; import { toast } from "sonner"; import copyToClipboard from '@/lib/clipboard'; function extractText(node: React.ReactNode): string { if (typeof node === "string") return node; if (Array.isArray(node)) return node.map(extractText).join(""); if ( React.isValidElement(node) && node.props && typeof node.props === "object" && "children" in node.props ) { return extractText(node.props.children as React.ReactNode); } return ""; } export default function CodeBlock(props: React.ComponentPropsWithoutRef<"pre">) { const t = useTranslations('CodeBlock'); let className: string | undefined = undefined; const child = props.children as React.ReactElement<{ className?: string; children?: React.ReactNode }> | undefined; if ( child && typeof child === "object" && "props" in child && child.props.className ) { className = child.props.className as string | undefined; } let language = ""; if (className) { const match = className.match(/language-(\w+)/); if (match) { language = match[1]; } } let codeContent = ""; if ( child && typeof child === "object" && "props" in child ) { codeContent = extractText(child.props.children); } async function handleCopy() { try { const ok = await copyToClipboard(codeContent); if (ok) toast.success(t("copy_success")); else toast.error(t("copy_failed") || 'Copy failed'); } catch (err) { console.error('copy failed', err); toast.error(t("copy_failed") || 'Copy failed'); } } return (
{language && ( {language} )}
    
); }