think.tsx 5.52 KB
import React, { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import LoadingIcon from '@/app/components/base/chat/chat/answer/components/loading-icon'
import cn from '@/utils/classnames'
import s from '../chat.module.css'

// Global storage for onThinkComplete callback
let globalOnThinkComplete: ((isComplete: boolean) => void) | null = null

// Function to set the global callback
export const setGlobalOnThinkComplete = (callback: ((isComplete: boolean) => void) | null) => {
  globalOnThinkComplete = callback
}

const hasEndThink = (children: any): boolean => {
  if (typeof children === 'string') return children.includes('[ENDTHINKFLAG]')

  if (Array.isArray(children)) return children.some(child => hasEndThink(child))

  if (children?.props?.children) return hasEndThink(children.props.children)

  return false
}

const removeEndThink = (children: any): any => {
  if (typeof children === 'string') return children.replace('[ENDTHINKFLAG]', '')

  if (Array.isArray(children)) return children.map(child => removeEndThink(child))

  if (children?.props?.children) {
    return React.cloneElement(children, {
      ...children.props,
      children: removeEndThink(children.props.children),
    })
  }

  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)
  const [isComplete, setIsComplete] = useState(false)
  const timerRef = useRef<NodeJS.Timeout>()
  const [isOpen, setIsOpen] = useState(false)

  useEffect(() => {
    if (isComplete) return

    timerRef.current = setInterval(() => {
      setElapsedTime(Math.floor((Date.now() - startTime) / 100) / 10)
    }, 100)

    return () => {
      if (timerRef.current) clearInterval(timerRef.current)
    }
  }, [startTime, isComplete])

  useEffect(() => {
    if (hasEndThink(children)) setIsComplete(true)
  }, [children])

  // Initialize open state based on completion status
  useEffect(() => {
    if (!isComplete) {
      setIsOpen(true)
    }
  }, [isComplete])

  return { elapsedTime, isComplete, isOpen, setIsOpen }
}

export const Think = ({ children, ...props }: any) => {
  const { elapsedTime, isComplete, isOpen, setIsOpen } = useThinkTimer(children)
  const displayContent = flattenNestedThink(removeEndThink(children))
  const { t } = useTranslation()

  // Notify parent component when thinking is complete
  useEffect(() => {
    if (isComplete) {
      // Use props callback first, fallback to global callback
      const callback = props.onThinkComplete || globalOnThinkComplete
      if (callback) {
        callback(true)
      }
    }
  }, [isComplete, props.onThinkComplete])

  // Handle summary click to toggle without scrolling
  const handleSummaryClick = (e: React.MouseEvent<HTMLElement>) => {
    e.preventDefault()
    e.stopPropagation()

    // Disable toggle when thinking is not complete
    if (!isComplete) return

    // Toggle the open state manually
    setIsOpen(!isOpen)
  }

  if (!(props['data-think'] ?? false)) return <details {...props}>{children}</details>

  return (
    <details open={isOpen} className="group">
      <summary
        className={cn(
          'flex cursor-pointer select-none list-none items-center whitespace-nowrap font-bold text-text-secondary',
        )}
        onClick={handleSummaryClick}>
        <div className="flex shrink-0 items-center think-class">
          {/* <svg
            className="mr-2 h-3 w-3 transition-transform duration-500 group-open:rotate-90"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
          </svg> */}
          <LoadingIcon />
          <span className={!isComplete ? s['text-shimmer'] : ''}>
            {isComplete ? `${t('common.chat.thought')}\t(${elapsedTime.toFixed(1)}s)` : `${t('common.chat.thinking')}`}
          </span>
          {isComplete ? (
            <div className={cn(s['arrow'], 'transition-transform duration-500', isOpen ? 'rotate-180' : '')}>
              <img src="https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-arrow.png" alt="arrow" />
            </div>
          ) : (
            ''
          )}
        </div>
      </summary>
      {displayContent && isOpen ? (
        <div className="pt-2 border-l border-components-panel-border pl-2 text-text-secondary think-class">
          {displayContent}
        </div>
      ) : null}
    </details>
  )
}

export default Think