import { useMemo, useCallback } from 'react' import { marked, type Tokens } from 'marked' import { CodeViewer } from '../chat/CodeViewer' type Props = { content: string } type CodeBlock = { id: string code: string language: string | undefined } const renderer = new marked.Renderer() let pendingCodeBlocks: CodeBlock[] = [] renderer.code = function ({ text, lang }: Tokens.Code) { const id = `cb-${pendingCodeBlocks.length}` pendingCodeBlocks.push({ id, code: text, language: lang || undefined }) return `
` } marked.setOptions({ breaks: true, gfm: true, }) marked.use({ renderer }) function parseMarkdown(content: string): { html: string; codeBlocks: CodeBlock[] } { pendingCodeBlocks = [] const html = marked.parse(content) as string const codeBlocks = [...pendingCodeBlocks] pendingCodeBlocks = [] return { html, codeBlocks } } export function MarkdownRenderer({ content }: Props) { const { html, codeBlocks } = useMemo(() => parseMarkdown(content), [content]) const parts = useMemo(() => { if (codeBlocks.length === 0) { return [{ type: 'html' as const, content: html }] } const result: Array<{ type: 'html'; content: string } | { type: 'code'; block: CodeBlock }> = [] let remaining = html for (const block of codeBlocks) { const marker = `` const idx = remaining.indexOf(marker) if (idx === -1) continue const before = remaining.slice(0, idx) if (before) { result.push({ type: 'html', content: before }) } result.push({ type: 'code', block }) remaining = remaining.slice(idx + marker.length) } if (remaining) { result.push({ type: 'html', content: remaining }) } return result }, [html, codeBlocks]) const handleClick = useCallback(async (event: React.MouseEvent