Files
planet/frontend/src/components/MarkdownRenderer/MarkdownRenderer.tsx
T

274 lines
8.0 KiB
TypeScript

import { memo } from 'react'
import type { ReactNode } from 'react'
import Scrollbar from '../Scrollbar/Scrollbar'
interface MarkdownRendererProps {
markdown: string
className?: string
getHeadingId?: () => (text: string, level: number) => string | undefined
transformLink?: (href: string) => MarkdownLink | null
}
interface MarkdownLink {
href: string
external?: boolean
}
function renderInlineMarkdown(text: string, transformLink?: MarkdownRendererProps['transformLink']): ReactNode[] {
const result: ReactNode[] = []
const pattern = /(\[[^\]]+\]\([^)]+\)|`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*)/g
let lastIndex = 0
let key = 0
for (const match of text.matchAll(pattern)) {
const matchedText = match[0]
const start = match.index ?? 0
if (start > lastIndex) {
result.push(text.slice(lastIndex, start))
}
if (matchedText.startsWith('[')) {
const linkMatch = matchedText.match(/^\[([^\]]+)\]\(([^)]+)\)$/)
if (linkMatch) {
const resolvedLink = transformLink?.(linkMatch[2])
const href = resolvedLink?.href || linkMatch[2]
const isExternal = resolvedLink?.external ?? true
result.push(
<a
key={`inline-${key}`}
href={href}
target={isExternal ? '_blank' : undefined}
rel={isExternal ? 'noreferrer' : undefined}
>
{linkMatch[1]}
</a>,
)
key += 1
lastIndex = start + matchedText.length
continue
}
}
if (matchedText.startsWith('`')) {
result.push(<code key={`inline-${key}`}>{matchedText.slice(1, -1)}</code>)
key += 1
lastIndex = start + matchedText.length
continue
}
if (matchedText.startsWith('**')) {
result.push(<strong key={`inline-${key}`}>{matchedText.slice(2, -2)}</strong>)
key += 1
lastIndex = start + matchedText.length
continue
}
if (matchedText.startsWith('*')) {
result.push(<em key={`inline-${key}`}>{matchedText.slice(1, -1)}</em>)
key += 1
lastIndex = start + matchedText.length
continue
}
}
if (lastIndex < text.length) {
result.push(text.slice(lastIndex))
}
return result
}
function MarkdownRenderer({
markdown,
className,
getHeadingId,
transformLink,
}: MarkdownRendererProps) {
const resolveHeadingId = getHeadingId?.()
const lines = markdown.replace(/\r\n/g, '\n').split('\n')
const nodes: ReactNode[] = []
let index = 0
while (index < lines.length) {
const line = lines[index]
const trimmed = line.trim()
if (!trimmed) {
index += 1
continue
}
if (trimmed.startsWith('<!--') && trimmed.endsWith('-->')) {
index += 1
continue
}
if (trimmed.startsWith('```')) {
const codeLines: string[] = []
index += 1
while (index < lines.length && !lines[index].trim().startsWith('```')) {
codeLines.push(lines[index])
index += 1
}
if (index < lines.length) {
index += 1
}
nodes.push(
<Scrollbar key={`block-${index}`} className="markdown-renderer__code-scroll">
<pre>
<code>{codeLines.join('\n')}</code>
</pre>
</Scrollbar>,
)
continue
}
if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed)) {
nodes.push(<hr key={`block-${index}`} />)
index += 1
continue
}
const headingMatch = trimmed.match(/^(#{1,6})\s+(.+)$/)
if (headingMatch) {
const level = headingMatch[1].length
const headingText = headingMatch[2]
const content = renderInlineMarkdown(headingText, transformLink)
const headingId = resolveHeadingId?.(headingText, level)
if (level === 1) nodes.push(<h1 key={`block-${index}`} id={headingId}>{content}</h1>)
else if (level === 2) nodes.push(<h2 key={`block-${index}`} id={headingId}>{content}</h2>)
else if (level === 3) nodes.push(<h3 key={`block-${index}`} id={headingId}>{content}</h3>)
else if (level === 4) nodes.push(<h4 key={`block-${index}`} id={headingId}>{content}</h4>)
else nodes.push(<p key={`block-${index}`} className="markdown-renderer__heading-fallback">{content}</p>)
index += 1
continue
}
if (trimmed.startsWith('> ')) {
const quoteLines: string[] = []
while (index < lines.length && lines[index].trim().startsWith('> ')) {
quoteLines.push(lines[index].trim().slice(2))
index += 1
}
nodes.push(<blockquote key={`block-${index}`}>{quoteLines.join(' ')}</blockquote>)
continue
}
const unorderedMatch = trimmed.match(/^[-*]\s+(.+)$/)
if (unorderedMatch) {
const items: string[] = []
while (index < lines.length) {
const itemMatch = lines[index].trim().match(/^[-*]\s+(.+)$/)
if (!itemMatch) break
items.push(itemMatch[1])
index += 1
}
nodes.push(
<ul key={`block-${index}`}>
{items.map((item, itemIndex) => (
<li key={`item-${itemIndex}`}>{renderInlineMarkdown(item, transformLink)}</li>
))}
</ul>,
)
continue
}
const orderedMatch = trimmed.match(/^\d+\.\s+(.+)$/)
if (orderedMatch) {
const items: string[] = []
while (index < lines.length) {
const itemMatch = lines[index].trim().match(/^\d+\.\s+(.+)$/)
if (!itemMatch) break
items.push(itemMatch[1])
index += 1
}
nodes.push(
<ol key={`block-${index}`}>
{items.map((item, itemIndex) => (
<li key={`item-${itemIndex}`}>{renderInlineMarkdown(item, transformLink)}</li>
))}
</ol>,
)
continue
}
const tableHeaderCells = parseTableRow(trimmed)
const tableDividerCells = lines[index + 1] ? parseTableDivider(lines[index + 1].trim()) : null
if (
tableHeaderCells &&
tableHeaderCells.length > 0 &&
tableDividerCells &&
tableDividerCells.length === tableHeaderCells.length
) {
const bodyRows: string[][] = []
index += 2
while (index < lines.length) {
const rowCells = parseTableRow(lines[index].trim())
if (!rowCells || rowCells.length !== tableHeaderCells.length) {
break
}
bodyRows.push(rowCells)
index += 1
}
nodes.push(
<Scrollbar key={`block-${index}`} className="markdown-renderer__table-wrap">
<table className="markdown-renderer__table">
<thead>
<tr>
{tableHeaderCells.map((cell, cellIndex) => (
<th key={`head-${cellIndex}`}>{renderInlineMarkdown(cell, transformLink)}</th>
))}
</tr>
</thead>
<tbody>
{bodyRows.map((row, rowIndex) => (
<tr key={`row-${rowIndex}`}>
{row.map((cell, cellIndex) => (
<td key={`cell-${rowIndex}-${cellIndex}`}>{renderInlineMarkdown(cell, transformLink)}</td>
))}
</tr>
))}
</tbody>
</table>
</Scrollbar>,
)
continue
}
const paragraphLines: string[] = []
while (index < lines.length && lines[index].trim()) {
paragraphLines.push(lines[index].trim())
index += 1
}
nodes.push(<p key={`block-${index}`}>{renderInlineMarkdown(paragraphLines.join(' '), transformLink)}</p>)
}
return <div className={className ? `markdown-renderer ${className}` : 'markdown-renderer'}>{nodes}</div>
}
export default memo(MarkdownRenderer)
function parseTableRow(line: string): string[] | null {
if (!line.includes('|')) {
return null
}
const normalized = line.replace(/^\|/, '').replace(/\|$/, '')
const cells = normalized.split('|').map((cell) => cell.trim())
return cells.length > 0 ? cells : null
}
function parseTableDivider(line: string): string[] | null {
const cells = parseTableRow(line)
if (!cells || cells.length === 0) {
return null
}
const isDivider = cells.every((cell) => /^:?-{3,}:?$/.test(cell))
return isDivider ? cells : null
}