index.tsx
10.6 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import ReactMarkdown from 'react-markdown'
import 'katex/dist/katex.min.css'
import RemarkMath from 'remark-math'
import RemarkBreaks from 'remark-breaks'
import RehypeKatex from 'rehype-katex'
import RemarkGfm from 'remark-gfm'
import RehypeRaw from 'rehype-raw'
import { flow } from 'lodash-es'
import cn from '@/utils/classnames'
import { customUrlTransform, preprocessLaTeX, preprocessThinkTag } from './markdown-utils'
import { Audio, Code, Img, Link, MarkdownButton, MarkdownForm, Paragraph, Script, Think, Video, Chart } from './blocks'
import { useMemo, useEffect, useRef, useState } from 'react'
/**
* @fileoverview Main Markdown rendering component.
* This file was refactored to extract individual block renderers and utility functions
* into separate modules for better organization and maintainability as of [Date of refactor].
* Further refactoring candidates (custom block components not fitting general categories)
* are noted in their respective files if applicable.
*/
type MarkdownProps = {
content: string
className?: string
customDisallowedElements?: string[]
operationClassName?: string
onJsonContentReady?: (jsonContent: any) => React.ReactNode
onThinkComplete?: (isComplete: boolean) => void
hideThink?: boolean
responding?: boolean // 添加 responding 状态
}
type MarkdownContent = {
mainContent: string
jsonContent?: any
}
export function Markdown(props: MarkdownProps) {
const processedContent = flow([preprocessThinkTag, preprocessLaTeX])(props.content)
const contentObj: MarkdownContent = useMemo(() => {
let mainContent = processedContent
let jsonContent: any = null
// 查找所有 ```json 代码块
const jsonCodeBlockRegex = /```json\s*([\s\S]*?)\s*```/g
let match
const allJsonBlocks: any[] = []
// 收集所有 JSON 块
while ((match = jsonCodeBlockRegex.exec(processedContent)) !== null) {
const jsonStr = match[1].trim()
try {
const parsed = JSON.parse(jsonStr)
allJsonBlocks.push(parsed)
} catch (e) {
console.error('JSON 解析失败:', e, '原始内容:', jsonStr)
}
}
// 取最后一个解析成功的 JSON
if (allJsonBlocks.length > 0) {
jsonContent = allJsonBlocks[allJsonBlocks.length - 1]
}
// 第二步:彻底移除所有代码块,但保留换行符
mainContent = mainContent
// 移除 ```json 代码块(支持多种格式),替换为单个换行
.replace(/```json\r?\n([\s\S]*?)\r?\n```/g, '\n')
.replace(/```json([\s\S]*?)```/g, '\n')
// 移除其他代码块,替换为单个换行
.replace(/```\r?\n([\s\S]*?)\r?\n```/g, '\n')
.replace(/```([\s\S]*?)```/g, '\n')
// 只清理连续3个以上的空行,保留正常的换行
.replace(/\n{3,}/g, '\n\n')
.trim()
// 过滤嵌套的 <details data-think=true> 标签
// 检查是否存在嵌套的 details(即在 details 内部还有 details)
const hasNestedDetails = /<details[^>]*data-think[^>]*>[\s\S]*<details[^>]*data-think[^>]*>/i.test(mainContent)
if (hasNestedDetails) {
// 去掉内层 details 的开始标签和结束标签,以及外层多余的结束标记和换行
// 匹配嵌套结构并清理
mainContent = mainContent.replace(
/<details[^>]*data-think[^>]*>\n([\s\S]*?)<details[^>]*data-think[^>]*>([\s\S]*?)<\/details>([\s\S]*?)[ENDTHINKFLAG]*<\/details>[\s\S]*$/gi,
'<details data-think=true>$1$2</details>$3'
)
// 清理最后的 \n[ENDTHINKFLAG]
mainContent = mainContent.replace(/\n\[ENDTHINKFLAG\]\s*$/gi, '')
}
return { mainContent, jsonContent }
}, [processedContent])
const latexContent = contentObj.mainContent
console.log(latexContent)
// 强行过滤所有代码块内容
const filteredContent = useMemo(() => {
if (!latexContent) return ''
let filtered = latexContent
// 如果需要隐藏 Think,则移除所有 <details> 标签及其内容
if (props.hideThink) {
// 更宽松的正则表达式,匹配各种格式的 details 标签
filtered = filtered.replace(/<details[^>]*data-think[^>]*>[\s\S]*?<\/details>/gi, '')
filtered = filtered.replace(/<details[^>]*data-think[^>]*>[\s\S]*/gi, '')
}
// 处理 <details> 内的 ```json:一旦出现就截断后面所有内容(适配流式输出)
// 查找每个 <details> 标签内的第一个 ```json 位置
const detailsRegex = /<details[^>]*data-think[^>]*>/gi
let result = filtered
while (true) {
const match = detailsRegex.exec(result)
if (!match) break
const detailsStartIndex = match.index
const detailsTagEnd = detailsStartIndex + match[0].length
// 在这个 details 标签后查找 </details>
const detailsEndIndex = result.indexOf('</details>', detailsTagEnd)
if (detailsEndIndex === -1) {
// 如果没有找到结束标签,说明是流式输出中还未完成的部分
// 检查从 details 开始到当前末尾是否有 ```json
const contentAfterDetails = result.substring(detailsTagEnd)
const jsonIndex = contentAfterDetails.indexOf('```json')
if (jsonIndex !== -1) {
// 找到 ```json,截断后面的所有内容
result = result.substring(0, detailsTagEnd + jsonIndex)
}
break
}
// 提取 details 内部的内容
const detailsContent = result.substring(detailsTagEnd, detailsEndIndex)
const jsonIndex = detailsContent.indexOf('```json')
if (jsonIndex !== -1) {
// 找到 ```json,只保留前面的内容
const beforeJson = detailsContent.substring(0, jsonIndex)
result = result.substring(0, detailsTagEnd) + beforeJson + result.substring(detailsEndIndex)
// 重置搜索,因为内容长度改变了
detailsRegex.lastIndex = 0
} else {
// 没找到,继续下一个
detailsRegex.lastIndex = detailsEndIndex
}
}
filtered = result
// 移除所有 ```json 和 ``` 标记,无论它们是否成对出现
filtered = filtered.replace(/```json\s*/gi, '')
filtered = filtered.replace(/```\s*/gi, '')
return filtered.trim()
}, [latexContent, props.hideThink])
// 创建 ref 来引用 markdown 容器
const markdownRef = useRef<HTMLDivElement>(null)
const [shouldAutoScroll, setShouldAutoScroll] = useState(true)
// 暴露禁用自动滚动的方法给子组件
useEffect(() => {
// 将方法挂载到 window 上,供 Think 组件调用
;(window as any).__disableMarkdownAutoScroll = () => {
setShouldAutoScroll(false)
}
return () => {
delete (window as any).__disableMarkdownAutoScroll
}
}, [])
// 检测用户是否正在手动滚动
useEffect(() => {
const handleUserScroll = () => {
// 用户手动滚动时,禁用自动滚动
setShouldAutoScroll(false)
}
// 添加滚动事件监听器
window.addEventListener('wheel', handleUserScroll, { passive: true })
window.addEventListener('touchmove', handleUserScroll, { passive: true })
window.addEventListener('scroll', handleUserScroll, { passive: true })
return () => {
// 清理事件监听器
window.removeEventListener('wheel', handleUserScroll)
window.removeEventListener('touchmove', handleUserScroll)
window.removeEventListener('scroll', handleUserScroll)
}
}, [])
// 当 responding 状态变化时,重置自动滚动标志
useEffect(() => {
if (props.responding) {
// 开始新的回复时,重新启用自动滚动
setShouldAutoScroll(true)
} else {
// 回复完成后,禁用自动滚动
setShouldAutoScroll(false)
}
}, [props.responding])
// 当内容更新且允许自动滚动时,自动滚动到底部
useEffect(() => {
// 如果用户正在点击 Think 组件,不执行自动滚动
if ((window as any).__isUserClickingThink) {
return
}
if (!shouldAutoScroll || !props.responding) {
return
}
if (markdownRef.current) {
// 找到最近的滚动容器
let scrollContainer = markdownRef.current.parentElement
while (scrollContainer && scrollContainer.scrollHeight <= scrollContainer.clientHeight) {
scrollContainer = scrollContainer.parentElement
}
if (scrollContainer) {
requestAnimationFrame(() => {
scrollContainer.scrollTo({
top: scrollContainer.scrollHeight,
behavior: 'smooth',
})
})
}
}
}, [filteredContent, contentObj.jsonContent, shouldAutoScroll, props.responding])
// 如果过滤后内容为空且没有 JSON 内容,则不渲染任何内容
if (!filteredContent && !contentObj.jsonContent) {
return null
}
return (
<>
<div ref={markdownRef} className={cn('markdown-body ', '!text-text-primary', props.className)}>
<ReactMarkdown
remarkPlugins={[RemarkGfm, [RemarkMath, { singleDollarTextMath: false }], RemarkBreaks]}
rehypePlugins={[
RehypeKatex,
RehypeRaw as any,
// The Rehype plug-in is used to remove the ref attribute of an element
() => {
return (tree: any) => {
const iterate = (node: any) => {
if (node.type === 'element' && node.properties?.ref) delete node.properties.ref
if (node.type === 'element' && !/^[a-z][a-z0-9]*$/i.test(node.tagName)) {
node.type = 'text'
node.value = `<${node.tagName}`
}
if (node.children) node.children.forEach(iterate)
}
tree.children.forEach(iterate)
}
},
]}
urlTransform={customUrlTransform}
disallowedElements={[
'iframe',
'head',
'html',
'meta',
'link',
'style',
'body',
...(props.customDisallowedElements || []),
]}
components={{
code: Code,
img: Img,
video: Video,
audio: Audio,
a: Link,
p: Paragraph,
button: MarkdownButton,
form: MarkdownForm,
script: Script as any,
details: Think,
}}>
{/* Markdown detect has problem. */}
{filteredContent}
</ReactMarkdown>
{contentObj.jsonContent && contentObj.jsonContent.is_chart == 'Y' ? (
<Chart content={contentObj.jsonContent} />
) : null}
</div>
{props.onJsonContentReady && contentObj.jsonContent ? (
<>{props.onJsonContentReady(contentObj.jsonContent)}</>
) : null}
</>
)
}