|
| 1 | +export type Segment = |
| 2 | + | { type: 'bold'; content: string } |
| 3 | + | { type: 'code'; content: string } |
| 4 | + | { type: 'highlighted'; content: string } |
| 5 | + | { type: 'link'; content: { name: string; address: string } } |
| 6 | + | { type: 'normal'; content: string }; |
| 7 | + |
| 8 | +export function segmentMarkdownText(text: string): Segment[] { |
| 9 | + if (!text) return []; |
| 10 | + const regex = /(\*\*(.*?)\*\*)|(```([\s\S]*?)```\s)|(`(.*?)`)|\[(.*?)\]\((.*?)\)|[^[\]*`]+/g; |
| 11 | + return ( |
| 12 | + text.match(regex)?.map(segment => { |
| 13 | + if (segment.startsWith('**')) { |
| 14 | + return { |
| 15 | + type: 'bold', |
| 16 | + content: segment.replace(/\*\*/g, ''), |
| 17 | + }; |
| 18 | + } else if (segment.startsWith('```')) { |
| 19 | + return { |
| 20 | + type: 'code', |
| 21 | + content: segment.replace(/```/g, ''), |
| 22 | + }; |
| 23 | + } else if (segment.startsWith('`')) { |
| 24 | + return { |
| 25 | + type: 'highlighted', |
| 26 | + content: segment.replace(/`/g, ''), |
| 27 | + }; |
| 28 | + } else if (segment.startsWith('[') && segment.endsWith(')')) { |
| 29 | + const nameMatch = segment.match(/\[(.*?)\]/); |
| 30 | + const addressMatch = segment.match(/\((.*?)\)/); |
| 31 | + return { |
| 32 | + type: 'link', |
| 33 | + content: { |
| 34 | + name: nameMatch ? nameMatch[1] : '', |
| 35 | + address: addressMatch ? addressMatch[1] : '', |
| 36 | + }, |
| 37 | + }; |
| 38 | + } else { |
| 39 | + return { |
| 40 | + type: 'normal', |
| 41 | + content: segment, |
| 42 | + }; |
| 43 | + } |
| 44 | + }) ?? [] |
| 45 | + ); |
| 46 | +} |
| 47 | + |
| 48 | +export function formatCodeSegment( |
| 49 | + text: string, |
| 50 | +): { language: string | undefined; code: string } { |
| 51 | + const lines = text.split('\n'); |
| 52 | + const language = lines.shift(); |
| 53 | + const nonEmptyLines = lines.filter(line => line.trim() !== ''); |
| 54 | + const code = nonEmptyLines.join('\n'); |
| 55 | + return { language, code }; |
| 56 | +} |
0 commit comments