|
| 1 | +import type { ReactNode } from "react"; |
| 2 | + |
| 3 | +const SAFE_URL_RE = /^(https?:\/\/|mailto:)/i; |
| 4 | + |
| 5 | +const isSafeUrl = (url: string): boolean => SAFE_URL_RE.test(url.trim()); |
| 6 | + |
| 7 | +const inlineTokenRe = /(`[^`\n]+`|\[[^\]\n]+\]\(([^)\s]+)(?:\s+"[^"]*")?\)|\*\*[^*\n]+\*\*|__[^_\n]+__|\*[^*\n]+\*|_[^_\n]+_|~~[^~\n]+~~)/g; |
| 8 | + |
| 9 | +const parseInline = (text: string, keyPrefix: string): ReactNode[] => { |
| 10 | + const out: ReactNode[] = []; |
| 11 | + let lastIndex = 0; |
| 12 | + let tokenIndex = 0; |
| 13 | + |
| 14 | + for (const match of text.matchAll(inlineTokenRe)) { |
| 15 | + const token = match[0]; |
| 16 | + const idx = match.index ?? 0; |
| 17 | + |
| 18 | + if (idx > lastIndex) { |
| 19 | + out.push(text.slice(lastIndex, idx)); |
| 20 | + } |
| 21 | + |
| 22 | + const key = `${keyPrefix}-t-${tokenIndex++}`; |
| 23 | + |
| 24 | + if (token.startsWith("`") && token.endsWith("`")) { |
| 25 | + out.push(<code key={key}>{token.slice(1, -1)}</code>); |
| 26 | + } else if (token.startsWith("**") && token.endsWith("**")) { |
| 27 | + out.push(<strong key={key}>{token.slice(2, -2)}</strong>); |
| 28 | + } else if (token.startsWith("__") && token.endsWith("__")) { |
| 29 | + out.push(<strong key={key}>{token.slice(2, -2)}</strong>); |
| 30 | + } else if (token.startsWith("*") && token.endsWith("*")) { |
| 31 | + out.push(<em key={key}>{token.slice(1, -1)}</em>); |
| 32 | + } else if (token.startsWith("_") && token.endsWith("_")) { |
| 33 | + out.push(<em key={key}>{token.slice(1, -1)}</em>); |
| 34 | + } else if (token.startsWith("~~") && token.endsWith("~~")) { |
| 35 | + out.push(<del key={key}>{token.slice(2, -2)}</del>); |
| 36 | + } else if (token.startsWith("[") && token.includes("](") && token.endsWith(")")) { |
| 37 | + const linkMatch = token.match(/^\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/); |
| 38 | + if (!linkMatch) { |
| 39 | + out.push(token); |
| 40 | + } else { |
| 41 | + const label = linkMatch[1]; |
| 42 | + const href = linkMatch[2]; |
| 43 | + if (isSafeUrl(href)) { |
| 44 | + out.push( |
| 45 | + <a key={key} href={href} target="_blank" rel="noreferrer"> |
| 46 | + {label} |
| 47 | + </a>, |
| 48 | + ); |
| 49 | + } else { |
| 50 | + out.push(label); |
| 51 | + } |
| 52 | + } |
| 53 | + } else { |
| 54 | + out.push(token); |
| 55 | + } |
| 56 | + |
| 57 | + lastIndex = idx + token.length; |
| 58 | + } |
| 59 | + |
| 60 | + if (lastIndex < text.length) { |
| 61 | + out.push(text.slice(lastIndex)); |
| 62 | + } |
| 63 | + |
| 64 | + return out; |
| 65 | +}; |
| 66 | + |
| 67 | +const renderInlineLines = (text: string, keyPrefix: string): ReactNode[] => { |
| 68 | + const lines = text.split("\n"); |
| 69 | + const out: ReactNode[] = []; |
| 70 | + lines.forEach((line, idx) => { |
| 71 | + if (idx > 0) out.push(<br key={`${keyPrefix}-br-${idx}`} />); |
| 72 | + out.push(...parseInline(line, `${keyPrefix}-l-${idx}`)); |
| 73 | + }); |
| 74 | + return out; |
| 75 | +}; |
| 76 | + |
| 77 | +const isUnorderedListItem = (line: string): boolean => /^\s*[-*+]\s+/.test(line); |
| 78 | +const isOrderedListItem = (line: string): boolean => /^\s*\d+\.\s+/.test(line); |
| 79 | + |
| 80 | +const MarkdownText = ({ text }: { text: string }) => { |
| 81 | + const source = text.replace(/\r\n?/g, "\n"); |
| 82 | + const lines = source.split("\n"); |
| 83 | + const nodes: ReactNode[] = []; |
| 84 | + |
| 85 | + let i = 0; |
| 86 | + while (i < lines.length) { |
| 87 | + const line = lines[i]; |
| 88 | + const trimmed = line.trim(); |
| 89 | + |
| 90 | + if (!trimmed) { |
| 91 | + i += 1; |
| 92 | + continue; |
| 93 | + } |
| 94 | + |
| 95 | + if (trimmed.startsWith("```")) { |
| 96 | + const lang = trimmed.slice(3).trim(); |
| 97 | + const codeLines: string[] = []; |
| 98 | + i += 1; |
| 99 | + while (i < lines.length && !lines[i].trim().startsWith("```")) { |
| 100 | + codeLines.push(lines[i]); |
| 101 | + i += 1; |
| 102 | + } |
| 103 | + if (i < lines.length && lines[i].trim().startsWith("```")) i += 1; |
| 104 | + nodes.push( |
| 105 | + <pre key={`code-${nodes.length}`} className="md-pre"> |
| 106 | + <code className={lang ? `language-${lang}` : undefined}>{codeLines.join("\n")}</code> |
| 107 | + </pre>, |
| 108 | + ); |
| 109 | + continue; |
| 110 | + } |
| 111 | + |
| 112 | + const headingMatch = trimmed.match(/^(#{1,6})\s+(.+)$/); |
| 113 | + if (headingMatch) { |
| 114 | + const level = headingMatch[1].length; |
| 115 | + const content = headingMatch[2]; |
| 116 | + const key = `h-${nodes.length}`; |
| 117 | + if (level === 1) nodes.push(<h1 key={key}>{renderInlineLines(content, key)}</h1>); |
| 118 | + else if (level === 2) nodes.push(<h2 key={key}>{renderInlineLines(content, key)}</h2>); |
| 119 | + else if (level === 3) nodes.push(<h3 key={key}>{renderInlineLines(content, key)}</h3>); |
| 120 | + else if (level === 4) nodes.push(<h4 key={key}>{renderInlineLines(content, key)}</h4>); |
| 121 | + else if (level === 5) nodes.push(<h5 key={key}>{renderInlineLines(content, key)}</h5>); |
| 122 | + else nodes.push(<h6 key={key}>{renderInlineLines(content, key)}</h6>); |
| 123 | + i += 1; |
| 124 | + continue; |
| 125 | + } |
| 126 | + |
| 127 | + if (trimmed.startsWith(">")) { |
| 128 | + const quoteLines: string[] = []; |
| 129 | + while (i < lines.length && lines[i].trim().startsWith(">")) { |
| 130 | + quoteLines.push(lines[i].trim().replace(/^>\s?/, "")); |
| 131 | + i += 1; |
| 132 | + } |
| 133 | + const content = quoteLines.join("\n"); |
| 134 | + const key = `q-${nodes.length}`; |
| 135 | + nodes.push(<blockquote key={key}>{renderInlineLines(content, key)}</blockquote>); |
| 136 | + continue; |
| 137 | + } |
| 138 | + |
| 139 | + if (isUnorderedListItem(line) || isOrderedListItem(line)) { |
| 140 | + const ordered = isOrderedListItem(line); |
| 141 | + const items: string[] = []; |
| 142 | + while (i < lines.length) { |
| 143 | + const candidate = lines[i]; |
| 144 | + if (ordered && isOrderedListItem(candidate)) { |
| 145 | + items.push(candidate.replace(/^\s*\d+\.\s+/, "")); |
| 146 | + i += 1; |
| 147 | + continue; |
| 148 | + } |
| 149 | + if (!ordered && isUnorderedListItem(candidate)) { |
| 150 | + items.push(candidate.replace(/^\s*[-*+]\s+/, "")); |
| 151 | + i += 1; |
| 152 | + continue; |
| 153 | + } |
| 154 | + if (!candidate.trim()) { |
| 155 | + i += 1; |
| 156 | + break; |
| 157 | + } |
| 158 | + break; |
| 159 | + } |
| 160 | + const key = `list-${nodes.length}`; |
| 161 | + if (ordered) { |
| 162 | + nodes.push( |
| 163 | + <ol key={key}> |
| 164 | + {items.map((item, idx) => ( |
| 165 | + <li key={`${key}-i-${idx}`}>{renderInlineLines(item, `${key}-i-${idx}`)}</li> |
| 166 | + ))} |
| 167 | + </ol>, |
| 168 | + ); |
| 169 | + } else { |
| 170 | + nodes.push( |
| 171 | + <ul key={key}> |
| 172 | + {items.map((item, idx) => ( |
| 173 | + <li key={`${key}-i-${idx}`}>{renderInlineLines(item, `${key}-i-${idx}`)}</li> |
| 174 | + ))} |
| 175 | + </ul>, |
| 176 | + ); |
| 177 | + } |
| 178 | + continue; |
| 179 | + } |
| 180 | + |
| 181 | + const paragraphLines: string[] = []; |
| 182 | + while (i < lines.length) { |
| 183 | + const current = lines[i]; |
| 184 | + const currentTrimmed = current.trim(); |
| 185 | + if (!currentTrimmed) break; |
| 186 | + if ( |
| 187 | + currentTrimmed.startsWith("```") || |
| 188 | + currentTrimmed.startsWith(">") || |
| 189 | + /^(#{1,6})\s+/.test(currentTrimmed) || |
| 190 | + isUnorderedListItem(current) || |
| 191 | + isOrderedListItem(current) |
| 192 | + ) { |
| 193 | + break; |
| 194 | + } |
| 195 | + paragraphLines.push(current); |
| 196 | + i += 1; |
| 197 | + } |
| 198 | + const content = paragraphLines.join("\n"); |
| 199 | + const key = `p-${nodes.length}`; |
| 200 | + nodes.push(<p key={key}>{renderInlineLines(content, key)}</p>); |
| 201 | + } |
| 202 | + |
| 203 | + return <div className="markdown-body">{nodes}</div>; |
| 204 | +}; |
| 205 | + |
| 206 | +export default MarkdownText; |
0 commit comments