import { Fragment, isValidElement, type ReactNode } from 'react';
const TOKEN_RE = /(\*\*[^*\n][\s\S]*?[^*\n]\*\*|`[^`\n]+`|\[[^\]\n]+\]\(https?:\/\/[^)\s]+\))/g;
function renderToken(token: string, key: string): ReactNode {
if (token.startsWith('**') && token.endsWith('**')) {
return (
{token.slice(2, -2)}
);
}
if (token.startsWith('`') && token.endsWith('`')) {
return (
{token.slice(1, -1)}
);
}
const link = token.match(/^\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)$/);
if (link) {
return (
{link[1]}
);
}
return token;
}
export function renderInlineMarkdown(text: string | null | undefined): ReactNode {
if (!text) return null;
const parts: ReactNode[] = [];
let lastIndex = 0;
for (const match of text.matchAll(TOKEN_RE)) {
const mi = match.index ?? 0;
if (mi > lastIndex) {
parts.push(text.slice(lastIndex, mi));
}
parts.push(renderToken(match[0], `md-${mi}`));
lastIndex = mi + match[0].length;
}
if (lastIndex < text.length) {
parts.push(text.slice(lastIndex));
}
return parts.map((part, index) => (
{part}
));
}
export function MarkdownText({ text }: { text?: string | null }): ReactNode {
return renderInlineMarkdown(text);
}