Commit 7f0507bb by liimin

refactor(chat): 重构聊天组件

- 移除不必要的导入和未使用的代码
- 优化组件结构和渲染逻辑
- 调整样式和布局
- 添加骨架屏加载状态
1 parent 3b6967f5
...@@ -8,4 +8,4 @@ const Chat = () => { ...@@ -8,4 +8,4 @@ const Chat = () => {
) )
} }
export default React.memo(Chat, () => true) export default Chat
...@@ -2,31 +2,19 @@ ...@@ -2,31 +2,19 @@
* @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-09 16:01:24 * @LastEditTime: 2025-07-10 19:56:41
* @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 { useEffect, useMemo, FC } from 'react'
import Chat from '../chat' import Chat from '../chat'
import type { ChatConfig, ChatItem, ChatItemInTree, OnSend } from '../types' import type { ChatConfig } from '../types'
import { useChat } from '../chat/hooks' import { useChat } from './hooks'
import Loading from '@/app/components/base/loading' import Loading from '@/app/components/base/loading'
import AppUnavailable from '@/app/components/base/app-unavailable' import AppUnavailable from '@/app/components/base/app-unavailable'
import { getLastAnswer, isValidGeneratedAnswer } from '../utils' import { stopChatMessageResponding } from '@/service/share'
import { useChatWithHistoryContext } from './context'
import { InputVarType } from '@/app/components/workflow/types'
import { TransferMethod } from '@/types/app'
import InputsForm from '@/app/components/base/chat/chat-with-history/inputs-form'
import { fetchSuggestedQuestions, getUrl, stopChatMessageResponding } from '@/service/share'
import AppIcon from '@/app/components/base/app-icon'
import AnswerIcon from '@/app/components/base/answer-icon'
import SuggestedQuestions from '@/app/components/base/chat/chat/answer/suggested-questions'
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' import { InputMessageType } from '../types'
import { useChatWithHistory } from './hooks' import { useChatWithHistory } from './hooks'
import { useChatStore } from './store'
import { ChatContextProvider } from '@/app/components/base/chat/chat/context' import { ChatContextProvider } from '@/app/components/base/chat/chat/context'
enum MessageListenerType { enum MessageListenerType {
...@@ -51,59 +39,20 @@ type Props = { ...@@ -51,59 +39,20 @@ type Props = {
} }
const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPracticeButton }) => { const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPracticeButton }) => {
const { const {
appParams,
currentConversationId,
appPrevChatTree,
newConversationInputs,
newConversationInputsRef,
handleNewConversation,
handleNewConversationCompleted,
isInstalledApp,
appId,
handleFeedback,
currentChatInstanceRef,
clearChatList,
setClearChatList,
appInfoLoading,
appInfoError,
} = useChatWithHistory(undefined, inputs)
const config = useMemo(() => {
const config = appParams || {}
return {
...config,
file_upload: {
...(config as any).file_upload,
fileUploadConfig: (config as any).system_parameters,
},
supportFeedback: true,
opening_statement: (config as any).opening_statement,
initial_message: (config as any).opening_statement,
} as ChatConfig
}, [appParams])
const { chatList, isResponding, handleRestart, handleStop, sendMessage, doRegenerate } = useChat(
config, config,
{ chatList,
inputs: inputs as any, handleStop,
inputsForm: [], //InputsForm, sendMessage,
}, doRegenerate,
appPrevChatTree, appInfoError,
taskId => stopChatMessageResponding('', taskId, isInstalledApp, appId), isResponding,
clearChatList, handleRestart,
setClearChatList,
currentConversationId,
handleNewConversationCompleted,
isInstalledApp,
newConversationInputs,
appId,
handleFeedback, handleFeedback,
handleNewConversation appInfoLoading,
) handleNewConversation,
useEffect(() => { } = useChat(undefined, inputs)
if (currentChatInstanceRef.current) currentChatInstanceRef.current.handleStop = handleStop
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => { useEffect(() => {
console.log(presuppositionQuestion)
if (presuppositionQuestion) { if (presuppositionQuestion) {
sendMessage(presuppositionQuestion, InputMessageType.BY_AUTO) sendMessage(presuppositionQuestion, InputMessageType.BY_AUTO)
} }
...@@ -115,7 +64,7 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice ...@@ -115,7 +64,7 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
try { try {
switch (data.type) { switch (data.type) {
case MessageListenerType.RESET_CHAT: case MessageListenerType.RESET_CHAT:
handleNewConversation() handleNewConversation(undefined, false)
data.payload.message && sendMessage(data.payload.message, InputMessageType.BY_AUTO) data.payload.message && sendMessage(data.payload.message, InputMessageType.BY_AUTO)
break break
} }
...@@ -134,12 +83,11 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice ...@@ -134,12 +83,11 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
} }
} }
}, []) }, [])
if (appInfoLoading) {
return <Loading type="app" />
} else if (appInfoError) {
return <AppUnavailable />
} else {
return ( return (
<>
{appInfoLoading && <Loading type="app" />}
{appInfoError && <AppUnavailable />}
{!appInfoLoading && !appInfoError && (
<div className="h-full overflow-hidden"> <div className="h-full overflow-hidden">
<ChatContextProvider <ChatContextProvider
config={config} config={config}
...@@ -149,30 +97,13 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice ...@@ -149,30 +97,13 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
onRegenerate={doRegenerate} onRegenerate={doRegenerate}
onRestart={handleRestart} onRestart={handleRestart}
onStopResponding={handleStop} onStopResponding={handleStop}
onFeedback={handleFeedback} onFeedback={handleFeedback}>
> <Chat/>
<Chat
// 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}
/>
</ChatContextProvider> </ChatContextProvider>
</div> </div>
)}
</>
) )
}
} }
export default ChatWrapper export default ChatWrapper
export {useChatWithHistory} from './useChatWithHistory'
export {useUrlParams} from './useUrlParams'
\ No newline at end of file \ No newline at end of file
export { useChatWithHistory } from './useChatWithHistory'
export { useUrlParams } from './useUrlParams'
export { useChat } from './useChat'
...@@ -30,10 +30,10 @@ export const useUrlParams = () => { ...@@ -30,10 +30,10 @@ export const useUrlParams = () => {
if (!paramsRef.current) { if (!paramsRef.current) {
const search = globalThis.location?.search ?? '' const search = globalThis.location?.search ?? ''
const urlParams = new URLSearchParams(search) const urlParams = new URLSearchParams(search)
const paramsObject:urlProps = Object.fromEntries(urlParams.entries()) const paramsObject: urlProps = Object.fromEntries(urlParams.entries())
const {practice_status,presuppositionProblem,domain,avatar,no_header,...inputs} = paramsObject const { practice_status, presuppositionProblem, domain, avatar, no_header, ...inputs } = paramsObject
const isShowPracticeButton = practice_status === PracticeStatus.Practicing || practice_status === PracticeStatus.Failed const isShowPracticeButton =
inputs.queryType = '0' practice_status === PracticeStatus.Practicing || practice_status === PracticeStatus.Failed
paramsRef.current = { paramsRef.current = {
inputs, inputs,
presuppositionProblem, presuppositionProblem,
......
import type { FC } from 'react' import type { FC } from 'react'
import { useEffect, useState, useCallback, useRef, memo, useMemo } from 'react' import { useEffect, useState } from 'react'
import { useAsyncEffect } from 'ahooks'
import { useThemeContext } from '../embedded-chatbot/theme/theme-context'
import { ChatWithHistoryContext, useChatWithHistoryContext } from './context'
import { useChatWithHistory } from './hooks'
import Header from './header'
import ChatWrapper from './chat-wrapper' import ChatWrapper from './chat-wrapper'
// import type { InstalledApp } from '@/models/explore' // import type { InstalledApp } from '@/models/explore'
import Loading from '@/app/components/base/loading' import Loading from '@/app/components/base/loading'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints' import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import { checkOrSetAccessToken } from '@/app/components/share/utils' import { checkOrSetAccessToken } from '@/app/components/share/utils'
import AppUnavailable from '@/app/components/base/app-unavailable' import AppUnavailable from '@/app/components/base/app-unavailable'
import Confirm from '@/app/components/base/confirm'
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, PracticeStatus } from '../types'
import { AVATAR_USER_URL, AVATAR_AI_URL, MAIN_TITLE } from '@/app/components/base/chat/constants'
import React from 'react' import React from 'react'
import { useUrlParams } from './hooks' import { useUrlParams } from './hooks'
type ChatWithHistoryProps = { type ChatWithHistoryProps = {
className?: string className?: string
} }
// type urlProps = {
// domain?: string
// no_header?: string // 是否显示头部
// avatar?: string // 头像
// business_type?: string // 业务类型
// brand?: string // 品牌
// one_id?: string // 唯一标识
// queryType?: string //问题类型
// position?: string // 岗位
// platformType?: string // 平台类型
// presuppositionProblem?: string // 平台类型
// practice_status?: PracticeStatus // 练习状态
// }
// console.log(111111111)
// // 获取地址栏参数
// const getQueryParams = function (): urlProps {
// const search = globalThis.location?.search ?? ''
// const urlParams = new URLSearchParams(search)
// const paramsObject = Object.fromEntries(urlParams.entries())
// const avatar = urlParams.get('avatar') ?? AVATAR_USER_URL
// const presuppositionProblem = urlParams.get('presuppositionProblem') ?? ''
// return {
// ...paramsObject,
// avatar,
// presuppositionProblem,
// queryType: '0',
// }
// }
// const inputs = getQueryParams()
// let { avatar, domain, presuppositionProblem, practice_status, ...newInputs } = inputs
// const isShowPracticeButton = practice_status === PracticeStatus.Practicing || practice_status === PracticeStatus.Failed
// const avatarUrl: string = avatar ?? AVATAR_USER_URL
// const useChatParams = () => {
// const params = useUrlParams()
// const { presuppositionProblem, isShowPracticeButton, inputs } = params!
// return { presuppositionProblem, isShowPracticeButton, newInputs }
// }
const ChatWithHistory: FC<ChatWithHistoryProps> = React.memo(() => { const ChatWithHistory: FC<ChatWithHistoryProps> = React.memo(() => {
// const { appInfoError, appInfoLoading, isMobile } = useChatWithHistoryContext() const isMobile = useBreakpoints() === MediaType.mobile
// console.log('appInfoLoading',appInfoLoading)
// if (appInfoLoading) {
// return <Loading type="app" />
// } else if (appInfoError) {
// return <AppUnavailable />
// } else {
// console.log('inputs', inputs)
// const isMobile = useBreakpoints() === MediaType.mobile
const { presuppositionProblem, isShowPracticeButton, inputs } = useUrlParams() const { presuppositionProblem, isShowPracticeButton, inputs } = useUrlParams()
console.log('inputs', inputs) console.log('inputs', inputs)
return ( return (
<div className={cn('flex h-full bg-background-default-burn', true && 'flex-col')}> <div className={cn('flex h-full bg-background-default-burn', isMobile && 'flex-col')}>
<div className={cn('relative grow', true && 'h-[calc(100%_-_56px)] p-0')}> <div className={cn('relative grow', isMobile && 'h-[calc(100%_-_56px)] p-0')}>
<div <div className={cn('flex h-full flex-col overflow-hidden border-components-panel-border-subtle chat-panel-bg')}>
className={cn('flex h-full flex-col overflow-hidden border-components-panel-border-subtle chat-panel-bg')}>
<ChatWrapper <ChatWrapper
presuppositionQuestion={presuppositionProblem} presuppositionQuestion={presuppositionProblem}
isShowPracticeButton={isShowPracticeButton} isShowPracticeButton={isShowPracticeButton}
...@@ -93,35 +37,25 @@ export type ChatWithHistoryWrapProps = { ...@@ -93,35 +37,25 @@ export type ChatWithHistoryWrapProps = {
installedAppInfo?: any //InstalledApp installedAppInfo?: any //InstalledApp
className?: string className?: string
} }
type LoadingType = 'loading' | 'success' | 'error'
const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, className }) => { const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, className }) => {
const [initialized, setInitialized] = useState(false) const [status, setStatus] = useState<LoadingType>('loading')
const [appUnavailable, setAppUnavailable] = useState<boolean>(false) const [isLoaded, setIsLoaded] = useState(false)
// const [isUnknownReason, setIsUnknownReason] = useState<boolean>(false) useEffect(() => {
const hasRendered = useRef(false) checkOrSetAccessToken()
useAsyncEffect(async () => { .then(() => setStatus('success'))
if (!initialized) { .catch(() => setStatus('error'))
// if (!installedAppInfo) { }, [])
try { useEffect(() => {
await checkOrSetAccessToken() if (status === 'success' && !isLoaded) {
console.log('222222',initialized,appUnavailable) setIsLoaded(true)
} catch (e: any) {
console.log('333333',initialized,appUnavailable)
setAppUnavailable(true)
if (e.status !== 404) {
// setIsUnknownReason(true)
}
}
console.log('44444',initialized,appUnavailable)
// }
setInitialized(true)
} }
}, []) // 添加正确依赖 }, [status, isLoaded])
console.log('initialized', initialized,appUnavailable)
return ( return (
<> <>
{!initialized && <Loading type="app" />} {status === 'loading' && <Loading type="app" />}
{initialized && appUnavailable && <AppUnavailable isUnknownReason={false} />} {status === 'error' && <AppUnavailable />}
{initialized && !appUnavailable && <ChatWithHistory className={className} />} {isLoaded && <ChatWithHistory className={className} />}
</> </>
) )
} }
......
...@@ -14,7 +14,7 @@ import { state } from 'mermaid/dist/rendering-util/rendering-elements/shapes/sta ...@@ -14,7 +14,7 @@ import { state } from 'mermaid/dist/rendering-util/rendering-elements/shapes/sta
type FooterProps = { type FooterProps = {
chatFooterClassName?: string chatFooterClassName?: string
chatFooterInnerClassName?: string chatFooterInnerClassName?: string
isShowPracticeButton: boolean // isShowPracticeButton: boolean
suggestedQuestions?: string[] suggestedQuestions?: string[]
isMobile?: boolean isMobile?: boolean
chatFooterRef: React.RefObject<HTMLDivElement> chatFooterRef: React.RefObject<HTMLDivElement>
...@@ -26,24 +26,17 @@ const Footer: FC<FooterProps> = ({ ...@@ -26,24 +26,17 @@ const Footer: FC<FooterProps> = ({
chatFooterInnerClassName, chatFooterInnerClassName,
isMobile, isMobile,
suggestedQuestions, suggestedQuestions,
isShowPracticeButton, // isShowPracticeButton,
chatFooterRef, chatFooterRef,
chatFooterInnerRef, chatFooterInnerRef,
}) => { }) => {
// const config = useChatStore(state=> state.config)
// const {config} = useChatContext()
// const hasTryToAsk = useMemo(
// () => config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length,
// [config?.suggested_questions_after_answer?.enabled, suggestedQuestions]
// )
console.log('Footer')
return ( return (
<div <div
className={`absolute bottom-0 flex justify-center bg-chat-input-mask ${chatFooterClassName}`} className={`absolute bottom-0 flex justify-center bg-chat-input-mask ${chatFooterClassName}`}
ref={chatFooterRef}> 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 />} {/* {isShowPracticeButton && <Practice />} */}
{ <StopResponding />} { <StopResponding />}
</div> </div>
{!!suggestedQuestions?.length && <TryToAsk suggestedQuestions={suggestedQuestions} isMobile={isMobile} />} {!!suggestedQuestions?.length && <TryToAsk suggestedQuestions={suggestedQuestions} isMobile={isMobile} />}
...@@ -53,6 +46,4 @@ const Footer: FC<FooterProps> = ({ ...@@ -53,6 +46,4 @@ const Footer: FC<FooterProps> = ({
) )
} }
export default memo(Footer, (prevProps, nextProps) => { export default memo(Footer)
return true
})
import {
useCallback,
useRef,
useState,
} from 'react'
export const useTextAreaHeight = () => {
const wrapperRef = useRef<HTMLDivElement>(null)
const textareaRef = useRef<HTMLTextAreaElement | undefined>(undefined)
const textValueRef = useRef<HTMLDivElement>(null)
const holdSpaceRef = useRef<HTMLDivElement>(null)
const [isMultipleLine, setIsMultipleLine] = useState(false)
const handleComputeHeight = useCallback(() => {
const textareaElement = textareaRef.current
if (wrapperRef.current && textareaElement && textValueRef.current && holdSpaceRef.current) {
const { width: wrapperWidth } = wrapperRef.current.getBoundingClientRect()
const { height: textareaHeight } = textareaElement.getBoundingClientRect()
const { width: textValueWidth } = textValueRef.current.getBoundingClientRect()
const { width: holdSpaceWidth } = holdSpaceRef.current.getBoundingClientRect()
if (textareaHeight > 32) {
setIsMultipleLine(true)
}
else {
if (textValueWidth + holdSpaceWidth >= wrapperWidth)
setIsMultipleLine(true)
else
setIsMultipleLine(false)
}
}
}, [])
const handleTextareaResize = useCallback(() => {
handleComputeHeight()
}, [handleComputeHeight])
return {
wrapperRef,
textareaRef,
textValueRef,
holdSpaceRef,
handleTextareaResize,
isMultipleLine,
setIsMultipleLine
}
}
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import Textarea from 'react-textarea-autosize'
import { useTranslation } from 'react-i18next'
import Recorder from 'js-audio-recorder'
import { useCheckInputsForms } from '../../check-input-forms-hooks'
import { useTextAreaHeight } from './hooks'
import Operation from './operation'
import cn from '@/utils/classnames'
import { FileListInChatInput } from '@/app/components/base/file-uploader'
import { useFile } from '@/app/components/base/file-uploader/hooks'
import { FileContextProvider, useFileStore } from '@/app/components/base/file-uploader/store'
import VoiceInput from '@/app/components/base/voice-input'
import { useToastContext } from '@/app/components/base/toast'
import FeatureBar from '@/app/components/base/features/new-feature-panel/feature-bar'
import type { FileUpload } from '@/app/components/base/features/types'
import { TransferMethod } from '@/types/app'
import { InputMessageType } from '../../../types'
import { useChatContext } from '../../context'
import Confirm from '@/app/components/base/confirm'
type ChatInputAreaProps = {
}
const ChatInputArea = ({
}: ChatInputAreaProps) => {
const { t } = useTranslation()
const { notify } = useToastContext()
const {isResponding, onSend:sendMessage, onRestart:restartChat,config} = useChatContext()
console.log('visionConfig', isResponding)
const visionConfig = config.file_upload
const speechToTextConfig = config.speech_to_text
// const sendMessage = useChatStore(state => state.sendMessage)
// const isResponding = useChatStore(state => state.isResponding)
// const restartChat = useChatStore(state => state.restartChat)
const {
wrapperRef,
textareaRef,
textValueRef,
holdSpaceRef,
handleTextareaResize,
isMultipleLine,
setIsMultipleLine,
} = useTextAreaHeight()
const [query, setQuery] = useState('')
const [showVoiceInput, setShowVoiceInput] = useState(false)
const filesStore = useFileStore()
const {
handleDragFileEnter,
handleDragFileLeave,
handleDragFileOver,
handleDropFile,
handleClipboardPasteFile,
isDragActive,
} = useFile(visionConfig!)
const { checkInputsForm } = useCheckInputsForms()
const historyRef = useRef([''])
const [currentIndex, setCurrentIndex] = useState(-1)
const isComposingRef = useRef(false)
// const { onSend } = useChatContext()
const [showConfirm, setShowConfirm] = useState<boolean>(false)
const featureBarDisabled = isResponding
const handleSend = () => {
if (isResponding) {
notify({
type: 'info',
message: t('appDebug.errorMessage.waitForResponse'),
})
return
}
if (sendMessage) {
const { files, setFiles } = filesStore.getState()
if (files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)) {
notify({
type: 'info',
message: t('appDebug.errorMessage.waitForFileUpload'),
})
return
}
if (!query || !query.trim()) {
notify({
type: 'info',
message: t('appAnnotation.errorMessage.queryRequired'),
})
return
}
// if (checkInputsForm(inputs, inputsForm)) {
sendMessage(query, InputMessageType.BY_HAND, files)
setQuery('')
setFiles([])
// }
}
}
const handleCompositionStart = () => {
// e: React.CompositionEvent<HTMLTextAreaElement>
isComposingRef.current = true
}
const handleCompositionEnd = () => {
// safari or some browsers will trigger compositionend before keydown.
// delay 50ms for safari.
setTimeout(() => {
isComposingRef.current = false
}, 50)
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
// if isComposing, exit
if (isComposingRef.current) return
e.preventDefault()
setQuery(query.replace(/\n$/, ''))
historyRef.current.push(query)
setCurrentIndex(historyRef.current.length)
handleSend()
} else if (e.key === 'ArrowUp' && !e.shiftKey && !e.nativeEvent.isComposing && e.metaKey) {
// When the cmd + up key is pressed, output the previous element
if (currentIndex > 0) {
setCurrentIndex(currentIndex - 1)
setQuery(historyRef.current[currentIndex - 1])
}
} else if (e.key === 'ArrowDown' && !e.shiftKey && !e.nativeEvent.isComposing && e.metaKey) {
// When the cmd + down key is pressed, output the next element
if (currentIndex < historyRef.current.length - 1) {
setCurrentIndex(currentIndex + 1)
setQuery(historyRef.current[currentIndex + 1])
} else if (currentIndex === historyRef.current.length - 1) {
// If it is the last element, clear the input box
setCurrentIndex(historyRef.current.length)
setQuery('')
}
}
}
const handleShowVoiceInput = useCallback(() => {
;(Recorder as any).getPermission().then(
() => {
setShowVoiceInput(true)
},
() => {
notify({ type: 'error', message: t('common.voiceInput.notAllow') })
},
)
}, [t, notify])
const handleRestart = useCallback(() => {
if (isResponding) {
notify({
type: 'info',
message: t('appDebug.errorMessage.waitForResponse'),
})
return
}
setShowConfirm(true)
}, [isResponding])
const doRestart = useCallback(() => {
restartChat()
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 hasQuery = useMemo(() => query.length > 0, [query])
useEffect(() => {
if (!hasQuery) {
setIsMultipleLine(false)
}
}, [hasQuery, setIsMultipleLine])
const maxRow = useMemo(() => {
return hasQuery ? undefined : 1
}, [hasQuery])
return (
<>
{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]">
<FileListInChatInput fileConfig={visionConfig!} />
<div ref={wrapperRef} className="flex items-center justify-between">
<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">
{query}
</div>
<Textarea
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',
)}
placeholder={t('common.chat.inputPlaceholder') || ''}
autoFocus
maxRows={maxRow}
onResize={handleTextareaResize}
value={query}
onChange={e => {
setQuery(e.target.value)
setTimeout(handleTextareaResize, 0)
}}
onKeyDown={handleKeyDown}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
onPaste={handleClipboardPasteFile}
onDragEnter={handleDragFileEnter}
onDragLeave={handleDragFileLeave}
onDragOver={handleDragFileOver}
onDrop={handleDropFile}
/>
</div>
{!isMultipleLine && operation}
</div>
{showVoiceInput && (
<VoiceInput onCancel={() => setShowVoiceInput(false)} onConverted={text => setQuery(text)} />
)}
</div>
{isMultipleLine && <div className="px-[9px]">{operation}</div>}
</div>
</>
)
}
const ChatInputAreaWrapper = (props: ChatInputAreaProps) => {
return (
<FileContextProvider>
<ChatInputArea {...props} />
</FileContextProvider>
)
}
export default ChatInputAreaWrapper
import { Dispatch, memo, SetStateAction, use, useMemo } from 'react'
import { RiMicLine, RiSendPlane2Fill } from '@remixicon/react'
import type { EnableType } from '../../types'
import type { Theme } from '../../embedded-chatbot/theme/theme-context'
import Button from '@/app/components/base/button'
import ActionButton from '@/app/components/base/action-button'
import { FileUploaderInChatInput } from '@/app/components/base/file-uploader'
import type { FileUpload } from '@/app/components/base/features/types'
import cn from '@/utils/classnames'
import { useChatStore } from '@/app/components/base/chat/chat-with-history/store'
import {
// SELF_INPUT,
SEND_BUTTON,
CLEAR_BUTTON,
} from '@/app/components/base/chat/constants'
type OperationProps = {
fileConfig?: FileUpload
speechToTextConfig?: EnableType
onShowVoiceInput?: () => void
onSend: () => void
imgUrl?: string
theme?: Theme | null
onRestart: () => void
}
const Operation = ({
ref,
onSend,
speechToTextConfig,
onShowVoiceInput,
onRestart,
}: OperationProps & {
ref: React.RefObject<HTMLDivElement>
}) => {
return (
<div className={cn('flex shrink-0 items-center justify-end')}>
<div className="absolute left-3">
<img onClick={onRestart} src={CLEAR_BUTTON} className="size-6 hover:cursor-pointer" alt="icon" />
</div>
<div className="flex items-center pl-1" ref={ref}>
<div className="flex items-center space-x-1 pr-2">
{/* {fileConfig?.enabled && <FileUploaderInChatInput fileConfig={fileConfig} />} */}
{speechToTextConfig?.enabled && (
<ActionButton size="l" onClick={onShowVoiceInput}>
<RiMicLine className="h-5 w-5" />
</ActionButton>
)}
</div>
<img onClick={onSend} src={SEND_BUTTON} className="size-6 hover:cursor-pointer" alt="icon" />
</div>
</div>
)
}
Operation.displayName = 'Operation'
export default memo(Operation)
import { FC, memo } from 'react' import { FC, memo, useMemo } 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' import { useChatContext } from '../context'
import { useChatStore } from '../../chat-with-history/store' import { useChatStore } from '../../chat-with-history/store'
import { state } from 'mermaid/dist/rendering-util/rendering-elements/shapes/state'
const StopRespondingButton: FC = () => { const StopRespondingButton: FC = () => {
const { t } = useTranslation() const { t } = useTranslation()
// const isResponding = useChatStore(state => state.isResponding)
// const stopResponding = useChatStore(state => state.stopResponding)
const { isResponding, onStopResponding: stopResponding } = useChatContext() const { isResponding, onStopResponding: stopResponding } = useChatContext()
const mc = useMemo(() => {
if (!isResponding) return null 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">
...@@ -19,6 +17,8 @@ const StopRespondingButton: FC = () => { ...@@ -19,6 +17,8 @@ const StopRespondingButton: FC = () => {
</Button> </Button>
</div> </div>
) )
}, [isResponding])
return mc
} }
export default memo(StopRespondingButton) export default StopRespondingButton
...@@ -771,6 +771,22 @@ export const useChat = ( ...@@ -771,6 +771,22 @@ export const useChat = (
}, },
[doSend], [doSend],
) )
const sendMessageAfterNewConversation =useCallback( (
message: string,
type: InputMessageType,
delay: number = 0
) => {
const trySendMessage = () => {
if (!currentConversationId) {
sendMessage(message, type)
} else {
console.log('trySendMessage')
setTimeout(trySendMessage, delay || 50)
}
}
trySendMessage()
},[])
const disablePracticeTags = useCallback(() => { const disablePracticeTags = useCallback(() => {
const lastTag = Array.from(document.querySelectorAll('.practice-tags')).pop() const lastTag = Array.from(document.querySelectorAll('.practice-tags')).pop()
if (!lastTag || lastTag.classList.contains('pointer-events-none')) return if (!lastTag || lastTag.classList.contains('pointer-events-none')) return
...@@ -890,6 +906,7 @@ export const useChat = ( ...@@ -890,6 +906,7 @@ export const useChat = (
handleStop, handleStop,
sendMessage, sendMessage,
doRegenerate, doRegenerate,
sendMessageAfterNewConversation
// handleAnnotationEdited, // handleAnnotationEdited,
// handleAnnotationAdded, // handleAnnotationAdded,
// handleAnnotationRemoved, // handleAnnotationRemoved,
......
...@@ -2,72 +2,30 @@ ...@@ -2,72 +2,30 @@
* @Author: liimin 17653212@qq.com * @Author: liimin 17653212@qq.com
* @Date: 2025-04-16 18:17:38 * @Date: 2025-04-16 18:17:38
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-09 17:06:00 * @LastEditTime: 2025-07-10 10:39:06
* @FilePath: \ai-assistant\app\components\base\chat\chat\index.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\index.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
import React, { import React, {
FC, FC,
memo, memo,
RefObject,
use,
useCallback,
useEffect, useEffect,
useImperativeHandle,
useMemo,
useRef, useRef,
useState,
} from 'react' } from 'react'
import {
InputMessageType,
SendProps,
type ChatConfig,
type ChatItem,
type ChatItemInTree,
type Feedback,
type InputMessageProp,
type OnRegenerate,
type OnSend,
} from '../types'
import Question from './question'
import Answer from './answer'
import AnswerIcon from '@/app/components/base/answer-icon' import AnswerIcon from '@/app/components/base/answer-icon'
import { ChatContextProvider, OnSendMessage } from './context'
import type { InputForm } from './type'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import type { Emoji } from '@/app/components/tools/types'
import InitQuestions from '@/app/components/base/chat/chat/answer/init-questions' import InitQuestions from '@/app/components/base/chat/chat/answer/init-questions'
import ChatFooter from './footer' import ChatFooter from './footer'
import chatStyles from './chat.module.css' import chatStyles from './chat.module.css'
import { FileEntity } from '../../file-uploader/types' import { AVATAR_USER_URL, AVATAR_AI_URL } from '@/app/components/base/chat/constants'
import { fetchSuggestedQuestions, getUrl, stopChatMessageResponding } from '@/service/share'
import { useChatWithHistory } from '../chat-with-history/hooks'
import { AVATAR_USER_URL, AVATAR_AI_URL, MAIN_TITLE } from '@/app/components/base/chat/constants'
import { getLastAnswer, isValidGeneratedAnswer } from '../utils'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints' import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import ChatBody from './body' import ChatBody from './body'
import { useChatStore } from '../chat-with-history/store'
export type ChatProps = { export type ChatProps = {
// inputs?: Record<string, any> // isShowPracticeButton: boolean
isShowPracticeButton: boolean
// ref: any
// appParams: ChatConfig
// currentConversationId: string
// appPrevChatTree: ChatItemInTree[]
// newConversationInputs: Record<string, any>
// newConversationInputsRef: RefObject<Record<string, any>>
// handleNewConversation: (v?: Record<string, any>, skipClear?: boolean) => void
// handleNewConversationCompleted: (newConversationId: string) => void
// isInstalledApp: boolean
// appId: string
// handleFeedback: (messageId: string, feedback: Feedback) => void
// currentChatInstanceRef: RefObject<{ handleStop: () => void }>
// clearChatList: boolean
// setClearChatList: (state: boolean) => void
} }
const Chat: FC<ChatProps> = ({ isShowPracticeButton }) => { const Chat: FC<ChatProps> = () => {
const chatContainerRef = useRef<HTMLDivElement>(null) const chatContainerRef = useRef<HTMLDivElement>(null)
const chatContainerInnerRef = useRef<HTMLDivElement>(null) const chatContainerInnerRef = useRef<HTMLDivElement>(null)
const chatFooterRef = useRef<HTMLDivElement>(null) const chatFooterRef = useRef<HTMLDivElement>(null)
...@@ -75,90 +33,10 @@ const Chat: FC<ChatProps> = ({ isShowPracticeButton }) => { ...@@ -75,90 +33,10 @@ const Chat: FC<ChatProps> = ({ isShowPracticeButton }) => {
const userScrolledRef = useRef(false) const userScrolledRef = useRef(false)
const tickingRef = useRef(false) const tickingRef = useRef(false)
const lastScrollHeightRef = useRef(0) const lastScrollHeightRef = useRef(0)
// const config = useChatStore(state => state.config)
// const config = useMemo(() => {
// const config = appParams || {}
// return {
// ...config,
// file_upload: {
// ...(config as any).file_upload,
// fileUploadConfig: (config as any).system_parameters,
// },
// supportFeedback: true,
// opening_statement: (config as any).opening_statement,
// initial_message: (config as any).opening_statement,
// } as ChatConfig
// }, [appParams, currentConversationId])
// const {
// chatList,
// setTargetMessageId,
// handleSend: onSend,
// handleStop,
// isResponding,
// suggestedQuestions,
// handleRestart,
// } =
// useChat(
// config,
// {
// inputs: inputs as any,
// inputsForm: [], //InputsForm,
// },
// appPrevChatTree,
// taskId => stopChatMessageResponding('', taskId, isInstalledApp, appId),
// clearChatList,
// setClearChatList,
// currentConversationId,
// )
const answerIcon = <AnswerIcon imageUrl={AVATAR_AI_URL} /> const answerIcon = <AnswerIcon imageUrl={AVATAR_AI_URL} />
const questionIcon = <AnswerIcon imageUrl={AVATAR_USER_URL} /> const questionIcon = <AnswerIcon imageUrl={AVATAR_USER_URL} />
const isMobile = useBreakpoints() === MediaType.mobile const isMobile = useBreakpoints() === MediaType.mobile
// useEffect(() => {
// if (currentChatInstanceRef.current) currentChatInstanceRef.current.handleStop = handleStop
// eslint-disable-next-line react-hooks/exhaustive-deps
// }, [])
// const doSend: OnSend = useCallback(
// ({ messageObj, files, parentMessageId }: SendProps) => {
// const data: any = {
// query: messageObj?.message,
// files,
// inputs: { ...newConversationInputs, queryType: messageObj?.type || InputMessageType.SELF },
// // conversation_id: currentConversationId,
// // parent_message_id: (isRegenerate ? parentAnswer?.id : getLastAnswer(chatList)?.id) || null,
// }
// onSend(
// getUrl('chat-messages', isInstalledApp, appId || ''),
// data,
// {
// onGetSuggestedQuestions: responseItemId => fetchSuggestedQuestions(responseItemId, isInstalledApp, appId),
// onConversationComplete: currentConversationId ? undefined : handleNewConversationCompleted,
// isPublicAPI: !isInstalledApp,
// },
// parentMessageId,
// )
// },
// [
// chatList,
// handleNewConversationCompleted,
// onSend,
// currentConversationId,
// newConversationInputs,
// isInstalledApp,
// appId,
// ],
// )
// const messageList = useMemo(() => {
// return chatList
// }, [chatList, currentConversationId])
// const onRestart = useCallback(() => {
// handleRestart(handleNewConversation)
// }, [handleRestart, handleNewConversation])
const handleScrollToBottom = () => { const handleScrollToBottom = () => {
const container = chatContainerRef.current const container = chatContainerRef.current
...@@ -197,39 +75,6 @@ const Chat: FC<ChatProps> = ({ isShowPracticeButton }) => { ...@@ -197,39 +75,6 @@ const Chat: FC<ChatProps> = ({ isShowPracticeButton }) => {
if (!container || !footer) return if (!container || !footer) return
container.style.paddingBottom = `${footer.clientHeight}px` container.style.paddingBottom = `${footer.clientHeight}px`
handleScrollToBottom() handleScrollToBottom()
// 创建并配置容器观察器
// const resizeContainerObserver = new ResizeObserver(entries => {
// for (const entry of entries) {
// const blockSize = entry.borderBoxSize?.[0]?.blockSize
// console.log(blockSize)
// if (blockSize !== undefined) {
// container.style.paddingBottom = `${blockSize}px`
// handleScrollToBottom()
// }
// }
// })
// 创建并配置页脚观察器
// const resizeFooterObserver = new ResizeObserver(entries => {
// for (const entry of entries) {
// // 使用可选链操作符确保兼容性
// const inlineSize = entry.borderBoxSize?.[0]?.inlineSize
// if (inlineSize !== undefined) {
// footer.style.width = `${inlineSize}px`
// }
// }
// })
// 观察 DOM 变化
// resizeContainerObserver.observe(footer)
// resizeFooterObserver.observe(container)
// 清理函数
// return () => {
// 明确清理所有观察器
// if (resizeContainerObserver) resizeContainerObserver.disconnect()
// if (resizeFooterObserver) resizeFooterObserver.disconnect()
// }
}, [handleScrollToBottom]) }, [handleScrollToBottom])
console.log('installedAppInfo') console.log('installedAppInfo')
return ( return (
...@@ -250,7 +95,7 @@ const Chat: FC<ChatProps> = ({ isShowPracticeButton }) => { ...@@ -250,7 +95,7 @@ const Chat: FC<ChatProps> = ({ isShowPracticeButton }) => {
chatFooterInnerClassName={chatFooterInnerClassName} chatFooterInnerClassName={chatFooterInnerClassName}
suggestedQuestions={[]} suggestedQuestions={[]}
isMobile={isMobile} isMobile={isMobile}
isShowPracticeButton={isShowPracticeButton} // isShowPracticeButton={isShowPracticeButton}
/> />
} }
</div> </div>
......
...@@ -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-12 13:54:54 * @LastEditTime: 2025-07-10 17:32:33
* @FilePath: \ai-assistant\app\components\base\chat\types.ts * @FilePath: \ai-assistant\app\components\base\chat\types.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
......
import React from 'react' import React from 'react'
import './style.css' import './style.css'
type ILoadingProps = { import { SkeletonContainer, SkeletonPoint, SkeletonRectangle, SkeletonRow } from '../skeleton'
type?: 'area' | 'app'
} type LoadingType = 'app' | 'skeleton'
const Loading = (
{ type = 'area' }: ILoadingProps = { type: 'area' }, const Loading: React.FC<{ type?: LoadingType }> = ({ type = 'app' }) => {
) => { if (type === 'app') {
return ( return (
<div className={`flex w-full items-center justify-center ${type === 'app' ? 'h-full' : ''}`}> <div className={`flex w-full items-center justify-center ${type === 'app' ? 'h-full' : ''}`}>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className='spin-animation'> <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className='spin-animation'>
...@@ -25,5 +24,16 @@ const Loading = ( ...@@ -25,5 +24,16 @@ const Loading = (
</div> </div>
) )
}else{
return (
<SkeletonContainer>
<SkeletonRow>
<SkeletonPoint />
<SkeletonRectangle className="w-96" />
</SkeletonRow>
</SkeletonContainer>
)
}
} }
export default Loading export default Loading
...@@ -736,8 +736,6 @@ html[data-theme="dark"] { ...@@ -736,8 +736,6 @@ html[data-theme="dark"] {
--color-saas-background: #0b0b0e; --color-saas-background: #0b0b0e;
--color-saas-pricing-grid-bg: #c8ceda33; --color-saas-pricing-grid-bg: #c8ceda33;
.chat-panel-bg { .chat-panel-bg {
background: background-color: #f5f9ff;
url("https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-bg.png") top / 100% 240px no-repeat,
#f5f9ff 0 240px / 100% calc(100% - 240px) no-repeat;
} }
} }
\ No newline at end of file \ No newline at end of file
...@@ -736,8 +736,6 @@ html[data-theme="light"] { ...@@ -736,8 +736,6 @@ html[data-theme="light"] {
--color-saas-background: #fcfcfd; --color-saas-background: #fcfcfd;
--color-saas-pricing-grid-bg: #c8ceda80; --color-saas-pricing-grid-bg: #c8ceda80;
.chat-panel-bg { .chat-panel-bg {
background: background-color: #f5f9ff;
url("https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-bg.png") top / 100% 240px no-repeat,
#f5f9ff 0 240px / 100% calc(100% - 240px) no-repeat;
} }
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!