'use client'; import React, { useState, useRef } from 'react'; import * as Prism from 'prismjs'; import 'prismjs/components/prism-python'; import 'prismjs/components/prism-typescript'; import 'prismjs/components/prism-javascript'; import 'prismjs/components/prism-jsx'; import 'prismjs/components/prism-tsx'; import 'prismjs/components/prism-docker'; import 'prismjs/components/prism-yaml'; import 'prismjs/components/prism-json'; import 'prismjs/components/prism-markup'; import 'prismjs/components/prism-css'; import 'prismjs/components/prism-sql'; import 'prismjs/components/prism-bash'; import 'prismjs/components/prism-markdown'; interface FileExampleProps { filename: string; content: string; language: string; description?: string; tags?: string[]; id: string; } const prismLanguageMap: Record = { py: 'python', ts: 'typescript', tsx: 'tsx', js: 'javascript', jsx: 'jsx', dockerfile: 'docker', docker: 'docker', yml: 'yaml', yaml: 'yaml', json: 'json', html: 'markup', css: 'css', sql: 'sql', sh: 'bash', bash: 'bash', md: 'markdown', }; export const FileExample: React.FC = ({ filename, content, language, id }) => { const [isExpanded, setIsExpanded] = useState(false); const [isCopied, setIsCopied] = useState(false); const contentRef = useRef(null); const safeId = String(id).replace(/[^a-zA-Z0-9_-]/g, ''); const headerId = `file-example-header-${safeId}`; const contentId = `file-example-content-${safeId}`; const fileExtension = filename.split('.').pop() || language; const prismLanguage = prismLanguageMap[fileExtension] || 'markup'; const highlightedCode = Prism.highlight( content, Prism.languages[prismLanguage] || Prism.languages.markup, prismLanguage, ); const toggleExpand = () => { setIsExpanded(!isExpanded); if (!isExpanded) { setTimeout(() => { contentRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); }, 120); } }; const handleCopy = async (e: React.MouseEvent) => { e.stopPropagation(); try { await navigator.clipboard.writeText(content); setIsCopied(true); setTimeout(() => setIsCopied(false), 900); } catch (err) { console.error('Failed to copy:', err); } }; const handleDownload = (e: React.MouseEvent) => { e.stopPropagation(); const blob = new Blob([content], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }; return (
{ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleExpand(); } }} aria-expanded={isExpanded} aria-controls={contentId} id={headerId} >
{filename}
          
        
); };