Commit 543e8e26 by 前端

Merge branch 'SAAS+V5.7.1' into 'master'

上线合并

See merge request !2
2 parents d9eec20f ecff0ea9
Showing 32 changed files with 888 additions and 196 deletions
...@@ -10,7 +10,7 @@ export function useAuthGuard(options?: { allowPublic?: boolean }) { ...@@ -10,7 +10,7 @@ export function useAuthGuard(options?: { allowPublic?: boolean }) {
const checkIsWorkWeChat = () => { const checkIsWorkWeChat = () => {
const ua = navigator.userAgent.toLowerCase() const ua = navigator.userAgent.toLowerCase()
const isWxWork = ua.includes('wxwork') const isWxWork = ua.includes('wxwork')
// if(!isWxWork) router.push('/not-work-wechat') if(!isWxWork) router.push('/not-work-wechat')
} }
checkIsWorkWeChat() checkIsWorkWeChat()
......
'use client'
import { useEffect, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import Loading from '@/app/components/base/loading'
export default function SettingPage() {
const searchParams = useSearchParams()
const [url, setUrl] = useState('')
const [loading, setLoading] = useState(true)
useEffect(() => {
const settingUrl = searchParams.get('settingUrl')
const sessionId = searchParams.get('sessionId')
const corpId = searchParams.get('corpId')
if (settingUrl) {
let fullUrl = decodeURIComponent(settingUrl)
if (sessionId || corpId) {
const separator = fullUrl.includes('?') ? '&' : '?'
const params = []
if (sessionId) params.push(`sessionId=${sessionId}`)
if (corpId) params.push(`corpId=${corpId}`)
fullUrl = `${fullUrl}${separator}${params.join('&')}`
}
setUrl(fullUrl)
setLoading(false)
} else {
setLoading(false)
}
}, [searchParams])
if (loading) {
return (
<div className="flex h-screen w-full items-center justify-center">
<Loading type="app" />
</div>
)
}
if (!url) {
return (
<div className="flex h-screen w-full items-center justify-center">
<div className="text-text-secondary">无效的请求</div>
</div>
)
}
return (
<div className="h-screen w-full">
<iframe
src={url}
className="h-full w-full border-0"
title="设置页面"
sandbox="allow-same-origin allow-scripts allow-forms allow-popups"
/>
</div>
)
}
\ No newline at end of file \ No newline at end of file
...@@ -54,6 +54,8 @@ const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) = ...@@ -54,6 +54,8 @@ const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) =
handleFeedback, handleFeedback,
// appInfoLoading, // appInfoLoading,
handleNewConversation, handleNewConversation,
isManuallyStopped,
taskId,
} = useChat(inputs) } = useChat(inputs)
useEffect(() => { useEffect(() => {
if (autoSendQuestion && config.initial_message !== undefined && isAutoSend) { if (autoSendQuestion && config.initial_message !== undefined && isAutoSend) {
...@@ -109,8 +111,8 @@ const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) = ...@@ -109,8 +111,8 @@ const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) =
onRestart={onRestart} onRestart={onRestart}
onFeedback={handleFeedback} onFeedback={handleFeedback}
onStopResponding={handleStop}> onStopResponding={handleStop}>
<ChatRespondingProvider isResponding={isResponding}> <ChatRespondingProvider isResponding={isResponding} taskId={taskId}>
<ChatListProvider chatList={chatList}> <ChatListProvider chatList={chatList} isManuallyStopped={isManuallyStopped}>
<Chat /> <Chat />
</ChatListProvider> </ChatListProvider>
</ChatRespondingProvider> </ChatRespondingProvider>
......
...@@ -23,6 +23,7 @@ const ChatContext = createContext<ChatContextValue>({ ...@@ -23,6 +23,7 @@ const ChatContext = createContext<ChatContextValue>({
onRestart: noop, onRestart: noop,
onSend: noop, onSend: noop,
onFeedback: noop, onFeedback: noop,
onStopResponding: noop,
}) })
type ChatContextProviderProps = { type ChatContextProviderProps = {
...@@ -45,7 +46,7 @@ export const ChatContextProvider = ({ ...@@ -45,7 +46,7 @@ export const ChatContextProvider = ({
onFeedback, onFeedback,
onStopResponding, onStopResponding,
}), }),
[], [onSend, onRegenerate, onRestart, onFeedback, onStopResponding],
) )
return <ChatContext.Provider value={value}>{children}</ChatContext.Provider> return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>
} }
......
...@@ -7,10 +7,12 @@ import { useMemo } from 'react' ...@@ -7,10 +7,12 @@ import { useMemo } from 'react'
type ChatListContext = { type ChatListContext = {
chatList: ChatItem[] chatList: ChatItem[]
isManuallyStopped?: boolean // 添加手动停止标记
} }
const ChatListContext = createContext<ChatListContext>({ const ChatListContext = createContext<ChatListContext>({
chatList: [], chatList: [],
isManuallyStopped: false,
}) })
export const useChatListContext = () => useContext(ChatListContext) export const useChatListContext = () => useContext(ChatListContext)
...@@ -19,7 +21,7 @@ type Props = { ...@@ -19,7 +21,7 @@ type Props = {
children: React.ReactNode children: React.ReactNode
} & ChatListContext } & ChatListContext
export const ChatListProvider = ({ children, chatList }: Props) => { export const ChatListProvider = ({ children, chatList, isManuallyStopped }: Props) => {
const value = { chatList } const value = { chatList, isManuallyStopped }
return <ChatListContext.Provider value={value}>{children}</ChatListContext.Provider> return <ChatListContext.Provider value={value}>{children}</ChatListContext.Provider>
} }
\ No newline at end of file \ No newline at end of file
...@@ -7,10 +7,12 @@ import { usePostMessage } from '../hooks' ...@@ -7,10 +7,12 @@ import { usePostMessage } from '../hooks'
type RespondingContext = { type RespondingContext = {
isResponding?: boolean isResponding?: boolean
taskId?: string
} }
const ChatRespondingContext = createContext<RespondingContext>({ const ChatRespondingContext = createContext<RespondingContext>({
isResponding: false, isResponding: false,
taskId: '',
}) })
export const useChatRespondingContext = () => useContext(ChatRespondingContext) export const useChatRespondingContext = () => useContext(ChatRespondingContext)
...@@ -19,9 +21,10 @@ type Props = { ...@@ -19,9 +21,10 @@ type Props = {
children: React.ReactNode children: React.ReactNode
} & RespondingContext } & RespondingContext
const postMessage = usePostMessage() const postMessage = usePostMessage()
export const ChatRespondingProvider = ({ children, isResponding }: Props) => { export const ChatRespondingProvider = ({ children, isResponding, taskId }: Props) => {
const __isResponding = useMemo(() => isResponding, [isResponding]) const __isResponding = useMemo(() => isResponding, [isResponding])
const value = useMemo(() => ({ isResponding: __isResponding }), [__isResponding]) const __taskId = useMemo(() => taskId, [taskId])
useEffect(() => postMessage(value), [__isResponding]) const value = useMemo(() => ({ isResponding: __isResponding, taskId: __taskId }), [__isResponding, __taskId])
useEffect(() => postMessage(value), [__isResponding, __taskId])
return <ChatRespondingContext.Provider value={value}>{children}</ChatRespondingContext.Provider> return <ChatRespondingContext.Provider value={value}>{children}</ChatRespondingContext.Provider>
} }
...@@ -52,6 +52,7 @@ interface ChatState { ...@@ -52,6 +52,7 @@ interface ChatState {
isResponding: boolean isResponding: boolean
suggestedQuestions: string[] suggestedQuestions: string[]
targetMessageId?: string targetMessageId?: string
isManuallyStopped?: boolean // 标记是否手动停止
// newConversationInputs: Record<string, any> // newConversationInputs: Record<string, any>
} }
...@@ -80,6 +81,7 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -80,6 +81,7 @@ export const useChat = (inputs: Inputs = {}) => {
isResponding: false, isResponding: false,
suggestedQuestions: [], suggestedQuestions: [],
targetMessageId: undefined, targetMessageId: undefined,
isManuallyStopped: false, // 初始化为 false
// newConversationInputs: inputs, // newConversationInputs: inputs,
}) })
...@@ -150,14 +152,29 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -150,14 +152,29 @@ export const useChat = (inputs: Inputs = {}) => {
// 处理停止响应 // 处理停止响应
const handleStop = useCallback(() => { const handleStop = useCallback(() => {
const currentTaskId = refs.current.taskId
refs.current.hasStopResponded = true refs.current.hasStopResponded = true
setState(prev => ({ ...prev, isResponding: false })) refs.current.isResponding = false
setState(prev => ({
...prev,
isResponding: false,
isManuallyStopped: true
}))
setTimeout(() => { setTimeout(() => {
if (stopChat && refs.current.taskId) stopChat(refs.current.taskId) if (stopChat && currentTaskId) stopChat(currentTaskId)
if (refs.current.conversationMessagesAbortController) refs.current.conversationMessagesAbortController.abort() if (refs.current.conversationMessagesAbortController) refs.current.conversationMessagesAbortController.abort()
if (refs.current.suggestedQuestionsAbortController) refs.current.suggestedQuestionsAbortController.abort() if (refs.current.suggestedQuestionsAbortController) refs.current.suggestedQuestionsAbortController.abort()
}, 100)
const lastAnswer = getLastAnswer(refs.current.chatTree)
refs.current.taskId = ''
if (lastAnswer && lastAnswer.id.startsWith('answer-placeholder-') && !lastAnswer.content.trim()) {
setState(prev => ({
...prev,
chatTree: prev.chatTree.filter(item => item.id !== lastAnswer.id),
}))
}
}, 50)
}, [stopChat]) }, [stopChat])
// 初始化 handleStop // 初始化 handleStop
...@@ -180,15 +197,13 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -180,15 +197,13 @@ export const useChat = (inputs: Inputs = {}) => {
if (inputs) { if (inputs) {
refs.current.inputs = inputs refs.current.inputs = inputs
} }
if (!isSkipClear) { setState(prev => ({
setState(prev => ({ ...prev,
...prev, chatTree: [],
chatTree: [], suggestedQuestions: [],
targetMessageId: undefined, targetMessageId: undefined,
suggestedQuestions: [], isManuallyStopped: false, // 新对话时重置
})) }))
refs.current.chatList = []
}
}, []) }, [])
// 处理新对话完成 // 处理新对话完成
...@@ -385,7 +400,11 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -385,7 +400,11 @@ export const useChat = (inputs: Inputs = {}) => {
setState(prev => ({ ...prev, isResponding: true })) setState(prev => ({ ...prev, isResponding: true }))
refs.current.isResponding = true refs.current.isResponding = true
refs.current.hasStopResponded = false // 只有在非手动停止状态下才重置 hasStopResponded
// 如果当前是手动停止状态,说明用户刚停止了上一个回答,现在开始新的回答
if (!refs.current.hasStopResponded || state.isManuallyStopped) {
refs.current.hasStopResponded = false
}
const { query, files, inputs, ...restData } = data const { query, files, inputs, ...restData } = data
const bodyParams = { const bodyParams = {
...@@ -440,7 +459,11 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -440,7 +459,11 @@ export const useChat = (inputs: Inputs = {}) => {
}) })
}, },
async onCompleted(hasError?: boolean) { async onCompleted(hasError?: boolean) {
setState(prev => ({ ...prev, isResponding: false })) refs.current.taskId = ''
setState(prev => ({
...prev,
isResponding: false
}))
refs.current.isResponding = false refs.current.isResponding = false
if (hasError) return if (hasError) return
...@@ -660,7 +683,9 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -660,7 +683,9 @@ export const useChat = (inputs: Inputs = {}) => {
handleFeedback, handleFeedback,
suggestedQuestions, suggestedQuestions,
handleNewConversation, handleNewConversation,
isManuallyStopped: state.isManuallyStopped, // 添加手动停止状态
taskId: refs.current.taskId,
}), }),
[config, chatList, isResponding, suggestedQuestions], [config, chatList, isResponding, suggestedQuestions, state.isManuallyStopped],
) )
} }
...@@ -10,7 +10,7 @@ type BasicContentProps = { ...@@ -10,7 +10,7 @@ type BasicContentProps = {
} }
const BasicContent: FC<BasicContentProps> = ({ onJsonContentReady, onThinkComplete }) => { const BasicContent: FC<BasicContentProps> = ({ onJsonContentReady, onThinkComplete }) => {
const { annotation, content, isError, hasAgentThoughts } = useChatBodyContext() const { annotation, content, isError, hasAgentThoughts, responding } = useChatBodyContext()
if (!content.trim() || hasAgentThoughts) return null if (!content.trim() || hasAgentThoughts) return null
...@@ -22,9 +22,9 @@ const BasicContent: FC<BasicContentProps> = ({ onJsonContentReady, onThinkComple ...@@ -22,9 +22,9 @@ const BasicContent: FC<BasicContentProps> = ({ onJsonContentReady, onThinkComple
content={content} content={content}
onJsonContentReady={onJsonContentReady} onJsonContentReady={onJsonContentReady}
onThinkComplete={onThinkComplete} onThinkComplete={onThinkComplete}
responding={responding} // 传递 responding 状态
/> />
) )
} }
export default memo(BasicContent) export default memo(BasicContent)
\ No newline at end of file \ No newline at end of file
import type { FC, ReactNode } from 'react' import type { FC, ReactNode } from 'react'
import { memo, useEffect, useRef, useState } from 'react' import { memo, useEffect, useRef, useState, useMemo } from 'react'
// import Operation from './components/operation' // import Operation from './components/operation'
import BasicContent from './components/basic-content' import BasicContent from './components/basic-content'
import More from './components/more' import More from './components/more'
...@@ -13,19 +13,17 @@ import { ...@@ -13,19 +13,17 @@ import {
} from '@/app/components/base/markdown/blocks' } from '@/app/components/base/markdown/blocks'
import { setGlobalOnThinkComplete } from '@/app/components/base/markdown/blocks/think' 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 = {
chatAnswerContainerInner?: string chatAnswerContainerInner?: string
} }
const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => { const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => {
const { containerRef, contentRef, more, isAnswer, content } = useChatBodyContext() const { containerRef, contentRef, more, isAnswer, content, responding } = useChatBodyContext()
const [jsonContent, setJsonContent] = useState<any>(null) const [jsonContent, setJsonContent] = useState<any>(null)
const thinkingComplete = useRef(false) const thinkingComplete = useRef(false)
// 设置全局回调 // 设置全局回调
useEffect(() => { useEffect(() => {
const handleThinkComplete = (isComplete: boolean) => { const handleThinkComplete = (isComplete: boolean) => {
console.log('chufa')
thinkingComplete.current = isComplete thinkingComplete.current = isComplete
} }
setGlobalOnThinkComplete(handleThinkComplete) setGlobalOnThinkComplete(handleThinkComplete)
...@@ -38,6 +36,23 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => { ...@@ -38,6 +36,23 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => {
if (!isAnswer) return null if (!isAnswer) return null
const shouldHideAnswer = useMemo(() => {
if (responding) return false
const thinkTagRegex1 = /<think>[\s\S]*?(<\/think>|$)/gi
const thinkTagRegex2 = /<details[^>]*data-think[^>]*>[\s\S]*?<\/details>/gi
let contentWithoutThink = content.replace(thinkTagRegex1, '').trim()
contentWithoutThink = contentWithoutThink.replace(thinkTagRegex2, '').trim()
return !contentWithoutThink
}, [content, responding])
// 如果应该隐藏,则不渲染任何内容
if (shouldHideAnswer) {
return null
}
const handleJsonContentReady = (content: any) => { const handleJsonContentReady = (content: any) => {
setJsonContent(content) setJsonContent(content)
return null // 不在 BasicContent 内部渲染 return null // 不在 BasicContent 内部渲染
...@@ -45,8 +60,8 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => { ...@@ -45,8 +60,8 @@ const Answer: FC<AnswerProps> = ({ chatAnswerContainerInner }) => {
return ( return (
<> <>
<div className="mb-2 flex last:mb-0"> <div className="MB-12 flex last:mb-0">
<div className="chat-answer-container group w-0 grow pb-2" ref={containerRef}> <div className="chat-answer-container group w-0 grow" ref={containerRef}>
{/* <LoadingAvatar /> */} {/* <LoadingAvatar /> */}
<div className={cn('group relative', chatAnswerContainerInner)}> <div className={cn('group relative', chatAnswerContainerInner)}>
<div <div
......
...@@ -29,6 +29,7 @@ interface ChatBodyContextType { ...@@ -29,6 +29,7 @@ interface ChatBodyContextType {
theme?: any theme?: any
isAnswer: boolean isAnswer: boolean
parentMessageId: ChatItem['parentMessageId'] parentMessageId: ChatItem['parentMessageId']
isManuallyStopped?: boolean // 添加手动停止标记
} }
// 创建 AnswerContext // 创建 AnswerContext
...@@ -85,7 +86,7 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({ ...@@ -85,7 +86,7 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null) const contentRef = useRef<HTMLDivElement>(null)
const { isResponding } = useChatRespondingContext() const { isResponding } = useChatRespondingContext()
const { chatList } = useChatListContext() const { chatList, isManuallyStopped } = useChatListContext() as any
const isLast = useMemo(() => isAnswer && item.id === chatList[chatList.length - 1]?.id, [chatList.length, isAnswer]) const isLast = useMemo(() => isAnswer && item.id === chatList[chatList.length - 1]?.id, [chatList.length, isAnswer])
const responding = isLast && isResponding const responding = isLast && isResponding
...@@ -116,8 +117,9 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({ ...@@ -116,8 +117,9 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
isAnswer, isAnswer,
content, content,
parentMessageId, parentMessageId,
isManuallyStopped, // 添加到 context
}), }),
[content, isAnswer, isLast, isError, responding], [content, isAnswer, isLast, isError, responding, isManuallyStopped],
) )
return <ChatBodyContext.Provider value={value}>{children}</ChatBodyContext.Provider> return <ChatBodyContext.Provider value={value}>{children}</ChatBodyContext.Provider>
......
...@@ -90,7 +90,6 @@ const TextInput: React.FC<{ ...@@ -90,7 +90,6 @@ const TextInput: React.FC<{
'body-lg-regular w-full resize-none bg-transparent p-1 leading-6 text-text-tertiary outline-none', 'body-lg-regular w-full resize-none bg-transparent p-1 leading-6 text-text-tertiary outline-none',
)} )}
placeholder={isResponding ? '正在生成回复...' : t('common.chat.inputPlaceholder') || ''} placeholder={isResponding ? '正在生成回复...' : t('common.chat.inputPlaceholder') || ''}
autoFocus
maxRows={maxRow} maxRows={maxRow}
onResize={handleTextareaResize} onResize={handleTextareaResize}
value={query} value={query}
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
import { useEffect } from 'react' import { useEffect } from 'react'
import { useStore } from '@/app/components/app/store' import { useStore } from '@/app/components/app/store'
const CONFIG_URL = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=glsk-ai-data-assistant-config&env=develop' const CONFIG_URL = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=glsk-ai-data-assistant-config'
export function ConfigLoader() { export function ConfigLoader() {
const setGlobalConfig = useStore(state => state.setGlobalConfig) const setGlobalConfig = useStore(state => state.setGlobalConfig)
......
...@@ -5,13 +5,19 @@ import { AI_DATA_SEND, AI_DATA_STOP } from '@/app/components/base/chat/constants ...@@ -5,13 +5,19 @@ import { AI_DATA_SEND, AI_DATA_STOP } from '@/app/components/base/chat/constants
const Send: FC = () => { const Send: FC = () => {
const { handleSend } = useMessageContext() const { handleSend } = useMessageContext()
const { isResponding } = useChatRespondingContext() const { isResponding, taskId } = useChatRespondingContext()
const { onStopResponding: stopResponding } = useChatContext() const { onStopResponding: stopResponding } = useChatContext()
return ( return (
<> <>
<div className="send-icon-box"> <div className="send-icon-box">
{isResponding && ( {isResponding && (
<img src={AI_DATA_STOP} onClick={stopResponding} alt="Stop" title="Stop" className="send-icon" /> <img
src={AI_DATA_STOP}
onClick={taskId ? stopResponding : undefined}
alt="Stop"
title="Stop"
className={`send-icon ${!taskId ? 'cursor-not-allowed opacity-50' : ''}`}
/>
)} )}
{!isResponding && <img src={AI_DATA_SEND} onClick={handleSend} alt="Send" title="Send" className="send-icon" />} {!isResponding && <img src={AI_DATA_SEND} onClick={handleSend} alt="Send" title="Send" className="send-icon" />}
</div> </div>
......
import { FC, memo } from 'react' import { FC, memo, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { useStore } from '@/app/components/app/store' import { useStore } from '@/app/components/app/store'
import { AI_DATA_SETTING ,GET_PARAMS} from '@/app/components/base/chat/constants' import { AI_DATA_SETTING, GET_PARAMS } from '@/app/components/base/chat/constants'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import { useChatRespondingContext } from '@/app/components/base/chat/chat-with-history/context'
import { useToastContext } from '@/app/components/base/toast'
import { useTranslation } from 'react-i18next'
const Setting: FC = () => { const Setting: FC = () => {
const handleSettingClick = () => { const router = useRouter()
const media = useBreakpoints()
const sessionId = GET_PARAMS.get('sessionId'), const isMobile = media === MediaType.mobile
corpId = GET_PARAMS.get('corpId') const { isResponding } = useChatRespondingContext()
const { notify } = useToastContext()
const { t } = useTranslation()
const handleSettingClick = useCallback(() => {
if (isResponding) {
notify({
type: 'info',
message: t('appDebug.errorMessage.waitForResponse'),
})
return
}
const sessionId = GET_PARAMS.get('sessionId')
const corpId = GET_PARAMS.get('corpId')
const { globalConfig } = useStore.getState() const { globalConfig } = useStore.getState()
if (!globalConfig) { if (!globalConfig) {
console.warn('全局配置尚未加载') console.warn('全局配置尚未加载')
return return
} }
const { settingUrl } = globalConfig const { settingUrl } = globalConfig
if (settingUrl) { if (settingUrl) {
window.open(`${settingUrl}?sessionId=${sessionId}&corpId=${corpId}`) window.open(`${settingUrl}?sessionId=${sessionId}&corpId=${corpId}`, '_blank', 'noopener,noreferrer')
// router.push(`/settingPage?settingUrl=${encodeURIComponent(settingUrl)}&sessionId=${sessionId}&corpId=${corpId}`)
} else { } else {
console.warn('配置中未设置 settingUrl') console.warn('配置中未设置 settingUrl')
} }
} }, [isMobile, router, isResponding, notify, t])
return ( return (
<> <>
<div className="fixed-button" onClick={handleSettingClick}> <div className="fixed-button" onClick={handleSettingClick}>
<img src={AI_DATA_SETTING} alt="Setting" title="Setting" className='footer-icon' /> <img src={AI_DATA_SETTING} alt="Setting" title="Setting" className="footer-icon" />
设置 设置
</div> </div>
</> </>
) )
} }
export default memo(Setting)
export default memo(Setting)
\ No newline at end of file \ No newline at end of file
.footer-mask{ .footer-mask{
padding-top: 8px; padding-top: 8px;
background: linear-gradient(180deg, rgba(237, 240, 255, 0.00) 0%, #E9F2FE 10.11%, #E8F2FE 100%); background: linear-gradient(180deg, rgba(237, 240, 255, 0.00) 0%, #E9F2FE 10.11%, #E8F2FE 100%);
}
.footer-box{
gap: 12px;
} }
\ No newline at end of file \ No newline at end of file
import React, { FC, memo, useMemo } from 'react' import React, { FC, memo, useMemo } from 'react'
import TryToAsk from './components/try-to-ask'
import ChatInput from './components/input' import ChatInput from './components/input'
import StopResponding from './components/stopResponding'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import ReStart from './components/operation/restart' import ReStart from './components/operation/restart'
import Setting from './components/operation/setting' import Setting from './components/operation/setting'
...@@ -22,7 +20,7 @@ const Footer: FC<FooterProps> = ({ isMobile, chatFooterRef, chatFooterInnerRef } ...@@ -22,7 +20,7 @@ const Footer: FC<FooterProps> = ({ isMobile, chatFooterRef, chatFooterInnerRef }
<div <div
ref={chatFooterInnerRef} ref={chatFooterInnerRef}
className={cn('relative', `mx-auto w-full max-w-[800px] ${isMobile ? 'px-2' : 'px-4'}`)}> className={cn('relative', `mx-auto w-full max-w-[800px] ${isMobile ? 'px-2' : 'px-4'}`)}>
<div className="mb-2 flex items-center relative h-8 gap-4"> <div className={cn('mb-2 flex items-center relative h-8', s['footer-box'])}>
<ReStart /> <ReStart />
<Setting /> <Setting />
{/* {isShowPracticeButton && <Practice />} */} {/* {isShowPracticeButton && <Practice />} */}
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
* @FilePath: \ai-assistant\app\components\base\chat\chat\index.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\index.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
import React, { FC, memo, useCallback, useEffect, useRef } from 'react' import React, { FC, memo, useCallback, useEffect, useRef, useState } from 'react'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import InitQuestions from '@/app/components/base/chat/chat/question/init-questions' import InitQuestions from '@/app/components/base/chat/chat/question/init-questions'
import ChatFooter from './footer' import ChatFooter from './footer'
...@@ -14,6 +14,7 @@ import chatStyles from './chat.module.css' ...@@ -14,6 +14,7 @@ import chatStyles from './chat.module.css'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints' import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import ChatBody from './body' import ChatBody from './body'
import s from './chat.module.css' import s from './chat.module.css'
import { useChatRespondingContext } from '@/app/components/base/chat/chat-with-history/context'
export type ChatProps = { export type ChatProps = {
// isShowPracticeButton: boolean // isShowPracticeButton: boolean
...@@ -25,27 +26,80 @@ const Chat: FC<ChatProps> = () => { ...@@ -25,27 +26,80 @@ const Chat: FC<ChatProps> = () => {
const chatFooterRef = useRef<HTMLDivElement>(null) const chatFooterRef = useRef<HTMLDivElement>(null)
const chatFooterInnerRef = useRef<HTMLDivElement>(null) const chatFooterInnerRef = useRef<HTMLDivElement>(null)
const lastScrollHeightRef = useRef(0) const lastScrollHeightRef = useRef(0)
const [shouldAutoScroll, setShouldAutoScroll] = useState(true)
const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null)
const { isResponding } = useChatRespondingContext()
// const answerIcon = <AnswerIcon imageUrl={AVATAR_AI_URL} /> // const answerIcon = <AnswerIcon imageUrl={AVATAR_AI_URL} />
// const questionIcon = <AnswerIcon imageUrl={AVATAR_USER_URL} /> // const questionIcon = <AnswerIcon imageUrl={AVATAR_USER_URL} />
const isMobile = useBreakpoints() === MediaType.mobile const isMobile = useBreakpoints() === MediaType.mobile
const handleScrollToBottom = useCallback(() => { const handleScrollToBottom = useCallback(() => {
if (!shouldAutoScroll) return // 如果不应自动滚动,则直接返回
const container = chatContainerRef.current const container = chatContainerRef.current
if (!container) return if (!container) return
const curScrollHeight = container.scrollHeight
const lastScrollHeigh = lastScrollHeightRef.current // 使用 requestAnimationFrame 确保 DOM 更新完成后再滚动
if (curScrollHeight !== lastScrollHeigh) { requestAnimationFrame(() => {
lastScrollHeightRef.current = curScrollHeight const curScrollHeight = container.scrollHeight
requestAnimationFrame(() => { const lastScrollHeigh = lastScrollHeightRef.current
// 添加平滑滚动效果
container.scrollTo({ // 只有当高度发生变化时才滚动
top: container.scrollHeight, if (curScrollHeight !== lastScrollHeigh) {
behavior: 'smooth', lastScrollHeightRef.current = curScrollHeight
})
}) // 立即滚动到底部
container.scrollTop = container.scrollHeight
// 同时也尝试平滑滚动(作为备选)
setTimeout(() => {
container.scrollTo({
top: container.scrollHeight,
behavior: 'smooth'
})
}, 100)
}
})
}, [shouldAutoScroll])
// 检测用户是否正在手动滚动
useEffect(() => {
const handleUserScroll = () => {
// 用户手动滚动时,暂时禁用自动滚动
setShouldAutoScroll(false)
// 清除之前的定时器
if (scrollTimeoutRef.current) {
clearTimeout(scrollTimeoutRef.current)
}
// 设置一个新的定时器,在一段时间没有用户交互后重新启用自动滚动
scrollTimeoutRef.current = setTimeout(() => {
if(isResponding) setShouldAutoScroll(true)
}, 5000) // 2秒后重新启用自动滚动
} }
}, [])
const container = chatContainerRef.current
if (container) {
// 添加滚动事件监听器到聊天容器
container.addEventListener('wheel', handleUserScroll, { passive: true })
container.addEventListener('touchmove', handleUserScroll, { passive: true })
container.addEventListener('scroll', handleUserScroll, { passive: true })
}
return () => {
// 清理事件监听器和定时器
if (container) {
container.removeEventListener('wheel', handleUserScroll)
container.removeEventListener('touchmove', handleUserScroll)
container.removeEventListener('scroll', handleUserScroll)
}
if (scrollTimeoutRef.current) {
clearTimeout(scrollTimeoutRef.current)
}
}
}, [isResponding])
// const chatContainerInnerClassName = `mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}` // const chatContainerInnerClassName = `mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}`
// 使用 MutationObserver 监听 DOM 变化 // 使用 MutationObserver 监听 DOM 变化
...@@ -53,20 +107,31 @@ const Chat: FC<ChatProps> = () => { ...@@ -53,20 +107,31 @@ const Chat: FC<ChatProps> = () => {
const container = chatContainerRef.current const container = chatContainerRef.current
if (!container) return if (!container) return
const observer = new MutationObserver(handleScrollToBottom) const observer = new MutationObserver(() => {
// 延迟一点时间确保内容完全渲染
setTimeout(handleScrollToBottom, 50)
})
observer.observe(container, { observer.observe(container, {
childList: true, childList: true,
subtree: true, subtree: true,
characterData: true,
}) })
return () => observer.disconnect() return () => observer.disconnect()
}, [handleScrollToBottom]) }, [handleScrollToBottom])
useEffect(() => { useEffect(() => {
const container = chatContainerRef.current const container = chatContainerRef.current
const footer = chatFooterRef.current const footer = chatFooterRef.current
if (!container || !footer) return if (!container || !footer) return
container.style.paddingBottom = `${footer.clientHeight}px` container.style.paddingBottom = `${footer.clientHeight}px`
handleScrollToBottom()
// 初始化时也滚动到底部
setTimeout(handleScrollToBottom, 100)
}, [handleScrollToBottom]) }, [handleScrollToBottom])
return ( return (
<div className="relative h-full"> <div className="relative h-full">
<div <div
...@@ -86,4 +151,4 @@ const Chat: FC<ChatProps> = () => { ...@@ -86,4 +151,4 @@ const Chat: FC<ChatProps> = () => {
) )
} }
export default memo(Chat) export default memo(Chat)
\ No newline at end of file \ No newline at end of file
...@@ -15,30 +15,103 @@ import { useChatConfigContext } from '../../chat-with-history/context/chat-confi ...@@ -15,30 +15,103 @@ import { useChatConfigContext } from '../../chat-with-history/context/chat-confi
import s from './question.module.scss' import s from './question.module.scss'
import { AI_TIPS } from '@/app/components/base/chat/constants' import { AI_TIPS } from '@/app/components/base/chat/constants'
type QuestionWithGroup = {
group: string
text: string
fullText: string
}
const InitQuestions: FC = () => { const InitQuestions: FC = () => {
const { suggested_questions = [] } = useChatConfigContext() const { suggested_questions = [] } = useChatConfigContext()
const [currentQuestions, setCurrentQuestions] = useState<string[]>([]) const [currentQuestions, setCurrentQuestions] = useState<QuestionWithGroup[]>([])
if (!suggested_questions.length) return null if (!suggested_questions.length) return null
// 解析问题,提取分组标记
const parseQuestion = (question: string): { group: string; text: string } => {
const match = question.match(/^\[(.*?)\]\s*(.*)$/)
if (match) {
return {
group: match[1].trim(),
text: match[2].trim()
}
}
return {
group: '默认',
text: question.trim()
}
}
// 将问题按组分类
const groupQuestions = useCallback((questions: string[]): Map<string, string[]> => {
const grouped = new Map<string, string[]>()
questions.forEach(q => {
const { group, text } = parseQuestion(q)
if (!grouped.has(group)) {
grouped.set(group, [])
}
grouped.get(group)!.push(text)
})
return grouped
}, [])
// 初始化或刷新问题时调用 // 初始化或刷新问题时调用
const getNewQuestions = useCallback(() => { const getNewQuestions = useCallback(() => {
const validQuestions = suggested_questions.filter(q => !!q && q.trim()) const validQuestions = suggested_questions.filter(q => !!q && q.trim())
// 过滤掉当前显示的问题 // 按组分类
const availableQuestions = validQuestions.filter(q => !currentQuestions.includes(q)) const groupedMap = groupQuestions(validQuestions)
// 如果没有可用问题,重置为所有问题 // 获取当前已使用的每个分类的问题
const questionsToUse = availableQuestions.length > 0 ? availableQuestions : validQuestions const currentGroupQuestions = new Map<string, Set<string>>()
currentQuestions.forEach(q => {
if (!currentGroupQuestions.has(q.group)) {
currentGroupQuestions.set(q.group, new Set())
}
currentGroupQuestions.get(q.group)!.add(q.text)
})
// 随机排序并取前4个 // 从每个组中随机选择一个问题
const newQuestions = questionsToUse const selectedQuestions: QuestionWithGroup[] = []
.sort(() => Math.random() - 0.5) const groups = Array.from(groupedMap.entries())
.slice(0, 4)
// 随机打乱组的顺序
const shuffledGroups = groups.sort(() => Math.random() - 0.5)
// 遍历每个组,每个组只选择一个问题
for (const [groupName, questions] of shuffledGroups) {
// 获取该组当前已使用的问题
const usedQuestions = currentGroupQuestions.get(groupName) || new Set()
// 过滤掉该组当前已显示的问题
const availableQuestions = questions.filter(q => !usedQuestions.has(q))
// 如果该组有可用问题,随机选择一个
if (availableQuestions.length > 0) {
const randomIndex = Math.floor(Math.random() * availableQuestions.length)
const selectedText = availableQuestions[randomIndex]
selectedQuestions.push({
group: groupName,
text: selectedText,
fullText: `[${groupName}] ${selectedText}`
})
} else if (questions.length > 0) {
// 如果该组没有可用问题,从所有问题中随机选择一个(允许重复)
const randomIndex = Math.floor(Math.random() * questions.length)
const selectedText = questions[randomIndex]
selectedQuestions.push({
group: groupName,
text: selectedText,
fullText: `[${groupName}] ${selectedText}`
})
}
}
setCurrentQuestions(newQuestions) setCurrentQuestions(selectedQuestions)
return newQuestions return selectedQuestions
}, [suggested_questions, currentQuestions]) }, [suggested_questions, currentQuestions, groupQuestions])
const handleRefresh = useCallback(() => { const handleRefresh = useCallback(() => {
getNewQuestions() getNewQuestions()
...@@ -53,7 +126,7 @@ const InitQuestions: FC = () => { ...@@ -53,7 +126,7 @@ const InitQuestions: FC = () => {
return useMemo(() => { return useMemo(() => {
return ( return (
<div className={cn('mb-4 flex last:mb-0', s['suggested-questions-box'])}> <div className={cn('MB-12 flex last:mb-0', s['suggested-questions-box'])}>
{/* <div className="relative h-10 w-10 shrink-0">{<AnswerIcon />}</div> */} {/* <div className="relative h-10 w-10 shrink-0">{<AnswerIcon />}</div> */}
<img src={AI_TIPS} alt="AI Tips" className={cn(s['suggested-questions-title'])} /> <img src={AI_TIPS} alt="AI Tips" className={cn(s['suggested-questions-title'])} />
<div className={cn(s['suggested-questions-list'], 'group w-0 grow')}> <div className={cn(s['suggested-questions-list'], 'group w-0 grow')}>
...@@ -83,10 +156,11 @@ const InitQuestions: FC = () => { ...@@ -83,10 +156,11 @@ const InitQuestions: FC = () => {
</div> </div>
<div className={cn('group relative w-full')}> <div className={cn('group relative w-full')}>
{currentQuestions.length > 0 && <InitSuggest suggestedQuestions={currentQuestions} />} {currentQuestions.length > 0 && <InitSuggest suggestedQuestions={currentQuestions} />}
</div> </div>
</div> </div>
</div> </div>
) )
}, [currentQuestions, handleRefresh]) }, [currentQuestions, handleRefresh])
} }
export default InitQuestions export default InitQuestions
\ No newline at end of file \ No newline at end of file
...@@ -14,20 +14,57 @@ import Button from '@/app/components/base/button/next-button' ...@@ -14,20 +14,57 @@ import Button from '@/app/components/base/button/next-button'
import { InputMessageType } from '@/app/components/base/chat/types' import { InputMessageType } from '@/app/components/base/chat/types'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import s from './question.module.scss' import s from './question.module.scss'
type QuestionItem = {
group?: string
text: string
fullText?: string
}
type InitSuggestProps = { type InitSuggestProps = {
suggestedQuestions?: string[] suggestedQuestions?: string[] | QuestionItem[]
} }
const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions = [] }) => { const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions = [] }) => {
const { onSend } = useChatContext() const { onSend } = useChatContext()
// 处理不同类型的数据
const normalizeQuestions = (questions: string[] | QuestionItem[]): QuestionItem[] => {
if (questions.length === 0) return []
// 如果是字符串数组,转换为 QuestionItem 格式
if (typeof questions[0] === 'string') {
return (questions as string[]).map(q => ({
text: q,
fullText: q,
}))
}
return questions as QuestionItem[]
}
const normalizedQuestions = normalizeQuestions(suggestedQuestions)
return ( return (
<div className={cn('w-full', s['suggested-questions-item-box'])}> <div className={cn('w-full', s['suggested-questions-item-box'])}>
{suggestedQuestions.map((question, index) => ( {normalizedQuestions.map((question, index) => (
<div <div
className={cn(s['suggested-questions-item'],'flex items-center')} className={cn(s['suggested-questions-item'], 'flex')}
key={index} key={index}
onClick={() => onSend?.(question, InputMessageType.QUESTION_IN_WELCOME)}> onClick={() => onSend?.(question.text, InputMessageType.QUESTION_IN_WELCOME)}>
<div className={cn(s['suggested-questions-item-text'])}>{question}</div> {question.group && question.group !== '默认' && (
<svg className={cn(s['suggested-questions-item-icon'])} width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg"> <span className={cn(s['suggested-questions-item-group'])}>{question.group}</span>
)}
<div className={cn(s['suggested-questions-item-text'], 'flex items-center gap-2')}>
<span>{question.text}</span>
</div>
<svg
className={cn(s['suggested-questions-item-icon'])}
width="15"
height="15"
viewBox="0 0 15 15"
fill="none"
xmlns="http://www.w3.org/2000/svg">
<path <path
d="M12.7895 8.7334L10.3872 5.68652C10.3434 5.6309 10.2876 5.58593 10.2239 5.55497C10.1602 5.52402 10.0903 5.5079 10.0195 5.50781H9.07031C8.97217 5.50781 8.91797 5.62061 8.97803 5.69824L11.0918 8.37891H2.22656C2.16211 8.37891 2.10938 8.43164 2.10938 8.49609V9.375C2.10938 9.43945 2.16211 9.49219 2.22656 9.49219H12.4204C12.813 9.49219 13.0312 9.04102 12.7895 8.7334Z" d="M12.7895 8.7334L10.3872 5.68652C10.3434 5.6309 10.2876 5.58593 10.2239 5.55497C10.1602 5.52402 10.0903 5.5079 10.0195 5.50781H9.07031C8.97217 5.50781 8.91797 5.62061 8.97803 5.69824L11.0918 8.37891H2.22656C2.16211 8.37891 2.10938 8.43164 2.10938 8.49609V9.375C2.10938 9.43945 2.16211 9.49219 2.22656 9.49219H12.4204C12.813 9.49219 13.0312 9.04102 12.7895 8.7334Z"
fill="#0A3479" fill="#0A3479"
......
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
border-radius: 16px; border-radius: 16px;
overflow: hidden; overflow: hidden;
flex-direction: column; flex-direction: column;
margin-bottom: 12px;
} }
.suggested-questions-title { .suggested-questions-title {
...@@ -42,9 +43,10 @@ ...@@ -42,9 +43,10 @@
.suggested-questions-item { .suggested-questions-item {
border-top: 1px solid #d8e6f066; border-top: 1px solid #d8e6f066;
padding: 16px 0; padding: 16px 0;
max-height: 75px; max-height: 80px;
box-sizing: border-box; box-sizing: border-box;
display: flex;
position: relative;
&-text { &-text {
display: -webkit-box; display: -webkit-box;
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
...@@ -54,7 +56,23 @@ ...@@ -54,7 +56,23 @@
word-break: break-word; word-break: break-word;
color: #0a3479; color: #0a3479;
font-size: 15px; font-size: 15px;
line-height: 26px;
}
&-group {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
padding: 0 8px;
border-radius: 16px;
background: #EDF1FF;
color: #4f72ff;
font-size: 13px;
height: 26px;
margin-right: 4px;
} }
&-icon { &-icon {
flex-shrink: 0; flex-shrink: 0;
margin-left: auto; margin-left: auto;
......
...@@ -17,7 +17,7 @@ import cn from '@/utils/classnames' ...@@ -17,7 +17,7 @@ import cn from '@/utils/classnames'
const Question: FC = () => { const Question: FC = () => {
const { content, theme } = useChatBodyContext() const { content, theme } = useChatBodyContext()
return ( return (
<div className="mb-4 flex justify-end pl-14 last:mb-0"> <div className="MB-12 flex justify-end pl-14 last:mb-0">
<div className={cn('group', 'relative', 'max-w-full')}> <div className={cn('group', 'relative', 'max-w-full')}>
<div <div
className={cn('rounded-br-none bg-[#3773F8] px-3 py-2 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'])}
......
.confirm-content{ .confirm-content-box{
background: linear-gradient(180deg, #EDF5FF 0%, #FFFFFF 100%); background: linear-gradient(180deg, #EDF5FF 0%, #FFFFFF 100%);
border-radius: 18px; border-radius: 18px;
color: #133368; color: #133368;
......
...@@ -91,7 +91,7 @@ function Confirm({ ...@@ -91,7 +91,7 @@ function Confirm({
e.stopPropagation() e.stopPropagation()
}}> }}>
<div ref={dialogRef} className={'relative w-[80%] max-w-[480px] overflow-hidden'}> <div ref={dialogRef} className={'relative w-[80%] max-w-[480px] overflow-hidden'}>
<div className={cn('shadows-shadow-lg flex max-w-full flex-col items-start rounded-2xl border-[0.5px] border-solid border-components-panel-border bg-components-panel-bg', s['confirm-content'])}> <div className={cn('shadows-shadow-lg flex max-w-full flex-col items-start rounded-2xl border-[0.5px] border-solid border-components-panel-border bg-components-panel-bg', s['confirm-content-box'])}>
<div className='flex flex-col items-start gap-2 self-stretch'> <div className='flex flex-col items-start gap-2 self-stretch'>
<div className={cn('title-2xl-semi-bold text-text-primary', s['confirm-title'])}>{title}</div> <div className={cn('title-2xl-semi-bold text-text-primary', s['confirm-title'])}>{title}</div>
<div className={cn('system-md-regular w-full text-text-tertiary', s['confirm-content'])}>{content}</div> <div className={cn('system-md-regular w-full text-text-tertiary', s['confirm-content'])}>{content}</div>
......
.chart-canvas{
width: 100%;
}
.chart-box-pie {
width: 100%;
height: 230px;
.chart-canvas{
width: 42%;
}
}
.chart-legend {
width: calc(58% - 15px);
margin-left: 15px;
display: flex;
flex-direction: column;
justify-content: center;
&-item {
display: flex;
align-items: center;
margin-bottom: 8px;
color: #133368;
font-size: 12px;
transition: opacity 0.3s ease;
&-hidden {
opacity: 0.4;
color: #999;
.chart-legend-color{
background-color: #999 !important;
}
}
}
&-color {
width: 8px;
height: 8px;
margin-right: 4px;
}
&-text-box {
width: 50%;
}
&-text{
display: block;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&-value{
width: calc(50% - 23px);
text-align: right;
}
&-line {
width: 1px;
height: 100%;
background: #1333681a;
margin: 0 5px;
}
}
\ No newline at end of file \ No newline at end of file
import { FC } from 'react' import { FC, useState, useRef, useEffect, useMemo } from 'react'
import ReactECharts from 'echarts-for-react' import ReactECharts from 'echarts-for-react'
import cn from '@/utils/classnames'
import s from './chart.module.scss'
type ChartProps = { type ChartProps = {
content: any | null content: any | null
} }
const formatValue = (value: number) => {
if (value >= 100000000) {
return `${(Math.floor(value / 100000000 * 100) / 100).toFixed(2)}亿`
}
if (value >= 1000) {
return `${(Math.floor(value / 10000 * 100) / 100).toFixed(2)}万`
}
return `${value}`
}
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]) {
...@@ -17,8 +28,25 @@ const Chart: FC<ChartProps> = ({ content }) => { ...@@ -17,8 +28,25 @@ const Chart: FC<ChartProps> = ({ content }) => {
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]
const chartRef = useRef<any>(null)
const [visibleItems, setVisibleItems] = useState<Set<string>>(new Set())
// 存储原始数据
const originalDataRef = useRef<any[]>([])
if (type == 'bar' || type == 'line') { if (type == 'bar' || type == 'line') {
option = { option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
},
formatter: (params: any) => {
let result = params[0].axisValue + '<br/>'
params.forEach((item: any) => {
result += `${item.marker} ${item.seriesName}: ${formatValue(item.value)}<br/>`
})
return result
}
},
grid: { grid: {
left: '20%', left: '20%',
right: '5%', right: '5%',
...@@ -130,28 +158,29 @@ const Chart: FC<ChartProps> = ({ content }) => { ...@@ -130,28 +158,29 @@ const Chart: FC<ChartProps> = ({ content }) => {
] as any ] as any
title = type == 'bar' ? '柱状图' : '折线图' title = type == 'bar' ? '柱状图' : '折线图'
} }
const pieColor = ['#2A82E4', '#00BAAD', '#43CF7C', '#A5D63F', '#FF8D1A', '#FFC300', '#7948EA', '#C6C6C6']
if (type == 'pie') { if (type == 'pie') {
option = { option = {
color: ['#2A82E4', '#00BAAD', '#43CF7C', '#A5D63F', '#FF8D1A', '#FFC300', '#7948EA', '#C6C6C6'], color: pieColor,
legend: { // legend: {
left: '52%', // left: '52%',
top: 'center', // top: 'center',
orient: 'vertical', // orient: 'vertical',
itemWidth: 8, // itemWidth: 8,
itemHeight: 8, // itemHeight: 8,
textStyle: { // textStyle: {
fontSize: 12, // fontSize: 12,
color: '#133368', // color: '#133368',
overflow: 'truncate', // overflow: 'truncate',
width: 130, // width: 130,
}, // },
itemGap: 8, // itemGap: 8,
}, // },
series: [ series: [
{ {
type: 'pie', type: 'pie',
radius: ['35%', '50%'], radius: ['70%', '100%'],
center: ['22%', '50%'], center: ['50%', '50%'],
padAngle: 3, padAngle: 3,
label: { label: {
show: false, show: false,
...@@ -166,7 +195,7 @@ const Chart: FC<ChartProps> = ({ content }) => { ...@@ -166,7 +195,7 @@ const Chart: FC<ChartProps> = ({ content }) => {
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: any, index: number) => ({ value: item, name: nameArray[index] })) return dataArray.map((item: any, index: number) => ({ value: item, name: nameArray[index] }))
} }
...@@ -183,13 +212,77 @@ const Chart: FC<ChartProps> = ({ content }) => { ...@@ -183,13 +212,77 @@ const Chart: FC<ChartProps> = ({ content }) => {
}, },
], ],
} }
title = '饼壮图' title = '饼状图'
// 保存原始数据
originalDataRef.current = option.series[0].data
} }
if (!title) return null if (!title) return null
// 初始化可见项状态
useEffect(() => {
if (type === 'pie' && visibleItems.size === 0) {
const allNames = new Set<string>(option.series[0].data.map((item: any) => item.name))
setVisibleItems(allNames)
}
}, [type])
// 计算当前显示的图表数据
const currentOption = useMemo(() => {
if (type !== 'pie') return option
const updatedData = option.series[0].data.map((item: any) => {
const original = originalDataRef.current.find((d: any) => d.name === item.name)
return {
...item,
value: visibleItems.has(item.name) ? original.value : 0
}
})
return {
...option,
series: [{ ...option.series[0], data: updatedData }]
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [visibleItems, type, option.series[0]?.data?.length])
// 切换图例项显示/隐藏
const handleToggleLegend = (name: string) => {
setVisibleItems(prev => {
const next = new Set(prev)
if (next.has(name)) {
next.delete(name)
} else {
next.add(name)
}
return next
})
}
return ( return (
<div className="chart-container"> <div className="chart-container">
<div className="chart-title">{title}</div> <div className="chart-title">{title}</div>
<ReactECharts option={option} style={{ height: 240 }} /> <div className={cn('chart-box flex', type == 'pie' && s['chart-box-pie'])}>
<div className={cn(s['chart-canvas'])}>
<ReactECharts ref={chartRef} option={currentOption} style={{ height: 240 }} />
</div>
{type == 'pie' && option.series[0]?.data && (
<div className={cn(s['chart-legend'])}>
{option.series[0].data.map((item: any, index: number) => (
<div
key={item.name}
className={cn(s['chart-legend-item'], !visibleItems.has(item.name) && s['chart-legend-item-hidden'])}
onClick={() => handleToggleLegend(item.name)}
>
<div
className={cn(s['chart-legend-color'])}
style={{ backgroundColor: pieColor[index] }}></div>
<div className={cn(s['chart-legend-text-box'])}>
<span className={cn(s['chart-legend-text'])}>{item.name}</span>
</div>
<div className={cn(s['chart-legend-line'])}></div>
<div className={cn(s['chart-legend-value'])}>{formatValue(item.value)}</div>
</div>
))}
</div>
)}
</div>
</div> </div>
) )
} }
......
...@@ -19,7 +19,9 @@ ...@@ -19,7 +19,9 @@
z-index: 2; z-index: 2;
.block { .block {
line-height: 24px; display: flex;
align-items: center;
justify-content: center;
height: 24px; height: 24px;
color: #4f72ff; color: #4f72ff;
font-size: 13px; font-size: 13px;
...@@ -41,10 +43,12 @@ ...@@ -41,10 +43,12 @@
display: block; display: block;
} }
} }
.expanded{
.expanded {
border-radius: 16px; border-radius: 16px;
border-bottom: 1px solid #fff; border-bottom: 1px solid #fff;
} }
.arrow { .arrow {
margin-left: auto; margin-left: auto;
width: 18px; width: 18px;
......
...@@ -5,6 +5,7 @@ import cn from '@/utils/classnames' ...@@ -5,6 +5,7 @@ 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 Toast from '@/app/components/base/toast'
import { GET_PARAMS } from '@/app/components/base/chat/constants' import { GET_PARAMS } from '@/app/components/base/chat/constants'
import { v4 as uuidv4 } from 'uuid'
type ReportProps = { type ReportProps = {
content: any | null content: any | null
...@@ -18,6 +19,7 @@ const Report: FC<ReportProps> = ({ content }) => { ...@@ -18,6 +19,7 @@ const Report: FC<ReportProps> = ({ content }) => {
const iframeRef = useRef<HTMLIFrameElement>(null) const iframeRef = useRef<HTMLIFrameElement>(null)
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
const [containerHeight, setContainerHeight] = useState(150) const [containerHeight, setContainerHeight] = useState(150)
const reportId = useRef<string>(uuidv4())
const handleToggleExpand = () => { const handleToggleExpand = () => {
setIsExpanded(!isExpanded) setIsExpanded(!isExpanded)
...@@ -26,16 +28,16 @@ const Report: FC<ReportProps> = ({ content }) => { ...@@ -26,16 +28,16 @@ const Report: FC<ReportProps> = ({ content }) => {
// 监听来自 iframe 的消息 // 监听来自 iframe 的消息
useEffect(() => { useEffect(() => {
const handleMessage = (event: MessageEvent) => { const handleMessage = (event: MessageEvent) => {
if (event.data && event.data.type === 'RESIZE_IFRAME') { if (event.data && event.data.type === 'RESIZE_IFRAME' && event.data.reportId === reportId.current) {
const height = event.data.height const height = event.data.height
if (height && height > 0) { if (height && height > 0) {
setContainerHeight(height) setContainerHeight(height)
console.log('收到 iframe 高度:', height) console.log('收到 iframe 高度:', height, 'reportId:', reportId.current)
} }
} }
if (event.data && event.data.type === 'COPY_SUCCESS') { if (event.data && event.data.type === 'COPY_SUCCESS') {
Toast.notify({ Toast.notify({
message: '链接复制成功,快去粘贴吧~', message: '链接复制成功,快去粘贴吧~',
type: 'success', type: 'success',
}) })
} }
...@@ -51,14 +53,17 @@ const Report: FC<ReportProps> = ({ content }) => { ...@@ -51,14 +53,17 @@ const Report: FC<ReportProps> = ({ content }) => {
// 向 iframe 发送获取高度的消息 // 向 iframe 发送获取高度的消息
const requestIframeHeight = () => { const requestIframeHeight = () => {
if (iframeRef.current && iframeRef.current.contentWindow) { if (iframeRef.current && iframeRef.current.contentWindow) {
iframeRef.current.contentWindow.postMessage({ type: 'GET_IFRAME_HEIGHT' }, '*') iframeRef.current.contentWindow.postMessage({
type: 'GET_IFRAME_HEIGHT',
reportId: reportId.current
}, '*')
} }
} }
// iframe 加载完成后请求高度 // iframe 加载完成后请求高度
const handleIframeLoad = () => { const handleIframeLoad = () => {
console.log('iframe 加载完成,请求高度') console.log('iframe 加载完成,请求高度, reportId:', reportId.current)
// 延迟发送,确保 iframe 内部内容已渲染 // 延迟发送,确保 iframe 内部内容已渲染
setTimeout(() => { setTimeout(() => {
requestIframeHeight() requestIframeHeight()
}, 300) }, 300)
...@@ -77,10 +82,10 @@ const Report: FC<ReportProps> = ({ content }) => { ...@@ -77,10 +82,10 @@ const Report: FC<ReportProps> = ({ content }) => {
if (!report_start_date) return '' if (!report_start_date) return ''
if (reportType === 2) { if (reportType === 2) {
// 月报:2026-01-10 转成 2026 年 1 月 // 月报:2026-01-10 转成 2026 年 1 月
return dayjs(report_start_date).format('YYYY年M月') return dayjs(report_start_date).format('YYYY年M月')
} else if (reportType === 1) { } else if (reportType === 1) {
// 周报:2026-01-10 转成 2026 年第 2 周 // 周报:2026-01-10 转成 2026 年第 2 周
const date = dayjs(report_start_date) const date = dayjs(report_start_date)
const year = date.year() const year = date.year()
// 计算是该年的第几周 // 计算是该年的第几周
...@@ -143,4 +148,4 @@ const Report: FC<ReportProps> = ({ content }) => { ...@@ -143,4 +148,4 @@ const Report: FC<ReportProps> = ({ content }) => {
) )
} }
export default Report export default Report
\ No newline at end of file \ No newline at end of file
...@@ -37,11 +37,43 @@ const removeEndThink = (children: any): any => { ...@@ -37,11 +37,43 @@ const removeEndThink = (children: any): any => {
return 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 useThinkTimer = (children: any) => {
const [startTime] = useState(Date.now()) 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 [isOpen, setIsOpen] = useState(false)
useEffect(() => { useEffect(() => {
if (isComplete) return if (isComplete) return
...@@ -59,12 +91,19 @@ const useThinkTimer = (children: any) => { ...@@ -59,12 +91,19 @@ const useThinkTimer = (children: any) => {
if (hasEndThink(children)) setIsComplete(true) if (hasEndThink(children)) setIsComplete(true)
}, [children]) }, [children])
return { elapsedTime, isComplete } // Initialize open state based on completion status
useEffect(() => {
if (!isComplete) {
setIsOpen(true)
}
}, [isComplete])
return { elapsedTime, isComplete, isOpen, setIsOpen }
} }
export const Think = ({ children, ...props }: any) => { export const Think = ({ children, ...props }: any) => {
const { elapsedTime, isComplete } = useThinkTimer(children) const { elapsedTime, isComplete, isOpen, setIsOpen } = useThinkTimer(children)
const displayContent = removeEndThink(children) const displayContent = flattenNestedThink(removeEndThink(children))
const { t } = useTranslation() const { t } = useTranslation()
// Notify parent component when thinking is complete // Notify parent component when thinking is complete
...@@ -78,11 +117,27 @@ export const Think = ({ children, ...props }: any) => { ...@@ -78,11 +117,27 @@ export const Think = ({ children, ...props }: any) => {
} }
}, [isComplete, props.onThinkComplete]) }, [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> if (!(props['data-think'] ?? false)) return <details {...props}>{children}</details>
return ( return (
<details {...(!isComplete && { open: true })} className="group"> <details open={isOpen} className="group">
<summary className="flex cursor-pointer select-none list-none items-center whitespace-nowrap font-bold text-text-secondary"> <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"> <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"
...@@ -96,7 +151,7 @@ export const Think = ({ children, ...props }: any) => { ...@@ -96,7 +151,7 @@ export const Think = ({ children, ...props }: any) => {
{isComplete ? `${t('common.chat.thought')}\t(${elapsedTime.toFixed(1)}s)` : `${t('common.chat.thinking')}`} {isComplete ? `${t('common.chat.thought')}\t(${elapsedTime.toFixed(1)}s)` : `${t('common.chat.thinking')}`}
</span> </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', isOpen ? '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" />
</div> </div>
) : ( ) : (
...@@ -104,13 +159,11 @@ export const Think = ({ children, ...props }: any) => { ...@@ -104,13 +159,11 @@ export const Think = ({ children, ...props }: any) => {
)} )}
</div> </div>
</summary> </summary>
{displayContent ? ( {displayContent && isOpen ? (
<div className=" border-l border-components-panel-border pl-2 text-text-secondary think-class"> <div className="pt-2 border-l border-components-panel-border pl-2 text-text-secondary think-class">
{displayContent} {displayContent}
</div> </div>
) : ( ) : null}
null
)}
</details> </details>
) )
} }
......
...@@ -8,20 +8,8 @@ import RehypeRaw from 'rehype-raw' ...@@ -8,20 +8,8 @@ import RehypeRaw from 'rehype-raw'
import { flow } from 'lodash-es' import { flow } from 'lodash-es'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { customUrlTransform, preprocessLaTeX, preprocessThinkTag } from './markdown-utils' import { customUrlTransform, preprocessLaTeX, preprocessThinkTag } from './markdown-utils'
import { import { Audio, Code, Img, Link, MarkdownButton, MarkdownForm, Paragraph, Script, Think, Video, Chart } from './blocks'
Audio, import { useMemo, useEffect, useRef, useState } from 'react'
Code,
Img,
Link,
MarkdownButton,
MarkdownForm,
Paragraph,
Script,
Think,
Video,
Chart,
} from './blocks'
import { useMemo } from 'react'
/** /**
* @fileoverview Main Markdown rendering component. * @fileoverview Main Markdown rendering component.
...@@ -36,8 +24,10 @@ type MarkdownProps = { ...@@ -36,8 +24,10 @@ 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 onThinkComplete?: (isComplete: boolean) => void
hideThink?: boolean
responding?: boolean // 添加 responding 状态
} }
type MarkdownContent = { type MarkdownContent = {
...@@ -55,7 +45,7 @@ export function Markdown(props: MarkdownProps) { ...@@ -55,7 +45,7 @@ export function Markdown(props: MarkdownProps) {
const jsonCodeBlockRegex = /```json\s*([\s\S]*?)\s*```/g const jsonCodeBlockRegex = /```json\s*([\s\S]*?)\s*```/g
let match let match
const allJsonBlocks: any[] = [] const allJsonBlocks: any[] = []
// 收集所有 JSON 块 // 收集所有 JSON 块
while ((match = jsonCodeBlockRegex.exec(processedContent)) !== null) { while ((match = jsonCodeBlockRegex.exec(processedContent)) !== null) {
const jsonStr = match[1].trim() const jsonStr = match[1].trim()
...@@ -66,54 +56,193 @@ export function Markdown(props: MarkdownProps) { ...@@ -66,54 +56,193 @@ export function Markdown(props: MarkdownProps) {
console.error('JSON 解析失败:', e, '原始内容:', jsonStr) console.error('JSON 解析失败:', e, '原始内容:', jsonStr)
} }
} }
// 取最后一个解析成功的 JSON // 取最后一个解析成功的 JSON
if (allJsonBlocks.length > 0) { if (allJsonBlocks.length > 0) {
jsonContent = allJsonBlocks[allJsonBlocks.length - 1] jsonContent = allJsonBlocks[allJsonBlocks.length - 1]
} }
// 第二步:彻底移除所有代码块 // 第二步:彻底移除所有代码块,但保留换行符
mainContent = mainContent mainContent = mainContent
// 移除 ```json 代码块(支持多种格式) // 移除 ```json 代码块(支持多种格式),替换为单个换行
.replace(/```json\r?\n([\s\S]*?)\r?\n```/g, '') .replace(/```json\r?\n([\s\S]*?)\r?\n```/g, '\n')
.replace(/```json([\s\S]*?)```/g, '') .replace(/```json([\s\S]*?)```/g, '\n')
// 移除其他代码块 // 移除其他代码块,替换为单个换行
.replace(/```\r?\n([\s\S]*?)\r?\n```/g, '') .replace(/```\r?\n([\s\S]*?)\r?\n```/g, '\n')
.replace(/```([\s\S]*?)```/g, '') .replace(/```([\s\S]*?)```/g, '\n')
// 清理空行 // 只清理连续3个以上的空行,保留正常的换行
.replace(/\n\s*\n\s*\n/g, '\n\n') .replace(/\n{3,}/g, '\n\n')
.replace(/^\s*\n/gm, '')
.trim() .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 } return { mainContent, jsonContent }
}, [processedContent]) }, [processedContent])
const latexContent = contentObj.mainContent const latexContent = contentObj.mainContent
console.log(latexContent)
// 强行过滤所有代码块内容 // 强行过滤所有代码块内容
const filteredContent = useMemo(() => { const filteredContent = useMemo(() => {
if (!latexContent) return '' if (!latexContent) return ''
let filtered = latexContent 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
// 移除所有 ```json 代码块 while (true) {
filtered = filtered.replace(/```json\s*[\s\S]*?```/g, '') const match = detailsRegex.exec(result)
if (!match) break
// 移除所有其他代码块
filtered = filtered.replace(/```\s*[\s\S]*?```/g, '') const detailsStartIndex = match.index
const detailsTagEnd = detailsStartIndex + match[0].length
// 清理连续空行
filtered = filtered.replace(/\n{3,}/g, '\n\n') // 在这个 details 标签后查找 </details>
const detailsEndIndex = result.indexOf('</details>', detailsTagEnd)
// 移除行首的空白行 if (detailsEndIndex === -1) {
filtered = filtered.replace(/^\s*\n/gm, '') // 如果没有找到结束标签,说明是流式输出中还未完成的部分
// 检查从 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() return filtered.trim()
}, [latexContent]) }, [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 ( return (
<> <>
<div className={cn('markdown-body ', '!text-text-primary', props.className)}> <div ref={markdownRef} className={cn('markdown-body ', '!text-text-primary', props.className)}>
<ReactMarkdown <ReactMarkdown
remarkPlugins={[RemarkGfm, [RemarkMath, { singleDollarTextMath: false }], RemarkBreaks]} remarkPlugins={[RemarkGfm, [RemarkMath, { singleDollarTextMath: false }], RemarkBreaks]}
rehypePlugins={[ rehypePlugins={[
......
...@@ -31,21 +31,30 @@ const Toast = ({ type = 'info', size = 'md', message, children, className, custo ...@@ -31,21 +31,30 @@ const Toast = ({ type = 'info', size = 'md', message, children, className, custo
if (typeof message !== 'string') return null if (typeof message !== 'string') return null
return ( return (
<div style={{ left: '50%', transform: 'translateX(-50%)', minWidth: '242px', maxWidth: 'min(343px, 91vw)', borderRadius: '54px' }} className={classNames(className, 'fixed my-4 flex-grow z-[9999] overflow-hidden', size === 'md' ? 'p-3' : 'p-2', 'top-0', 'right-0')}> <div
className={classNames(
className,
'fixed top-4 left-1/2 z-[9999] overflow-hidden flex items-center',
'flex flex-col items-center',
size === 'md' ? 'px-3 py-2' : 'px-2 py-1'
)}
style={{
transform: 'translateX(-50%)',
maxWidth: '70vw',
borderRadius: '54px',
width: 'fit-content',
}}
>
<div className="absolute inset-0 -z-10" style={{ backgroundColor: 'rgba(0, 0, 0, 0.5)' }} /> <div className="absolute inset-0 -z-10" style={{ backgroundColor: 'rgba(0, 0, 0, 0.5)' }} />
<div className={`flex ${size === 'md' ? 'gap-1' : 'gap-0.5'}`}> <div className={`flex ${size === 'md' ? 'gap-1' : 'gap-0.5'} items-center`}>
<div className={`flex items-center justify-center ${size === 'md' ? 'p-0.5' : 'p-1'}`}> <div className={`flex items-center justify-center flex-shrink-0 ${size === 'md' ? 'p-0.5' : 'p-1'}`}>
{type === 'success' && <RiCheckboxCircleFill className={`${size === 'md' ? 'h-5 w-5' : 'h-4 w-4'} text-white`} aria-hidden="true" />} {type === 'success' && <RiCheckboxCircleFill className={`${size === 'md' ? 'h-5 w-5' : 'h-4 w-4'} text-white`} aria-hidden="true" />}
{type === 'error' && <RiErrorWarningFill className={`${size === 'md' ? 'h-5 w-5' : 'h-4 w-4'} text-white`} aria-hidden="true" />} {type === 'error' && <RiErrorWarningFill className={`${size === 'md' ? 'h-5 w-5' : 'h-4 w-4'} text-white`} aria-hidden="true" />}
{type === 'warning' && <RiAlertFill className={`${size === 'md' ? 'h-5 w-5' : 'h-4 w-4'} text-white`} aria-hidden="true" />} {type === 'warning' && <RiAlertFill className={`${size === 'md' ? 'h-5 w-5' : 'h-4 w-4'} text-white`} aria-hidden="true" />}
{type === 'info' && <RiInformation2Fill className={`${size === 'md' ? 'h-5 w-5' : 'h-4 w-4'} text-white`} aria-hidden="true" />} {type === 'info' && <RiInformation2Fill className={`${size === 'md' ? 'h-5 w-5' : 'h-4 w-4'} text-white`} aria-hidden="true" />}
</div> </div>
<div className={`flex py-1 ${size === 'md' ? 'px-1' : 'px-0.5'} grow flex-col items-start gap-1`}> <div className={`flex items-center text-white flex-1 min-w-[45vw]`}>
<div className="flex items-center gap-1"> {message}
<div className="system-sm-semibold" style={{ color: 'white', fontSize: '14px' }}>{message}</div>
{customComponent}
</div>
{children && <div className="system-xs-regular" style={{ color: 'white', fontSize: '14px' }}>{children}</div>}
</div> </div>
{/* {close && ( {/* {close && (
<ActionButton className="z-[1000]" onClick={close}> <ActionButton className="z-[1000]" onClick={close}>
...@@ -122,4 +131,4 @@ Toast.notify = ({ type, size = 'md', message, duration, className, customCompone ...@@ -122,4 +131,4 @@ Toast.notify = ({ type, size = 'md', message, duration, className, customCompone
} }
} }
export default Toast export default Toast
\ No newline at end of file \ No newline at end of file
...@@ -239,7 +239,6 @@ button:focus-within { ...@@ -239,7 +239,6 @@ button:focus-within {
.system-sm-semibold { .system-sm-semibold {
font-size: 13px; font-size: 13px;
font-weight: 600; font-weight: 600;
line-height: 16px;
} }
.system-sm-semibold-uppercase { .system-sm-semibold-uppercase {
...@@ -780,4 +779,8 @@ button:focus-within { ...@@ -780,4 +779,8 @@ button:focus-within {
.footer-icon { .footer-icon {
width: 18px; width: 18px;
height: 18px; height: 18px;
}
.MB-12{
margin-bottom: 12px;
} }
\ No newline at end of file \ No newline at end of file
...@@ -420,7 +420,9 @@ ...@@ -420,7 +420,9 @@
margin-top: 0; margin-top: 0;
margin-bottom: 12px; margin-bottom: 12px;
} }
.markdown-body details{
margin-bottom: 0;
}
.markdown-body ul, .markdown-body ul,
.markdown-body ol { .markdown-body ol {
padding-left: 2em; padding-left: 2em;
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!