index.tsx 10.6 KB
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}
    </>
  )
}