import React, { useState, useEffect, useRef } from 'react'; import ReactMarkdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; import remarkAlert from 'remark-github-blockquote-alert'; import rehypeRaw from 'rehype-raw'; import { Copy, Check } from 'lucide-react'; import { subscribeToStyleConfig } from '../services/codeStyleService'; import { CopyButton } from './CopyButton'; import { CustomBlockquote } from './CustomBlockquote'; import 'github-markdown-css/github-markdown-dark.css'; import 'remark-github-blockquote-alert/alert.css'; interface MarkdownRendererProps { content: string; onBlockDoubleClick?: (type: 'code' | 'quote', index: number) => void; } export const MarkdownRenderer: React.FC = ({ content, onBlockDoubleClick }) => { const [showCopyButton, setShowCopyButton] = useState(false); const [copied, setCopied] = useState(false); const containerRef = useRef(null); useEffect(() => { const unsubscribe = subscribeToStyleConfig((config) => { setShowCopyButton(config.showCopyButton); }); return () => unsubscribe(); }, []); const handleCopy = () => { navigator.clipboard.writeText(content); setCopied(true); setTimeout(() => setCopied(false), 2000); }; const handleBlockDoubleClick = (e: React.MouseEvent, type: 'code' | 'quote') => { if (!onBlockDoubleClick || !containerRef.current) return; e.stopPropagation(); // Prevent bubbling const wrapper = e.currentTarget as HTMLElement; const selector = type === 'quote' ? 'blockquote' : 'pre'; const block = wrapper.querySelector(selector); if (!block) return; const allBlocks = Array.from(containerRef.current.querySelectorAll(selector)); const index = allBlocks.indexOf(block as any); if (index !== -1) { onBlockDoubleClick(type, index); } }; return (
{showCopyButton && ( )} { const isCenter = align === 'center'; return (
{children}
); }, blockquote: ({ children, ...props }) => (
handleBlockDoubleClick(e, 'quote')} > {children}
), code: ({ inline, children, className, style, ...props }: any) => { const codeString = String(children).replace(/\n$/, ''); if (inline) { return ( {children} ); } return ( {codeString.split('\n').map((line, i) => { const highlighted = line .replace(/(\b(?:const|let|var|function|return|if|else|for|while|class|import|export|from|default|async|await|try|catch|throw|new)\b)/g, '$1') .replace(/(['"`].*?['"`])/g, '$1') .replace(/(\b\d+\b)/g, '$1') .replace(/(\/\/.*$)/g, '$1') .replace(/([{}()[\];,.])/g, '$1'); return (
); })} ); }, pre: ({ children, ...props }: any) => { // Extract text content from the code block for the copy button let codeText = ''; const childProps = (children as any)?.props; if (React.isValidElement(children) && childProps && childProps.children) { codeText = String(childProps.children); } const showCopy = props['data-show-copy'] === 'true' || (props['data-show-copy'] === undefined && showCopyButton); return (
handleBlockDoubleClick(e, 'code')} >
                  {children}
                
{showCopy && }
); }, }} > {content}
); };