Commit 8d74b84b by liimin

refactor(chat): 重构聊天组件和逻辑

- 优化了 ChatWrapper、Chat、InitQuestions 组件的结构和性能
- 重构了 useChat hook,提高了聊天逻辑的可维护性和可测试性
- 添加了 useSyncState hook 以同步聊天状态
- 调整了聊天数据的处理方式,使用 immer 进行不可变数据更新
- 优化了 SSE 请求的处理逻辑
- 提升了代码的可读性和可维护性
1 parent e25e6f38
...@@ -4,11 +4,11 @@ ...@@ -4,11 +4,11 @@
* @Author: limin * @Author: limin
* @Date: 2025-04-16 18:17:38 * @Date: 2025-04-16 18:17:38
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-21 20:46:08 * @LastEditTime: 2025-07-23 00:07:10
* @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\chat-wrapper.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\chat-wrapper.tsx
*/ */
import { useEffect, FC } from 'react' import { useEffect, FC, useCallback } from 'react'
import Chat from '../chat' import Chat from '../chat'
import { useChat } from './hooks' import { useChat } from './hooks'
import { InputMessageType } from '../types' import { InputMessageType } from '../types'
...@@ -18,6 +18,7 @@ import { ...@@ -18,6 +18,7 @@ import {
ChatListProvider, ChatListProvider,
ChatRespondingProvider, ChatRespondingProvider,
} from '@/app/components/base/chat/chat-with-history/context' } from '@/app/components/base/chat/chat-with-history/context'
import React from 'react'
enum MessageListenerType { enum MessageListenerType {
RESET_CHAT = 'reset_chat', RESET_CHAT = 'reset_chat',
...@@ -39,7 +40,7 @@ type Props = { ...@@ -39,7 +40,7 @@ type Props = {
inputs?: Record<string, any> inputs?: Record<string, any>
// isShowPracticeButton: boolean // isShowPracticeButton: boolean
} }
const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => { const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) => {
const { const {
config, config,
chatList, chatList,
...@@ -52,17 +53,16 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => { ...@@ -52,17 +53,16 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => {
handleFeedback, handleFeedback,
// appInfoLoading, // appInfoLoading,
handleNewConversation, handleNewConversation,
} = useChat(undefined, inputs) } = useChat(inputs)
useEffect(() => { useEffect(() => {
if (presuppositionQuestion && config.initial_message !== undefined) { if (presuppositionQuestion && config.initial_message !== undefined) {
setTimeout(() => sendMessage(presuppositionQuestion, InputMessageType.BY_AUTO), 0) const timer = setTimeout(() => sendMessage(presuppositionQuestion, InputMessageType.BY_AUTO), 0)
return () => clearTimeout(timer)
} }
}, [presuppositionQuestion, config.initial_message]) }, [presuppositionQuestion, config.initial_message])
useEffect(() => { const handleGlobalMessage = useCallback((data: MessageListenerProps) => {
Object.defineProperty(globalThis, SEND_MESSAGE_KEY, {
value: (data: MessageListenerProps) => {
try { try {
switch (data.type) { switch (data.type) {
case MessageListenerType.RESET_CHAT: case MessageListenerType.RESET_CHAT:
...@@ -73,7 +73,11 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => { ...@@ -73,7 +73,11 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => {
} catch (error) { } catch (error) {
console.error('send failed:', error) console.error('send failed:', error)
} }
}, }, [])
useEffect(() => {
Object.defineProperty(globalThis, SEND_MESSAGE_KEY, {
value: handleGlobalMessage,
writable: false, writable: false,
configurable: true, configurable: true,
enumerable: false, enumerable: false,
...@@ -81,7 +85,7 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => { ...@@ -81,7 +85,7 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => {
return () => { return () => {
if (SEND_MESSAGE_KEY in globalThis) { if (SEND_MESSAGE_KEY in globalThis) {
delete (globalThis as IGlobalThis)[SEND_MESSAGE_KEY] // 使用 Symbol 作为 key delete (globalThis as IGlobalThis)[SEND_MESSAGE_KEY]
} }
} }
}, []) }, [])
...@@ -104,6 +108,6 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => { ...@@ -104,6 +108,6 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => {
</ChatConfigProvider> </ChatConfigProvider>
</div> </div>
) )
} })
export default ChatWrapper export default ChatWrapper
...@@ -13,9 +13,8 @@ type Props = { ...@@ -13,9 +13,8 @@ type Props = {
} }
export const ChatConfigProvider = ({ children, config }: Props) => { export const ChatConfigProvider = ({ children, config }: Props) => {
// 只暴露你真正关心的字段(可根据需要扩展) const value = useMemo(() => {
const value = useMemo( return {
() => ({
appId: config.appId, appId: config.appId,
initial_message: config.initial_message, initial_message: config.initial_message,
suggested_questions: config.suggested_questions, suggested_questions: config.suggested_questions,
...@@ -24,9 +23,8 @@ export const ChatConfigProvider = ({ children, config }: Props) => { ...@@ -24,9 +23,8 @@ export const ChatConfigProvider = ({ children, config }: Props) => {
supportAnnotation: config.supportAnnotation, supportAnnotation: config.supportAnnotation,
supportCitationHitInfo: config.supportCitationHitInfo, supportCitationHitInfo: config.supportCitationHitInfo,
speech_to_text: config.speech_to_text, speech_to_text: config.speech_to_text,
}), }
[config.initial_message], }, []) as ChatConfig
) as ChatConfig
return <ChatConfigContext.Provider value={value}>{children}</ChatConfigContext.Provider> return <ChatConfigContext.Provider value={value}>{children}</ChatConfigContext.Provider>
} }
......
export { useChatWithHistory } from './useChatWithHistory' export { useChatWithHistory } from './useChatWithHistory'
export { useUrlParams } from './useUrlParams' export { useUrlParams } from './useUrlParams'
export { useChat } from './useChat' export { useChat } from './useChat'
export { default as useSyncState } from './useSyncState'
import React from 'react';
type Getter<T> = () => T;
type Setter<T> = (pre: T) => T;
export default function useSyncState<T>(defaultValue: T | Getter<T>) {
const [, forceUpdate] = React.useState(0);
const stateRef = React.useRef<T>(
typeof defaultValue === 'function' ? (defaultValue as Getter<T>)() : defaultValue,
);
const setState = React.useCallback((action: React.SetStateAction<T>) => {
stateRef.current =
typeof action === 'function' ? (action as Setter<T>)(stateRef.current) : action;
forceUpdate((prev) => prev + 1);
}, []);
const getState: Getter<T> = React.useCallback(() => stateRef.current, []);
return [stateRef.current, setState, getState] as const;
}
...@@ -7,7 +7,7 @@ import { PracticeStatus } from '../../types' ...@@ -7,7 +7,7 @@ import { PracticeStatus } from '../../types'
* 保证只在组件首次挂载时执行一次 * 保证只在组件首次挂载时执行一次
*/ */
type urlProps = { export type Inputs = {
domain?: string domain?: string
no_header?: string // 是否显示头部 no_header?: string // 是否显示头部
avatar?: string // 头像 avatar?: string // 头像
...@@ -27,7 +27,7 @@ type ParamsExtenal = { ...@@ -27,7 +27,7 @@ type ParamsExtenal = {
export const useUrlParams = (): ParamsExtenal => { export const useUrlParams = (): ParamsExtenal => {
const search = globalThis.location?.search ?? '' const search = globalThis.location?.search ?? ''
const urlParams = new URLSearchParams(search) const urlParams = new URLSearchParams(search)
const paramsObject: urlProps = Object.fromEntries(urlParams.entries()) const paramsObject: Inputs = Object.fromEntries(urlParams.entries())
const { practice_status, presuppositionProblem, domain, avatar, no_header, ...inputs } = paramsObject const { practice_status, presuppositionProblem, domain, avatar, no_header, ...inputs } = paramsObject
// const isShowPracticeButton = // const isShowPracticeButton =
// practice_status === PracticeStatus.Practicing || practice_status === PracticeStatus.Failed // practice_status === PracticeStatus.Practicing || practice_status === PracticeStatus.Failed
......
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
* @Author: liimin 17653212@qq.com * @Author: liimin 17653212@qq.com
* @Date: 2025-04-16 18:17:38 * @Date: 2025-04-16 18:17:38
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-21 21:07:03 * @LastEditTime: 2025-07-23 20:01:19
* @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, useEffect, useRef } from 'react' import React, { FC, memo, useCallback, useEffect, useRef } 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'
...@@ -29,7 +29,7 @@ const Chat: FC<ChatProps> = () => { ...@@ -29,7 +29,7 @@ const Chat: FC<ChatProps> = () => {
// 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 = () => { const handleScrollToBottom = useCallback(() => {
const container = chatContainerRef.current const container = chatContainerRef.current
if (!container) return if (!container) return
const curScrollHeight = container.scrollHeight const curScrollHeight = container.scrollHeight
...@@ -44,7 +44,7 @@ const Chat: FC<ChatProps> = () => { ...@@ -44,7 +44,7 @@ const Chat: FC<ChatProps> = () => {
}) })
}) })
} }
} }, [])
// 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 变化
...@@ -73,7 +73,9 @@ const Chat: FC<ChatProps> = () => { ...@@ -73,7 +73,9 @@ const Chat: FC<ChatProps> = () => {
className={cn('relative h-full overflow-y-auto overflow-x-hidden', chatStyles.chatContainer)}> className={cn('relative h-full overflow-y-auto overflow-x-hidden', chatStyles.chatContainer)}>
<div <div
ref={chatContainerInnerRef} ref={chatContainerInnerRef}
className={cn('w-full', 'px-8', `mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}`)}> className={cn('w-full', 'px-8', `mx-auto pt-6 w-full max-w-[800px]`, {
'px-4': isMobile,
})}>
<InitQuestions /> <InitQuestions />
<ChatBody /> <ChatBody />
</div> </div>
......
...@@ -4,22 +4,20 @@ ...@@ -4,22 +4,20 @@
* @Author: limin * @Author: limin
* @Date: 2025-06-23 15:19:04 * @Date: 2025-06-23 15:19:04
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-21 22:56:46 * @LastEditTime: 2025-07-23 16:10:28
* @FilePath: \ai-assistant\app\components\base\chat\chat\question\init-questions.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\question\init-questions.tsx
*/ */
import type { FC } from 'react' import type { FC } from 'react'
import { memo, useMemo } from 'react' import { memo, useMemo, useEffect } from 'react'
import InitSuggest from './init-suggest' import InitSuggest from './init-suggest'
import AnswerIcon from '@/app/components/base/answer-icon' import AnswerIcon from '@/app/components/base/answer-icon'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { Markdown } from '@/app/components/base/markdown' import { Markdown } from '@/app/components/base/markdown'
import { useChatConfigContext } from '../../chat-with-history/context/chat-config-context' import { useChatConfigContext } from '../../chat-with-history/context/chat-config-context'
type InitQuestionsProps = {
chatAnswerContainerInner?: string const InitQuestions: FC = () => {
}
const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) => {
const { suggested_questions = [], initial_message } = useChatConfigContext() const { suggested_questions = [], initial_message } = useChatConfigContext()
if (!suggested_questions.length && !initial_message) return null if (!initial_message && !suggested_questions.length) return null
return useMemo(() => { return useMemo(() => {
const suggestedQuestions = suggested_questions const suggestedQuestions = suggested_questions
.filter(q => !!q && q.trim()) .filter(q => !!q && q.trim())
...@@ -29,7 +27,7 @@ const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) => ...@@ -29,7 +27,7 @@ const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) =>
<div className="mb-2 flex last:mb-0"> <div className="mb-2 flex last:mb-0">
<div className="relative h-10 w-10 shrink-0">{<AnswerIcon />}</div> <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="chat-answer-container group ml-4 w-0 grow pb-2">
<div className={cn('group relative pr-14', chatAnswerContainerInner)}> <div className={cn('group relative pr-14')}>
<div <div
className={cn( className={cn(
'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary', 'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary',
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!