(props: { children: any })
| 197 | } |
| 198 | |
| 199 | export function PreCode(props: { children: any }) { |
| 200 | const ref = useRef<HTMLPreElement>(null) |
| 201 | const refText = ref.current?.innerText |
| 202 | const [mermaidCode, setMermaidCode] = useState('') |
| 203 | const [isCopied, setIsCopied] = useState(false) |
| 204 | const [isDownloading, setIsDownloading] = useState(false) |
| 205 | |
| 206 | const renderMermaid = useDebouncedCallback(() => { |
| 207 | if (!ref.current) return |
| 208 | const mermaidDom = ref.current.querySelector('code.language-mermaid') |
| 209 | if (mermaidDom) { |
| 210 | setMermaidCode((mermaidDom as HTMLElement).innerText) |
| 211 | } |
| 212 | }, 600) |
| 213 | |
| 214 | useEffect(() => { |
| 215 | setTimeout(renderMermaid, 1) |
| 216 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 217 | }, [refText]) |
| 218 | |
| 219 | const handleCopy = async () => { |
| 220 | if (ref.current) { |
| 221 | const code = ref.current.innerText |
| 222 | const success = await copyToClipboard(code) |
| 223 | if (success) { |
| 224 | setIsCopied(true) |
| 225 | setTimeout(() => setIsCopied(false), 2000) |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | const handleDownload = async () => { |
| 231 | if (ref.current) { |
| 232 | const code = ref.current.innerText |
| 233 | const codeElement = ref.current.querySelector('code') |
| 234 | const language = codeElement?.className.match(/language-(\w+)/)?.[1] || 'txt' |
| 235 | |
| 236 | // 根据语言类型确定文件扩展名 |
| 237 | const extensionMap: Record<string, string> = { |
| 238 | javascript: 'js', |
| 239 | typescript: 'ts', |
| 240 | python: 'py', |
| 241 | java: 'java', |
| 242 | cpp: 'cpp', |
| 243 | csharp: 'cs', |
| 244 | go: 'go', |
| 245 | rust: 'rs', |
| 246 | php: 'php', |
| 247 | ruby: 'rb', |
| 248 | swift: 'swift', |
| 249 | kotlin: 'kt', |
| 250 | shell: 'sh', |
| 251 | bash: 'sh', |
| 252 | powershell: 'ps1', |
| 253 | json: 'json', |
| 254 | xml: 'xml', |
| 255 | yaml: 'yaml', |
| 256 | yml: 'yml', |
nothing calls this directly
no outgoing calls
no test coverage detected