|
| 1 | +import React from "react"; |
| 2 | + |
| 3 | +interface RichTextSubtextProps { |
| 4 | + text: string; |
| 5 | + className?: string; |
| 6 | +} |
| 7 | + |
| 8 | +/** |
| 9 | + * Component that renders text with clickable links. |
| 10 | + * Detects URLs in the text and converts them to clickable links. |
| 11 | + * Also supports markdown-style links like [text](url). |
| 12 | + */ |
| 13 | +export function RichTextSubtext({ |
| 14 | + text, |
| 15 | + className = "", |
| 16 | +}: RichTextSubtextProps) { |
| 17 | + // Function to parse text and create React elements |
| 18 | + const parseText = (input: string): React.ReactNode[] => { |
| 19 | + const elements: React.ReactNode[] = []; |
| 20 | + |
| 21 | + // Regex to match markdown links [text](url) and plain URLs |
| 22 | + const combinedRegex = /(\[([^\]]+)\]\(([^)]+)\))|(https?:\/\/[^\s]+)/g; |
| 23 | + |
| 24 | + let lastIndex = 0; |
| 25 | + let match; |
| 26 | + let key = 0; |
| 27 | + |
| 28 | + while ((match = combinedRegex.exec(input)) !== null) { |
| 29 | + // Add text before the match |
| 30 | + if (match.index > lastIndex) { |
| 31 | + elements.push( |
| 32 | + <span key={`text-${key++}`}> |
| 33 | + {input.slice(lastIndex, match.index)} |
| 34 | + </span> |
| 35 | + ); |
| 36 | + } |
| 37 | + |
| 38 | + if (match[1]) { |
| 39 | + // Markdown-style link [text](url) |
| 40 | + const linkText = match[2]; |
| 41 | + const url = match[3]; |
| 42 | + elements.push( |
| 43 | + <a |
| 44 | + key={`link-${key++}`} |
| 45 | + href={url} |
| 46 | + target="_blank" |
| 47 | + rel="noopener noreferrer" |
| 48 | + className="text-link hover:text-link-hover underline" |
| 49 | + onClick={(e) => e.stopPropagation()} |
| 50 | + > |
| 51 | + {linkText} |
| 52 | + </a> |
| 53 | + ); |
| 54 | + } else if (match[4]) { |
| 55 | + // Plain URL |
| 56 | + const url = match[4]; |
| 57 | + elements.push( |
| 58 | + <a |
| 59 | + key={`link-${key++}`} |
| 60 | + href={url} |
| 61 | + target="_blank" |
| 62 | + rel="noopener noreferrer" |
| 63 | + className="text-link hover:text-link-hover underline" |
| 64 | + onClick={(e) => e.stopPropagation()} |
| 65 | + > |
| 66 | + {url} |
| 67 | + </a> |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + lastIndex = match.index + match[0].length; |
| 72 | + } |
| 73 | + |
| 74 | + // Add remaining text after the last match |
| 75 | + if (lastIndex < input.length) { |
| 76 | + elements.push( |
| 77 | + <span key={`text-${key++}`}>{input.slice(lastIndex)}</span> |
| 78 | + ); |
| 79 | + } |
| 80 | + |
| 81 | + return elements; |
| 82 | + }; |
| 83 | + |
| 84 | + return <div className={className}>{parseText(text)}</div>; |
| 85 | +} |
0 commit comments