Commit e25e6f38 by liimin

refactor(chat): 优化聊天组件初始化逻辑和性能

- 修改了 ChatWrapper 组件中的 useEffect,增加了对 config.initial_message 的判断
- 移除了 ChatConfigProvider 中的 opening_statement 属性
- 调整了 useChat hook 中的逻辑,使用 initial_message 替代 opening_statement
- 优化了 Chat 组件的结构,移除了不必要的类名和属性
- 改进了 InitQuestions 组件的性能,使用 useMemo 避免不必要的渲染
1 parent 9de4be95
/*
* @Descripttion:
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-04-16 18:17:38
* @LastEditors: limin
* @LastEditTime: 2025-07-17 16:34:07
* @LastEditTime: 2025-07-21 20:46:08
* @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\chat-wrapper.tsx
*/
......@@ -55,10 +55,10 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => {
} = useChat(undefined, inputs)
useEffect(() => {
if (presuppositionQuestion) {
sendMessage(presuppositionQuestion, InputMessageType.BY_AUTO)
if (presuppositionQuestion && config.initial_message !== undefined) {
setTimeout(() => sendMessage(presuppositionQuestion, InputMessageType.BY_AUTO), 0)
}
}, [presuppositionQuestion])
}, [presuppositionQuestion, config.initial_message])
useEffect(() => {
Object.defineProperty(globalThis, SEND_MESSAGE_KEY, {
......@@ -85,7 +85,7 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => {
}
}
}, [])
if (config.initial_message === undefined) return null
return (
<div className="h-full overflow-hidden">
<ChatConfigProvider config={config}>
......
......@@ -21,7 +21,6 @@ export const ChatConfigProvider = ({ children, config }: Props) => {
suggested_questions: config.suggested_questions,
file_upload: config.file_upload,
supportFeedback: config.supportFeedback,
opening_statement: config.opening_statement,
supportAnnotation: config.supportAnnotation,
supportCitationHitInfo: config.supportCitationHitInfo,
speech_to_text: config.speech_to_text,
......
......@@ -4,7 +4,7 @@
* @Author: limin
* @Date: 2025-07-10 15:04:55
* @LastEditors: limin
* @LastEditTime: 2025-07-17 18:14:48
* @LastEditTime: 2025-07-21 23:56:43
* @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\hooks\useChat.ts
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
......@@ -61,7 +61,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
const [suggestedQuestions, setSuggestQuestions] = useState<string[]>([])
const conversationMessagesAbortControllerRef = useRef<AbortController | null>(null)
const suggestedQuestionsAbortControllerRef = useRef<AbortController | null>(null)
const chatListRef = useRef<ChatItemInTree[]>([])
const [chatTree, setChatTree] = useState<ChatItemInTree[]>([])
const chatTreeRef = useRef<ChatItemInTree[]>(chatTree)
const [targetMessageId, setTargetMessageId] = useState<string>()
......@@ -73,7 +73,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
isLoading: appInfoLoading,
error: appInfoError,
} = useSWR(installedAppInfo ? null : 'appInfo', fetchAppInfo, { revalidateOnFocus: false })
const appId = useMemo(() => appInfo?.app_id, [appInfo])
const appId = appInfo?.app_id
const swrKey = useMemo(() => {
if (!appId) {
return null
......@@ -95,7 +95,6 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
fileUploadConfig: (cfg as any).system_parameters,
},
supportFeedback: true,
opening_statement: (cfg as any).opening_statement,
initial_message: (cfg as any).opening_statement,
} as ChatConfig
}, [appParams])
......@@ -133,10 +132,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
}, [])
/** Final chat list that will be rendered */
const chatList = useMemo(() => {
return [...threadMessages]
}, [threadMessages])
const chatListRef = useRef<ChatItemInTree[]>(chatList)
const chatList = useMemo(() => [...threadMessages], [threadMessages])
useEffect(() => {
chatListRef.current = chatList
}, [chatList])
......@@ -197,7 +193,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
const handleRestart = useCallback(
(cb?: any) => {
conversationId.current = ''
// conversationId.current = ''
taskIdRef.current = ''
chatListRef.current = []
handleStop()
......
......@@ -4,11 +4,11 @@
* @Author: limin
* @Date: 2025-04-16 18:17:38
* @LastEditors: limin
* @LastEditTime: 2025-07-17 19:45:58
* @LastEditTime: 2025-07-21 16:25:39
* @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\index.tsx
*/
import type { FC } from 'react'
import { useEffect, useState } from 'react'
import { memo, useEffect, useState } from 'react'
import ChatWrapper from './chat-wrapper'
import Loading from '@/app/components/base/loading'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
......@@ -66,4 +66,4 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta
)
}
export default ChatWithHistoryWrapWithCheckToken
export default memo(ChatWithHistoryWrapWithCheckToken)
import { FC, memo } from 'react'
import { FileListInChatInput } from '@/app/components/base/file-uploader'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
import { useChatConfigContext } from '@/app/components/base/chat/chat-with-history/context/chat-config-context'
const FileList: FC = () => {
const { file_upload } = useChatConfigContext ()
return <FileListInChatInput fileConfig={file_upload} />
......
......@@ -3,11 +3,11 @@ import { useToastContext } from '@/app/components/base/toast'
import { FC, memo, useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { CLEAR_BUTTON } from '@/app/components/base/chat/constants'
import { useChatRespondingContext,useChatContext } from '@/app/components/base/chat/chat-with-history/context'
import { useChatRespondingContext, useChatContext } from '@/app/components/base/chat/chat-with-history/context'
const ReStart: FC = () => {
const { t } = useTranslation()
const { notify } = useToastContext()
const { onRestart: restartChat } = useChatContext()
const { onRestart: restartChat } = useChatContext()
const { isResponding } = useChatRespondingContext()
const [showConfirm, setShowConfirm] = useState<boolean>(false)
const handleRestart = useCallback(() => {
......
......@@ -5,8 +5,8 @@ import { useTranslation } from 'react-i18next'
import { useChatRespondingContext,useChatContext } from '@/app/components/base/chat/chat-with-history/context'
const StopRespondingButton: FC = () => {
const { t } = useTranslation()
const { onStopResponding: stopResponding } = useChatContext()
const { isResponding } = useChatRespondingContext()
const { onStopResponding: stopResponding } = useChatContext()
if (!isResponding) return null
return (
<div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2">
......
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 StopResponding from './components/stopResponding'
import cn from '@/utils/classnames'
type FooterProps = {
chatFooterClassName?: string
chatFooterInnerClassName?: string
// isShowPracticeButton: boolean
suggestedQuestions?: string[]
isMobile?: boolean
chatFooterRef: React.RefObject<HTMLDivElement>
chatFooterInnerRef: React.RefObject<HTMLDivElement>
}
const Footer: FC<FooterProps> = ({
chatFooterClassName,
chatFooterInnerClassName,
// isMobile,
// suggestedQuestions,
// isShowPracticeButton,
chatFooterRef,
chatFooterInnerRef,
}) => {
const Footer: FC<FooterProps> = ({ isMobile, chatFooterRef, chatFooterInnerRef }) => {
return (
<div
className={`absolute bottom-0 flex justify-center bg-chat-input-mask ${chatFooterClassName}`}
ref={chatFooterRef}>
<div ref={chatFooterInnerRef} className={cn('relative', chatFooterInnerClassName)}>
<div className={`absolute bottom-0 flex justify-center bg-chat-input-mask pb-4 w-full`} ref={chatFooterRef}>
<div
ref={chatFooterInnerRef}
className={cn('relative', `mx-auto w-full max-w-[800px] ${isMobile ? 'px-2' : 'px-4'}`)}>
<div className="mb-2 flex items-center justify-between relative h-8">
{/* {isShowPracticeButton && <Practice />} */}
{ <StopResponding />}
{<StopResponding />}
</div>
{/* {!!suggestedQuestions?.length && <TryToAsk suggestedQuestions={suggestedQuestions} isMobile={isMobile} />} */}
{<ChatInput />}
......
......@@ -2,17 +2,15 @@
* @Author: liimin 17653212@qq.com
* @Date: 2025-04-16 18:17:38
* @LastEditors: limin
* @LastEditTime: 2025-07-16 18:48:45
* @LastEditTime: 2025-07-21 21:07:03
* @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
*/
import React, { FC, memo, useEffect, useRef } from 'react'
import AnswerIcon from '@/app/components/base/answer-icon'
import cn from '@/utils/classnames'
import InitQuestions from '@/app/components/base/chat/chat/question/init-questions'
import ChatFooter from './footer'
import chatStyles from './chat.module.css'
import { AVATAR_USER_URL, AVATAR_AI_URL } from '@/app/components/base/chat/constants'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import ChatBody from './body'
......@@ -48,9 +46,7 @@ const Chat: FC<ChatProps> = () => {
}
}
const chatContainerInnerClassName = `mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}`
const chatFooterClassName = 'pb-4 w-full'
const chatFooterInnerClassName = `mx-auto w-full max-w-[800px] ${isMobile ? 'px-2' : 'px-4'}`
// const chatContainerInnerClassName = `mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}`
// 使用 MutationObserver 监听 DOM 变化
useEffect(() => {
const container = chatContainerRef.current
......@@ -75,20 +71,14 @@ const Chat: FC<ChatProps> = () => {
<div
ref={chatContainerRef}
className={cn('relative h-full overflow-y-auto overflow-x-hidden', chatStyles.chatContainer)}>
<div ref={chatContainerInnerRef} className={cn('w-full', 'px-8', chatContainerInnerClassName)}>
<div
ref={chatContainerInnerRef}
className={cn('w-full', 'px-8', `mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}`)}>
<InitQuestions />
<ChatBody />
</div>
</div>
<ChatFooter
chatFooterRef={chatFooterRef}
chatFooterInnerRef={chatFooterInnerRef}
chatFooterClassName={chatFooterClassName}
chatFooterInnerClassName={chatFooterInnerClassName}
// suggestedQuestions={[]}
isMobile={isMobile}
// isShowPracticeButton={isShowPracticeButton}
/>
<ChatFooter chatFooterRef={chatFooterRef} chatFooterInnerRef={chatFooterInnerRef} isMobile={isMobile} />
</div>
)
}
......
/*
* @Descripttion:
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-06-23 15:19:04
* @LastEditors: limin
* @LastEditTime: 2025-07-17 16:32:28
* @LastEditTime: 2025-07-21 22:56:46
* @FilePath: \ai-assistant\app\components\base\chat\chat\question\init-questions.tsx
*/
import type { FC } from 'react'
import { memo } from 'react'
import { memo, useMemo } from 'react'
import InitSuggest from './init-suggest'
import AnswerIcon from '@/app/components/base/answer-icon'
import cn from '@/utils/classnames'
......@@ -18,27 +18,29 @@ type InitQuestionsProps = {
chatAnswerContainerInner?: string
}
const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) => {
const { suggested_questions, initial_message } = useChatConfigContext()
if (!suggested_questions?.length || !initial_message?.trim()) return null
const suggestedQuestions = suggested_questions
.filter(q => !!q && q.trim())
.sort(() => Math.random() - 0.5)
.slice(0, 3)
return (
<div className="mb-2 flex last:mb-0">
<div className="relative h-10 w-10 shrink-0">{<AnswerIcon />}</div>
<div className="chat-answer-container group ml-4 w-0 grow pb-2">
<div className={cn('group relative pr-14', chatAnswerContainerInner)}>
<div
className={cn(
'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary',
)}>
<Markdown content={initial_message} />
<InitSuggest suggestedQuestions={suggestedQuestions} />
const { suggested_questions = [], initial_message } = useChatConfigContext()
if (!suggested_questions.length && !initial_message) return null
return useMemo(() => {
const suggestedQuestions = suggested_questions
.filter(q => !!q && q.trim())
.sort(() => Math.random() - 0.5)
.slice(0, 3)
return (
<div className="mb-2 flex last:mb-0">
<div className="relative h-10 w-10 shrink-0">{<AnswerIcon />}</div>
<div className="chat-answer-container group ml-4 w-0 grow pb-2">
<div className={cn('group relative pr-14', chatAnswerContainerInner)}>
<div
className={cn(
'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary',
)}>
{initial_message && <Markdown content={initial_message} />}
{suggestedQuestions.length > 0 && <InitSuggest suggestedQuestions={suggestedQuestions} />}
</div>
</div>
</div>
</div>
</div>
)
)
}, [initial_message])
}
export default memo(InitQuestions)
export default InitQuestions
/*
* @Descripttion:
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-07-15 09:16:38
* @LastEditors: limin
* @LastEditTime: 2025-07-17 16:31:54
* @LastEditTime: 2025-07-21 16:39:18
* @FilePath: \ai-assistant\app\components\base\chat\chat\question\init-suggest.tsx
*/
import type { FC } from 'react'
......
/*
* @Descripttion:
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-04-16 18:17:38
* @LastEditors: limin
* @LastEditTime: 2025-07-17 16:32:50
* @LastEditTime: 2025-07-21 16:36:40
* @FilePath: \ai-assistant\app\components\base\chat\chat\question\question.tsx
*/
import type { FC } from 'react'
import { memo } from 'react'
import { memo, useMemo } from 'react'
import { CssTransform } from '@/app/components/base/chat/embedded-chatbot/theme/utils'
import { Markdown } from '@/app/components/base/markdown'
import { useChatBodyContext } from '@/app/components/base/chat/chat/body/context'
......
......@@ -12,7 +12,7 @@ const ImageLink: FC<LinkProps> = ({ node }) => {
className="max-w-full h-auto rounded-lg cursor-pointer hover:opacity-90"
onClick={() => setImagePreviewUrl(node.properties.href)}
/>
<ImagePreview url={imagePreviewUrl} onCancel={() => setImagePreviewUrl('')} title={''} />
{imagePreviewUrl && <ImagePreview url={imagePreviewUrl} onCancel={() => setImagePreviewUrl('')} title={''} />}
</>
)
}
......
......@@ -24,6 +24,6 @@ const Paragraph = (paragraph: any) => {
// if(node.properties.dataDisable==='disable'){
// return <div className="practice-tags">{children}</div>
// }
return <p>{children}</p>
return <div>{children}</div>
}
export default Paragraph
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!