Commit 85696125 by 李伟康

fix(markdown): 解决嵌套Think组件渲染问题

- 添加flattenNestedThink函数处理嵌套details元素转换为div
- 在Think组件中应用flattenNestedThink修复重渲染问题
- 添加嵌套details标签检测和清理逻辑
- 优化滚动行为配置确保平滑滚动
- 简化导入语句和代码格式调整
1 parent ad0f02e0
......@@ -37,6 +37,37 @@ const removeEndThink = (children: any): any => {
return children
}
// Convert nested details elements to div to prevent Think component re-rendering
// 只过滤内层嵌套的 Think 组件,不影响外层
const flattenNestedThink = (children: any): any => {
if (!children) return null
if (typeof children === 'string') return children
if (Array.isArray(children)) {
return children.map(child => flattenNestedThink(child))
}
// If it's a details element with data-think, convert it to div
// 这里处理的是内层嵌套的 Think
if (children.type === 'details' || children.props?.['data-think']) {
return React.cloneElement(children, {
...children.props,
as: 'div',
'data-think': undefined,
open: true,
})
}
if (children.props?.children) {
return React.cloneElement(children, {
...children.props,
children: flattenNestedThink(children.props.children),
})
}
return children
}
const useThinkTimer = (children: any) => {
const [startTime] = useState(Date.now())
const [elapsedTime, setElapsedTime] = useState(0)
......@@ -72,7 +103,7 @@ const useThinkTimer = (children: any) => {
export const Think = ({ children, ...props }: any) => {
const { elapsedTime, isComplete, isOpen, setIsOpen } = useThinkTimer(children)
const displayContent = removeEndThink(children)
const displayContent = flattenNestedThink(removeEndThink(children))
const { t } = useTranslation()
// Notify parent component when thinking is complete
......
......@@ -8,19 +8,7 @@ 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 { Audio, Code, Img, Link, MarkdownButton, MarkdownForm, Paragraph, Script, Think, Video, Chart } from './blocks'
import { useMemo, useEffect, useRef, useState } from 'react'
/**
......@@ -36,7 +24,7 @@ type MarkdownProps = {
className?: string
customDisallowedElements?: string[]
operationClassName?: string
onJsonContentReady?: (jsonContent: any) => React.ReactNode,
onJsonContentReady?: (jsonContent: any) => React.ReactNode
onThinkComplete?: (isComplete: boolean) => void
hideThink?: boolean
responding?: boolean // 添加 responding 状态
......@@ -57,7 +45,7 @@ export function Markdown(props: MarkdownProps) {
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()
......@@ -68,7 +56,7 @@ export function Markdown(props: MarkdownProps) {
console.error('JSON 解析失败:', e, '原始内容:', jsonStr)
}
}
// 取最后一个解析成功的 JSON
if (allJsonBlocks.length > 0) {
jsonContent = allJsonBlocks[allJsonBlocks.length - 1]
......@@ -86,25 +74,40 @@ export function Markdown(props: MarkdownProps) {
.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
// 强行过滤所有代码块内容
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, '')
}
// 移除所有 ```json 和 ``` 标记,无论它们是否成对出现
filtered = filtered.replace(/```json\s*/gi, '')
filtered = filtered.replace(/```\s*/gi, '')
......@@ -122,7 +125,7 @@ export function Markdown(props: MarkdownProps) {
;(window as any).__disableMarkdownAutoScroll = () => {
setShouldAutoScroll(false)
}
return () => {
delete (window as any).__disableMarkdownAutoScroll
}
......@@ -165,23 +168,23 @@ export function Markdown(props: MarkdownProps) {
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'
behavior: 'smooth',
})
})
}
......@@ -195,9 +198,7 @@ export function Markdown(props: MarkdownProps) {
return (
<>
<div
ref={markdownRef}
className={cn('markdown-body ', '!text-text-primary', props.className)}>
<div ref={markdownRef} className={cn('markdown-body ', '!text-text-primary', props.className)}>
<ReactMarkdown
remarkPlugins={[RemarkGfm, [RemarkMath, { singleDollarTextMath: false }], RemarkBreaks]}
rehypePlugins={[
......@@ -255,4 +256,4 @@ export function Markdown(props: MarkdownProps) {
) : null}
</>
)
}
\ No newline at end of file
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!