"use client"; import * as React from "react"; import { cn, isSafeUrl } from "./lib/utils"; export interface MarkdownPreviewProps extends React.HTMLAttributes { source?: string; } /** Pure markdown to JSX renderer: headings, lists, inline code, links, bold. */ export function MarkdownPreview({ source = "", className, ...props }: MarkdownPreviewProps) { return (
{render(source)}
); } function inline(text: string): React.ReactNode { const parts = text.split(/(\*\*[^*]+\*\*|`[^`]+`|\[[^\]]+\]\([^)]+\))/g); return parts.map((part, i) => { if (part.startsWith("**") && part.endsWith("**")) return {part.slice(2, -2)}; if (part.startsWith("`") && part.endsWith("`")) return {part.slice(1, -1)}; const link = part.match(/\[([^\]]+)\]\(([^)]+)\)/); if (link) { if (!isSafeUrl(link[2])) return {link[1]}; return {link[1]}; } return part; }); } function render(src: string): React.ReactNode { const lines = src.split("\n"); const out: React.ReactNode[] = []; let list: string[] = []; let inCode = false; let codeLines: string[] = []; const flushList = () => { if (list.length) { out.push(); list = []; } }; for (const line of lines) { if (line.trim().startsWith("```")) { if (inCode) { out.push(
{codeLines.join("\n")}
); codeLines = []; inCode = false; } else { inCode = true; flushList(); } continue; } if (inCode) { codeLines.push(line); continue; } const h = line.match(/^(#{1,4})\s+(.*)/); if (h) { flushList(); const level = h[1].length; const Tag = (["h1", "h2", "h3", "h4"] as const)[level - 1] ?? "h4"; const sz = ["text-xl font-bold", "text-lg font-bold", "text-base font-semibold", "text-sm font-semibold"][level - 1]; out.push({inline(h[2])}); continue; } if (/^[-*]\s+/.test(line)) { list.push(line.replace(/^[-*]\s+/, "")); continue; } flushList(); if (line.trim() === "") { out.push(
); continue; } out.push(

{inline(line)}

); } flushList(); return out; }