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(
| {renderInline(h)} | )}
|---|
| {renderInline(c)} | )}
{renderInline(b)}
)}{renderInline(line)}
) i++ } return out }, [text]) return