algospaced-dsa / algospaced-ui /src /components /MarkdownRenderer.tsx
iamfebin's picture
perf(lighthouse): optimize bundle chunking, webp asset compression, and seo metadata
b53e6f3
Raw History Blame Contribute Delete
9.94 kB
import React, { lazy, Suspense } from 'react';
import { renderInlineMarkdown } from '../utils/markdownUtils';
const KatexRenderer = lazy(() => import('./KatexRenderer'));
interface MarkdownRendererProps {
content: string;
className?: string;
}
/**
* Full Markdown + LaTeX component with retro aesthetic
*/
export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({ content, className = '' }) => {
if (!content) return null;
// Split content into distinct structural blocks (code blocks, display math blocks, and normal text segments)
const blockRegex = /(```[\s\S]*?```|\$\$[\s\S]*?\$\$|\\\[[\s\S]*?\\\])/g;
const blocks = content.split(blockRegex);
return (
<div className={`markdown-content space-y-2.5 text-ink-black text-xs leading-relaxed font-sans ${className}`}>
{blocks.map((block, blockIndex) => {
if (!block) return null;
const trimmedBlock = block.trim();
// Code Block: ```lang ... ```
if (trimmedBlock.startsWith('```') && trimmedBlock.endsWith('```') && trimmedBlock.length >= 6) {
const firstLineEnd = trimmedBlock.indexOf('\n');
const lang = firstLineEnd !== -1 ? trimmedBlock.slice(3, firstLineEnd).trim() : '';
const codeContent =
firstLineEnd !== -1
? trimmedBlock.slice(firstLineEnd + 1, -3).trimEnd()
: trimmedBlock.slice(3, -3).trim();
return (
<div
key={`code-${blockIndex}`}
className="my-3 rounded-md overflow-hidden border-[2px] border-ink-black shadow-[3px_3px_0px_0px_#1E293B] bg-[#1E293B]"
>
{lang && (
<div className="bg-slate-800 text-slate-400 px-3 py-1 text-[9px] font-arcade uppercase tracking-wider border-b border-slate-700 flex justify-between items-center">
<span>{lang}</span>
<span className="text-[8px] opacity-70">SNIPPET</span>
</div>
)}
<pre className="p-3 overflow-x-auto font-mono text-[11px] text-[#4ADE80] leading-relaxed custom-scrollbar selection:bg-[#4ADE80] selection:text-[#1E293B]">
<code>{codeContent}</code>
</pre>
</div>
);
}
// Display Math Block: $$ ... $$ or \[ ... \]
if (
(trimmedBlock.startsWith('$$') && trimmedBlock.endsWith('$$') && trimmedBlock.length >= 4) ||
(trimmedBlock.startsWith('\\[') && trimmedBlock.endsWith('\\]') && trimmedBlock.length >= 4)
) {
const math = trimmedBlock.slice(2, -2);
return (
<div
key={`math-${blockIndex}`}
className="my-3 p-3 bg-slate-50 border-2 border-ink-black rounded overflow-x-auto text-center shadow-[2px_2px_0px_0px_rgba(30,41,59,0.3)] custom-scrollbar"
>
<Suspense fallback={<span className="font-mono text-xs opacity-75">{math}</span>}>
<KatexRenderer math={math} displayMode={true} />
</Suspense>
</div>
);
}
// Normal text lines, headings, tables, lists, blockquotes
const lines = block.split('\n');
const renderedElements: React.ReactNode[] = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
const trimmed = line.trim();
const lineKey = `${blockIndex}-${i}`;
// Empty line
if (trimmed === '') {
renderedElements.push(<div key={lineKey} className="h-1" />);
i++;
continue;
}
// Table detection
if (trimmed.startsWith('|') && trimmed.endsWith('|') && i + 1 < lines.length && lines[i + 1].trim().startsWith('|')) {
const tableLines: string[] = [];
while (i < lines.length && lines[i].trim().startsWith('|') && lines[i].trim().endsWith('|')) {
tableLines.push(lines[i].trim());
i++;
}
if (tableLines.length >= 2) {
const headerCells = tableLines[0]
.slice(1, -1)
.split('|')
.map(c => c.trim());
const bodyRows = tableLines.slice(2).map(row =>
row
.slice(1, -1)
.split('|')
.map(c => c.trim())
);
renderedElements.push(
<div key={`table-${lineKey}`} className="my-3 overflow-x-auto border-2 border-ink-black rounded shadow-[2px_2px_0px_0px_#1E293B]">
<table className="w-full text-left border-collapse text-xs">
<thead>
<tr className="bg-slate-200 border-b-2 border-ink-black">
{headerCells.map((cell, idx) => (
<th key={idx} className="p-2 font-bold font-headline-md border-r last:border-r-0 border-ink-black">
{renderInlineMarkdown(cell)}
</th>
))}
</tr>
</thead>
<tbody>
{bodyRows.map((row, rowIdx) => (
<tr key={rowIdx} className={`border-b border-slate-300 last:border-b-0 ${rowIdx % 2 === 1 ? 'bg-slate-50' : 'bg-white'}`}>
{row.map((cell, cellIdx) => (
<td key={cellIdx} className="p-2 border-r last:border-r-0 border-slate-200 font-medium">
{renderInlineMarkdown(cell)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
continue;
}
}
// Headings
if (trimmed.startsWith('#### ')) {
renderedElements.push(
<h4 key={lineKey} className="text-xs font-bold text-ink-black mt-3 mb-1 font-headline-md">
{renderInlineMarkdown(trimmed.substring(5))}
</h4>
);
i++;
continue;
}
if (trimmed.startsWith('### ')) {
renderedElements.push(
<h3 key={lineKey} className="text-xs font-bold text-primary mt-4 mb-1.5 uppercase font-arcade tracking-wide flex items-center gap-1.5">
<span className="w-2 h-2 bg-primary inline-block rounded-xs" />
{renderInlineMarkdown(trimmed.substring(4))}
</h3>
);
i++;
continue;
}
if (trimmed.startsWith('## ')) {
renderedElements.push(
<h2 key={lineKey} className="text-sm font-extrabold text-ink-black mt-4 mb-2 font-headline-md border-b-2 border-ink-black pb-1">
{renderInlineMarkdown(trimmed.substring(3))}
</h2>
);
i++;
continue;
}
if (trimmed.startsWith('# ')) {
renderedElements.push(
<h1 key={lineKey} className="text-base font-black text-ink-black mt-5 mb-2 font-headline-md">
{renderInlineMarkdown(trimmed.substring(2))}
</h1>
);
i++;
continue;
}
// Horizontal rule
if (trimmed === '---' || trimmed === '***' || trimmed === '___') {
renderedElements.push(<hr key={lineKey} className="my-3 border-t-2 border-dashed border-slate-300" />);
i++;
continue;
}
// Blockquote
if (line.trim().startsWith('>')) {
renderedElements.push(
<blockquote key={lineKey} className="border-l-4 border-primary pl-3 py-1 my-2 bg-slate-50 italic text-slate-700">
{renderInlineMarkdown(line.trim().substring(1).trim())}
</blockquote>
);
i++;
continue;
}
// Unordered list item (- or *)
if (trimmed.startsWith('- ') || trimmed.startsWith('* ') || trimmed.startsWith('+ ')) {
const indentLevel = line.search(/\S/) >= 2 ? 'pl-6' : 'pl-2';
renderedElements.push(
<div key={lineKey} className={`flex items-start gap-2 my-1 ${indentLevel}`}>
<span className="text-primary font-bold mt-0.5 shrink-0">•</span>
<div className="text-ink-black leading-relaxed flex-1 font-medium">
{renderInlineMarkdown(trimmed.substring(2))}
</div>
</div>
);
i++;
continue;
}
// Ordered list item (1. 2. etc.)
const numberedMatch = trimmed.match(/^(\d+)\.\s+(.*)$/);
if (numberedMatch) {
const indentLevel = line.search(/\S/) >= 2 ? 'pl-6' : 'pl-2';
renderedElements.push(
<div key={lineKey} className={`flex items-start gap-2 my-1 ${indentLevel}`}>
<span className="text-primary font-arcade text-[9px] font-bold mt-1 shrink-0 px-1 py-0.2 bg-slate-100 border border-ink-black rounded-xs">
{numberedMatch[1]}
</span>
<div className="text-ink-black leading-relaxed flex-1 font-medium">
{renderInlineMarkdown(numberedMatch[2])}
</div>
</div>
);
i++;
continue;
}
// Default paragraph
renderedElements.push(
<p key={lineKey} className="text-ink-black my-1 font-medium leading-relaxed">
{renderInlineMarkdown(line)}
</p>
);
i++;
}
return <React.Fragment key={`block-${blockIndex}`}>{renderedElements}</React.Fragment>;
})}
</div>
);
};
export default MarkdownRenderer;