Commit 8d74b84b by liimin

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

- 优化了 ChatWrapper、Chat、InitQuestions 组件的结构和性能
- 重构了 useChat hook,提高了聊天逻辑的可维护性和可测试性
- 添加了 useSyncState hook 以同步聊天状态
- 调整了聊天数据的处理方式,使用 immer 进行不可变数据更新
- 优化了 SSE 请求的处理逻辑
- 提升了代码的可读性和可维护性
1 parent e25e6f38
......@@ -4,11 +4,11 @@
* @Author: limin
* @Date: 2025-04-16 18:17:38
* @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
*/
import { useEffect, FC } from 'react'
import { useEffect, FC, useCallback } from 'react'
import Chat from '../chat'
import { useChat } from './hooks'
import { InputMessageType } from '../types'
......@@ -18,6 +18,7 @@ import {
ChatListProvider,
ChatRespondingProvider,
} from '@/app/components/base/chat/chat-with-history/context'
import React from 'react'
enum MessageListenerType {
RESET_CHAT = 'reset_chat',
......@@ -39,7 +40,7 @@ type Props = {
inputs?: Record<string, any>
// isShowPracticeButton: boolean
}
const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => {
const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) => {
const {
config,
chatList,
......@@ -52,28 +53,31 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => {
handleFeedback,
// appInfoLoading,
handleNewConversation,
} = useChat(undefined, inputs)
} = useChat(inputs)
useEffect(() => {
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])
const handleGlobalMessage = useCallback((data: MessageListenerProps) => {
try {
switch (data.type) {
case MessageListenerType.RESET_CHAT:
handleNewConversation(undefined, false)
data.payload.message && sendMessage(data.payload.message, InputMessageType.BY_AUTO)
break
}
} catch (error) {
console.error('send failed:', error)
}
}, [])
useEffect(() => {
Object.defineProperty(globalThis, SEND_MESSAGE_KEY, {
value: (data: MessageListenerProps) => {
try {
switch (data.type) {
case MessageListenerType.RESET_CHAT:
handleNewConversation(undefined, false)
data.payload.message && sendMessage(data.payload.message, InputMessageType.BY_AUTO)
break
}
} catch (error) {
console.error('send failed:', error)
}
},
value: handleGlobalMessage,
writable: false,
configurable: true,
enumerable: false,
......@@ -81,7 +85,7 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => {
return () => {
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 }) => {
</ChatConfigProvider>
</div>
)
}
})
export default ChatWrapper
......@@ -13,9 +13,8 @@ type Props = {
}
export const ChatConfigProvider = ({ children, config }: Props) => {
// 只暴露你真正关心的字段(可根据需要扩展)
const value = useMemo(
() => ({
const value = useMemo(() => {
return {
appId: config.appId,
initial_message: config.initial_message,
suggested_questions: config.suggested_questions,
......@@ -24,9 +23,8 @@ export const ChatConfigProvider = ({ children, config }: Props) => {
supportAnnotation: config.supportAnnotation,
supportCitationHitInfo: config.supportCitationHitInfo,
speech_to_text: config.speech_to_text,
}),
[config.initial_message],
) as ChatConfig
}
}, []) as ChatConfig
return <ChatConfigContext.Provider value={value}>{children}</ChatConfigContext.Provider>
}
......
export { useChatWithHistory } from './useChatWithHistory'
export { useUrlParams } from './useUrlParams'
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'
* 保证只在组件首次挂载时执行一次
*/
type urlProps = {
export type Inputs = {
domain?: string
no_header?: string // 是否显示头部
avatar?: string // 头像
......@@ -27,7 +27,7 @@ type ParamsExtenal = {
export const useUrlParams = (): ParamsExtenal => {
const search = globalThis.location?.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 isShowPracticeButton =
// practice_status === PracticeStatus.Practicing || practice_status === PracticeStatus.Failed
......
......@@ -2,11 +2,11 @@
* @Author: liimin 17653212@qq.com
* @Date: 2025-04-16 18:17:38
* @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
* @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 InitQuestions from '@/app/components/base/chat/chat/question/init-questions'
import ChatFooter from './footer'
......@@ -29,7 +29,7 @@ const Chat: FC<ChatProps> = () => {
// const questionIcon = <AnswerIcon imageUrl={AVATAR_USER_URL} />
const isMobile = useBreakpoints() === MediaType.mobile
const handleScrollToBottom = () => {
const handleScrollToBottom = useCallback(() => {
const container = chatContainerRef.current
if (!container) return
const curScrollHeight = container.scrollHeight
......@@ -44,7 +44,7 @@ const Chat: FC<ChatProps> = () => {
})
})
}
}
}, [])
// const chatContainerInnerClassName = `mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}`
// 使用 MutationObserver 监听 DOM 变化
......@@ -73,7 +73,9 @@ const Chat: FC<ChatProps> = () => {
className={cn('relative h-full overflow-y-auto overflow-x-hidden', chatStyles.chatContainer)}>
<div
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 />
<ChatBody />
</div>
......
......@@ -4,22 +4,20 @@
* @Author: limin
* @Date: 2025-06-23 15:19:04
* @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
*/
import type { FC } from 'react'
import { memo, useMemo } from 'react'
import { memo, useMemo, useEffect } from 'react'
import InitSuggest from './init-suggest'
import AnswerIcon from '@/app/components/base/answer-icon'
import cn from '@/utils/classnames'
import { Markdown } from '@/app/components/base/markdown'
import { useChatConfigContext } from '../../chat-with-history/context/chat-config-context'
type InitQuestionsProps = {
chatAnswerContainerInner?: string
}
const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) => {
const InitQuestions: FC = () => {
const { suggested_questions = [], initial_message } = useChatConfigContext()
if (!suggested_questions.length && !initial_message) return null
if (!initial_message && !suggested_questions.length) return null
return useMemo(() => {
const suggestedQuestions = suggested_questions
.filter(q => !!q && q.trim())
......@@ -29,7 +27,7 @@ const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) =>
<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('group relative pr-14')}>
<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 is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!