import React, { useMemo } from 'react' // 轻量 Markdown 渲染:支持标题、加粗、列表、表格、引用、分隔线、行内代码 function renderInline(text: string): React.ReactNode[] { const nodes: React.ReactNode[] = [] let rest = text let key = 0 while (rest) { const m = rest.match(/\*\*([^*]+)\*\*|`([^`]+)`/) if (!m) { nodes.push(rest); break } const idx = m.index ?? 0 if (idx > 0) nodes.push(rest.slice(0, idx)) if (m[1] !== undefined) nodes.push({m[1]}) else nodes.push({m[2]}) rest = rest.slice(idx + m[0].length) } return nodes } export function Markdown({ text, streaming }: { text: string; streaming?: boolean }) { const blocks = useMemo(() => { const lines = text.split('\n') const out: React.ReactNode[] = [] let i = 0 let key = 0 while (i < lines.length) { const line = lines[i] // 表格 if (line.trim().startsWith('|') && i + 1 < lines.length && /^\|[\s:|-]+\|/.test(lines[i + 1].trim())) { const header = line.trim().slice(1, -1).split('|').map(s => s.trim()) const rows: string[][] = [] i += 2 while (i < lines.length && lines[i].trim().startsWith('|')) { rows.push(lines[i].trim().slice(1, -1).split('|').map(s => s.trim())) i++ } out.push( {header.map((h, j) => )}{rows.map((r, ri) => {r.map((c, ci) => )})}
{renderInline(h)}
{renderInline(c)}
) continue } // 无序列表 if (/^\s*-\s+/.test(line)) { const items: string[] = [] while (i < lines.length && /^\s*-\s+/.test(lines[i])) { items.push(lines[i].replace(/^\s*-\s+/, '')) i++ } out.push() continue } // 有序列表 if (/^\s*\d+\.\s+/.test(line)) { const items: string[] = [] while (i < lines.length && /^\s*\d+\.\s+/.test(lines[i])) { items.push(lines[i].replace(/^\s*\d+\.\s+/, '')) i++ } out.push(
    {items.map((it, j) =>
  1. {renderInline(it)}
  2. )}
) continue } // 标题 const h3 = line.match(/^###\s+(.*)/) if (h3) { out.push(

{renderInline(h3[1])}

); i++; continue } const h4 = line.match(/^####\s+(.*)/) if (h4) { out.push(

{renderInline(h4[1])}

); i++; continue } // 引用(用作提示块) if (/^>\s?/.test(line)) { const buf: string[] = [] while (i < lines.length && /^>\s?/.test(lines[i])) { buf.push(lines[i].replace(/^>\s?/, '')) i++ } out.push(
{buf.map((b, j) =>

{renderInline(b)}

)}
) continue } // 分隔线 if (/^---+$/.test(line.trim())) { out.push(
); i++; continue } // 空行 if (!line.trim()) { i++; continue } // 普通段落 out.push(

{renderInline(line)}

) i++ } return out }, [text]) return
{blocks}
}