index.tsx
9.66 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
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, Review } 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 状态
isAnswer?: boolean // 标识是否为回答内容
}
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])
// 创建 ref 来引用 markdown 容器
const markdownRef = useRef<HTMLDivElement>(null)
const [shouldAutoScroll, setShouldAutoScroll] = useState(true)
// 用于跟踪已通知的 JSON 内容,避免重复调用回调导致死循环
const notifiedJsonRef = useRef<any>(null)
// 暴露禁用自动滚动的方法给子组件
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',
})
})
}
}
}, [contentObj.mainContent, contentObj.jsonContent, shouldAutoScroll, props.responding])
// 如果过滤后内容为空且没有 JSON 内容,则不渲染任何内容
if (!contentObj.mainContent && !contentObj.jsonContent) {
return null
}
// 尝试将 mainContent 中的 JSON 字符串转换为对象
let parsedJsonFromMainContent: any = null
if (contentObj.mainContent) {
try {
// 尝试直接解析整个内容
parsedJsonFromMainContent = JSON.parse(contentObj.mainContent)
} catch (e) {
// 如果不是有效的 JSON,尝试提取 JSON 部分
try {
// 查找第一个 { 和最后一个 } 之间的内容
const jsonMatch = contentObj.mainContent.match(/\{[\s\S]*\}/)
if (jsonMatch) {
parsedJsonFromMainContent = JSON.parse(jsonMatch[0])
}
} catch (e2) {
console.error('从 mainContent 解析 JSON 失败:', e2)
}
}
}
// 当解析到新的 JSON 内容时,通知父组件
useEffect(() => {
if (parsedJsonFromMainContent && props.isAnswer && props.onJsonContentReady) {
// 使用 JSON.stringify 进行深度比较,避免引用不同但内容相同的情况
const currentJsonStr = JSON.stringify(parsedJsonFromMainContent)
const notifiedJsonStr = notifiedJsonRef.current ? JSON.stringify(notifiedJsonRef.current) : null
// 只有当 JSON 内容真正发生变化时才调用回调
if (currentJsonStr !== notifiedJsonStr) {
notifiedJsonRef.current = parsedJsonFromMainContent
props.onJsonContentReady(parsedJsonFromMainContent)
}
} else if (!parsedJsonFromMainContent) {
// 如果没有 JSON 内容,重置 ref
notifiedJsonRef.current = null
}
}, [parsedJsonFromMainContent, props.isAnswer, props.onJsonContentReady])
if(parsedJsonFromMainContent && props.isAnswer) 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,
}}>
{contentObj.mainContent}
</ReactMarkdown>
</div>
</>
)
}