| 2 | |
| 3 | // 解析行内 Markdown |
| 4 | const parseInlineMarkdown = (text: string): React.ReactNode => { |
| 5 | const parts: React.ReactNode[] = []; |
| 6 | let currentText = ''; |
| 7 | let i = 0; |
| 8 | |
| 9 | while (i < text.length) { |
| 10 | // 处理 HTML 图片标签 <img ...> |
| 11 | if (text.slice(i, i + 4) === '<img') { |
| 12 | if (currentText) { |
| 13 | parts.push(currentText); |
| 14 | currentText = ''; |
| 15 | } |
| 16 | i += 4; |
| 17 | let imgTag = '<img'; |
| 18 | let inQuotes = false; |
| 19 | let quoteChar = ''; |
| 20 | |
| 21 | while (i < text.length) { |
| 22 | const char = text[i]; |
| 23 | imgTag += char; |
| 24 | |
| 25 | if ((char === '"' || char === "'") && !inQuotes) { |
| 26 | inQuotes = true; |
| 27 | quoteChar = char; |
| 28 | } else if (char === quoteChar && inQuotes) { |
| 29 | inQuotes = false; |
| 30 | } else if (char === '>' && !inQuotes) { |
| 31 | i++; |
| 32 | break; |
| 33 | } |
| 34 | i++; |
| 35 | } |
| 36 | |
| 37 | // 解析 img 标签属性 |
| 38 | const srcMatch = imgTag.match(/src\s*=\s*["']([^"']+)["']/); |
| 39 | const altMatch = imgTag.match(/alt\s*=\s*["']([^"']+)["']/); |
| 40 | const widthMatch = imgTag.match(/width\s*=\s*["']?(\d+)["']?/); |
| 41 | |
| 42 | if (srcMatch) { |
| 43 | const src = srcMatch[1]; |
| 44 | const alt = altMatch ? altMatch[1] : ''; |
| 45 | const width = widthMatch ? widthMatch[1] : undefined; |
| 46 | |
| 47 | parts.push( |
| 48 | <img |
| 49 | key={`html-img-${i}`} |
| 50 | src={src} |
| 51 | alt={alt} |
| 52 | width={width} |
| 53 | className="max-w-full h-auto rounded-lg my-4" |
| 54 | /> |
| 55 | ); |
| 56 | } else { |
| 57 | parts.push(imgTag); |
| 58 | } |
| 59 | } |
| 60 | // 处理 Markdown 图片  |
| 61 | else if (text.slice(i, i + 2) === '![') { |