Commit 63bf4926 by liimin

refactor(base): 重构聊天组件

- 移除不必要的 props 和 context
- 优化组件结构和逻辑
- 提高代码复用性和可维护性
1 parent 5b99a30e
......@@ -2,14 +2,14 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17
* @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
* @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 Chat from '../chat'
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 { useChatWithHistoryContext } from './context'
import { InputVarType } from '@/app/components/workflow/types'
......@@ -23,12 +23,7 @@ import { Markdown } from '@/app/components/base/markdown'
import cn from '@/utils/classnames'
// import { SELF_INPUT } from "@/app/components/base/chat/constants";
import { InputMessageType } from '../types'
type Props = {
avatar: string
aiAvatar: string
presuppositionQuestion?: string
// hasAutoSended: React.MutableRefObject<boolean>
}
import { useChatWithHistory } from './hooks'
enum MessageListenerType {
RESET_CHAT = 'reset_chat',
}
......@@ -39,14 +34,24 @@ type MessageListenerProps = {
}
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 {
appParams,
appPrevChatTree,
currentConversationId,
currentConversationItem,
currentConversationInputs,
appPrevChatTree,
newConversationInputs,
newConversationInputsRef,
handleNewConversation,
handleNewConversationCompleted,
isInstalledApp,
......@@ -55,165 +60,39 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, presuppositionQuestion }) =>
currentChatInstanceRef,
clearChatList,
setClearChatList,
setIsResponding,
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
}
}
}, [])
} = useChatWithHistory(undefined, inputs)
useEffect(() => {
if (currentChatInstanceRef.current) currentChatInstanceRef.current.handleStop = handleStop
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
if (!hasAutoSended.current && presuppositionQuestion) {
hasAutoSended.current = true
doSend({
message: presuppositionQuestion,
type: InputMessageType.SYSTEM,
})
if (presuppositionQuestion) {
chatRef.current?.handleSend(
{
message: presuppositionQuestion,
type: InputMessageType.SYSTEM,
},
undefined,
)
}
}, [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 (
<div className="h-full overflow-hidden">
<Chat
config={appConfig}
chatList={messageList}
isResponding={respondingState}
onSend={doSend}
onRestart={onRestart}
onRegenerate={doRegenerate}
onStopResponding={handleStop}
onFeedback={handleFeedback}
answerIcon={answerIcon}
questionIcon={questionIcon}
ref={chatRef}
inputs={inputs}
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>
)
......
......@@ -30,17 +30,14 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp, inputs: Reco
)
const [clearChatList, setClearChatList] = useState(false)
const [isResponding, setIsResponding] = useState(false)
const appPrevChatTree = useMemo(() => [], [])
const { t } = useTranslation()
const newConversationInputsRef = useRef<Record<string, any>>({})
const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>(inputs)
const { notify } = useToastContext()
const currentChatInstanceRef = useRef<{ handleStop: () => void }>({
handleStop: noop,
})
const handleNewConversation = useCallback(
(inputs?: Record<string, any>) => {
currentChatInstanceRef.current.handleStop()
......@@ -91,7 +88,7 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp, inputs: Reco
currentChatInstanceRef,
clearChatList,
setClearChatList,
isResponding,
setIsResponding,
// isResponding,
// setIsResponding,
}
}
......@@ -16,7 +16,6 @@ import cn from '@/utils/classnames'
// import { SELF_INPUT } from "@/app/components/base/chat/constants";
import { InputMessageType, PracticeStatus } from '../types'
import { AVATAR_USER_URL, AVATAR_AI_URL, MAIN_TITLE } from '@/app/components/base/chat/constants'
type ChatWithHistoryProps = {
className?: string
}
......@@ -55,119 +54,36 @@ const isShowPracticeButton = practice_status === PracticeStatus.Practicing || pr
const avatarUrl: string = avatar ?? AVATAR_USER_URL
const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {
const { appInfoError, appInfoLoading, appChatListDataLoading, chatShouldReloadKey, isMobile, handleNewConversation } =
useChatWithHistoryContext()
const { appInfoError, appInfoLoading, isMobile } = useChatWithHistoryContext()
if (appInfoLoading) {
return <Loading type="app" />
}
if (appInfoError) {
} else if (appInfoError) {
return <AppUnavailable />
}
return (
<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('flex h-full flex-col overflow-hidden border-components-panel-border-subtle chat-panel-bg')}>
{!newInputs.no_header && <Header avatar={avatarUrl} title={MAIN_TITLE} />}
{!appChatListDataLoading && (
<ChatWrapper
presuppositionQuestion={presuppositionProblem}
// doClear={doClear}
// hasAutoSended={hasAutoSended}
key={chatShouldReloadKey}
avatar={avatarUrl}
aiAvatar={AVATAR_AI_URL}
/>
)}
} else {
return (
<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('flex h-full flex-col overflow-hidden border-components-panel-border-subtle chat-panel-bg')}>
{
<ChatWrapper
presuppositionQuestion={presuppositionProblem}
isShowPracticeButton={isShowPracticeButton}
inputs={newInputs}
/>
}
</div>
</div>
</div>
</div>
)
)
}
}
export type ChatWithHistoryWrapProps = {
installedAppInfo?: any //InstalledApp
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 [initialized, setInitialized] = useState(false)
const [appUnavailable, setAppUnavailable] = useState<boolean>(false)
......@@ -191,7 +107,7 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta
}, [initialized, installedAppInfo]) // 添加正确依赖
if (!initialized) return null
else if (appUnavailable) return <AppUnavailable isUnknownReason={isUnknownReason} />
else return <ChatWithHistoryWrap installedAppInfo={installedAppInfo} className={className} />
else return <ChatWithHistory className={className} />
}
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'
import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows'
import cn from '@/utils/classnames'
import { FileList } from '@/app/components/base/file-uploader'
import { useChatContext } from '../context'
type AnswerProps = {
item: ChatItem
question: string
index: number
config?: ChatConfig
answerIcon?: ReactNode
responding?: boolean
showPromptLog?: boolean
isLast?: boolean
chatAnswerContainerInner?: string
hideProcessDetail?: boolean
// appData?: AppData
noChatInput?: boolean
switchSibling?: (siblingMessageId: string) => void
}
......@@ -36,16 +33,11 @@ const Answer: FC<AnswerProps> = ({
item,
question,
index,
config,
answerIcon,
responding,
showPromptLog,
isLast,
chatAnswerContainerInner,
hideProcessDetail,
// appData,
noChatInput,
switchSibling,
}) => {
const { t } = useTranslation()
const { content, citation, agent_thoughts, more, annotation, workflowProcess, allFiles, message_files } = item
......@@ -55,7 +47,8 @@ const Answer: FC<AnswerProps> = ({
const [contentWidth, setContentWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const { config, isResponding } = useChatContext()
const responding = isLast && isResponding
const getContainerWidth = () => {
if (containerRef.current) setContainerWidth(containerRef.current?.clientWidth + 16)
}
......
......@@ -6,12 +6,14 @@ import SuggestedQuestions from './suggested-questions'
// import { EditTitle } from "@/app/components/app/annotation/edit-annotation-modal/edit-item";
import AnswerIcon from '@/app/components/base/answer-icon'
import cn from '@/utils/classnames'
import { useChatContext } from '../context'
type InitQuestionsProps = {
config: ChatConfig
// config: ChatConfig
answerIcon: ReactNode
chatAnswerContainerInner?: string
}
const InitQuestions: FC<InitQuestionsProps> = ({ config, answerIcon, chatAnswerContainerInner }) => {
const InitQuestions: FC<InitQuestionsProps> = ({ answerIcon, chatAnswerContainerInner }) => {
const {config} = useChatContext()
const questions = useMemo(() => {
const { suggested_questions, initial_message } = config
const suggestedQuestions = suggested_questions
......@@ -40,9 +42,4 @@ const InitQuestions: FC<InitQuestionsProps> = ({ config, answerIcon, chatAnswerC
</div>
)
}
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
export default memo(InitQuestions)
......@@ -23,34 +23,32 @@ import Confirm from '@/app/components/base/confirm'
type ChatInputAreaProps = {
showFeatureBar?: boolean
showFileUpload?: boolean
featureBarDisabled?: boolean
// featureBarDisabled?: boolean
onFeatureBarClick?: (state: boolean) => void
visionConfig?: FileUpload
speechToTextConfig?: EnableType
onSend?: OnSend
onRestart: () => void
// visionConfig?: FileUpload
// speechToTextConfig?: EnableType
// inputs?: Record<string, any>
// inputsForm?: InputForm[]
// theme?: Theme | null
isResponding?: boolean
disabled?: boolean
}
const ChatInputArea = ({
showFeatureBar,
showFileUpload,
featureBarDisabled,
// featureBarDisabled,
onFeatureBarClick,
visionConfig,
speechToTextConfig = { enabled: true },
onRestart,
// visionConfig,
// speechToTextConfig = { enabled: true },
// inputs = {},
// inputsForm = [],
// theme,
isResponding,
// disabled,
}: ChatInputAreaProps) => {
const { t } = useTranslation()
const { onSend, onRestart, isResponding,config } = useChatContext()
const { notify } = useToastContext()
const visionConfig = config.file_upload
const speechToTextConfig = config.speech_to_text
const {
wrapperRef,
textareaRef,
......@@ -75,8 +73,9 @@ const ChatInputArea = ({
const historyRef = useRef([''])
const [currentIndex, setCurrentIndex] = useState(-1)
const isComposingRef = useRef(false)
const { onSend } = useChatContext()
// const { onSend } = useChatContext()
const [showConfirm, setShowConfirm] = useState<boolean>(false)
const featureBarDisabled = isResponding
const handleSend = () => {
if (isResponding) {
notify({
......
......@@ -2,28 +2,26 @@
import type { ReactNode } from 'react'
import { createContext, useContext } from 'use-context-selector'
import type { ChatProps } from './index'
import { noop } from 'lodash-es'
import { ChatConfig, ChatItem, Feedback, OnRegenerate, OnSend } from '../types'
export type ChatContextValue = Pick<ChatProps, 'config'
| 'isResponding'
| 'chatList'
// | 'showPromptLog'
| 'questionIcon'
| 'answerIcon'
| 'onSend'
| 'onRegenerate'
| 'onStopResponding'
| 'onRestart'
// | 'onAnnotationEdited'
// | 'onAnnotationAdded'
// | 'onAnnotationRemoved'
| 'onFeedback'
>
export type ChatContextValue = {
config: ChatConfig
chatList: ChatItem[]
isResponding?: boolean
onSend: OnSend
onRegenerate?: OnRegenerate
onStopResponding?: () => void
onRestart: () => void
onFeedback?: (messageId: string, feedback: Feedback) => void
}
const ChatContext = createContext<ChatContextValue>({
chatList: [],
config: {} as ChatConfig,
onRestart: noop,
onSend: noop,
chatList: [],
onFeedback:noop
})
type ChatContextProviderProps = {
......@@ -35,35 +33,24 @@ export const ChatContextProvider = ({
config,
isResponding,
chatList,
// showPromptLog,
questionIcon,
answerIcon,
onSend,
onRegenerate,
onRestart,
// onAnnotationEdited,
// onAnnotationAdded,
// onAnnotationRemoved,
onFeedback,
onStopResponding
onStopResponding,
}: ChatContextProviderProps) => {
return (
<ChatContext.Provider value={{
config,
isResponding,
chatList: chatList || [],
// showPromptLog,
questionIcon,
answerIcon,
onSend,
onRegenerate,
// onAnnotationEdited,
// onAnnotationAdded,
// onAnnotationRemoved,
onRestart,
onFeedback,
onStopResponding
}}>
<ChatContext.Provider
value={{
config,
isResponding,
chatList: chatList || [],
onSend,
onRegenerate,
onRestart,
onFeedback,
onStopResponding,
}}>
{children}
</ChatContext.Provider>
)
......
import React, { FC, memo } from 'react'
import React, { FC, memo, useMemo} from 'react'
import { useTranslation } from 'react-i18next'
import type { ChatConfig, OnSend } from '@/app/components/base/chat/types'
import type { ThemeBuilder } from '@/app/components/base/chat/embedded-chatbot/theme/theme-context'
......@@ -8,48 +8,54 @@ import Practice from './practice'
import ChatInputArea from '../chat-input-area'
import StopResponding from './stopResponding'
import cn from '@/utils/classnames'
import { useChatContext } from '../context'
type FooterProps = {
chatFooterClassName?: string
chatFooterInnerClassName?: string
isShowPracticeButton: boolean
suggestedQuestions?: string[]
onSend: OnSend
noStopResponding?: boolean
onStopResponding?: () => void
noChatInput?: 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>
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 { t } = useTranslation()
const hasTryToAsk = config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length && onSend
const Footer: FC<FooterProps> = ({
chatFooterClassName,
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 (
<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 className="mb-2 flex items-center justify-between relative h-8">
{isShowPracticeButton && <Practice question={t('appDebug.feature.practice.text')} onSend={onSend} />}
{isResponding && !noStopResponding && <StopResponding onStopResponding={onStopResponding} />}
{isShowPracticeButton && <Practice />}
{ <StopResponding />}
</div>
{hasTryToAsk && <TryToAsk suggestedQuestions={suggestedQuestions} onSend={onSend} 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} />}
{hasTryToAsk && <TryToAsk suggestedQuestions={suggestedQuestions} isMobile={isMobile} />}
{<ChatInputArea />}
</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 { memo } from 'react'
import type { OnSend } from '@/app/components/base/chat/types'
import Button from '@/app/components/base/button'
import { InputMessageType } from '@/app/components/base/chat/types'
import { Practice as PracticeIcon } from '@/app/components/base/icons/src/image/icons'
import { useChatContext } from '../context'
type PracticeProps = {
question: string
onSend: OnSend
}
const Practice: FC<PracticeProps> = ({ question }) => {
import { useTranslation } from 'react-i18next'
const Practice: FC = () => {
const { t } = useTranslation()
const { onSend } = useChatContext()
const question = t('appDebug.feature.practice.text')
console.log('question', question)
return (
<div>
{
......@@ -33,7 +32,4 @@ const Practice: FC<PracticeProps> = ({ question }) => {
</div>
)
}
const PracticeMemo = memo(Practice)
export default PracticeMemo
export default memo(Practice)
......@@ -2,12 +2,11 @@ import { FC, memo } from 'react'
import Button from '@/app/components/base/button'
import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
import { useTranslation } from 'react-i18next'
interface StopButtonProps {
onStopResponding?: () => void
}
const StopRespondingButton: FC<StopButtonProps> = ({ onStopResponding }) => {
import { useChatContext } from '../context'
const StopRespondingButton: FC = () => {
const { t } = useTranslation()
const { onStopResponding,isResponding } = useChatContext()
if(!isResponding) return null
return (
<div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2">
<Button onClick={onStopResponding}>
......@@ -18,5 +17,4 @@ const StopRespondingButton: FC<StopButtonProps> = ({ onStopResponding }) => {
)
}
const MemoizedStopRespondingButton = memo(StopRespondingButton, (prev, next) => true)
export default MemoizedStopRespondingButton
export default memo(StopRespondingButton)
......@@ -6,16 +6,16 @@ import Button from '@/app/components/base/button'
import Divider from '@/app/components/base/divider'
import cn from '@/utils/classnames'
import { InputMessageType } from '@/app/components/base/chat/types'
import { useChatContext } from '../context'
type TryToAskProps = {
suggestedQuestions: string[]
onSend: OnSend
suggestedQuestions?: string[]
isMobile?: boolean
}
const TryToAsk: FC<TryToAskProps> = ({
suggestedQuestions,
onSend,
isMobile,
}) => {
const { onSend } = useChatContext()
const { t } = useTranslation()
return (
......@@ -27,7 +27,7 @@ const TryToAsk: FC<TryToAskProps> = ({
</div>
<div className={cn('flex flex-wrap justify-center', isMobile && 'justify-end')}>
{
suggestedQuestions.map((suggestQuestion, index) => (
suggestedQuestions?.map((suggestQuestion, index) => (
<Button
size='small'
key={index}
......
......@@ -814,3 +814,16 @@ export const useChat = (
// 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'
type QuestionProps = {
item: ChatItem
questionIcon?: ReactNode
theme: Theme | null | undefined
theme?: Theme | null | undefined
}
const Question: FC<QuestionProps> = ({ item, questionIcon, theme }) => {
const { content, message_files } = item
return (
<div className="mb-2 flex justify-end pl-14 last:mb-0">
<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} />}
<Markdown content={content} />
</div>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!