Commit 63bf4926 by liimin

refactor(base): 重构聊天组件

- 移除不必要的 props 和 context
- 优化组件结构和逻辑
- 提高代码复用性和可维护性
1 parent 5b99a30e
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn * @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17 * @Date: 2025-04-22 09:29:17
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-02 19:52:58 * @LastEditTime: 2025-07-03 18:48:32
* @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
* @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 { useCallback, useEffect, useMemo, useState, FC, useRef, use } from 'react' import { useCallback, useEffect, useMemo, useState, FC, useRef, use } from 'react'
import Chat from '../chat' import Chat from '../chat'
import type { ChatConfig, ChatItem, ChatItemInTree, OnSend } from '../types' import type { ChatConfig, ChatItem, ChatItemInTree, OnSend } from '../types'
import { useChat } from '../chat/hooks' import { useChat, useChatMethods } from '../chat/hooks'
import { getLastAnswer, isValidGeneratedAnswer } from '../utils' import { getLastAnswer, isValidGeneratedAnswer } from '../utils'
import { useChatWithHistoryContext } from './context' import { useChatWithHistoryContext } from './context'
import { InputVarType } from '@/app/components/workflow/types' import { InputVarType } from '@/app/components/workflow/types'
...@@ -23,12 +23,7 @@ import { Markdown } from '@/app/components/base/markdown' ...@@ -23,12 +23,7 @@ import { Markdown } from '@/app/components/base/markdown'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
// import { SELF_INPUT } from "@/app/components/base/chat/constants"; // import { SELF_INPUT } from "@/app/components/base/chat/constants";
import { InputMessageType } from '../types' import { InputMessageType } from '../types'
type Props = { import { useChatWithHistory } from './hooks'
avatar: string
aiAvatar: string
presuppositionQuestion?: string
// hasAutoSended: React.MutableRefObject<boolean>
}
enum MessageListenerType { enum MessageListenerType {
RESET_CHAT = 'reset_chat', RESET_CHAT = 'reset_chat',
} }
...@@ -39,14 +34,24 @@ type MessageListenerProps = { ...@@ -39,14 +34,24 @@ type MessageListenerProps = {
} }
type: MessageListenerType type: MessageListenerType
} }
const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, presuppositionQuestion }) => { const SEND_MESSAGE_KEY = 'sendMessage' // 使用 Symbol 避免命名冲突
// 扩展 globalThis 类型
interface IGlobalThis {
[SEND_MESSAGE_KEY]?: (data: MessageListenerProps) => void
}
type Props = {
presuppositionQuestion?: string
inputs?: Record<string, any>
isShowPracticeButton: boolean
}
const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPracticeButton }) => {
const chatRef = useRef<{ handleSend: Function }>()
const { const {
appParams, appParams,
appPrevChatTree,
currentConversationId, currentConversationId,
currentConversationItem, appPrevChatTree,
currentConversationInputs,
newConversationInputs, newConversationInputs,
newConversationInputsRef,
handleNewConversation, handleNewConversation,
handleNewConversationCompleted, handleNewConversationCompleted,
isInstalledApp, isInstalledApp,
...@@ -55,165 +60,39 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, presuppositionQuestion }) => ...@@ -55,165 +60,39 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, presuppositionQuestion }) =>
currentChatInstanceRef, currentChatInstanceRef,
clearChatList, clearChatList,
setClearChatList, setClearChatList,
setIsResponding, } = useChatWithHistory(undefined, inputs)
isShowPracticeButton,
} = useChatWithHistoryContext()
const appConfig = useMemo(() => {
const config = appParams || {}
return {
...config,
file_upload: {
...(config as any).file_upload,
fileUploadConfig: (config as any).system_parameters,
},
supportFeedback: true,
opening_statement: currentConversationId
? currentConversationItem?.introduction
: (config as any).opening_statement,
initial_message: (config as any).opening_statement,
} as ChatConfig
}, [appParams, currentConversationItem?.introduction, currentConversationId])
const {
chatList,
setTargetMessageId,
handleSend,
handleStop,
isResponding: respondingState,
// suggestedQuestions,
handleRestart,
} = useChat(
appConfig,
{
inputs: (currentConversationId ? currentConversationInputs : newConversationInputs) as any,
inputsForm: [], //InputsForm,
},
appPrevChatTree,
taskId => stopChatMessageResponding('', taskId, isInstalledApp, appId),
clearChatList,
setClearChatList,
currentConversationId,
)
const hasAutoSended = useRef<boolean>(false)
const SEND_MESSAGE_KEY = 'sendMessage' // 使用 Symbol 避免命名冲突
// 扩展 globalThis 类型
interface IGlobalThis {
[SEND_MESSAGE_KEY]?: (data: MessageListenerProps) => void
}
useEffect(() => {
Object.defineProperty(globalThis, SEND_MESSAGE_KEY, {
value: (data: MessageListenerProps) => {
try {
switch (data.type) {
case MessageListenerType.RESET_CHAT:
handleNewConversation()
data.payload.message &&
doSend({
message: data.payload.message,
type: InputMessageType.SYSTEM,
})
break
}
} catch (error) {
console.error('send failed:', error)
}
},
writable: false,
configurable: true,
enumerable: false,
})
return () => {
if (SEND_MESSAGE_KEY in globalThis) {
delete (globalThis as IGlobalThis)[SEND_MESSAGE_KEY] // 使用 Symbol 作为 key
}
}
}, [])
useEffect(() => { useEffect(() => {
if (currentChatInstanceRef.current) currentChatInstanceRef.current.handleStop = handleStop if (presuppositionQuestion) {
// eslint-disable-next-line react-hooks/exhaustive-deps chatRef.current?.handleSend(
}, []) {
message: presuppositionQuestion,
useEffect(() => { type: InputMessageType.SYSTEM,
if (!hasAutoSended.current && presuppositionQuestion) { },
hasAutoSended.current = true undefined,
doSend({ )
message: presuppositionQuestion,
type: InputMessageType.SYSTEM,
})
} }
}, [presuppositionQuestion]) }, [presuppositionQuestion])
useEffect(() => {
setIsResponding(respondingState)
}, [respondingState, setIsResponding])
const doSend: OnSend = useCallback(
(messageObj, files, isRegenerate = false, parentAnswer: ChatItem | null = null) => {
const data: any = {
query: messageObj.message,
files,
inputs: { ...newConversationInputs, queryType: messageObj.type },
conversation_id: currentConversationId,
parent_message_id: (isRegenerate ? parentAnswer?.id : getLastAnswer(chatList)?.id) || null,
}
handleSend(getUrl('chat-messages', isInstalledApp, appId || ''), data, {
onGetSuggestedQuestions: responseItemId => fetchSuggestedQuestions(responseItemId, isInstalledApp, appId),
onConversationComplete: currentConversationId ? undefined : handleNewConversationCompleted,
isPublicAPI: !isInstalledApp,
})
},
[
chatList,
handleNewConversationCompleted,
handleSend,
currentConversationId,
currentConversationItem,
currentConversationInputs,
newConversationInputs,
isInstalledApp,
appId,
],
)
const doRegenerate = useCallback(
(chatItem: ChatItemInTree) => {
const question = chatList.find(item => item.id === chatItem.parentMessageId)!
const parentAnswer = chatList.find(item => item.id === question.parentMessageId)
doSend(
{ message: question.content, type: InputMessageType.SELF },
question.message_files,
true,
isValidGeneratedAnswer(parentAnswer) ? parentAnswer : null,
)
},
[chatList, doSend],
)
const messageList = useMemo(() => {
return chatList
}, [chatList, currentConversationId])
const onRestart = useCallback(() => {
handleRestart(handleNewConversation)
}, [handleRestart, handleNewConversation])
const answerIcon = <AnswerIcon imageUrl={aiAvatar} />
const questionIcon = <AnswerIcon imageUrl={avatar} />
return ( return (
<div className="h-full overflow-hidden"> <div className="h-full overflow-hidden">
<Chat <Chat
config={appConfig} ref={chatRef}
chatList={messageList} inputs={inputs}
isResponding={respondingState}
onSend={doSend}
onRestart={onRestart}
onRegenerate={doRegenerate}
onStopResponding={handleStop}
onFeedback={handleFeedback}
answerIcon={answerIcon}
questionIcon={questionIcon}
isShowPracticeButton={isShowPracticeButton} isShowPracticeButton={isShowPracticeButton}
appParams={appParams}
clearChatList={clearChatList}
setClearChatList={setClearChatList}
currentChatInstanceRef={currentChatInstanceRef}
handleFeedback={handleFeedback}
appId={appId || ''}
isInstalledApp={isInstalledApp}
currentConversationId={currentConversationId}
appPrevChatTree={appPrevChatTree}
newConversationInputs={newConversationInputs}
newConversationInputsRef={newConversationInputsRef}
handleNewConversation={handleNewConversation}
handleNewConversationCompleted={handleNewConversationCompleted}
/> />
</div> </div>
) )
......
...@@ -30,17 +30,14 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp, inputs: Reco ...@@ -30,17 +30,14 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp, inputs: Reco
) )
const [clearChatList, setClearChatList] = useState(false) const [clearChatList, setClearChatList] = useState(false)
const [isResponding, setIsResponding] = useState(false)
const appPrevChatTree = useMemo(() => [], []) const appPrevChatTree = useMemo(() => [], [])
const { t } = useTranslation() const { t } = useTranslation()
const newConversationInputsRef = useRef<Record<string, any>>({}) const newConversationInputsRef = useRef<Record<string, any>>({})
const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>(inputs) const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>(inputs)
const { notify } = useToastContext() const { notify } = useToastContext()
const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ const currentChatInstanceRef = useRef<{ handleStop: () => void }>({
handleStop: noop, handleStop: noop,
}) })
const handleNewConversation = useCallback( const handleNewConversation = useCallback(
(inputs?: Record<string, any>) => { (inputs?: Record<string, any>) => {
currentChatInstanceRef.current.handleStop() currentChatInstanceRef.current.handleStop()
...@@ -91,7 +88,7 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp, inputs: Reco ...@@ -91,7 +88,7 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp, inputs: Reco
currentChatInstanceRef, currentChatInstanceRef,
clearChatList, clearChatList,
setClearChatList, setClearChatList,
isResponding, // isResponding,
setIsResponding, // setIsResponding,
} }
} }
...@@ -16,7 +16,6 @@ import cn from '@/utils/classnames' ...@@ -16,7 +16,6 @@ import cn from '@/utils/classnames'
// import { SELF_INPUT } from "@/app/components/base/chat/constants"; // import { SELF_INPUT } from "@/app/components/base/chat/constants";
import { InputMessageType, PracticeStatus } from '../types' import { InputMessageType, PracticeStatus } from '../types'
import { AVATAR_USER_URL, AVATAR_AI_URL, MAIN_TITLE } from '@/app/components/base/chat/constants' import { AVATAR_USER_URL, AVATAR_AI_URL, MAIN_TITLE } from '@/app/components/base/chat/constants'
type ChatWithHistoryProps = { type ChatWithHistoryProps = {
className?: string className?: string
} }
...@@ -55,119 +54,36 @@ const isShowPracticeButton = practice_status === PracticeStatus.Practicing || pr ...@@ -55,119 +54,36 @@ const isShowPracticeButton = practice_status === PracticeStatus.Practicing || pr
const avatarUrl: string = avatar ?? AVATAR_USER_URL const avatarUrl: string = avatar ?? AVATAR_USER_URL
const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => { const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {
const { appInfoError, appInfoLoading, appChatListDataLoading, chatShouldReloadKey, isMobile, handleNewConversation } = const { appInfoError, appInfoLoading, isMobile } = useChatWithHistoryContext()
useChatWithHistoryContext()
if (appInfoLoading) { if (appInfoLoading) {
return <Loading type="app" /> return <Loading type="app" />
} } else if (appInfoError) {
if (appInfoError) {
return <AppUnavailable /> return <AppUnavailable />
} } else {
return ( return (
<div className={cn('flex h-full bg-background-default-burn', isMobile && 'flex-col', className)}> <div className={cn('flex h-full bg-background-default-burn', isMobile && 'flex-col', className)}>
<div className={cn('relative grow', isMobile && 'h-[calc(100%_-_56px)] p-0')}> <div className={cn('relative grow', isMobile && 'h-[calc(100%_-_56px)] p-0')}>
<div className={cn('flex h-full flex-col overflow-hidden border-components-panel-border-subtle chat-panel-bg')}> <div
{!newInputs.no_header && <Header avatar={avatarUrl} title={MAIN_TITLE} />} className={cn('flex h-full flex-col overflow-hidden border-components-panel-border-subtle chat-panel-bg')}>
{!appChatListDataLoading && ( {
<ChatWrapper <ChatWrapper
presuppositionQuestion={presuppositionProblem} presuppositionQuestion={presuppositionProblem}
// doClear={doClear} isShowPracticeButton={isShowPracticeButton}
// hasAutoSended={hasAutoSended} inputs={newInputs}
key={chatShouldReloadKey} />
avatar={avatarUrl} }
aiAvatar={AVATAR_AI_URL} </div>
/>
)}
</div> </div>
</div> </div>
</div> )
) }
} }
export type ChatWithHistoryWrapProps = { export type ChatWithHistoryWrapProps = {
installedAppInfo?: any //InstalledApp installedAppInfo?: any //InstalledApp
className?: string className?: string
} }
const ChatWithHistoryWrap: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, className }) => {
// const media = useBreakpoints()
// const isMobile = media === MediaType.mobile
// const themeBuilder = useThemeContext()
const {
// appInfoError,
// appInfoLoading,
// appData,
appParams,
// appMeta,
// appChatListDataLoading,
currentConversationId,
appPrevChatTree,
newConversationInputs,
newConversationInputsRef,
handleNewConversation,
// handleChangeConversation,
handleNewConversationCompleted,
// chatShouldReloadKey,
isInstalledApp,
// appId,
handleFeedback,
currentChatInstanceRef,
// clearChatList,
// setClearChatList,
isResponding,
setIsResponding,
} = useChatWithHistory(installedAppInfo, newInputs)
return (
<ChatWithHistoryContext.Provider
value={{
// appInfoError,
// appInfoLoading,
// appData,
appParams,
// appMeta,
// appChatListDataLoading,
currentConversationId,
currentConversationItem: undefined,
appPrevChatTree,
// pinnedConversationList,
// conversationList,
newConversationInputs,
newConversationInputsRef,
// handleNewConversationInputsChange,
// inputsForms,
handleNewConversation,
// handleStartChat,
// handleChangeConversation,
// handlePinConversation,
// handleUnpinConversation,
// handleDeleteConversation,
// conversationRenaming,
// handleRenameConversation,
handleNewConversationCompleted,
// chatShouldReloadKey,
// isMobile,
isInstalledApp,
// appId,
handleFeedback,
currentChatInstanceRef,
// themeBuilder,
// sidebarCollapseState,
// handleSidebarCollapse,
// clearChatList,
// setClearChatList,
isResponding,
setIsResponding,
currentConversationInputs: null,
// setCurrentConversationInputs,
isShowPracticeButton,
}}>
<ChatWithHistory className={className} />
</ChatWithHistoryContext.Provider>
)
}
const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, className }) => { const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, className }) => {
const [initialized, setInitialized] = useState(false) const [initialized, setInitialized] = useState(false)
const [appUnavailable, setAppUnavailable] = useState<boolean>(false) const [appUnavailable, setAppUnavailable] = useState<boolean>(false)
...@@ -191,7 +107,7 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta ...@@ -191,7 +107,7 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta
}, [initialized, installedAppInfo]) // 添加正确依赖 }, [initialized, installedAppInfo]) // 添加正确依赖
if (!initialized) return null if (!initialized) return null
else if (appUnavailable) return <AppUnavailable isUnknownReason={isUnknownReason} /> else if (appUnavailable) return <AppUnavailable isUnknownReason={isUnknownReason} />
else return <ChatWithHistoryWrap installedAppInfo={installedAppInfo} className={className} /> else return <ChatWithHistory className={className} />
} }
export default ChatWithHistoryWrapWithCheckToken export default ChatWithHistoryWrapWithCheckToken
import { create } from 'zustand'
import { InputMessageProp } from '../types'
import { FileEntity } from '../../file-uploader/types'
import { noop } from 'lodash-es'
type State = {
handleNewConversation: () => void
handleSend: (query: InputMessageProp, files: FileEntity[] | undefined) => void
}
type Action = {
setHandleNewConversation: (fn: () => void) => void
setHandleSend: (fn: (query: InputMessageProp, files: FileEntity[] | undefined) => void) => void
}
export const useChatStore = create<State & Action>(set => ({
handleNewConversation: noop,
setHandleNewConversation: handleNewConversation => set({ handleNewConversation }),
handleSend: noop,
setHandleSend: handleSend => set({ handleSend }),
}))
...@@ -16,19 +16,16 @@ import AnswerIcon from '@/app/components/base/answer-icon' ...@@ -16,19 +16,16 @@ import AnswerIcon from '@/app/components/base/answer-icon'
import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows' import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { FileList } from '@/app/components/base/file-uploader' import { FileList } from '@/app/components/base/file-uploader'
import { useChatContext } from '../context'
type AnswerProps = { type AnswerProps = {
item: ChatItem item: ChatItem
question: string question: string
index: number index: number
config?: ChatConfig
answerIcon?: ReactNode answerIcon?: ReactNode
responding?: boolean
showPromptLog?: boolean showPromptLog?: boolean
isLast?: boolean isLast?: boolean
chatAnswerContainerInner?: string chatAnswerContainerInner?: string
hideProcessDetail?: boolean
// appData?: AppData
noChatInput?: boolean noChatInput?: boolean
switchSibling?: (siblingMessageId: string) => void switchSibling?: (siblingMessageId: string) => void
} }
...@@ -36,16 +33,11 @@ const Answer: FC<AnswerProps> = ({ ...@@ -36,16 +33,11 @@ const Answer: FC<AnswerProps> = ({
item, item,
question, question,
index, index,
config,
answerIcon, answerIcon,
responding,
showPromptLog, showPromptLog,
isLast, isLast,
chatAnswerContainerInner, chatAnswerContainerInner,
hideProcessDetail,
// appData,
noChatInput, noChatInput,
switchSibling,
}) => { }) => {
const { t } = useTranslation() const { t } = useTranslation()
const { content, citation, agent_thoughts, more, annotation, workflowProcess, allFiles, message_files } = item const { content, citation, agent_thoughts, more, annotation, workflowProcess, allFiles, message_files } = item
...@@ -55,7 +47,8 @@ const Answer: FC<AnswerProps> = ({ ...@@ -55,7 +47,8 @@ const Answer: FC<AnswerProps> = ({
const [contentWidth, setContentWidth] = useState(0) const [contentWidth, setContentWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null) const contentRef = useRef<HTMLDivElement>(null)
const { config, isResponding } = useChatContext()
const responding = isLast && isResponding
const getContainerWidth = () => { const getContainerWidth = () => {
if (containerRef.current) setContainerWidth(containerRef.current?.clientWidth + 16) if (containerRef.current) setContainerWidth(containerRef.current?.clientWidth + 16)
} }
......
...@@ -6,12 +6,14 @@ import SuggestedQuestions from './suggested-questions' ...@@ -6,12 +6,14 @@ import SuggestedQuestions from './suggested-questions'
// import { EditTitle } from "@/app/components/app/annotation/edit-annotation-modal/edit-item"; // import { EditTitle } from "@/app/components/app/annotation/edit-annotation-modal/edit-item";
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 { useChatContext } from '../context'
type InitQuestionsProps = { type InitQuestionsProps = {
config: ChatConfig // config: ChatConfig
answerIcon: ReactNode answerIcon: ReactNode
chatAnswerContainerInner?: string chatAnswerContainerInner?: string
} }
const InitQuestions: FC<InitQuestionsProps> = ({ config, answerIcon, chatAnswerContainerInner }) => { const InitQuestions: FC<InitQuestionsProps> = ({ answerIcon, chatAnswerContainerInner }) => {
const {config} = useChatContext()
const questions = useMemo(() => { const questions = useMemo(() => {
const { suggested_questions, initial_message } = config const { suggested_questions, initial_message } = config
const suggestedQuestions = suggested_questions const suggestedQuestions = suggested_questions
...@@ -40,9 +42,4 @@ const InitQuestions: FC<InitQuestionsProps> = ({ config, answerIcon, chatAnswerC ...@@ -40,9 +42,4 @@ const InitQuestions: FC<InitQuestionsProps> = ({ config, answerIcon, chatAnswerC
</div> </div>
) )
} }
export default memo(InitQuestions)
const MemoInitQuestions = memo(InitQuestions, (prev, next) => {
return prev.config.initial_message === next.config.initial_message && prev.config.suggested_questions?.length === next.config.suggested_questions?.length
})
export default MemoInitQuestions
...@@ -23,34 +23,32 @@ import Confirm from '@/app/components/base/confirm' ...@@ -23,34 +23,32 @@ import Confirm from '@/app/components/base/confirm'
type ChatInputAreaProps = { type ChatInputAreaProps = {
showFeatureBar?: boolean showFeatureBar?: boolean
showFileUpload?: boolean showFileUpload?: boolean
featureBarDisabled?: boolean // featureBarDisabled?: boolean
onFeatureBarClick?: (state: boolean) => void onFeatureBarClick?: (state: boolean) => void
visionConfig?: FileUpload // visionConfig?: FileUpload
speechToTextConfig?: EnableType // speechToTextConfig?: EnableType
onSend?: OnSend
onRestart: () => void
// inputs?: Record<string, any> // inputs?: Record<string, any>
// inputsForm?: InputForm[] // inputsForm?: InputForm[]
// theme?: Theme | null // theme?: Theme | null
isResponding?: boolean
disabled?: boolean disabled?: boolean
} }
const ChatInputArea = ({ const ChatInputArea = ({
showFeatureBar, showFeatureBar,
showFileUpload, showFileUpload,
featureBarDisabled, // featureBarDisabled,
onFeatureBarClick, onFeatureBarClick,
visionConfig, // visionConfig,
speechToTextConfig = { enabled: true }, // speechToTextConfig = { enabled: true },
onRestart,
// inputs = {}, // inputs = {},
// inputsForm = [], // inputsForm = [],
// theme, // theme,
isResponding,
// disabled, // disabled,
}: ChatInputAreaProps) => { }: ChatInputAreaProps) => {
const { t } = useTranslation() const { t } = useTranslation()
const { onSend, onRestart, isResponding,config } = useChatContext()
const { notify } = useToastContext() const { notify } = useToastContext()
const visionConfig = config.file_upload
const speechToTextConfig = config.speech_to_text
const { const {
wrapperRef, wrapperRef,
textareaRef, textareaRef,
...@@ -75,8 +73,9 @@ const ChatInputArea = ({ ...@@ -75,8 +73,9 @@ const ChatInputArea = ({
const historyRef = useRef(['']) const historyRef = useRef([''])
const [currentIndex, setCurrentIndex] = useState(-1) const [currentIndex, setCurrentIndex] = useState(-1)
const isComposingRef = useRef(false) const isComposingRef = useRef(false)
const { onSend } = useChatContext() // const { onSend } = useChatContext()
const [showConfirm, setShowConfirm] = useState<boolean>(false) const [showConfirm, setShowConfirm] = useState<boolean>(false)
const featureBarDisabled = isResponding
const handleSend = () => { const handleSend = () => {
if (isResponding) { if (isResponding) {
notify({ notify({
......
...@@ -2,28 +2,26 @@ ...@@ -2,28 +2,26 @@
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { createContext, useContext } from 'use-context-selector' import { createContext, useContext } from 'use-context-selector'
import type { ChatProps } from './index'
import { noop } from 'lodash-es' import { noop } from 'lodash-es'
import { ChatConfig, ChatItem, Feedback, OnRegenerate, OnSend } from '../types'
export type ChatContextValue = Pick<ChatProps, 'config' export type ChatContextValue = {
| 'isResponding' config: ChatConfig
| 'chatList' chatList: ChatItem[]
// | 'showPromptLog' isResponding?: boolean
| 'questionIcon' onSend: OnSend
| 'answerIcon' onRegenerate?: OnRegenerate
| 'onSend' onStopResponding?: () => void
| 'onRegenerate' onRestart: () => void
| 'onStopResponding' onFeedback?: (messageId: string, feedback: Feedback) => void
| 'onRestart' }
// | 'onAnnotationEdited'
// | 'onAnnotationAdded'
// | 'onAnnotationRemoved'
| 'onFeedback'
>
const ChatContext = createContext<ChatContextValue>({ const ChatContext = createContext<ChatContextValue>({
chatList: [], config: {} as ChatConfig,
onRestart: noop, onRestart: noop,
onSend: noop,
chatList: [],
onFeedback:noop
}) })
type ChatContextProviderProps = { type ChatContextProviderProps = {
...@@ -35,35 +33,24 @@ export const ChatContextProvider = ({ ...@@ -35,35 +33,24 @@ export const ChatContextProvider = ({
config, config,
isResponding, isResponding,
chatList, chatList,
// showPromptLog,
questionIcon,
answerIcon,
onSend, onSend,
onRegenerate, onRegenerate,
onRestart, onRestart,
// onAnnotationEdited,
// onAnnotationAdded,
// onAnnotationRemoved,
onFeedback, onFeedback,
onStopResponding onStopResponding,
}: ChatContextProviderProps) => { }: ChatContextProviderProps) => {
return ( return (
<ChatContext.Provider value={{ <ChatContext.Provider
config, value={{
isResponding, config,
chatList: chatList || [], isResponding,
// showPromptLog, chatList: chatList || [],
questionIcon, onSend,
answerIcon, onRegenerate,
onSend, onRestart,
onRegenerate, onFeedback,
// onAnnotationEdited, onStopResponding,
// onAnnotationAdded, }}>
// onAnnotationRemoved,
onRestart,
onFeedback,
onStopResponding
}}>
{children} {children}
</ChatContext.Provider> </ChatContext.Provider>
) )
......
import React, { FC, memo } from 'react' import React, { FC, memo, useMemo} from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import type { ChatConfig, OnSend } from '@/app/components/base/chat/types' import type { ChatConfig, OnSend } from '@/app/components/base/chat/types'
import type { ThemeBuilder } from '@/app/components/base/chat/embedded-chatbot/theme/theme-context' import type { ThemeBuilder } from '@/app/components/base/chat/embedded-chatbot/theme/theme-context'
...@@ -8,48 +8,54 @@ import Practice from './practice' ...@@ -8,48 +8,54 @@ import Practice from './practice'
import ChatInputArea from '../chat-input-area' import ChatInputArea from '../chat-input-area'
import StopResponding from './stopResponding' import StopResponding from './stopResponding'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { useChatContext } from '../context'
type FooterProps = { type FooterProps = {
chatFooterClassName?: string chatFooterClassName?: string
chatFooterInnerClassName?: string chatFooterInnerClassName?: string
isShowPracticeButton: boolean isShowPracticeButton: boolean
suggestedQuestions?: string[] suggestedQuestions?: string[]
onSend: OnSend
noStopResponding?: boolean
onStopResponding?: () => void
noChatInput?: boolean
isMobile?: boolean isMobile?: boolean
inputDisabled?: boolean
showFeatureBar?: boolean
showFileUpload?: boolean
onFeatureBarClick?: (state: boolean) => void
onRestart: () => void
inputs?: Record<string, any>
inputsForm?: InputForm[]
// themeBuilder?: ThemeBuilder
config?: ChatConfig
chatFooterRef: React.RefObject<HTMLDivElement> chatFooterRef: React.RefObject<HTMLDivElement>
chatFooterInnerRef: React.RefObject<HTMLDivElement> chatFooterInnerRef: React.RefObject<HTMLDivElement>
isResponding?: boolean
} }
const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName, onSend, noStopResponding, onStopResponding, noChatInput, isMobile, inputDisabled, showFeatureBar, showFileUpload, onFeatureBarClick, onRestart, inputs, inputsForm, config, suggestedQuestions, isShowPracticeButton, chatFooterRef, chatFooterInnerRef, isResponding }) => { const Footer: FC<FooterProps> = ({
const { t } = useTranslation() chatFooterClassName,
const hasTryToAsk = config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length && onSend chatFooterInnerClassName,
isMobile,
suggestedQuestions,
isShowPracticeButton,
chatFooterRef,
chatFooterInnerRef,
}) => {
console.log('Footer')
const { config } = useChatContext()
const hasTryToAsk = useMemo(
() => config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length,
[config?.suggested_questions_after_answer?.enabled, suggestedQuestions]
)
return ( return (
<div className={`absolute bottom-0 flex justify-center bg-chat-input-mask ${(hasTryToAsk || !noChatInput || !noStopResponding) && chatFooterClassName}`} ref={chatFooterRef}> <div
className={`absolute bottom-0 flex justify-center bg-chat-input-mask ${chatFooterClassName}`}
ref={chatFooterRef}>
<div ref={chatFooterInnerRef} className={cn('relative', chatFooterInnerClassName)}> <div ref={chatFooterInnerRef} className={cn('relative', chatFooterInnerClassName)}>
<div className="mb-2 flex items-center justify-between relative h-8"> <div className="mb-2 flex items-center justify-between relative h-8">
{isShowPracticeButton && <Practice question={t('appDebug.feature.practice.text')} onSend={onSend} />} {isShowPracticeButton && <Practice />}
{isResponding && !noStopResponding && <StopResponding onStopResponding={onStopResponding} />} { <StopResponding />}
</div> </div>
{hasTryToAsk && <TryToAsk suggestedQuestions={suggestedQuestions} onSend={onSend} isMobile={isMobile} />} {hasTryToAsk && <TryToAsk suggestedQuestions={suggestedQuestions} isMobile={isMobile} />}
{!noChatInput && <ChatInputArea disabled={inputDisabled} showFeatureBar={showFeatureBar} showFileUpload={showFileUpload} featureBarDisabled={isResponding} onFeatureBarClick={onFeatureBarClick} visionConfig={config?.file_upload} speechToTextConfig={config?.speech_to_text} onSend={onSend} onRestart={onRestart} isResponding={isResponding} />} {<ChatInputArea />}
</div> </div>
</div> </div>
) )
} }
const MemoFooter = memo(Footer, (prevProps, nextProps) => {
return prevProps.isResponding === nextProps.isResponding
})
export default MemoFooter export default memo(Footer, (prevProps, nextProps) => {
return (
prevProps.chatFooterClassName === nextProps.chatFooterClassName &&
prevProps.chatFooterInnerClassName === nextProps.chatFooterInnerClassName &&
prevProps.isMobile === nextProps.isMobile &&
prevProps.suggestedQuestions === nextProps.suggestedQuestions &&
prevProps.isShowPracticeButton === nextProps.isShowPracticeButton
)
})
import type { FC } from 'react' import type { FC } from 'react'
import { memo } from 'react' import { memo } from 'react'
import type { OnSend } from '@/app/components/base/chat/types'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
import { InputMessageType } from '@/app/components/base/chat/types' import { InputMessageType } from '@/app/components/base/chat/types'
import { Practice as PracticeIcon } from '@/app/components/base/icons/src/image/icons' import { Practice as PracticeIcon } from '@/app/components/base/icons/src/image/icons'
import { useChatContext } from '../context' import { useChatContext } from '../context'
type PracticeProps = { import { useTranslation } from 'react-i18next'
question: string const Practice: FC = () => {
onSend: OnSend const { t } = useTranslation()
}
const Practice: FC<PracticeProps> = ({ question }) => {
const { onSend } = useChatContext() const { onSend } = useChatContext()
const question = t('appDebug.feature.practice.text')
console.log('question', question)
return ( return (
<div> <div>
{ {
...@@ -33,7 +32,4 @@ const Practice: FC<PracticeProps> = ({ question }) => { ...@@ -33,7 +32,4 @@ const Practice: FC<PracticeProps> = ({ question }) => {
</div> </div>
) )
} }
export default memo(Practice)
const PracticeMemo = memo(Practice)
export default PracticeMemo
...@@ -2,12 +2,11 @@ import { FC, memo } from 'react' ...@@ -2,12 +2,11 @@ import { FC, memo } from 'react'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices' import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useChatContext } from '../context'
interface StopButtonProps { const StopRespondingButton: FC = () => {
onStopResponding?: () => void
}
const StopRespondingButton: FC<StopButtonProps> = ({ onStopResponding }) => {
const { t } = useTranslation() const { t } = useTranslation()
const { onStopResponding,isResponding } = useChatContext()
if(!isResponding) return null
return ( return (
<div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2"> <div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2">
<Button onClick={onStopResponding}> <Button onClick={onStopResponding}>
...@@ -18,5 +17,4 @@ const StopRespondingButton: FC<StopButtonProps> = ({ onStopResponding }) => { ...@@ -18,5 +17,4 @@ const StopRespondingButton: FC<StopButtonProps> = ({ onStopResponding }) => {
) )
} }
const MemoizedStopRespondingButton = memo(StopRespondingButton, (prev, next) => true) export default memo(StopRespondingButton)
export default MemoizedStopRespondingButton
...@@ -6,16 +6,16 @@ import Button from '@/app/components/base/button' ...@@ -6,16 +6,16 @@ import Button from '@/app/components/base/button'
import Divider from '@/app/components/base/divider' import Divider from '@/app/components/base/divider'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { InputMessageType } from '@/app/components/base/chat/types' import { InputMessageType } from '@/app/components/base/chat/types'
import { useChatContext } from '../context'
type TryToAskProps = { type TryToAskProps = {
suggestedQuestions: string[] suggestedQuestions?: string[]
onSend: OnSend
isMobile?: boolean isMobile?: boolean
} }
const TryToAsk: FC<TryToAskProps> = ({ const TryToAsk: FC<TryToAskProps> = ({
suggestedQuestions, suggestedQuestions,
onSend,
isMobile, isMobile,
}) => { }) => {
const { onSend } = useChatContext()
const { t } = useTranslation() const { t } = useTranslation()
return ( return (
...@@ -27,7 +27,7 @@ const TryToAsk: FC<TryToAskProps> = ({ ...@@ -27,7 +27,7 @@ const TryToAsk: FC<TryToAskProps> = ({
</div> </div>
<div className={cn('flex flex-wrap justify-center', isMobile && 'justify-end')}> <div className={cn('flex flex-wrap justify-center', isMobile && 'justify-end')}>
{ {
suggestedQuestions.map((suggestQuestion, index) => ( suggestedQuestions?.map((suggestQuestion, index) => (
<Button <Button
size='small' size='small'
key={index} key={index}
......
...@@ -814,3 +814,16 @@ export const useChat = ( ...@@ -814,3 +814,16 @@ export const useChat = (
// handleAnnotationRemoved, // handleAnnotationRemoved,
}; };
}; };
export const useChatMethods = () => {
const [methods, setMethods] = useState<{
handleNewConversation: Function
handleSend: Function
}>()
const registerMethods = useCallback((newMethods: typeof methods) => {
setMethods(newMethods)
}, [])
return { methods, registerMethods }
}
...@@ -18,14 +18,14 @@ import { FileList } from '@/app/components/base/file-uploader' ...@@ -18,14 +18,14 @@ import { FileList } from '@/app/components/base/file-uploader'
type QuestionProps = { type QuestionProps = {
item: ChatItem item: ChatItem
questionIcon?: ReactNode questionIcon?: ReactNode
theme: Theme | null | undefined theme?: Theme | null | undefined
} }
const Question: FC<QuestionProps> = ({ item, questionIcon, theme }) => { const Question: FC<QuestionProps> = ({ item, questionIcon, theme }) => {
const { content, message_files } = item const { content, message_files } = item
return ( return (
<div className="mb-2 flex justify-end pl-14 last:mb-0"> <div className="mb-2 flex justify-end pl-14 last:mb-0">
<div className="group relative mr-4 max-w-full"> <div className="group relative mr-4 max-w-full">
<div className="rounded-2xl bg-[#D1E9FF]/50 px-4 py-3 text-sm text-gray-900" style={theme?.chatBubbleColorStyle ? CssTransform(theme.chatBubbleColorStyle) : {}}> <div className="rounded-2xl bg-[#D1E9FF]/50 px-4 py-3 text-sm text-gray-900" style={theme?.chatBubbleColorStyle ? CssTransform(theme?.chatBubbleColorStyle) : {}}>
{!!message_files?.length && <FileList files={message_files} showDeleteAction={false} showDownloadAction={true} />} {!!message_files?.length && <FileList files={message_files} showDeleteAction={false} showDownloadAction={true} />}
<Markdown content={content} /> <Markdown content={content} />
</div> </div>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!