import { Fragment, type ReactNode } from "react"; type MessageContentProps = { content: string; }; function renderInline(text: string, keyPrefix: string): ReactNode[] { const tokens = text.split(/(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g); return tokens.map((token, index) => { const key = `${keyPrefix}-${index}`; if (token.startsWith("`") && token.endsWith("`")) { return {token.slice(1, -1)}; } if (token.startsWith("**") && token.endsWith("**")) { return {token.slice(2, -2)}; } const link = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/); if (link) { return ( {link[1]} ); } return {token}; }); } export function MessageContent({ content }: MessageContentProps) { const lines = content.replaceAll("\r\n", "\n").split("\n"); const blocks: ReactNode[] = []; let codeLines: string[] | null = null; let codeLanguage = ""; let paragraph: string[] = []; let list: string[] = []; const flushParagraph = () => { if (!paragraph.length) return; blocks.push(

{renderInline(paragraph.join(" "), `paragraph-${blocks.length}`)}

, ); paragraph = []; }; const flushList = () => { if (!list.length) return; blocks.push( , ); list = []; }; lines.forEach((line, index) => { if (line.trimStart().startsWith("```") && codeLines === null) { flushParagraph(); flushList(); codeLines = []; codeLanguage = line.trim().slice(3).trim(); return; } if (line.trimStart().startsWith("```") && codeLines !== null) { blocks.push(
          {codeLines.join("\n")}
        
, ); codeLines = null; codeLanguage = ""; return; } if (codeLines !== null) { codeLines.push(line); return; } if (!line.trim()) { flushParagraph(); flushList(); return; } const heading = line.match(/^(#{1,3})\s+(.+)$/); if (heading) { flushParagraph(); flushList(); const level = heading[1].length; const Heading = `h${level}` as "h1" | "h2" | "h3"; blocks.push( {renderInline(heading[2], `heading-${index}`)} , ); return; } const item = line.match(/^\s*[-*]\s+(.+)$/); if (item) { flushParagraph(); list.push(item[1]); return; } flushList(); paragraph.push(line.trim()); }); const finalCodeText = (codeLines as string[] | null)?.join("\n"); if (finalCodeText !== undefined) { blocks.push(
        {finalCodeText}
      
, ); } flushParagraph(); flushList(); return
{blocks}
; }