Commit 9b439533 by liimin

refactor(chat): 优化聊天组件功能和样式

- 修改预设问题发送类型为 SYSTEM
- 移除重置对话功能,改为重启对话
- 优化输入框组件,增加重启对话按钮
- 调整消息列表渲染逻辑
- 统一操作按钮样式
1 parent fad5869e
{ {
"printWidth": 80, "printWidth": 120,
"tabWidth": 2, "tabWidth": 2,
"singleQuote": true, "singleQuote": true,
"trailingComma": "all", "trailingComma": "all",
"semi": false, "semi": false,
"wrap_line_length": 80, "wrap_line_length": 120,
"wrap_attributes": "auto", "wrap_attributes": "auto",
"proseWrap": "always", "proseWrap": "always",
"arrowParens": "avoid", "arrowParens": "avoid",
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @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-06-26 16:34:29 * @LastEditTime: 2025-06-29 00:05:04
* @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
*/ */
...@@ -26,10 +26,9 @@ import { InputMessageType } from '../types' ...@@ -26,10 +26,9 @@ import { InputMessageType } from '../types'
type Props = { type Props = {
avatar: string avatar: string
aiAvatar: string aiAvatar: string
doClear?: () => void
presuppositionQuestion?: string presuppositionQuestion?: string
} }
const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuestion }) => { const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, presuppositionQuestion }) => {
const { appParams, appPrevChatTree, currentConversationId, currentConversationItem, currentConversationInputs, newConversationInputs, newConversationInputsRef, handleNewConversationCompleted, isMobile, isInstalledApp, appId, appMeta, handleFeedback, currentChatInstanceRef, appData, themeBuilder, clearChatList, setClearChatList, setIsResponding, isShowPracticeButton } = useChatWithHistoryContext() const { appParams, appPrevChatTree, currentConversationId, currentConversationItem, currentConversationInputs, newConversationInputs, newConversationInputsRef, handleNewConversationCompleted, isMobile, isInstalledApp, appId, appMeta, handleFeedback, currentChatInstanceRef, appData, themeBuilder, clearChatList, setClearChatList, setIsResponding, isShowPracticeButton } = useChatWithHistoryContext()
const appConfig = useMemo(() => { const appConfig = useMemo(() => {
...@@ -53,6 +52,7 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest ...@@ -53,6 +52,7 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest
handleStop, handleStop,
isResponding: respondingState, isResponding: respondingState,
suggestedQuestions, suggestedQuestions,
handleRestart
} = useChat( } = useChat(
appConfig, appConfig,
{ {
...@@ -99,7 +99,7 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest ...@@ -99,7 +99,7 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest
if (!hasAutoSended.current && presuppositionQuestion) { if (!hasAutoSended.current && presuppositionQuestion) {
doSend({ doSend({
message: presuppositionQuestion, message: presuppositionQuestion,
type: InputMessageType.SELF, type: InputMessageType.SYSTEM,
}) })
hasAutoSended.current = true hasAutoSended.current = true
} }
...@@ -194,7 +194,7 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest ...@@ -194,7 +194,7 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest
chatFooterClassName="pb-4" chatFooterClassName="pb-4"
chatFooterInnerClassName={`mx-auto w-full max-w-[800px] ${isMobile ? 'px-2' : 'px-4'}`} chatFooterInnerClassName={`mx-auto w-full max-w-[800px] ${isMobile ? 'px-2' : 'px-4'}`}
onSend={doSend} onSend={doSend}
onClear={doClear} onRestart={handleRestart}
inputs={currentConversationId ? (currentConversationInputs as any) : newConversationInputs} inputs={currentConversationId ? (currentConversationInputs as any) : newConversationInputs}
// inputsForm={[]} // inputsForm={[]}
onRegenerate={doRegenerate} onRegenerate={doRegenerate}
...@@ -210,7 +210,7 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest ...@@ -210,7 +210,7 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest
suggestedQuestions={suggestedQuestions} suggestedQuestions={suggestedQuestions}
answerIcon={answerIcon} answerIcon={answerIcon}
questionIcon={questionIcon} questionIcon={questionIcon}
hideProcessDetail // hideProcessDetail
themeBuilder={themeBuilder} themeBuilder={themeBuilder}
// switchSibling={siblingMessageId => setTargetMessageId(siblingMessageId)} // switchSibling={siblingMessageId => setTargetMessageId(siblingMessageId)}
// inputDisabled={inputDisabled} // inputDisabled={inputDisabled}
......
...@@ -54,22 +54,8 @@ const { avatar, domain, presuppositionProblem, practice_status, ...newInputs } = ...@@ -54,22 +54,8 @@ const { avatar, domain, presuppositionProblem, practice_status, ...newInputs } =
const isShowPracticeButton = practice_status === PracticeStatus.Practicing || practice_status === PracticeStatus.Failed const isShowPracticeButton = practice_status === PracticeStatus.Practicing || practice_status === PracticeStatus.Failed
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 [showConfirm, setShowConfirm] = useState(false)
const handleReset = () => {
handleNewConversation()
setTimeout(() => {
handleNewConversation()
}, 1000)
setShowConfirm(false)
}
const handleCancelConfirm = () => {
setShowConfirm(false)
}
const { appInfoError, appInfoLoading, appChatListDataLoading, chatShouldReloadKey, isMobile, handleNewConversation } = useChatWithHistoryContext() const { appInfoError, appInfoLoading, appChatListDataLoading, chatShouldReloadKey, isMobile, handleNewConversation } = useChatWithHistoryContext()
const doClear = useCallback(() => {
setShowConfirm(true)
}, [handleNewConversation])
if (appInfoLoading) { if (appInfoLoading) {
return <Loading type="app" /> return <Loading type="app" />
} }
...@@ -79,14 +65,13 @@ const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => { ...@@ -79,14 +65,13 @@ const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {
} }
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)}>
{showConfirm && <Confirm title="重置对话" confirmText="确认" cancelText="取消" content="您确定要重置此对话吗?" isShow onCancel={handleCancelConfirm} onConfirm={handleReset} />}
<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 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} />} {!newInputs.no_header && <Header avatar={avatarUrl} title={MAIN_TITLE} />}
{!appChatListDataLoading && ( {!appChatListDataLoading && (
<ChatWrapper <ChatWrapper
presuppositionQuestion={presuppositionProblem} presuppositionQuestion={presuppositionProblem}
doClear={doClear} // doClear={doClear}
key={chatShouldReloadKey} key={chatShouldReloadKey}
avatar={avatarUrl} avatar={avatarUrl}
aiAvatar={AVATAR_AI_URL} aiAvatar={AVATAR_AI_URL}
......
...@@ -27,7 +27,10 @@ const SuggestedQuestions: FC<SuggestedQuestionsProps> = ({ item }) => { ...@@ -27,7 +27,10 @@ const SuggestedQuestions: FC<SuggestedQuestionsProps> = ({ item }) => {
return ( return (
<div className="w-[fit-content]"> <div className="w-[fit-content]">
{suggestedQuestions.map((question, index) => ( {suggestedQuestions.map((question, index) => (
<Button key={index} text={question} onClick={() => onSend?.({ message: question, type: InputMessageType.SYSTEM })}></Button> <Button
key={index}
text={question}
onClick={() => onSend?.({ message: question, type: InputMessageType.SYSTEM })}></Button>
))} ))}
</div> </div>
) )
......
...@@ -18,7 +18,8 @@ import FeatureBar from '@/app/components/base/features/new-feature-panel/feature ...@@ -18,7 +18,8 @@ import FeatureBar from '@/app/components/base/features/new-feature-panel/feature
import type { FileUpload } from '@/app/components/base/features/types' import type { FileUpload } from '@/app/components/base/features/types'
import { TransferMethod } from '@/types/app' import { TransferMethod } from '@/types/app'
import { InputMessageType } from '../../types' import { InputMessageType } from '../../types'
import { useChatContext } from '../context'
import Confirm from '@/app/components/base/confirm'
type ChatInputAreaProps = { type ChatInputAreaProps = {
showFeatureBar?: boolean showFeatureBar?: boolean
showFileUpload?: boolean showFileUpload?: boolean
...@@ -27,25 +28,55 @@ type ChatInputAreaProps = { ...@@ -27,25 +28,55 @@ type ChatInputAreaProps = {
visionConfig?: FileUpload visionConfig?: FileUpload
speechToTextConfig?: EnableType speechToTextConfig?: EnableType
onSend?: OnSend onSend?: OnSend
onClear?: () => void onRestart: () => void
inputs?: Record<string, any> inputs?: Record<string, any>
inputsForm?: InputForm[] inputsForm?: InputForm[]
theme?: Theme | null theme?: Theme | null
isResponding?: boolean isResponding?: boolean
disabled?: boolean disabled?: boolean
} }
const ChatInputArea = ({ showFeatureBar, showFileUpload, featureBarDisabled, onFeatureBarClick, visionConfig, speechToTextConfig = { enabled: true }, onSend, onClear, inputs = {}, inputsForm = [], theme, isResponding, disabled }: ChatInputAreaProps) => { const ChatInputArea = ({
showFeatureBar,
showFileUpload,
featureBarDisabled,
onFeatureBarClick,
visionConfig,
speechToTextConfig = { enabled: true },
onRestart,
inputs = {},
inputsForm = [],
theme,
isResponding,
disabled,
}: ChatInputAreaProps) => {
const { t } = useTranslation() const { t } = useTranslation()
const { notify } = useToastContext() const { notify } = useToastContext()
const { wrapperRef, textareaRef, textValueRef, holdSpaceRef, handleTextareaResize, isMultipleLine, setIsMultipleLine } = useTextAreaHeight() const {
wrapperRef,
textareaRef,
textValueRef,
holdSpaceRef,
handleTextareaResize,
isMultipleLine,
setIsMultipleLine,
} = useTextAreaHeight()
const [query, setQuery] = useState('') const [query, setQuery] = useState('')
const [showVoiceInput, setShowVoiceInput] = useState(false) const [showVoiceInput, setShowVoiceInput] = useState(false)
const filesStore = useFileStore() const filesStore = useFileStore()
const { handleDragFileEnter, handleDragFileLeave, handleDragFileOver, handleDropFile, handleClipboardPasteFile, isDragActive } = useFile(visionConfig!) const {
handleDragFileEnter,
handleDragFileLeave,
handleDragFileOver,
handleDropFile,
handleClipboardPasteFile,
isDragActive,
} = useFile(visionConfig!)
const { checkInputsForm } = useCheckInputsForms() const { checkInputsForm } = useCheckInputsForms()
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 [showConfirm, setShowConfirm] = useState<boolean>(false)
const handleSend = () => { const handleSend = () => {
if (isResponding) { if (isResponding) {
notify({ notify({
...@@ -78,11 +109,7 @@ const ChatInputArea = ({ showFeatureBar, showFileUpload, featureBarDisabled, onF ...@@ -78,11 +109,7 @@ const ChatInputArea = ({ showFeatureBar, showFileUpload, featureBarDisabled, onF
// } // }
} }
} }
const handleClear = () => {
if (onClear) {
onClear()
}
}
const handleCompositionStart = () => { const handleCompositionStart = () => {
// e: React.CompositionEvent<HTMLTextAreaElement> // e: React.CompositionEvent<HTMLTextAreaElement>
isComposingRef.current = true isComposingRef.current = true
...@@ -133,32 +160,77 @@ const ChatInputArea = ({ showFeatureBar, showFileUpload, featureBarDisabled, onF ...@@ -133,32 +160,77 @@ const ChatInputArea = ({ showFeatureBar, showFileUpload, featureBarDisabled, onF
) )
}, [t, notify]) }, [t, notify])
const operation = <Operation ref={holdSpaceRef} fileConfig={visionConfig} speechToTextConfig={speechToTextConfig} onShowVoiceInput={handleShowVoiceInput} onClear={handleClear} onSend={handleSend} theme={theme} /> const handleRestart = useCallback(() => {
if (isResponding) {
notify({
type: 'info',
message: t('appDebug.errorMessage.waitForResponse'),
})
return
}
setShowConfirm(true)
}, [isResponding])
const doRestart = useCallback(() => {
onRestart()
setShowConfirm(false)
},[])
const operation = (
<Operation
ref={holdSpaceRef}
fileConfig={visionConfig}
speechToTextConfig={speechToTextConfig}
onShowVoiceInput={handleShowVoiceInput}
onRestart={handleRestart}
onSend={handleSend}
theme={theme}
/>
)
// const clear = <Operation ref={holdSpaceRef} onSend={handleClear} imgUrl={CLEAR_BUTTON} /> // const clear = <Operation ref={holdSpaceRef} onSend={handleClear} imgUrl={CLEAR_BUTTON} />
const hasQuery = useMemo(() => query.length > 0, [query]) const hasQuery = useMemo(() => query.length > 0, [query])
useEffect(() => { useEffect(() => {
if (!hasQuery) { if (!hasQuery) {
setIsMultipleLine(false) setIsMultipleLine(false)
} }
}, [hasQuery, setIsMultipleLine]) }, [hasQuery, setIsMultipleLine])
const maxRow = useMemo(() => { const maxRow = useMemo(() => {
return hasQuery ? undefined : 1 return hasQuery ? undefined : 1
}, [hasQuery]) }, [hasQuery])
return ( return (
<> <>
<div className={cn('relative z-10 rounded-xl border border-components-chat-input-border bg-[#fff] pb-[9px] shadow-md', isDragActive && 'border border-dashed border-components-option-card-option-selected-border')}> {showConfirm && (
<Confirm
title="重置对话"
confirmText="确认"
cancelText="取消"
content="您确定要重置此对话吗?"
isShow
onCancel={() => setShowConfirm(false)}
onConfirm={doRestart}
/>
)}
<div
className={cn(
'relative z-10 rounded-xl border border-components-chat-input-border bg-[#fff] pb-[9px] shadow-md',
isDragActive && 'border border-dashed border-components-option-card-option-selected-border',
)}>
<div className="relative max-h-[158px] overflow-y-auto overflow-x-hidden px-[9px] pt-[9px]"> <div className="relative max-h-[158px] overflow-y-auto overflow-x-hidden px-[9px] pt-[9px]">
<FileListInChatInput fileConfig={visionConfig!} /> <FileListInChatInput fileConfig={visionConfig!} />
<div ref={wrapperRef} className="flex items-center justify-between"> <div ref={wrapperRef} className="flex items-center justify-between">
<div className="relative flex w-full grow items-center ml-8"> <div className="relative flex w-full grow items-center ml-8">
<div ref={textValueRef} className="body-lg-regular pointer-events-none invisible absolute h-auto w-auto whitespace-pre p-1 leading-6"> <div
ref={textValueRef}
className="body-lg-regular pointer-events-none invisible absolute h-auto w-auto whitespace-pre p-1 leading-6">
{query} {query}
</div> </div>
<Textarea <Textarea
ref={ref => (textareaRef.current = ref as any)} ref={ref => (textareaRef.current = ref as any)}
className={cn('body-lg-regular w-full resize-none bg-transparent p-1 leading-6 text-text-tertiary outline-none')} className={cn(
'body-lg-regular w-full resize-none bg-transparent p-1 leading-6 text-text-tertiary outline-none',
)}
placeholder={t('common.chat.inputPlaceholder') || ''} placeholder={t('common.chat.inputPlaceholder') || ''}
autoFocus autoFocus
maxRows={maxRow} maxRows={maxRow}
...@@ -180,11 +252,19 @@ const maxRow = useMemo(() => { ...@@ -180,11 +252,19 @@ const maxRow = useMemo(() => {
</div> </div>
{!isMultipleLine && operation} {!isMultipleLine && operation}
</div> </div>
{showVoiceInput && <VoiceInput onCancel={() => setShowVoiceInput(false)} onConverted={text => setQuery(text)} />} {showVoiceInput && (
<VoiceInput onCancel={() => setShowVoiceInput(false)} onConverted={text => setQuery(text)} />
)}
</div> </div>
{isMultipleLine && <div className="px-[9px]">{operation}</div>} {isMultipleLine && <div className="px-[9px]">{operation}</div>}
</div> </div>
{showFeatureBar && <FeatureBar showFileUpload={showFileUpload} disabled={featureBarDisabled} onFeatureBarClick={onFeatureBarClick} />} {showFeatureBar && (
<FeatureBar
showFileUpload={showFileUpload}
disabled={featureBarDisabled}
onFeatureBarClick={onFeatureBarClick}
/>
)}
</> </>
) )
} }
......
import { memo, use, useMemo } from "react"; import { Dispatch, memo, SetStateAction, use, useMemo } from 'react'
import { RiMicLine, RiSendPlane2Fill } from "@remixicon/react"; import { RiMicLine, RiSendPlane2Fill } from '@remixicon/react'
import type { EnableType } from "../../types"; import type { EnableType } from '../../types'
import type { Theme } from "../../embedded-chatbot/theme/theme-context"; import type { Theme } from '../../embedded-chatbot/theme/theme-context'
import Button from "@/app/components/base/button"; import Button from '@/app/components/base/button'
import ActionButton from "@/app/components/base/action-button"; import ActionButton from '@/app/components/base/action-button'
import { FileUploaderInChatInput } from "@/app/components/base/file-uploader"; import { FileUploaderInChatInput } from '@/app/components/base/file-uploader'
import type { FileUpload } from "@/app/components/base/features/types"; import type { FileUpload } from '@/app/components/base/features/types'
import cn from "@/utils/classnames"; import cn from '@/utils/classnames'
import { import {
// SELF_INPUT, // SELF_INPUT,
SEND_BUTTON, SEND_BUTTON,
CLEAR_BUTTON, CLEAR_BUTTON,
} from '@/app/components/base/chat/constants' } from '@/app/components/base/chat/constants'
type OperationProps = { type OperationProps = {
fileConfig?: FileUpload; fileConfig?: FileUpload
speechToTextConfig?: EnableType; speechToTextConfig?: EnableType
onShowVoiceInput?: () => void; onShowVoiceInput?: () => void
onSend: () => void; onSend: () => void
imgUrl?: string; imgUrl?: string
theme?: Theme | null; theme?: Theme | null
onClear: () => void; onRestart: () => void
}; }
const Operation = ({ const Operation = ({
ref, ref,
onSend, onSend,
speechToTextConfig, speechToTextConfig,
onShowVoiceInput, onShowVoiceInput,
onClear, onRestart,
}: OperationProps & { }: OperationProps & {
ref: React.RefObject<HTMLDivElement>; ref: React.RefObject<HTMLDivElement>
}) => { }) => {
return ( return (
<div className={cn("flex shrink-0 items-center justify-end")}> <div className={cn('flex shrink-0 items-center justify-end')}>
<div className="absolute left-3"> <div className="absolute left-3">
<img <img onClick={onRestart} src={CLEAR_BUTTON} className="size-6 hover:cursor-pointer" alt="icon" />
onClick={onClear}
src={CLEAR_BUTTON}
className="size-6 hover:cursor-pointer"
alt="icon"
/>
</div> </div>
<div className="flex items-center pl-1" ref={ref}> <div className="flex items-center pl-1" ref={ref}>
<div className='flex items-center space-x-1 pr-2'> <div className="flex items-center space-x-1 pr-2">
{/* {fileConfig?.enabled && <FileUploaderInChatInput fileConfig={fileConfig} />} */} {/* {fileConfig?.enabled && <FileUploaderInChatInput fileConfig={fileConfig} />} */}
{ {speechToTextConfig?.enabled && (
speechToTextConfig?.enabled && ( <ActionButton size="l" onClick={onShowVoiceInput}>
<ActionButton <RiMicLine className="h-5 w-5" />
size='l'
onClick={onShowVoiceInput}
>
<RiMicLine className='h-5 w-5' />
</ActionButton> </ActionButton>
) )}
}
</div> </div>
<img <img onClick={onSend} src={SEND_BUTTON} className="size-6 hover:cursor-pointer" alt="icon" />
onClick={onSend}
src={SEND_BUTTON}
className="size-6 hover:cursor-pointer"
alt="icon"
/>
</div> </div>
</div> </div>
); )
}; }
Operation.displayName = "Operation"; Operation.displayName = 'Operation'
export default memo(Operation); export default memo(Operation)
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
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 type { ChatProps } from './index'
import { noop } from 'lodash-es'
export type ChatContextValue = Pick<ChatProps, 'config' export type ChatContextValue = Pick<ChatProps, 'config'
| 'isResponding' | 'isResponding'
...@@ -12,6 +13,8 @@ export type ChatContextValue = Pick<ChatProps, 'config' ...@@ -12,6 +13,8 @@ export type ChatContextValue = Pick<ChatProps, 'config'
| 'answerIcon' | 'answerIcon'
| 'onSend' | 'onSend'
| 'onRegenerate' | 'onRegenerate'
| 'onStopResponding'
| 'onRestart'
// | 'onAnnotationEdited' // | 'onAnnotationEdited'
// | 'onAnnotationAdded' // | 'onAnnotationAdded'
// | 'onAnnotationRemoved' // | 'onAnnotationRemoved'
...@@ -20,6 +23,7 @@ export type ChatContextValue = Pick<ChatProps, 'config' ...@@ -20,6 +23,7 @@ export type ChatContextValue = Pick<ChatProps, 'config'
const ChatContext = createContext<ChatContextValue>({ const ChatContext = createContext<ChatContextValue>({
chatList: [], chatList: [],
onRestart: noop,
}) })
type ChatContextProviderProps = { type ChatContextProviderProps = {
...@@ -36,10 +40,12 @@ export const ChatContextProvider = ({ ...@@ -36,10 +40,12 @@ export const ChatContextProvider = ({
answerIcon, answerIcon,
onSend, onSend,
onRegenerate, onRegenerate,
onRestart,
// onAnnotationEdited, // onAnnotationEdited,
// onAnnotationAdded, // onAnnotationAdded,
// onAnnotationRemoved, // onAnnotationRemoved,
onFeedback, onFeedback,
onStopResponding
}: ChatContextProviderProps) => { }: ChatContextProviderProps) => {
return ( return (
<ChatContext.Provider value={{ <ChatContext.Provider value={{
...@@ -54,7 +60,9 @@ export const ChatContextProvider = ({ ...@@ -54,7 +60,9 @@ export const ChatContextProvider = ({
// onAnnotationEdited, // onAnnotationEdited,
// onAnnotationAdded, // onAnnotationAdded,
// onAnnotationRemoved, // onAnnotationRemoved,
onRestart,
onFeedback, onFeedback,
onStopResponding
}}> }}>
{children} {children}
</ChatContext.Provider> </ChatContext.Provider>
......
...@@ -22,7 +22,7 @@ type FooterProps = { ...@@ -22,7 +22,7 @@ type FooterProps = {
showFeatureBar?: boolean showFeatureBar?: boolean
showFileUpload?: boolean showFileUpload?: boolean
onFeatureBarClick?: (state: boolean) => void onFeatureBarClick?: (state: boolean) => void
onClear?: () => void onRestart: () => void
inputs?: Record<string, any> inputs?: Record<string, any>
inputsForm?: InputForm[] inputsForm?: InputForm[]
themeBuilder?: ThemeBuilder themeBuilder?: ThemeBuilder
...@@ -32,7 +32,7 @@ type FooterProps = { ...@@ -32,7 +32,7 @@ type FooterProps = {
isResponding?: boolean isResponding?: boolean
} }
const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName, onSend, noStopResponding, onStopResponding, noChatInput, isMobile, inputDisabled, showFeatureBar, showFileUpload, onFeatureBarClick, onClear, inputs, inputsForm, themeBuilder, config, suggestedQuestions, isShowPracticeButton, chatFooterRef, chatFooterInnerRef, isResponding }) => { const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName, onSend, noStopResponding, onStopResponding, noChatInput, isMobile, inputDisabled, showFeatureBar, showFileUpload, onFeatureBarClick, onRestart, inputs, inputsForm, themeBuilder, config, suggestedQuestions, isShowPracticeButton, chatFooterRef, chatFooterInnerRef, isResponding }) => {
const { t } = useTranslation() const { t } = useTranslation()
const hasTryToAsk = config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length && onSend const hasTryToAsk = config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length && onSend
return ( return (
...@@ -43,7 +43,7 @@ const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName ...@@ -43,7 +43,7 @@ const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName
{isResponding && !noStopResponding && <StopResponding onStopResponding={onStopResponding} />} {isResponding && !noStopResponding && <StopResponding onStopResponding={onStopResponding} />}
</div> </div>
{hasTryToAsk && <TryToAsk suggestedQuestions={suggestedQuestions} onSend={onSend} isMobile={isMobile} />} {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} onClear={onClear} inputs={inputs} inputsForm={inputsForm} theme={themeBuilder?.theme} isResponding={isResponding} />} {!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} inputs={inputs} inputsForm={inputsForm} theme={themeBuilder?.theme} isResponding={isResponding} />}
</div> </div>
</div> </div>
) )
......
...@@ -4,11 +4,13 @@ import type { OnSend } from '@/app/components/base/chat/types' ...@@ -4,11 +4,13 @@ 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'
type PracticeProps = { type PracticeProps = {
question: string question: string
onSend: OnSend onSend: OnSend
} }
const Practice: FC<PracticeProps> = ({ question, onSend }) => { const Practice: FC<PracticeProps> = ({ question }) => {
const { onSend } = useChatContext()
return ( return (
<div> <div>
{ {
...@@ -19,7 +21,7 @@ const Practice: FC<PracticeProps> = ({ question, onSend }) => { ...@@ -19,7 +21,7 @@ const Practice: FC<PracticeProps> = ({ question, onSend }) => {
rounded-8 rounded-8
shadow-[0_3px_8px_0_#7D94B840]" shadow-[0_3px_8px_0_#7D94B840]"
onClick={() => onClick={() =>
onSend({ onSend?.({
message: question, message: question,
type: InputMessageType.SELF, type: InputMessageType.SELF,
}) })
......
...@@ -2,21 +2,14 @@ ...@@ -2,21 +2,14 @@
* @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-06-27 10:27:07 * @LastEditTime: 2025-06-29 02:06:50
* @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 type { ReactNode } from 'react' import type { ReactNode } from 'react'
import React, { FC, memo, useCallback, useEffect, useRef } from 'react' import React, { FC, memo, useCallback, useEffect, useRef } from 'react'
// import { useShallow } from 'zustand/react/shallow' // import { useShallow } from 'zustand/react/shallow'
import type { import type { ChatConfig, ChatItem, Feedback, InputMessageProp, OnRegenerate, OnSend } from '../types'
ChatConfig,
ChatItem,
Feedback,
InputMessageProp,
OnRegenerate,
OnSend,
} from '../types'
import type { ThemeBuilder } from '../embedded-chatbot/theme/theme-context' import type { ThemeBuilder } from '../embedded-chatbot/theme/theme-context'
import Question from './question' import Question from './question'
import Answer from './answer' import Answer from './answer'
...@@ -42,7 +35,7 @@ export type ChatProps = { ...@@ -42,7 +35,7 @@ export type ChatProps = {
onStopResponding?: () => void onStopResponding?: () => void
noChatInput?: boolean noChatInput?: boolean
onSend?: OnSend onSend?: OnSend
onClear?: () => void onRestart: () => void
inputs?: Record<string, any> inputs?: Record<string, any>
inputsForm?: InputForm[] inputsForm?: InputForm[]
onRegenerate?: OnRegenerate onRegenerate?: OnRegenerate
...@@ -85,7 +78,7 @@ const Chat: FC<ChatProps> = ({ ...@@ -85,7 +78,7 @@ const Chat: FC<ChatProps> = ({
appData, appData,
config, config,
onSend, onSend,
onClear, onRestart,
inputs, inputs,
inputsForm, inputsForm,
onRegenerate, onRegenerate,
...@@ -146,10 +139,7 @@ const Chat: FC<ChatProps> = ({ ...@@ -146,10 +139,7 @@ const Chat: FC<ChatProps> = ({
if (!container) return if (!container) return
// 如果用户没有手动滚动,则直接到底 // 如果用户没有手动滚动,则直接到底
const isAtBottom = const isAtBottom = Math.abs(container.scrollHeight - container.clientHeight - container.scrollTop) <= 1
Math.abs(
container.scrollHeight - container.clientHeight - container.scrollTop,
) <= 1
if (!userScrolledRef.current || isAtBottom) { if (!userScrolledRef.current || isAtBottom) {
// 添加节流控制 // 添加节流控制
...@@ -270,8 +260,7 @@ const Chat: FC<ChatProps> = ({ ...@@ -270,8 +260,7 @@ const Chat: FC<ChatProps> = ({
if (!container) return if (!container) return
const handleScroll = () => { const handleScroll = () => {
const bottomThreshold = const bottomThreshold = container.scrollHeight - container.clientHeight - 8
container.scrollHeight - container.clientHeight - 8
const isUserScroll = container.scrollTop < bottomThreshold const isUserScroll = container.scrollTop < bottomThreshold
userScrolledRef.current = isUserScroll userScrolledRef.current = isUserScroll
} }
...@@ -280,13 +269,11 @@ const Chat: FC<ChatProps> = ({ ...@@ -280,13 +269,11 @@ const Chat: FC<ChatProps> = ({
return () => container.removeEventListener('scroll', handleScroll) return () => container.removeEventListener('scroll', handleScroll)
}, []) }, [])
const handleSend: OnSend = useCallback( const handleSend: OnSend = (query: InputMessageProp, files: FileEntity[] | undefined) => {
(query: InputMessageProp, files: FileEntity[] | undefined) => {
onSend && onSend(query, files) onSend && onSend(query, files)
userScrolledRef.current = false userScrolledRef.current = false
}, }
[onSend],
)
return ( return (
<ChatContextProvider <ChatContextProvider
config={config} config={config}
...@@ -297,6 +284,8 @@ const Chat: FC<ChatProps> = ({ ...@@ -297,6 +284,8 @@ const Chat: FC<ChatProps> = ({
answerIcon={answerIcon} answerIcon={answerIcon}
onSend={handleSend} onSend={handleSend}
onRegenerate={onRegenerate} onRegenerate={onRegenerate}
onRestart={onRestart}
// onStopResponding={onStopResponding}
// onAnnotationAdded={onAnnotationAdded} // onAnnotationAdded={onAnnotationAdded}
// onAnnotationEdited={onAnnotationEdited} // onAnnotationEdited={onAnnotationEdited}
// onAnnotationRemoved={onAnnotationRemoved} // onAnnotationRemoved={onAnnotationRemoved}
...@@ -310,13 +299,7 @@ const Chat: FC<ChatProps> = ({ ...@@ -310,13 +299,7 @@ const Chat: FC<ChatProps> = ({
chatStyles.chatContainer, chatStyles.chatContainer,
)}> )}>
{chatNode} {chatNode}
<div <div ref={chatContainerInnerRef} className={cn('w-full', !noSpacing && 'px-8', chatContainerInnerClassName)}>
ref={chatContainerInnerRef}
className={cn(
'w-full',
!noSpacing && 'px-8',
chatContainerInnerClassName,
)}>
{config?.initial_message && ( {config?.initial_message && (
<InitQuestions <InitQuestions
config={config} config={config}
...@@ -346,14 +329,7 @@ const Chat: FC<ChatProps> = ({ ...@@ -346,14 +329,7 @@ const Chat: FC<ChatProps> = ({
/> />
) )
} }
return ( return <Question key={item.id} item={item} questionIcon={questionIcon} theme={themeBuilder?.theme} />
<Question
key={item.id}
item={item}
questionIcon={questionIcon}
theme={themeBuilder?.theme}
/>
)
})} })}
</div> </div>
</div> </div>
...@@ -366,7 +342,7 @@ const Chat: FC<ChatProps> = ({ ...@@ -366,7 +342,7 @@ const Chat: FC<ChatProps> = ({
onSend={handleSend} onSend={handleSend}
inputs={inputs} inputs={inputs}
inputsForm={inputsForm} inputsForm={inputsForm}
onClear={onClear} onRestart={onRestart}
noStopResponding={noStopResponding} noStopResponding={noStopResponding}
onStopResponding={onStopResponding} onStopResponding={onStopResponding}
noChatInput={noChatInput} noChatInput={noChatInput}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!