Commit 472df0ed by 李伟康

refactor(chat): 重构思考模块实现全局回调机制

- 移除Answer组件中的局部onThinkComplete回调,改用全局回调机制
- 在think模块中实现setGlobalOnThinkComplete函数管理全局回调
- 优化思考计时器逻辑,简化时间计算方式
- 更新报告组件样式,调整边框和圆角显示效果
- 修改发送按钮组件结构,添加容器盒子并支持响应式切换
- 调整全局样式中发送图标布局和遮罩效果
1 parent 56a15766
...@@ -11,6 +11,7 @@ import { useChatBodyContext } from '../body/context' ...@@ -11,6 +11,7 @@ import { useChatBodyContext } from '../body/context'
import { import {
Report Report
} from '@/app/components/base/markdown/blocks' } from '@/app/components/base/markdown/blocks'
import { setGlobalOnThinkComplete } from '@/app/components/base/markdown/blocks/think'
import s from './index.module.scss' import s from './index.module.scss'
type AnswerProps = { type AnswerProps = {
...@@ -21,6 +22,20 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => { ...@@ -21,6 +22,20 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => {
const [jsonContent, setJsonContent] = useState<any>(null) const [jsonContent, setJsonContent] = useState<any>(null)
const thinkingComplete = useRef(false) const thinkingComplete = useRef(false)
// 设置全局回调
useEffect(() => {
const handleThinkComplete = (isComplete: boolean) => {
console.log('chufa')
thinkingComplete.current = isComplete
}
setGlobalOnThinkComplete(handleThinkComplete)
// 清理函数
return () => {
setGlobalOnThinkComplete(null)
}
}, [])
if (!isAnswer) return null if (!isAnswer) return null
const handleJsonContentReady = (content: any) => { const handleJsonContentReady = (content: any) => {
...@@ -28,10 +43,6 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => { ...@@ -28,10 +43,6 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => {
return null // 不在 BasicContent 内部渲染 return null // 不在 BasicContent 内部渲染
} }
const handleThinkComplete = (isComplete: boolean) => {
console.log('chufa')
thinkingComplete.current = isComplete
}
return ( return (
<> <>
<div className="mb-2 flex last:mb-0"> <div className="mb-2 flex last:mb-0">
...@@ -52,7 +63,6 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => { ...@@ -52,7 +63,6 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => {
{/* 内容 */} {/* 内容 */}
<BasicContent <BasicContent
onJsonContentReady={handleJsonContentReady} onJsonContentReady={handleJsonContentReady}
onThinkComplete={handleThinkComplete}
/> />
</div> </div>
</div> </div>
......
...@@ -7,8 +7,15 @@ const Send: FC = () => { ...@@ -7,8 +7,15 @@ const Send: FC = () => {
const { handleSend } = useMessageContext() const { handleSend } = useMessageContext()
const { isResponding } = useChatRespondingContext() const { isResponding } = useChatRespondingContext()
const { onStopResponding: stopResponding } = useChatContext() const { onStopResponding: stopResponding } = useChatContext()
if (isResponding) return <img src={AI_DATA_STOP} onClick={stopResponding} alt="Stop" title="Stop" className='send-icon' /> return (
<>
return <img src={AI_DATA_SEND} onClick={handleSend} alt="Send" title="Send" className='send-icon' /> <div className="send-icon-box">
{isResponding && (
<img src={AI_DATA_STOP} onClick={stopResponding} alt="Stop" title="Stop" className="send-icon" />
)}
{!isResponding && <img src={AI_DATA_SEND} onClick={handleSend} alt="Send" title="Send" className="send-icon" />}
</div>
</>
)
} }
export default memo(Send) export default memo(Send)
...@@ -11,6 +11,13 @@ ...@@ -11,6 +11,13 @@
font-size: 16px; font-size: 16px;
font-weight: 500; font-weight: 500;
padding: 12px 12px 8px; padding: 12px 12px 8px;
border: 1px solid #fff;
border-bottom: none;
border-radius: 16px 16px 0 0;
background: #edf5ff;
position: relative;
z-index: 2;
.block { .block {
line-height: 24px; line-height: 24px;
height: 24px; height: 24px;
...@@ -29,12 +36,15 @@ ...@@ -29,12 +36,15 @@
height: 20px; height: 20px;
border-radius: 584px; border-radius: 584px;
background: linear-gradient(165deg, #4f72ff 10.64%, #4ea9fd 50%, #4ce0fc 89.36%); background: linear-gradient(165deg, #4f72ff 10.64%, #4ea9fd 50%, #4ce0fc 89.36%);
box-shadow: 2px 0 3px 0 rgba(131, 189, 255, 0.4); box-shadow: 2px 0 3px 0 rgba(131, 189, 255, 0.4);
display: block; display: block;
} }
} }
.expanded{
border-radius: 16px;
border-bottom: 1px solid #fff;
}
.arrow { .arrow {
margin-left: auto; margin-left: auto;
width: 18px; width: 18px;
......
...@@ -102,7 +102,7 @@ const Report: FC<ReportProps> = ({ content }) => { ...@@ -102,7 +102,7 @@ const Report: FC<ReportProps> = ({ content }) => {
<div className={cn(s['report-box'])}> <div className={cn(s['report-box'])}>
{reportUrl && ( {reportUrl && (
<> <>
<div className={cn(s['report-type-title'])} onClick={handleToggleExpand} style={{ cursor: 'pointer' }}> <div className={cn(s['report-type-title'], !isExpanded ? s['expanded'] : '')} onClick={handleToggleExpand} style={{ cursor: 'pointer' }}>
展业{report_type} 展业{report_type}
<div className={cn(s['block'])}>{reportDateText()}</div> <div className={cn(s['block'])}>{reportDateText()}</div>
<div className={cn(s['arrow'], 'transition-transform duration-500', isExpanded && 'rotate-180')}> <div className={cn(s['arrow'], 'transition-transform duration-500', isExpanded && 'rotate-180')}>
...@@ -130,7 +130,7 @@ const Report: FC<ReportProps> = ({ content }) => { ...@@ -130,7 +130,7 @@ const Report: FC<ReportProps> = ({ content }) => {
border: 'none', border: 'none',
display: 'block', display: 'block',
borderRadius: '0 0 16px 16px', borderRadius: '0 0 16px 16px',
minHeight: '600px', minHeight: '300px',
height: `${containerHeight}px`, height: `${containerHeight}px`,
}} }}
scrolling="no" scrolling="no"
......
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'
// 全局存储每个思考块的开始时间,key 为 children 的字符串表示
const thinkStartTimes = new Map<string, number>()
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
}
const useThinkTimer = (children: any) => {
const [elapsedTime, setElapsedTime] = useState(0)
const [isComplete, setIsComplete] = useState(false)
const timerRef = useRef<NodeJS.Timeout>()
const elapsedTimeRef = useRef<number>(0) // 用 ref 保存最新的 elapsed time
// 生成一个稳定的 key,基于 children 的内容
const childrenKey = React.useMemo(() => {
return 'think-block'
}, [])
// 获取或设置开始时间
let startTime = thinkStartTimes.get(childrenKey)
if (!startTime) {
startTime = Date.now()
thinkStartTimes.set(childrenKey, startTime)
}
useEffect(() => {
if (isComplete) return
timerRef.current = setInterval(() => {
const now = Date.now()
const elapsed = Math.floor((now - startTime!) / 100) / 10
elapsedTimeRef.current = elapsed // 同步更新 ref
setElapsedTime(elapsed)
}, 100)
return () => {
if (timerRef.current) clearInterval(timerRef.current)
}
}, [isComplete, startTime])
useEffect(() => {
const hasEnd = hasEndThink(children)
if (hasEnd) {
// 在设置为完成之前,先确保 elapsedTime 是最新的
setElapsedTime(elapsedTimeRef.current)
setIsComplete(true)
}
}, [children])
return { elapsedTime, isComplete }
}
export const Think = ({ children, ...props }: any) => {
const { elapsedTime, isComplete } = useThinkTimer(children)
const displayContent = removeEndThink(children)
const { t } = useTranslation()
// 当思考完成时,通知父组件
useEffect(() => {
if (isComplete && props.onThinkComplete) {
props.onThinkComplete(true)
}
}, [isComplete, props.onThinkComplete])
if (!(props['data-think'] ?? false)) return <details {...props}>{children}</details>
return (
<details {...(!isComplete && { open: true })} className="group">
<summary className="flex cursor-pointer select-none list-none items-center whitespace-nowrap font-bold text-text-secondary">
<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 group-open:rotate-180')}>
<img src="https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-arrow.png" alt="arrow" />
</div>
) : (
''
)}
</div>
</summary>
{displayContent ? (
<div className="ml-2 border-l border-components-panel-border pl-3 text-text-secondary think-class">
{displayContent}
</div>
) : (
null
)}
</details>
)
}
export default Think
\ No newline at end of file \ No newline at end of file
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
}
const useThinkTimer = (children: any) => {
const [startTime] = useState(Date.now())
const [elapsedTime, setElapsedTime] = useState(0)
const [isComplete, setIsComplete] = useState(false)
const timerRef = useRef<NodeJS.Timeout>()
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])
return { elapsedTime, isComplete }
}
export const Think = ({ children, ...props }: any) => {
const { elapsedTime, isComplete } = useThinkTimer(children)
const displayContent = 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])
if (!(props['data-think'] ?? false)) return <details {...props}>{children}</details>
return (
<details {...(!isComplete && { open: true })} className="group">
<summary className="flex cursor-pointer select-none list-none items-center whitespace-nowrap font-bold text-text-secondary">
<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 group-open:rotate-180')}>
<img src="https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-arrow.png" alt="arrow" />
</div>
) : (
''
)}
</div>
</summary>
{displayContent ? (
<div className=" border-l border-components-panel-border pl-2 text-text-secondary think-class">
{displayContent}
</div>
) : (
null
)}
</details>
)
}
export default Think
...@@ -158,7 +158,6 @@ export function Markdown(props: MarkdownProps) { ...@@ -158,7 +158,6 @@ export function Markdown(props: MarkdownProps) {
form: MarkdownForm, form: MarkdownForm,
script: Script as any, script: Script as any,
details: Think, details: Think,
// details: (thinkProps) => <Think {...thinkProps} onThinkComplete={props.onThinkComplete} />,
}}> }}>
{/* Markdown detect has problem. */} {/* Markdown detect has problem. */}
{filteredContent} {filteredContent}
......
...@@ -745,13 +745,39 @@ button:focus-within { ...@@ -745,13 +745,39 @@ button:focus-within {
min-height: 48px; min-height: 48px;
} }
.send-icon-box {
width: 40px;
height: 32px;
position: relative;
display: flex;
align-items: center;
overflow: hidden;
}
.send-icon-box::after {
content: "";
width: 40px;
height: 40px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: url('https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-btn-mask.png') center no-repeat;
background-size: contain;
}
.send-icon { .send-icon {
width: 32px; width: 32px;
height: 32px; height: 32px;
box-shadow: 2.667px 0 4px 0 rgba(131, 189, 255, 0.40); border-radius: 100%;
border-radius: 100%; transform: translateX(1px);
position: relative;
z-index: 2;
} }
.footer-icon{
.footer-icon {
width: 18px; width: 18px;
height: 18px; height: 18px;
} }
\ No newline at end of file \ 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!