index.tsx 9.66 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, 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>
    </>
  )
}