Commit 56a15766 by 李伟康

feat(chat): 添加企业微信环境检测和思考块优化

- 添加useAuthGuard钩子检测是否在企业微信环境中运行
- 实现不在企业微信环境时跳转到提示页面
- 优化思考块显示效果和计时逻辑
- 添加思考完成状态回调通知机制
- 改进图表组件样式和数据处理
- 优化报告组件展开收起动画效果
- 调整聊天界面UI细节和布局样式
- 修复JSON代码块解析和显示问题
1 parent d440b375
'use client' 'use client'
import React from 'react' import React from 'react'
import ChatWithHistoryWrap from '@/app/components/base/chat/chat-with-history' import ChatWithHistoryWrap from '@/app/components/base/chat/chat-with-history'
import { useEffect } from 'react'
import { useRouter } from 'next/navigation'
export function useAuthGuard(options?: { allowPublic?: boolean }) {
const router = useRouter()
useEffect(() => {
const checkIsWorkWeChat = () => {
const ua = navigator.userAgent.toLowerCase()
const isWxWork = ua.includes('wxwork')
// if(!isWxWork) router.push('/not-work-wechat')
}
checkIsWorkWeChat()
}, [router, options])
}
const Chat = () => { const Chat = () => {
return ( useAuthGuard()
<ChatWithHistoryWrap /> return <ChatWithHistoryWrap />
)
} }
export default Chat export default Chat
.container{
display: flex;
align-items: center;
flex-direction: column;
justify-content: center;
padding: 0 60px;
height: 100vh;
}
.icon{
width: 160px;
height: 160px;
margin: auto;
}
.title {
color: #0A3479;
text-align: center;
font-size: 14px;
margin-bottom: 4px;
}
.description {
color: rgba(10, 52, 121, 0.60);
text-align: center;
font-size: 13px;
}
\ No newline at end of file \ No newline at end of file
'use client'
import React from 'react'
import cn from 'classnames'
import s from './index.module.scss'
const NotWorkWeChatPage = () => {
return (
<div className={cn(s['container'],'layout-bg')}>
<div className="max-w-md w-full text-center">
<img src="https://img02.glsx.com.cn/weapp/resource/saas/ai/not-ww.png" alt="Not Work WeChat" className={cn(s['icon'],)} />
{/* 标题文字 */}
<h1 className={cn(s['title'],)}>
请在企业微信中打开
</h1>
{/* 描述文字 */}
<p className={cn(s['description'],)}>
「AI 智能问数」功能仅支持在企业微信客户端中使用,请在企业微信中重新打开。
</p>
</div>
</div>
)
}
export default NotWorkWeChatPage
\ No newline at end of file \ No newline at end of file
...@@ -5,10 +5,11 @@ import cn from '@/utils/classnames' ...@@ -5,10 +5,11 @@ import cn from '@/utils/classnames'
import { useChatBodyContext } from '../../body/context' import { useChatBodyContext } from '../../body/context'
type BasicContentProps = { type BasicContentProps = {
onJsonContentReady?: (jsonContent: any) => React.ReactNode onJsonContentReady?: (jsonContent: any) => React.ReactNode,
onThinkComplete?: (isComplete: boolean) => void
} }
const BasicContent: FC<BasicContentProps> = ({ onJsonContentReady }) => { const BasicContent: FC<BasicContentProps> = ({ onJsonContentReady, onThinkComplete }) => {
const { annotation, content, isError, hasAgentThoughts } = useChatBodyContext() const { annotation, content, isError, hasAgentThoughts } = useChatBodyContext()
if (!content.trim() || hasAgentThoughts) return null if (!content.trim() || hasAgentThoughts) return null
...@@ -20,6 +21,8 @@ const BasicContent: FC<BasicContentProps> = ({ onJsonContentReady }) => { ...@@ -20,6 +21,8 @@ const BasicContent: FC<BasicContentProps> = ({ onJsonContentReady }) => {
className={cn(isError && '!text-[#F04438]')} className={cn(isError && '!text-[#F04438]')}
content={content} content={content}
onJsonContentReady={onJsonContentReady} onJsonContentReady={onJsonContentReady}
onThinkComplete={onThinkComplete}
/> />
) )
} }
......
...@@ -4,6 +4,6 @@ ...@@ -4,6 +4,6 @@
} }
.report-container{ .report-container{
margin: 16px 0; margin: 0 0 12px;
border-radius: 16px; border-radius: 16px;
} }
\ No newline at end of file \ No newline at end of file
...@@ -17,8 +17,9 @@ type AnswerProps = { ...@@ -17,8 +17,9 @@ type AnswerProps = {
chatAnswerContainerInner?: string chatAnswerContainerInner?: string
} }
const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => { const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => {
const { containerRef, contentRef, more, isAnswer } = useChatBodyContext() const { containerRef, contentRef, more, isAnswer, content } = useChatBodyContext()
const [jsonContent, setJsonContent] = useState<any>(null) const [jsonContent, setJsonContent] = useState<any>(null)
const thinkingComplete = useRef(false)
if (!isAnswer) return null if (!isAnswer) return null
...@@ -26,6 +27,11 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => { ...@@ -26,6 +27,11 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => {
setJsonContent(content) setJsonContent(content)
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">
...@@ -35,8 +41,9 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => { ...@@ -35,8 +41,9 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => {
<div <div
ref={contentRef} ref={contentRef}
className={cn( className={cn(
'body-lg-regular relative inline-block max-w-full rounded-2xl rounded-bl-none bg-chat-bubble-bg px-3 py-3 text-text-primary', 'body-lg-regular relative inline-block rounded-2xl rounded-bl-none bg-chat-bubble-bg px-3 py-3 text-text-primary',
s['chat-answer-container-inner'] s['chat-answer-container-inner'],
`${thinkingComplete.current ? 'w-full' : 'max-w-full'}`
)}> )}>
{/* 工具 */} {/* 工具 */}
{/* <Operation /> */} {/* <Operation /> */}
...@@ -45,6 +52,7 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => { ...@@ -45,6 +52,7 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => {
{/* 内容 */} {/* 内容 */}
<BasicContent <BasicContent
onJsonContentReady={handleJsonContentReady} onJsonContentReady={handleJsonContentReady}
onThinkComplete={handleThinkComplete}
/> />
</div> </div>
</div> </div>
...@@ -60,4 +68,4 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => { ...@@ -60,4 +68,4 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => {
</> </>
) )
} }
export default memo(Answer) export default memo(Answer)
\ No newline at end of file \ No newline at end of file
...@@ -76,7 +76,7 @@ const TextInput: React.FC<{ ...@@ -76,7 +76,7 @@ const TextInput: React.FC<{
}, [hasQuery]) }, [hasQuery])
return ( return (
// <div ref={wrapperRef} className="flex items-center justify-between"> // <div ref={wrapperRef} className="flex items-center justify-between">
<div ref={wrapperRef} className="flex items-center justify-between h-full m-h-48"> <div ref={wrapperRef} className="flex items-center justify-between h-full">
<div className="relative flex w-full grow items-center h-full"> <div className="relative flex w-full grow items-center h-full">
<div <div
ref={textValueRef} ref={textValueRef}
......
...@@ -2,7 +2,8 @@ ...@@ -2,7 +2,8 @@
min-height: 48px; min-height: 48px;
border-radius: 29px; border-radius: 29px;
background-color: #fff; background-color: #fff;
padding: 0 8px 0 16px; padding: 8px 8px 8px 16px;
box-sizing: border-box;
} }
.text-input{ .text-input{
font-size: 15px; font-size: 15px;
......
...@@ -18,9 +18,9 @@ const Question: FC = () => { ...@@ -18,9 +18,9 @@ const Question: FC = () => {
const { content, theme } = useChatBodyContext() const { content, theme } = useChatBodyContext()
return ( return (
<div className="mb-2 flex justify-end pl-14 last:mb-0"> <div className="mb-2 flex justify-end pl-14 last:mb-0">
<div className={cn('group', 'relative', 'mr-2', 'max-w-full')}> <div className={cn('group', 'relative', 'max-w-full')}>
<div <div
className={cn('rounded-br-none bg-[#3773F8] px-3 py-3 text-sm text-gray-900', s['question-boder'])} className={cn('rounded-br-none bg-[#3773F8] px-3 py-2 text-sm text-gray-900', s['question-boder'])}
style={theme?.chatBubbleColorStyle ? CssTransform(theme?.chatBubbleColorStyle) : {}}> style={theme?.chatBubbleColorStyle ? CssTransform(theme?.chatBubbleColorStyle) : {}}>
{/* {!!message_files?.length && <FileList files={message_files} showDeleteAction={false} showDownloadAction={true} />} */} {/* {!!message_files?.length && <FileList files={message_files} showDeleteAction={false} showDownloadAction={true} />} */}
<Markdown content={content} className='!text-white' /> <Markdown content={content} className='!text-white' />
......
...@@ -26,8 +26,8 @@ export const LOADING_ICON = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/lo ...@@ -26,8 +26,8 @@ export const LOADING_ICON = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/lo
export const AI_TIPS = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-tips.png' export const AI_TIPS = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-tips.png'
export const AI_DATA_SEND = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-send.png' export const AI_DATA_SEND = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-send.png?v=1'
export const AI_DATA_STOP = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-stop.png' export const AI_DATA_STOP = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-stop.png?v=1'
export const AI_DATA_CLEAR = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-clear.png' export const AI_DATA_CLEAR = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-clear.png'
export const AI_DATA_SETTING = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-setting.png' export const AI_DATA_SETTING = 'https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-setting.png'
......
...@@ -5,7 +5,6 @@ type ChartProps = { ...@@ -5,7 +5,6 @@ type ChartProps = {
content: any | null content: any | null
} }
const Chart: FC<ChartProps> = ({ content }) => { const Chart: FC<ChartProps> = ({ content }) => {
const chartData = content const chartData = content
if (!chartData || !chartData.chart?.[0]) { if (!chartData || !chartData.chart?.[0]) {
...@@ -13,11 +12,11 @@ const Chart: FC<ChartProps> = ({ content }) => { ...@@ -13,11 +12,11 @@ const Chart: FC<ChartProps> = ({ content }) => {
} }
if (chartData.is_chart == 'N') return null if (chartData.is_chart == 'N') return null
let [data_1, data_2] = chartData.chart let [data_1, data_2] = chartData.chart
let { type, metric } = data_1 let { type, metric } = data_1
let option: any = {} let option: any = {}
let title = '' let title = ''
let legendData = [metric] let legendData = [metric]
if(data_2) legendData = [metric, data_2.metric] if (data_2) legendData = [metric, data_2.metric]
if (type == 'bar' || type == 'line') { if (type == 'bar' || type == 'line') {
option = { option = {
grid: { grid: {
...@@ -38,7 +37,7 @@ const Chart: FC<ChartProps> = ({ content }) => { ...@@ -38,7 +37,7 @@ const Chart: FC<ChartProps> = ({ content }) => {
}, },
xAxis: { xAxis: {
type: 'category', type: 'category',
boundaryGap:type == 'bar', boundaryGap: type == 'bar',
data: data_1.name, data: data_1.name,
splitLine: { splitLine: {
show: true, show: true,
...@@ -135,7 +134,7 @@ const Chart: FC<ChartProps> = ({ content }) => { ...@@ -135,7 +134,7 @@ const Chart: FC<ChartProps> = ({ content }) => {
option = { option = {
color: ['#2A82E4', '#00BAAD', '#43CF7C', '#A5D63F', '#FF8D1A', '#FFC300', '#7948EA', '#C6C6C6'], color: ['#2A82E4', '#00BAAD', '#43CF7C', '#A5D63F', '#FF8D1A', '#FFC300', '#7948EA', '#C6C6C6'],
legend: { legend: {
left: '50%', left: '52%',
top: 'center', top: 'center',
orient: 'vertical', orient: 'vertical',
itemWidth: 8, itemWidth: 8,
...@@ -143,15 +142,17 @@ const Chart: FC<ChartProps> = ({ content }) => { ...@@ -143,15 +142,17 @@ const Chart: FC<ChartProps> = ({ content }) => {
textStyle: { textStyle: {
fontSize: 12, fontSize: 12,
color: '#133368', color: '#133368',
overflow: 'truncate',
width: 130,
}, },
itemGap: 8, itemGap: 8,
}, },
series: [ series: [
{ {
type: 'pie', type: 'pie',
radius: ['30%', '50%'], radius: ['35%', '50%'],
center: ['20%', '50%'], center: ['22%', '50%'],
padAngle: 5, padAngle: 3,
label: { label: {
show: false, show: false,
position: 'center', position: 'center',
...@@ -159,20 +160,23 @@ const Chart: FC<ChartProps> = ({ content }) => { ...@@ -159,20 +160,23 @@ const Chart: FC<ChartProps> = ({ content }) => {
labelLine: { labelLine: {
show: false, show: false,
}, },
emphasis: {
disabled: true,
},
data: (() => { data: (() => {
const dataArray = data_1.data || [] const dataArray = data_1.data || []
const nameArray = data_1.name || [] const nameArray = data_1.name || []
if (dataArray.length <= 7) { if (dataArray.length <= 7) {
return dataArray.map((item, index) => ({ value: item, name: nameArray[index] })) return dataArray.map((item: any, index: number) => ({ value: item, name: nameArray[index] }))
} }
const top7 = dataArray.slice(0, 7).map((item, index) => ({ const top7 = dataArray.slice(0, 7).map((item: any, index: number) => ({
value: item, value: item,
name: nameArray[index], name: nameArray[index],
})) }))
const otherSum = dataArray.slice(7).reduce((sum, val) => sum + val, 0) const otherSum = dataArray.slice(7).reduce((sum: number, val: number) => sum + val, 0 as number)
return [...top7, { value: otherSum, name: '其他' }] return [...top7, { value: otherSum, name: '其他' }]
})(), })(),
......
...@@ -29,7 +29,15 @@ ...@@ -29,7 +29,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;
} }
}
.arrow {
margin-left: auto;
width: 18px;
height: 18px;
} }
\ No newline at end of file \ No newline at end of file
...@@ -3,6 +3,9 @@ import { useStore } from '@/app/components/app/store' ...@@ -3,6 +3,9 @@ import { useStore } from '@/app/components/app/store'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import s from './index.module.scss' import s from './index.module.scss'
import Toast from '@/app/components/base/toast'
import { GET_PARAMS } from '@/app/components/base/chat/constants'
type ReportProps = { type ReportProps = {
content: any | null content: any | null
} }
...@@ -11,8 +14,65 @@ const Report: FC<ReportProps> = ({ content }) => { ...@@ -11,8 +14,65 @@ const Report: FC<ReportProps> = ({ content }) => {
const { globalConfig } = useStore.getState() const { globalConfig } = useStore.getState()
const { report_end_date, report_start_date, report_type } = content const { report_end_date, report_start_date, report_type } = content
const reportType = report_type == '周报' ? 1 : 2 const reportType = report_type == '周报' ? 1 : 2
const [isExpanded, setIsExpanded] = useState(true)
const iframeRef = useRef<HTMLIFrameElement>(null) const iframeRef = useRef<HTMLIFrameElement>(null)
const [iframeHeight, setIframeHeight] = useState(500) // 默认高度 const containerRef = useRef<HTMLDivElement>(null)
const [containerHeight, setContainerHeight] = useState(800)
const handleToggleExpand = () => {
setIsExpanded(!isExpanded)
}
// 监听来自 iframe 的消息
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
if (event.data && event.data.type === 'RESIZE_IFRAME') {
const height = event.data.height
if (height && height > 0) {
setContainerHeight(height)
console.log('收到 iframe 高度:', height)
}
}
if (event.data && event.data.type === 'COPY_SUCCESS') {
Toast.notify({
message: '链接复制成功,快去粘贴吧~',
type: 'success',
})
}
}
window.addEventListener('message', handleMessage)
return () => {
window.removeEventListener('message', handleMessage)
}
}, [])
// 向 iframe 发送获取高度的消息
const requestIframeHeight = () => {
if (iframeRef.current && iframeRef.current.contentWindow) {
iframeRef.current.contentWindow.postMessage({ type: 'GET_IFRAME_HEIGHT' }, '*')
}
}
// iframe 加载完成后请求高度
const handleIframeLoad = () => {
console.log('iframe 加载完成,请求高度')
// 延迟发送,确保 iframe 内部内容已渲染
setTimeout(() => {
requestIframeHeight()
}, 300)
}
// 展开时也请求一次高度
useEffect(() => {
if (isExpanded) {
setTimeout(() => {
requestIframeHeight()
}, 100)
}
}, [isExpanded])
const reportDateText = () => { const reportDateText = () => {
if (!report_start_date) return '' if (!report_start_date) return ''
...@@ -34,50 +94,51 @@ const Report: FC<ReportProps> = ({ content }) => { ...@@ -34,50 +94,51 @@ const Report: FC<ReportProps> = ({ content }) => {
console.warn('全局配置尚未加载') console.warn('全局配置尚未加载')
return null return null
} }
if (!report_start_date || !report_end_date) return null
const corpId = GET_PARAMS.get('corpId')
let { reportUrl } = globalConfig let { reportUrl } = globalConfig
reportUrl += `?reportStartDate=${report_start_date}&reportEndDate=${report_end_date}&reportType=${reportType}` reportUrl += `?reportStartDate=${report_start_date}&reportEndDate=${report_end_date}&reportType=${reportType}&corpId=${corpId}`
const handleIframeLoad = () => {
if (iframeRef.current) {
try {
// 获取 iframe 内部文档的高度
const iframeDoc = iframeRef.current.contentDocument || iframeRef.current.contentWindow?.document
if (iframeDoc?.body) {
const height = Math.max(
iframeDoc.body.scrollHeight,
iframeDoc.body.offsetHeight,
iframeDoc.documentElement.scrollHeight,
iframeDoc.documentElement.offsetHeight,
)
setIframeHeight(height)
}
} catch (error) {
console.warn('无法获取 iframe 高度,可能由于跨域限制:', error)
// 跨域时使用默认高度或估算高度
setIframeHeight(800)
}
}
}
return ( return (
<div className={cn(s['report-box'])}> <div className={cn(s['report-box'])}>
{reportUrl && ( {reportUrl && (
<div className={cn(s['report-type-title'])}> <>
展业{report_type} <div className={cn(s['report-type-title'])} onClick={handleToggleExpand} style={{ cursor: 'pointer' }}>
<div className={cn(s['block'])}>{reportDateText()}</div> 展业{report_type}
</div> <div className={cn(s['block'])}>{reportDateText()}</div>
<div className={cn(s['arrow'], 'transition-transform duration-500', isExpanded && 'rotate-180')}>
<img src="https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-arrow.png" alt="arrow" />
</div>
</div>
{/* 外层控制高度的容器 */}
<div
style={{
overflow: 'hidden',
transition: 'height 0.5s ease',
height: isExpanded ? `${containerHeight}px` : '0px',
}}>
{/* 实际内容容器 */}
<div ref={containerRef} style={{ height: '100%' }}>
<iframe
ref={iframeRef}
src={reportUrl}
title="报告预览"
width="100%"
height={containerHeight}
onLoad={handleIframeLoad}
style={{
border: 'none',
display: 'block',
borderRadius: '0 0 16px 16px',
minHeight: '600px',
height: `${containerHeight}px`,
}}
scrolling="no"
/>
</div>
</div>
</>
)} )}
{reportUrl ? (
<iframe
ref={iframeRef}
src={reportUrl}
title="报告预览"
width="100%"
height={iframeHeight}
onLoad={handleIframeLoad}
style={{ border: 'none', display: 'block', borderRadius: '16px' }}
/>
) : null}
</div> </div>
) )
} }
......
...@@ -3,6 +3,9 @@ import { useTranslation } from 'react-i18next' ...@@ -3,6 +3,9 @@ import { useTranslation } from 'react-i18next'
import LoadingIcon from '@/app/components/base/chat/chat/answer/components/loading-icon' import LoadingIcon from '@/app/components/base/chat/chat/answer/components/loading-icon'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import s from '../chat.module.css' import s from '../chat.module.css'
// 全局存储每个思考块的开始时间,key 为 children 的字符串表示
const thinkStartTimes = new Map<string, number>()
const hasEndThink = (children: any): boolean => { const hasEndThink = (children: any): boolean => {
if (typeof children === 'string') return children.includes('[ENDTHINKFLAG]') if (typeof children === 'string') return children.includes('[ENDTHINKFLAG]')
...@@ -29,25 +32,45 @@ const removeEndThink = (children: any): any => { ...@@ -29,25 +32,45 @@ const removeEndThink = (children: any): any => {
} }
const useThinkTimer = (children: any) => { const useThinkTimer = (children: any) => {
const [startTime] = useState(Date.now())
const [elapsedTime, setElapsedTime] = useState(0) const [elapsedTime, setElapsedTime] = useState(0)
const [isComplete, setIsComplete] = useState(false) const [isComplete, setIsComplete] = useState(false)
const timerRef = useRef<NodeJS.Timeout>() 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(() => { useEffect(() => {
if (isComplete) return if (isComplete) return
timerRef.current = setInterval(() => { timerRef.current = setInterval(() => {
setElapsedTime(Math.floor((Date.now() - startTime) / 100) / 10) const now = Date.now()
const elapsed = Math.floor((now - startTime!) / 100) / 10
elapsedTimeRef.current = elapsed // 同步更新 ref
setElapsedTime(elapsed)
}, 100) }, 100)
return () => { return () => {
if (timerRef.current) clearInterval(timerRef.current) if (timerRef.current) clearInterval(timerRef.current)
} }
}, [startTime, isComplete]) }, [isComplete, startTime])
useEffect(() => { useEffect(() => {
if (hasEndThink(children)) setIsComplete(true) const hasEnd = hasEndThink(children)
if (hasEnd) {
// 在设置为完成之前,先确保 elapsedTime 是最新的
setElapsedTime(elapsedTimeRef.current)
setIsComplete(true)
}
}, [children]) }, [children])
return { elapsedTime, isComplete } return { elapsedTime, isComplete }
...@@ -58,11 +81,18 @@ export const Think = ({ children, ...props }: any) => { ...@@ -58,11 +81,18 @@ export const Think = ({ children, ...props }: any) => {
const displayContent = removeEndThink(children) const displayContent = removeEndThink(children)
const { t } = useTranslation() const { t } = useTranslation()
// 当思考完成时,通知父组件
useEffect(() => {
if (isComplete && props.onThinkComplete) {
props.onThinkComplete(true)
}
}, [isComplete, props.onThinkComplete])
if (!(props['data-think'] ?? false)) return <details {...props}>{children}</details> if (!(props['data-think'] ?? false)) return <details {...props}>{children}</details>
return ( return (
<details {...(!isComplete && { open: true })} className="group"> <details {...(!isComplete && { open: true })} className="group">
<summary className="flex cursor-pointer select-none list-none items-center whitespace-nowrap pl-2 font-bold text-text-secondary"> <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"> <div className="flex shrink-0 items-center think-class">
{/* <svg {/* <svg
className="mr-2 h-3 w-3 transition-transform duration-500 group-open:rotate-90" className="mr-2 h-3 w-3 transition-transform duration-500 group-open:rotate-90"
...@@ -72,7 +102,9 @@ export const Think = ({ children, ...props }: any) => { ...@@ -72,7 +102,9 @@ export const Think = ({ children, ...props }: any) => {
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg> */} </svg> */}
<LoadingIcon /> <LoadingIcon />
{isComplete ? `${t('common.chat.thought')}\t(${elapsedTime.toFixed(1)}s)` : `${t('common.chat.thinking')}`} <span className={!isComplete ? s['text-shimmer'] : ''}>
{isComplete ? `${t('common.chat.thought')}\t(${elapsedTime.toFixed(1)}s)` : `${t('common.chat.thinking')}`}
</span>
{isComplete ? ( {isComplete ? (
<div className={cn(s['arrow'], 'transition-transform duration-500 group-open:rotate-180')}> <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" /> <img src="https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-arrow.png" alt="arrow" />
...@@ -83,7 +115,7 @@ export const Think = ({ children, ...props }: any) => { ...@@ -83,7 +115,7 @@ export const Think = ({ children, ...props }: any) => {
</div> </div>
</summary> </summary>
{displayContent ? ( {displayContent ? (
<div className="ml-2 border-l border-components-panel-border p-3 text-text-secondary think-class"> <div className="ml-2 border-l border-components-panel-border pl-3 text-text-secondary think-class">
{displayContent} {displayContent}
</div> </div>
) : ( ) : (
...@@ -93,4 +125,4 @@ export const Think = ({ children, ...props }: any) => { ...@@ -93,4 +125,4 @@ export const Think = ({ children, ...props }: any) => {
) )
} }
export default Think export default Think
\ No newline at end of file \ No newline at end of file
...@@ -19,6 +19,31 @@ ...@@ -19,6 +19,31 @@
border: none !important; border: none !important;
} }
@keyframes textShimmer {
0% {
background-position: 200% center;
}
100% {
background-position: -200% center;
}
}
.text-shimmer {
background: linear-gradient(
120deg,
rgba(19, 51, 104, 0.6) 0%,
rgba(19, 51, 104, 0.6) 45%,
rgba(19, 51, 104, 0.1),
rgba(19, 51, 104, 0.6) 55%,
rgba(19, 51, 104, 0.6) 100%
);
background-size: 200% auto;
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
animation: textShimmer 2s linear infinite;
}
.report-container { .report-container {
width: calc(100vw - 52px); width: calc(100vw - 52px);
} }
\ No newline at end of file \ No newline at end of file
...@@ -36,7 +36,8 @@ type MarkdownProps = { ...@@ -36,7 +36,8 @@ type MarkdownProps = {
className?: string className?: string
customDisallowedElements?: string[] customDisallowedElements?: string[]
operationClassName?: string operationClassName?: string
onJsonContentReady?: (jsonContent: any) => React.ReactNode onJsonContentReady?: (jsonContent: any) => React.ReactNode,
onThinkComplete?: (isComplete: boolean) => void
} }
type MarkdownContent = { type MarkdownContent = {
...@@ -47,34 +48,69 @@ type MarkdownContent = { ...@@ -47,34 +48,69 @@ type MarkdownContent = {
export function Markdown(props: MarkdownProps) { export function Markdown(props: MarkdownProps) {
const processedContent = flow([preprocessThinkTag, preprocessLaTeX])(props.content) const processedContent = flow([preprocessThinkTag, preprocessLaTeX])(props.content)
const contentObj: MarkdownContent = useMemo(() => { const contentObj: MarkdownContent = useMemo(() => {
const jsonCodeBlockRegex = /```json\s*[\s\S]*?```/g let mainContent = processedContent
const match = jsonCodeBlockRegex.exec(processedContent) let jsonContent: any = null
if (match && match.index !== undefined) {
const mainContent = processedContent.substring(0, match.index)
// 提取第一个 ```json 块的内容
const jsonBlock = match[0]
// 移除 ```json 和 ``` 标记
const jsonContent = jsonBlock
.replace(/^```json\s*/, '')
.replace(/\s*```$/, '')
.trim()
// 查找所有 ```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 { try {
const parsedJson = JSON.parse(jsonContent) const parsed = JSON.parse(jsonStr)
return { mainContent, jsonContent: parsedJson } allJsonBlocks.push(parsed)
} catch (e) { } catch (e) {
console.error('JSON 解析失败:', e) console.error('JSON 解析失败:', e, '原始内容:', jsonStr)
console.error('原始 JSON 内容:', jsonContent)
// JSON 解析失败时,将整个内容作为 mainContent
return { mainContent: processedContent }
} }
} }
// 取最后一个解析成功的 JSON
if (allJsonBlocks.length > 0) {
jsonContent = allJsonBlocks[allJsonBlocks.length - 1]
}
// 第二步:彻底移除所有代码块
mainContent = mainContent
// 移除 ```json 代码块(支持多种格式)
.replace(/```json\r?\n([\s\S]*?)\r?\n```/g, '')
.replace(/```json([\s\S]*?)```/g, '')
// 移除其他代码块
.replace(/```\r?\n([\s\S]*?)\r?\n```/g, '')
.replace(/```([\s\S]*?)```/g, '')
// 清理空行
.replace(/\n\s*\n\s*\n/g, '\n\n')
.replace(/^\s*\n/gm, '')
.trim()
return { mainContent: processedContent } return { mainContent, jsonContent }
}, [processedContent]) }, [processedContent])
const latexContent = contentObj.mainContent const latexContent = contentObj.mainContent
// 强行过滤所有代码块内容
const filteredContent = useMemo(() => {
if (!latexContent) return ''
let filtered = latexContent
// 移除所有 ```json 代码块
filtered = filtered.replace(/```json\s*[\s\S]*?```/g, '')
// 移除所有其他代码块
filtered = filtered.replace(/```\s*[\s\S]*?```/g, '')
// 清理连续空行
filtered = filtered.replace(/\n{3,}/g, '\n\n')
// 移除行首的空白行
filtered = filtered.replace(/^\s*\n/gm, '')
return filtered.trim()
}, [latexContent])
return ( return (
<> <>
<div className={cn('markdown-body ', '!text-text-primary', props.className)}> <div className={cn('markdown-body ', '!text-text-primary', props.className)}>
...@@ -122,9 +158,10 @@ export function Markdown(props: MarkdownProps) { ...@@ -122,9 +158,10 @@ 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. */}
{latexContent} {filteredContent}
</ReactMarkdown> </ReactMarkdown>
{contentObj.jsonContent && contentObj.jsonContent.is_chart == 'Y' ? ( {contentObj.jsonContent && contentObj.jsonContent.is_chart == 'Y' ? (
<Chart content={contentObj.jsonContent} /> <Chart content={contentObj.jsonContent} />
......
...@@ -748,6 +748,8 @@ button:focus-within { ...@@ -748,6 +748,8 @@ button:focus-within {
.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%;
} }
.footer-icon{ .footer-icon{
width: 18px; width: 18px;
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!