components/linyi/markdown-renderer.tsx
class-variance-authoritylucide-react
"use client"; import * as React from "react";import { cva, type VariantProps } from "class-variance-authority";import { ExternalLink } from "lucide-react";import { cn } from "@/lib/cn";import { CodeBlock } from "@/components/linyi/code-block"; export const markdownRendererVariants = cva( "w-full text-fg break-words [overflow-wrap:anywhere]", { variants: { size: { sm: "text-xs leading-relaxed space-y-2.5", md: "text-[13px] leading-[1.7] space-y-3", }, }, defaultVariants: { size: "md", }, }); type MarkdownBlock = | { type: "heading"; level: 1 | 2 | 3 | 4; text: string } | { type: "paragraph"; text: string } | { type: "code"; language: string; filename?: string; code: string; closed: boolean } | { type: "quote"; lines: string[] } | { type: "list"; ordered: boolean; items: { text: string; checked?: boolean }[] } | { type: "table"; headers: string[]; alignments: ("left" | "center" | "right")[]; rows: string[][] } | { type: "hr" }; function sanitizeHref(raw: string): string | null { const trimmed = raw.trim(); if (!trimmed) return null; if (trimmed.startsWith("#") || trimmed.startsWith("/")) return trimmed; try { const parsed = new URL(trimmed); if ( parsed.protocol === "https:" || parsed.protocol === "http:" || parsed.protocol === "mailto:" ) { return parsed.href; } return null; } catch { return null; }} function splitTableRow(line: string): string[] { const stripped = line.trim().replace(/^\|/, "").replace(/\|$/, ""); return stripped.split("|").map((cell) => cell.trim());} function isTableSeparator(line: string): boolean { const trimmed = line.trim(); if (!trimmed.includes("|")) return false; const cells = splitTableRow(trimmed); return cells.length > 0 && cells.every((c) => /^:?-{3,}:?$/.test(c));} function parseTableAlignments(line: string): ("left" | "center" | "right")[] { return splitTableRow(line).map((cell) => { const starts = cell.startsWith(":"); const ends = cell.endsWith(":"); if (starts && ends) return "center"; if (ends) return "right"; return "left"; });} function parseMarkdownBlocks(source: string): MarkdownBlock[] { const lines = source.replace(/\r\n?/g, "\n").split("\n"); const blocks: MarkdownBlock[] = []; let i = 0; while (i < lines.length) { const line = lines[i]; const trimmed = line.trim(); if (!trimmed) { i += 1; continue; } // Fenced code block (tolerates unclosed fence during streaming) const fenceMatch = trimmed.match(/^```([^\s`]*)(?:\s+(.*))?$/); if (fenceMatch) { const language = fenceMatch[1] || "text"; const filename = fenceMatch[2]?.trim() || undefined; const codeLines: string[] = []; let closed = false; i += 1; while (i < lines.length) { if (/^```\s*$/.test(lines[i].trim())) { closed = true; i += 1; break; } codeLines.push(lines[i]); i += 1; } blocks.push({ type: "code", language, filename, code: codeLines.join("\n"), closed, }); continue; } // Horizontal rule if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { blocks.push({ type: "hr" }); i += 1; continue; } // Heading const headingMatch = trimmed.match(/^(#{1,4})\s+(.+)$/); if (headingMatch) { blocks.push({ type: "heading", level: headingMatch[1].length as 1 | 2 | 3 | 4, text: headingMatch[2].trim(), }); i += 1; continue; } // GFM Table if ( trimmed.includes("|") && i + 1 < lines.length && isTableSeparator(lines[i + 1]) ) { const headers = splitTableRow(line); const alignments = parseTableAlignments(lines[i + 1]); i += 2; const rows: string[][] = []; while (i < lines.length && lines[i].trim().includes("|")) { rows.push(splitTableRow(lines[i])); i += 1; } blocks.push({ type: "table", headers, alignments, rows }); continue; } // Blockquote if (trimmed.startsWith(">")) { const quoteLines: string[] = []; while (i < lines.length && lines[i].trim().startsWith(">")) { quoteLines.push(lines[i].trim().replace(/^>\s?/, "")); i += 1; } blocks.push({ type: "quote", lines: quoteLines }); continue; } // Unordered or task list if (/^[-*+]\s+/.test(trimmed)) { const items: { text: string; checked?: boolean }[] = []; while (i < lines.length && /^\s*[-*+]\s+/.test(lines[i])) { const raw = lines[i].trim().replace(/^[-*+]\s+/, ""); const taskMatch = raw.match(/^\[([ xX])\]\s+(.*)$/); if (taskMatch) { items.push({ checked: taskMatch[1].toLowerCase() === "x", text: taskMatch[2], }); } else { items.push({ text: raw }); } i += 1; } blocks.push({ type: "list", ordered: false, items }); continue; } // Ordered list if (/^\d+\.\s+/.test(trimmed)) { const items: { text: string }[] = []; while (i < lines.length && /^\s*\d+\.\s+/.test(lines[i])) { items.push({ text: lines[i].trim().replace(/^\d+\.\s+/, "") }); i += 1; } blocks.push({ type: "list", ordered: true, items }); continue; } // Paragraph (collect consecutive plain lines) const paraLines: string[] = []; while (i < lines.length) { const cur = lines[i].trim(); if ( !cur || cur.startsWith("```") || /^#{1,4}\s+/.test(cur) || cur.startsWith(">") || /^[-*+]\s+/.test(cur) || /^\d+\.\s+/.test(cur) || /^(?:-{3,}|\*{3,}|_{3,})$/.test(cur) || (cur.includes("|") && i + 1 < lines.length && isTableSeparator(lines[i + 1])) ) { break; } paraLines.push(cur); i += 1; } blocks.push({ type: "paragraph", text: paraLines.join(" ") }); } return blocks;} const INLINE_TOKEN_RE = /(`[^`\n]+`|\*\*[^*\n]+\*\*|~~[^~\n]+~~|\*[^*\n]+\*|\[[^\]\n]+\]\([^)\n]+\))/g; function renderInline(text: string): React.ReactNode[] { const nodes: React.ReactNode[] = []; let lastIdx = 0; let match: RegExpExecArray | null; let tokenKey = 0; INLINE_TOKEN_RE.lastIndex = 0; while ((match = INLINE_TOKEN_RE.exec(text)) !== null) { if (match.index > lastIdx) { nodes.push(text.slice(lastIdx, match.index)); } const token = match[0]; const key = `tok-${tokenKey++}`; if (token.startsWith("`") && token.endsWith("`")) { nodes.push( <code key={key} className="rounded-badge border border-line bg-well px-1.5 py-0.5 font-mono-num text-[0.88em] text-fg" > {token.slice(1, -1)} </code> ); } else if (token.startsWith("**") && token.endsWith("**")) { nodes.push( <strong key={key} className="font-semibold text-fg"> {token.slice(2, -2)} </strong> ); } else if (token.startsWith("~~") && token.endsWith("~~")) { nodes.push( <del key={key} className="text-fg-muted line-through"> {token.slice(2, -2)} </del> ); } else if (token.startsWith("*") && token.endsWith("*")) { nodes.push( <em key={key} className="italic text-fg-secondary"> {token.slice(1, -1)} </em> ); } else if (token.startsWith("[")) { const linkMatch = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/); if (linkMatch) { const safeUrl = sanitizeHref(linkMatch[2]); if (safeUrl) { const isExternal = safeUrl.startsWith("http://") || safeUrl.startsWith("https://"); nodes.push( <a key={key} href={safeUrl} target={isExternal ? "_blank" : undefined} rel={isExternal ? "noopener noreferrer" : undefined} className="inline-flex items-baseline gap-0.5 font-medium text-accent underline decoration-accent/40 underline-offset-2 transition-colors hover:decoration-accent" > <span>{linkMatch[1]}</span> {isExternal && ( <ExternalLink className="inline h-3 w-3 self-center flex-shrink-0" aria-hidden="true" /> )} </a> ); } else { // 危险协议降级为纯文本 nodes.push(<span key={key}>{linkMatch[1]}</span>); } } } lastIdx = match.index + token.length; } if (lastIdx < text.length) { nodes.push(text.slice(lastIdx)); } return nodes;} const StreamingCaret = () => ( <span aria-hidden="true" className="ml-0.5 inline-block h-[1em] w-[2px] align-text-bottom bg-accent animate-pulse motion-reduce:animate-none" />); const MarkdownBlockView = React.memo(function MarkdownBlockView({ block, compact, isTailStreaming,}: { block: MarkdownBlock; compact: boolean; isTailStreaming: boolean;}) { switch (block.type) { case "heading": { const cls = block.level === 1 ? "text-base font-semibold tracking-tight text-fg pt-1" : block.level === 2 ? "text-sm font-semibold tracking-tight text-fg border-b border-line pb-1 pt-1" : block.level === 3 ? "text-[13px] font-semibold text-fg pt-0.5" : "text-xs font-semibold text-fg-secondary"; const Tag = `h${block.level}` as "h1" | "h2" | "h3" | "h4"; return ( <Tag className={cls}> {renderInline(block.text)} {isTailStreaming && <StreamingCaret />} </Tag> ); } case "paragraph": return ( <p className="text-fg-secondary"> {renderInline(block.text)} {isTailStreaming && <StreamingCaret />} </p> ); case "code": return ( <div className="my-1"> <CodeBlock code={block.code || " "} language={block.language} filename={block.filename} compact={compact} showLineNumbers={!compact} /> </div> ); case "quote": return ( <blockquote className="rounded-r-[10px] border-l-2 border-accent bg-surface-2/65 px-3 py-2 text-fg-secondary"> {block.lines.map((line, idx) => ( <p key={idx} className={idx > 0 ? "mt-1" : undefined}> {renderInline(line)} {isTailStreaming && idx === block.lines.length - 1 && ( <StreamingCaret /> )} </p> ))} </blockquote> ); case "list": { const ListTag = block.ordered ? "ol" : "ul"; return ( <ListTag className={cn( "space-y-1 pl-4 text-fg-secondary", block.ordered ? "list-decimal" : "list-disc" )} > {block.items.map((item, idx) => ( <li key={idx} className={ item.checked !== undefined ? "list-none -ml-4 flex items-start gap-2" : undefined } > {item.checked !== undefined && ( <span aria-hidden="true" className={cn( "mt-1 inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center rounded-[4px] border text-[9px]", item.checked ? "border-success bg-success text-accent-fg" : "border-line-strong bg-surface" )} > {item.checked ? "✓" : ""} </span> )} <span> {renderInline(item.text)} {isTailStreaming && idx === block.items.length - 1 && ( <StreamingCaret /> )} </span> </li> ))} </ListTag> ); } case "table": return ( <div className="w-full overflow-x-auto rounded-[12px] border border-line bg-surface"> <table className="w-full min-w-[320px] border-collapse text-left text-xs"> <thead> <tr className="border-b border-line bg-surface-2/65 text-fg-secondary"> {block.headers.map((header, idx) => { const align = block.alignments[idx] ?? "left"; return ( <th key={idx} scope="col" className={cn( "px-3 py-2 font-medium whitespace-nowrap", align === "right" && "text-right", align === "center" && "text-center" )} > {renderInline(header)} </th> ); })} </tr> </thead> <tbody className="divide-y divide-line"> {block.rows.map((row, rIdx) => ( <tr key={rIdx} className="hover:bg-surface-hover/50"> {block.headers.map((_, cIdx) => { const align = block.alignments[cIdx] ?? "left"; const cellText = row[cIdx] ?? ""; return ( <td key={cIdx} className={cn( "px-3 py-1.5 text-fg", align === "right" && "text-right font-mono-num", align === "center" && "text-center" )} > {renderInline(cellText)} </td> ); })} </tr> ))} </tbody> </table> </div> ); case "hr": return <hr className="my-2 border-t border-line" />; default: return null; }}); export interface MarkdownRendererProps extends Omit<React.ComponentPropsWithRef<"div">, "children">, VariantProps<typeof markdownRendererVariants> { content: string; streaming?: boolean; compact?: boolean;} export function MarkdownRenderer({ content, streaming = false, compact = false, size, className, ...props}: MarkdownRendererProps) { const blocks = React.useMemo(() => parseMarkdownBlocks(content), [content]); const resolvedSize = size ?? (compact ? "sm" : "md"); return ( <div aria-busy={streaming || undefined} className={cn(markdownRendererVariants({ size: resolvedSize }), className)} {...props} > {blocks.map((block, idx) => ( <MarkdownBlockView key={`${idx}-${block.type}`} block={block} compact={compact} isTailStreaming={streaming && idx === blocks.length - 1} /> ))} </div> );}