import React from 'react'
// 轻量 Markdown 排版:给人看的「AI 守则」「热榜原文」等,同一份文字 AI 也直接读。
function inline(s: string, key = ''): React.ReactNode[] {
const out: React.ReactNode[] = []
const re = /(\*\*([^*]+)\*\*|`([^`]+)`|\[([^\]]+)\]\(([^)\s]+)\))/g
let last = 0, m: RegExpExecArray | null, i = 0
while ((m = re.exec(s))) {
if (m.index > last) out.push(s.slice(last, m.index))
if (m[2]) out.push({m[2]})
else if (m[3]) out.push({m[3]})
else if (m[4]) out.push({m[4]})
last = m.index + m[0].length
}
if (last < s.length) out.push(s.slice(last))
return out
}
type Li = { text: string; kids: Li[] }
function parseList(lines: string[]): { ordered: boolean; items: Li[] } {
const ordered = /^\s*\d+[.、]\s/.test(lines[0])
const items: Li[] = []
for (const l of lines) {
const ind = l.match(/^\s*/)![0].length
const text = l.replace(/^\s*(?:[-*]|\d+[.、])\s+/, '')
if (ind >= 2 && items.length) items[items.length - 1].kids.push({ text, kids: [] })
else items.push({ text, kids: [] })
}
return { ordered, items }
}
export function Md({ text, className }: { text: string; className?: string }) {
const lines = String(text || '').replace(/\r/g, '').split('\n')
const blocks: React.ReactNode[] = []
let i = 0, k = 0
const isList = (l: string) => /^\s*(?:[-*]|\d+[.、])\s+/.test(l)
while (i < lines.length) {
const l = lines[i]
if (!l.trim()) { i++; continue }
const h = l.match(/^(#{1,4})\s+(.*)$/)
if (h) { const T = (`h${Math.min(4, h[1].length + 1)}`) as any; blocks.push(
{buf.join('\n')}); continue
}
if (l.startsWith('>')) {
const buf: string[] = []
while (i < lines.length && lines[i].startsWith('>')) buf.push(lines[i++].replace(/^>\s?/, ''))
blocks.push({inline(buf.join(' '))}); continue } if (l.trim().startsWith('|')) { const rows: string[][] = [] while (i < lines.length && lines[i].trim().startsWith('|')) { const cells = lines[i].trim().replace(/^\||\|$/g, '').split('|').map(c => c.trim()) if (!cells.every(c => /^:?-{2,}:?$/.test(c))) rows.push(cells) i++ } const [head, ...body] = rows blocks.push(
| {inline(c)} | )}
|---|
| {inline(c)} | )}
{buf.map((b, j) =>
}{inline(b, `${j}-`)}