-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMarkdown.tsx
More file actions
252 lines (219 loc) · 8.4 KB
/
Markdown.tsx
File metadata and controls
252 lines (219 loc) · 8.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import type { ReactNode } from 'react'
interface MarkdownProps {
text: string
className?: string
}
export default function Markdown({ text, className }: MarkdownProps) {
// Inline parsing: parse bold, italic, underline, links, images, inline code
function parseInline(str: string): ReactNode[] {
const nodes: ReactNode[] = []
// A helper function to safely parse inline and return an array of react nodes
function renderTextSegments(text: string): ReactNode[] {
let result: ReactNode[] = []
// Process in order: image links, images, regular links, and then formatting
const imageInsideLinkRegex = /\[!\[([^\]]*)\]\(([^)]+)\)\]\(([^)]+)\)/g
// Handle mixed content within links: [text  more text](link_url)
const mixedContentLinkRegex = /\[([^\]]*?!\[[^\]]*?\]\([^)]+?\)[^\]]*?)\]\(([^)]+)\)/g
const imageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g
const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g
const codeRegex = /`([^`]+)`/g
const boldRegex = /\*\*([^*]+)\*\*/g
const italicRegex = /\*(?!\s)([^*]+?)(?!\s)\*/g
const underlineRegex = /__(.+?)__/g
function applyRegex(
currentText: ReactNode[],
regex: RegExp,
renderFn: (match: RegExpExecArray) => ReactNode
) {
const newResult: ReactNode[] = []
for (const segment of currentText) {
if (typeof segment === 'string') {
const str = segment
let lastIndex = 0
let match: RegExpExecArray | null
regex.lastIndex = 0 // Reset regex for safety
while ((match = regex.exec(str)) !== null) {
// Add text before match
if (match.index > lastIndex) {
newResult.push(str.slice(lastIndex, match.index))
}
// Add replaced node
newResult.push(renderFn(match))
lastIndex = match.index + match[0].length
}
if (lastIndex < str.length) {
newResult.push(str.slice(lastIndex))
}
} else {
// If it's already a ReactNode (not a string), just push it
newResult.push(segment)
}
}
return newResult
}
// Start with entire text as a single segment
result = [text]
// Apply in a specific order to handle nested elements:
// First handle image-inside-link pattern
result = applyRegex(result, imageInsideLinkRegex, (m) => <a href={m[3]} key={`imglink-${m[3]}`}>
<img alt={m[1]} src={m[2]} key={`img-in-link-${m[2]}`} />
</a>)
// Then handle mixed content links (with images and text)
result = applyRegex(result, mixedContentLinkRegex, (m) => <a href={m[2]} key={`mixed-${m[2]}`}>{parseInline(m[1])}</a>)
// Then handle regular images and links
result = applyRegex(result, imageRegex, (m) => <img key={`img-${m[2]}`} alt={m[1]} src={m[2]} />)
result = applyRegex(result, linkRegex, (m) => <a href={m[2]} key={`link-${m[2]}`}>{parseInline(m[1])}</a>)
// Finally handle text formatting
result = applyRegex(result, codeRegex, (m) => <code key={`code-${m.index}`}>{m[1]}</code>)
result = applyRegex(result, boldRegex, (m) => <strong key={`bold-${m.index}`}>{m[1]}</strong>)
result = applyRegex(result, italicRegex, (m) => <em key={`italic-${m.index}`}>{m[1]}</em>)
result = applyRegex(result, underlineRegex, (m) => <u key={`underline-${m.index}`}>{m[1]}</u>)
return result
}
nodes.push(...renderTextSegments(str))
return nodes
}
// Block-level parsing: paragraphs, headers, lists, code blocks
type NodeType =
| { type: 'paragraph', content: string }
| { type: 'header', level: number, content: string }
| { type: 'codeblock', content: string }
| { type: 'list', ordered: boolean, items: ListItemType[] }
interface ListItemType {
content: string
children: NodeType[]
}
function parseBlocks(lines: string[]): NodeType[] {
let i = 0
const nodes: NodeType[] = []
function parseList(startIndent: number, ordered: boolean): { node: NodeType, endIndex: number } {
const items: ListItemType[] = []
while (i < lines.length) {
const line = lines[i]
const indent = /^(\s*)/.exec(line)?.[1].length ?? 0
// Check if line is a list item at or deeper than startIndent
const liMatch = ordered
? /^\s*\d+\.\s+(.*)/.exec(line)
: /^\s*-\s+(.*)/.exec(line)
if (!liMatch || indent < startIndent) {
break
}
const content = liMatch[1]
i++
// Check if next lines form sub-lists or paragraphs under this item
const children: NodeType[] = []
while (i < lines.length) {
const subline = lines[i]
const subIndent = /^(\s*)/.exec(subline)?.[1].length ?? 0
// Check for sub-list
const subOlMatch = /^\s*\d+\.\s+(.*)/.exec(subline)
const subUlMatch = /^\s*-\s+(.*)/.exec(subline)
if ((subOlMatch || subUlMatch) && subIndent > startIndent) {
const { node: sublist, endIndex } = parseList(subIndent, !!subOlMatch)
children.push(sublist)
i = endIndex
} else if (subline.trim().length === 0 || subIndent > startIndent) {
if (subline.trim().length !== 0) {
// paragraph under item
children.push({ type: 'paragraph', content: subline.trim() })
}
i++
} else {
break
}
}
items.push({ content, children })
}
return { node: { type: 'list', ordered, items }, endIndex: i }
}
while (i < lines.length) {
const line = lines[i]
// Skip blank lines
if (line.trim() === '') {
i++
continue
}
// Check for code block
if (line.trim().startsWith('```')) {
i++
const codeLines: string[] = []
while (i < lines.length && !lines[i].trim().startsWith('```')) {
codeLines.push(lines[i])
i++
}
i++ // skip the ending ```
nodes.push({ type: 'codeblock', content: codeLines.join('\n') })
continue
}
// Check for headers
const headerMatch = /^(#{1,3})\s+(.*)/.exec(line)
if (headerMatch) {
const level = headerMatch[1].length
const content = headerMatch[2]
nodes.push({ type: 'header', level, content })
i++
continue
}
// Check for list item
const olMatch = /^\s*\d+\.\s+(.*)/.exec(line)
const ulMatch = /^\s*-\s+(.*)/.exec(line)
if (olMatch || ulMatch) {
const indent = /^(\s*)/.exec(line)?.[1].length ?? 0
const ordered = !!olMatch
const { node, endIndex } = parseList(indent, ordered)
nodes.push(node)
i = endIndex
continue
}
// If not code block, header, or list, treat as paragraph
nodes.push({ type: 'paragraph', content: line })
i++
}
return nodes
}
const lines = text.split('\n')
const ast = parseBlocks(lines)
// Convert AST to React elements
function renderNodes(nodes: NodeType[]): ReactNode {
return nodes.map((node, idx) => {
switch (node.type) {
case 'paragraph':
return <p key={idx}>{...parseInline(node.content)}</p>
case 'header':
if (node.level === 1) return <h1 key={idx}>{...parseInline(node.content)}</h1>
if (node.level === 2) return <h2 key={idx}>{...parseInline(node.content)}</h2>
if (node.level === 3) return <h3 key={idx}>{...parseInline(node.content)}</h3>
return <p key={idx}>{...parseInline(node.content)}</p>
case 'codeblock':
return (
<pre key={idx}>
<code>{node.content}</code>
</pre>
)
case 'list':
if (node.ordered) {
return (
<ol key={idx}>
{node.items.map((item, liIndex) => <li key={liIndex}>
{...parseInline(item.content)}
{renderNodes(item.children)}
</li>)}
</ol>
)
} else {
return (
<ul key={idx}>
{node.items.map((item, liIndex) => <li key={liIndex}>
{...parseInline(item.content)}
{renderNodes(item.children)}
</li>)}
</ul>
)
}
default:
return null
}
})
}
return <div className={className}>{renderNodes(ast)}</div>
}