Commit d4cafcfe by liimin

refactor(chat): 重构聊天组件的上下文结构

- 将 ChatContext 分为三个独立的上下文:
  - ChatConfigContext: 包含聊天配置
  - ChatRuntimeContext: 包含聊天运行时数据和方法
  - ChatOperationContext: 包含聊天操作相关数据
- 更新了相关组件和文件,使其使用新的上下文结构
- 删除了不必要的代码和导入,简化了代码结构
1 parent c09e9442
Showing 36 changed files with 226 additions and 579 deletions
......@@ -2,7 +2,7 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17
* @LastEditors: limin
* @LastEditTime: 2025-07-10 19:56:41
* @LastEditTime: 2025-07-15 23:45:09
* @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
*/
......@@ -15,7 +15,9 @@ import AppUnavailable from '@/app/components/base/app-unavailable'
import { stopChatMessageResponding } from '@/service/share'
import { InputMessageType } from '../types'
import { useChatWithHistory } from './hooks'
import { ChatContextProvider } from '@/app/components/base/chat/chat/context'
import { ChatContextProvider } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { ChatRuntimeProvider } from './context/chat-runtime-context'
import { ChatConfigProvider } from './context/chat-config-context'
enum MessageListenerType {
RESET_CHAT = 'reset_chat',
......@@ -44,14 +46,14 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
handleStop,
sendMessage,
doRegenerate,
appInfoError,
// appInfoError,
isResponding,
handleRestart,
handleFeedback,
appInfoLoading,
// appInfoLoading,
handleNewConversation,
} = useChat(undefined, inputs)
useEffect(() => {
if (presuppositionQuestion) {
sendMessage(presuppositionQuestion, InputMessageType.BY_AUTO)
......@@ -84,25 +86,20 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
}
}, [])
return (
<>
{appInfoLoading && <Loading type="app" />}
{appInfoError && <AppUnavailable />}
{!appInfoLoading && !appInfoError && (
<div className="h-full overflow-hidden">
<ChatContextProvider
config={config}
chatList={chatList}
isResponding={isResponding}
onSend={sendMessage}
onRegenerate={doRegenerate}
onRestart={handleRestart}
onStopResponding={handleStop}
onFeedback={handleFeedback}>
<Chat/>
</ChatContextProvider>
</div>
)}
</>
<div className="h-full overflow-hidden">
<ChatConfigProvider config={config}>
<ChatContextProvider
onSend={sendMessage}
onRegenerate={doRegenerate}
onRestart={handleRestart}
onStopResponding={handleStop}
onFeedback={handleFeedback}>
<ChatRuntimeProvider chatList={chatList} isResponding={isResponding}>
<Chat />
</ChatRuntimeProvider>
</ChatContextProvider>
</ChatConfigProvider>
</div>
)
}
......
// app/components/base/chat/chat/chat-config-context.tsx
'use client'
import { createContext, useContext } from 'use-context-selector'
import type { ChatConfig } from '../../types'
import { useMemo } from 'react'
const ChatConfigContext = createContext<ChatConfig>({} as ChatConfig)
type Props = {
children: React.ReactNode
config: ChatConfig
}
export const ChatConfigProvider = ({ children, config }: Props) => {
// 只暴露你真正关心的字段(可根据需要扩展)
const value = useMemo(
() => ({
appId: config.appId,
initial_message: config.initial_message,
suggested_questions: config.suggested_questions,
file_upload: config.file_upload,
supportFeedback: config.supportFeedback,
opening_statement: config.opening_statement,
supportAnnotation: config.supportAnnotation,
supportCitationHitInfo: config.supportCitationHitInfo,
speech_to_text: config.speech_to_text,
}),
[config.initial_message],
) as ChatConfig
return <ChatConfigContext.Provider value={value}>{children}</ChatConfigContext.Provider>
}
export const useChatConfigContext = () => useContext(ChatConfigContext)
'use client'
import { useMemo, type ReactNode } from 'react'
import { useMemo } from 'react'
import { createContext, useContext } from 'use-context-selector'
import { noop } from 'lodash-es'
import { ChatConfig, ChatItem, Feedback, InputMessageProp, InputMessageType, OnRegenerate, OnSend } from '../types'
import { FileEntity } from '../../file-uploader/types'
import type { Feedback, InputMessageType, OnRegenerate } from '@/app/components/base/chat/types'
import { FileEntity } from '@/app/components/base/file-uploader/types'
export type OnSendMessage = (
message: string,
type?: InputMessageType,
files?: FileEntity[],
parentMessageId?: string,
) => void
export type ChatContextValue = {
config: ChatConfig
chatList: ChatItem[]
isResponding?: boolean
onSend: OnSendMessage
onRegenerate?: OnRegenerate
onStopResponding?: () => void
onRestart: () => void
onFeedback?: (messageId: string, feedback: Feedback) => void
onStopResponding?: () => void
}
const ChatContext = createContext<ChatContextValue>({
config: {} as ChatConfig,
onRestart: noop,
onSend: noop,
chatList: [],
onFeedback: noop,
})
type ChatContextProviderProps = {
children: ReactNode
children: React.ReactNode
} & ChatContextValue
export const ChatContextProvider = ({
children,
config,
isResponding,
chatList,
onSend,
onRegenerate,
onRestart,
onFeedback,
onStopResponding,
}: ChatContextProviderProps) => {
return (
<ChatContext.Provider
value={{
config,
isResponding,
chatList: chatList || [],
onSend,
onRegenerate,
onRestart,
onFeedback,
onStopResponding,
}}>
{children}
</ChatContext.Provider>
const value = useMemo(
() => ({
onSend,
onRegenerate,
onRestart,
onFeedback,
onStopResponding,
}),
[onSend, onRegenerate, onRestart, onFeedback, onStopResponding],
)
return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>
}
export const useChatContext = () => useContext(ChatContext)
export default ChatContext
// app/components/base/chat/chat/chat-runtime-context.tsx
'use client'
import { createContext, useContext } from 'use-context-selector'
import type { ChatItem } from '../../types'
type RuntimeContext = {
chatList: ChatItem[]
isResponding?: boolean
}
const ChatRuntimeContext = createContext<RuntimeContext>({
chatList: [],
isResponding: false,
})
export const useChatRuntimeContext = () => useContext(ChatRuntimeContext)
type Props = {
children: React.ReactNode
} & RuntimeContext
export const ChatRuntimeProvider = ({ children, chatList, isResponding }: Props) => {
const value = { chatList, isResponding }
return <ChatRuntimeContext.Provider value={value}>{children}</ChatRuntimeContext.Provider>
}
......@@ -13,8 +13,8 @@ import {
import type { InstalledApp } from '@/models/app'
import { useToastContext } from '@/app/components/base/toast'
import { useAppFavicon } from '@/hooks/use-app-favicon'
import { noop, uniqBy } from 'lodash-es'
import { OnSendMessage } from '../../chat/context'
import { cloneDeep, noop, uniqBy } from 'lodash-es'
import { OnSendMessage } from '../context/chat-context'
import { getProcessedFiles, getProcessedFilesFromResponse } from '../../../file-uploader/utils'
import { getProcessedInputs } from '../../chat/utils'
import { getLastAnswer, getThreadMessages } from '../../utils'
......@@ -31,6 +31,10 @@ type SendCallback = {
onConversationComplete?: (conversationId: string) => void
isPublicAPI?: boolean
}
type UpdateChatTreeNode = {
(id: string, fields: Partial<ChatItemInTree>): void
(id: string, update: (node: ChatItemInTree) => void): void
}
export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, any> = {}) => {
const { t } = useTranslation()
const { notify } = useToastContext()
......@@ -75,16 +79,16 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
{ revalidateOnFocus: false },
)
const config = useMemo(() => {
const config = appParams || {}
const cfg = cloneDeep(appParams) || {}
return {
...config,
...cfg,
file_upload: {
...(config as any).file_upload,
fileUploadConfig: (config as any).system_parameters,
...(cfg as any).file_upload,
fileUploadConfig: (cfg as any).system_parameters,
},
supportFeedback: true,
opening_statement: (config as any).opening_statement,
initial_message: (config as any).opening_statement,
opening_statement: (cfg as any).opening_statement,
initial_message: (cfg as any).opening_statement,
} as ChatConfig
}, [appParams])
......@@ -99,7 +103,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
setClearChatList(true)
}
},
[setClearChatList],
[],
)
const handleNewConversationCompleted = useCallback(
(newConversationId: string) => {
......@@ -154,11 +158,6 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
})
}, [])
type UpdateChatTreeNode = {
(id: string, fields: Partial<ChatItemInTree>): void
(id: string, update: (node: ChatItemInTree) => void): void
}
const updateChatTreeNode: UpdateChatTreeNode = useCallback(
(id: string, fieldsOrUpdate: Partial<ChatItemInTree> | ((node: ChatItemInTree) => void)) => {
const nextState = produceChatTreeNode(id, node => {
......@@ -551,14 +550,14 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
},
[
t,
chatTree.length,
// chatTree.length,
threadMessages,
config?.suggested_questions_after_answer,
updateCurrentQAOnTree,
updateChatTreeNode,
// config?.suggested_questions_after_answer,
// updateCurrentQAOnTree,
// updateChatTreeNode,
notify,
handleResponding,
formatTime,
// handleResponding,
// formatTime,
// params.token,
// params.appId,
// pathname,
......@@ -587,11 +586,10 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
},
[
handleSend,
isInstalledApp,
appId,
newConversationInputs,
getUrl,
fetchSuggestedQuestions,
// appId,
// newConversationInputs,
// getUrl,
// fetchSuggestedQuestions,
handleNewConversationCompleted,
],
)
......
import { create } from 'zustand'
import { ChatConfig, ChatItemInTree, Feedback } from '@/app/components/base/chat/types'
import { OnSendMessage } from '@/app/components/base/chat/chat/context'
import { OnSendMessage } from '@/app/components/base/chat/chat-with-history/context/chat-context'
type OnRegenerate = (chatItem: ChatItemInTree) => void
type State = {
......
......@@ -3,15 +3,17 @@ import { memo, useMemo } from 'react'
import { RiThumbDownLine, RiThumbUpLine } from '@remixicon/react'
import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
import { useOperationContext } from '../../context/operation'
import { useChatContext } from '../../../context'
import { useChatContext } from '../../../../chat-with-history/context/chat-context'
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
const FeedbackActive: FC = () => {
const { config, onFeedback } = useChatContext()
const { onFeedback } = useChatContext()
const { supportFeedback } = useChatConfigContext()
const { handleFeedback, localFeedback, isOpeningStatement } = useOperationContext()
// 判断是否已点赞
const feedbackActive = useMemo(
() => config?.supportFeedback && localFeedback?.rating && !isOpeningStatement,
[config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
() => supportFeedback && localFeedback?.rating && !isOpeningStatement,
[supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
)
return useMemo(() => {
if (!feedbackActive) return null
......
......@@ -3,15 +3,18 @@ import { memo, useMemo } from 'react'
import { RiThumbDownLine, RiThumbUpLine } from '@remixicon/react'
import ActionButton from '@/app/components/base/action-button'
import { useOperationContext } from '../../context/operation'
import { useChatContext } from '../../../context'
import { useChatContext } from '../../../../chat-with-history/context/chat-context'
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
const Feedback: FC = () => {
const { config, onFeedback } = useChatContext()
const { onFeedback } = useChatContext()
const { supportFeedback } = useChatConfigContext()
const { handleFeedback, localFeedback, isOpeningStatement } = useOperationContext()
// 判断反馈按钮是否启用
const feedbackEnabled = useMemo(
() => config?.supportFeedback && !localFeedback?.rating && !isOpeningStatement,
[config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
() => supportFeedback && !localFeedback?.rating && !isOpeningStatement,
[supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
)
return useMemo(() => {
if (feedbackEnabled) {
......
......@@ -6,7 +6,6 @@ import { useOperationContext } from '../../context/operation'
const Regenerate: FC = memo(() => {
const { noChatInput, isLast, handleRegenerate } = useOperationContext()
if (noChatInput|| !isLast) return null
return (
<ActionButton onClick={() => handleRegenerate()}>
......
......@@ -2,12 +2,12 @@ import type { FC } from 'react'
import { memo } from 'react'
import { RiEditLine } from '@remixicon/react'
import ActionButton from '@/app/components/base/action-button'
import { useChatContext } from '../../../context'
import { useOperationContext } from '../../context/operation'
import { useOperationContext } from '@/app/components/base/chat/chat/answer/context/operation'
import { useChatConfigContext } from '@/app/components/base/chat/chat-with-history/context/chat-config-context'
const Reply: FC = memo(() => {
const { setIsShowReplyModal } = useOperationContext()
const { config } = useChatContext()
if (!config?.supportAnnotation || !config.annotation_reply?.enabled) return null
const { annotation_reply,supportAnnotation } = useChatConfigContext()
if (!supportAnnotation || !annotation_reply?.enabled) return null
return (
<ActionButton onClick={() => setIsShowReplyModal(true)}>
<RiEditLine className="h-4 w-4" />
......
......@@ -9,7 +9,7 @@
import type { FC } from 'react'
import { memo, useMemo } from 'react'
import type { ChatItem } from '../../../types'
import { useChatContext } from '../../context'
import { useChatContext } from '../../../chat-with-history/context/chat-context'
import Button from '@/app/components/base/button/next-button'
// import { AUTO_INPUT } from '@/app/components/base/chat/constants'
import { InputMessageType } from '../../../types'
......
import React, { createContext, useContext, useState, useEffect, useRef } from 'react'
import { useChatContext } from '../../context'
import { useChatContext } from '../../../chat-with-history/context/chat-context'
import { MessageMore } from '../../type'
import { ChatItem } from '../../../types'
import { useChatRuntimeContext } from '../../../chat-with-history/context/chat-runtime-context'
// 定义 AnswerContext 的类型
interface AnswerContextType {
......@@ -70,7 +71,7 @@ export const AnswerProvider: React.FC<AnswerProviderProps> = ({
const [contentWidth, setContentWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const { isResponding } = useChatContext()
const { isResponding } = useChatRuntimeContext()
const responding = isLast && isResponding
const getContainerWidth = () => {
......
......@@ -2,10 +2,11 @@
import type { FC } from 'react'
import React, { createContext, useCallback, useContext, useMemo, useState } from 'react'
import { useChatContext } from '../../context'
import { useChatContext } from '../../../chat-with-history/context/chat-context'
import Toast from '@/app/components/base/toast'
import { useChatBodyContext } from '../../body/context'
import { ChatItem, OnRegenerate } from '../../../types'
import { useChatConfigContext } from '../../../chat-with-history/context/chat-config-context'
interface OperationContextType {
content: string
......@@ -35,10 +36,11 @@ export const OperationProvider: FC<OperationProviderProps> = ({
// noChatInput,
children,
}) => {
const { config, onFeedback,onRegenerate } = useChatContext()
const {onFeedback,onRegenerate } = useChatContext()
const {supportFeedback,text_to_speech,annotation_reply,supportAnnotation} = useChatConfigContext()
const [showLike, setShowLike] = useState(false)
const { id, isOpeningStatement, content: messageContent, isLast,noChatInput,annotation,parentMessageId,containerWidth,contentWidth, showPromptLog,feedback, adminFeedback, agent_thoughts, } = useChatBodyContext()
const [localFeedback, setLocalFeedback] = useState(config?.supportAnnotation ? adminFeedback : feedback)
const [localFeedback, setLocalFeedback] = useState(supportAnnotation ? adminFeedback : feedback)
const [isShowReplyModal, setIsShowReplyModal] = useState(false)
const maxSize = containerWidth - contentWidth - 4
// 计算内容
......@@ -49,7 +51,7 @@ export const OperationProvider: FC<OperationProviderProps> = ({
// 处理反馈
const handleFeedback = async (rating: 'like' | 'dislike' | null) => {
if (!config?.supportFeedback || !onFeedback || showLike) return
if (!supportFeedback || !onFeedback || showLike) return
try {
setShowLike(true)
await onFeedback(id, { rating })
......@@ -72,18 +74,18 @@ export const OperationProvider: FC<OperationProviderProps> = ({
let width = 0
if (!isOpeningStatement) width += 26
if (!isOpeningStatement && showPromptLog) width += 28 + 8
if (!isOpeningStatement && config?.text_to_speech?.enabled) width += 26
if (!isOpeningStatement && config?.supportAnnotation && config?.annotation_reply?.enabled) width += 26
if (config?.supportFeedback && !localFeedback?.rating && !isOpeningStatement) width += 60 + 8
if (config?.supportFeedback && localFeedback?.rating && !isOpeningStatement) width += 28 + 8
if (!isOpeningStatement && text_to_speech?.enabled) width += 26
if (!isOpeningStatement && supportAnnotation && annotation_reply?.enabled) width += 26
if (supportFeedback && !localFeedback?.rating && !isOpeningStatement) width += 60 + 8
if (supportFeedback && localFeedback?.rating && !isOpeningStatement) width += 28 + 8
return width
}, [
isOpeningStatement,
showPromptLog,
config?.text_to_speech?.enabled,
config?.supportAnnotation,
config?.annotation_reply?.enabled,
config?.supportFeedback,
text_to_speech?.enabled,
supportAnnotation,
annotation_reply?.enabled,
supportFeedback,
localFeedback?.rating,
onFeedback,
])
......
import React, { createContext, useContext, useState, useEffect, useRef, use, useCallback, useMemo } from 'react'
import { useChatContext } from '../context'
import { useChatContext } from '../../chat-with-history/context/chat-context'
import { MessageMore } from '../type'
import { ChatItem } from '../../types'
import { useChatRuntimeContext } from '../../chat-with-history/context/chat-runtime-context'
// 定义 AnswerContext 的类型
interface ChatBodyContextType {
......@@ -89,8 +90,7 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
const [contentWidth, setContentWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const { isResponding } = useChatContext()
const { chatList } = useChatContext()
const { isResponding, chatList } = useChatRuntimeContext()
const isLast = isAnswer && item.id === chatList[chatList.length - 1]?.id
const responding = isLast && isResponding
......
import { memo, FC, useEffect, ReactNode } from 'react'
import Answer from '@/app/components/base/chat/chat/answer'
import Question from '@/app/components/base/chat/chat/question/question'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { ChatBodyProvider } from '@/app/components/base/chat/chat/body/context'
import { useChatRuntimeContext } from '../../chat-with-history/context/chat-runtime-context'
type ChatBodyProps = {
noChatInput?: boolean
}
const ChatBody: FC<ChatBodyProps> = ({ noChatInput }) => {
// const chatList = useChatStore(state=>state.chatList)
const { chatList } = useChatContext()
const { chatList } = useChatRuntimeContext()
return (
<>
{chatList.map((item, index) => (
......
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 type { EnableType, OnSend } from '../../types'
import type { Theme } from '../../embedded-chatbot/theme/theme-context'
import type { InputForm } from '../type'
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'
import { useChatStore } from '../../chat-with-history/store'
type ChatInputAreaProps = {
showFeatureBar?: boolean
showFileUpload?: boolean
// featureBarDisabled?: boolean
onFeatureBarClick?: (state: boolean) => void
// visionConfig?: FileUpload
// speechToTextConfig?: EnableType
// inputs?: Record<string, any>
// inputsForm?: InputForm[]
// theme?: Theme | null
disabled?: boolean
}
const ChatInputArea = ({
showFeatureBar,
showFileUpload,
// featureBarDisabled,
onFeatureBarClick,
// visionConfig,
// speechToTextConfig = { enabled: true },
// inputs = {},
// inputsForm = [],
// theme,
// disabled,
}: ChatInputAreaProps) => {
const { t } = useTranslation()
// const { onSend, onRestart, isResponding } = useChatContext()
// const config= useChatStore(state => state.config)
// console.log('config', config)
const { notify } = useToastContext()
const {isResponding, onSend:sendMessage, onRestart:restartChat,config} = useChatContext()
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>
{showFeatureBar && (
<FeatureBar
showFileUpload={showFileUpload}
disabled={featureBarDisabled}
onFeatureBarClick={onFeatureBarClick}
/>
)}
</>
)
}
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 { FileListInChatInput } from '@/app/components/base/file-uploader'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
const FileList: FC = () => {
const { config } = useChatContext()
return <FileListInChatInput fileConfig={config.file_upload} />
const { file_upload } = useChatConfigContext ()
return <FileListInChatInput fileConfig={file_upload} />
}
export default memo(FileList)
import Confirm from '@/app/components/base/confirm'
import { useToastContext } from '@/app/components/base/toast'
import { FC, memo, useCallback, useState } from 'react'
import { useChatContext } from '../../../context'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { useTranslation } from 'react-i18next'
import { CLEAR_BUTTON } from '@/app/components/base/chat/constants'
import { useChatRuntimeContext } from '@/app/components/base/chat/chat-with-history/context/chat-runtime-context'
const ReStart: FC = () => {
const { t } = useTranslation()
const { notify } = useToastContext()
const { isResponding, onRestart: restartChat } = useChatContext()
const { onRestart: restartChat } = useChatContext()
const { isResponding } = useChatRuntimeContext ()
const [showConfirm, setShowConfirm] = useState<boolean>(false)
const handleRestart = useCallback(() => {
if (isResponding) {
......
import { useToastContext } from '@/app/components/base/toast'
import { FC, memo, useCallback, useState } from 'react'
import { useChatContext } from '../../../context'
import { useChatContext } from '../../../../chat-with-history/context/chat-context'
import { useTranslation } from 'react-i18next'
import ActionButton from '@/app/components/base/action-button'
import { RiMicLine } from '@remixicon/react'
import Recorder from 'js-audio-recorder'
import { useMessageContext } from '../../context'
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
const SpeechToText: FC = () => {
const { t } = useTranslation()
const { notify } = useToastContext()
const { config } = useChatContext()
const speechToTextConfig = config.speech_to_text
const { speech_to_text } = useChatConfigContext()
const speechToTextConfig = speech_to_text
const { setShowVoiceInput } = useMessageContext()
const handleShowVoiceInput = useCallback(() => {
;(Recorder as any).getPermission().then(
......
......@@ -3,7 +3,7 @@ import { memo } from 'react'
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'
import { useChatContext } from '../../../chat-with-history/context/chat-context'
import { useTranslation } from 'react-i18next'
import { useChatStore } from '@/app/components/base/chat/chat-with-history/store'
const Practice: FC = () => {
......
......@@ -2,10 +2,13 @@ import { FC, memo, useMemo } 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'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { useChatRuntimeContext } from '../../../chat-with-history/context/chat-runtime-context'
const StopRespondingButton: FC = () => {
const { t } = useTranslation()
const { isResponding, onStopResponding: stopResponding } = useChatContext()
const { onStopResponding: stopResponding } = useChatContext()
const { isResponding } = useChatRuntimeContext()
const mc = useMemo(() => {
if (!isResponding) return null
return (
......
......@@ -5,7 +5,7 @@ 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'
import { useChatContext } from '../../../chat-with-history/context/chat-context'
type TryToAskProps = {
suggestedQuestions?: string[]
isMobile?: boolean
......
import { createContext, useContext, useState, useCallback, useMemo } from 'react'
import type { ReactNode } from 'react'
import { useChatContext } from '../context'
import { useChatContext } from '../../chat-with-history/context/chat-context'
import { useToastContext } from '@/app/components/base/toast'
import { useFileStore } from '@/app/components/base/file-uploader/store'
import { TransferMethod } from '@/types/app'
import { useTranslation } from 'react-i18next'
import { InputMessageType } from '../../types'
import { useChatRuntimeContext } from '../../chat-with-history/context/chat-runtime-context'
// 定义消息上下文类型
interface MessageContextType {
......@@ -35,7 +36,8 @@ export const MessageProvider = ({ children }: { children: ReactNode }) => {
const { t } = useTranslation()
const [query, setQuery] = useState('')
const [showVoiceInput, setShowVoiceInput] = useState(false)
const { isResponding, onSend: sendMessage } = useChatContext()
const { isResponding } = useChatRuntimeContext()
const { onSend: sendMessage } = useChatContext()
const { notify } = useToastContext()
const filesStore = useFileStore()
const [isMultipleLine, setIsMultipleLine] = useState(false)
......@@ -72,26 +74,18 @@ export const MessageProvider = ({ children }: { children: ReactNode }) => {
}, [query, isResponding, sendMessage, filesStore, notify, t])
// 提供上下文值
const value = useMemo(() => ({
query,
setQuery,
handleSend,
showVoiceInput,
setShowVoiceInput,
isMultipleLine,
setIsMultipleLine
}), [
query,
showVoiceInput,
handleSend,
setShowVoiceInput,
isMultipleLine,
setIsMultipleLine
])
return (
<MessageContext.Provider value={value}>
{children}
</MessageContext.Provider>
const value = useMemo(
() => ({
query,
setQuery,
handleSend,
showVoiceInput,
setShowVoiceInput,
isMultipleLine,
setIsMultipleLine,
}),
[query, showVoiceInput, handleSend, setShowVoiceInput, isMultipleLine, setIsMultipleLine],
)
}
\ No newline at end of file
return <MessageContext.Provider value={value}>{children}</MessageContext.Provider>
}
import { useFile } from '@/app/components/base/file-uploader/hooks'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { useChatConfigContext } from '../../../chat-with-history/context/chat-config-context'
const useFileOperation = () => {
const { config } = useChatContext()
const visionConfig = config.file_upload
const { file_upload } = useChatConfigContext ()
const visionConfig = file_upload
const {
handleDragFileEnter,
handleDragFileLeave,
......
......@@ -28,7 +28,7 @@ import type { FileEntity } from '@/app/components/base/file-uploader/types'
import { getProcessedFiles, getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
import { useChatStore } from '../chat-with-history/store'
import { state } from 'mermaid/dist/rendering-util/rendering-elements/shapes/state'
import { OnSendMessage } from './context'
import { OnSendMessage } from '../chat-with-history/context/chat-context'
import { fetchSuggestedQuestions, getUrl } from '@/service/share'
import { set } from 'immer/dist/internal'
type GetAbortController = (abortController: AbortController) => void
......
......@@ -2,7 +2,7 @@
* @Author: liimin 17653212@qq.com
* @Date: 2025-04-16 18:17:38
* @LastEditors: limin
* @LastEditTime: 2025-07-15 15:35:35
* @LastEditTime: 2025-07-15 20:45:57
* @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
*/
......
......@@ -5,31 +5,19 @@ import InitSuggest from './init-suggest'
// 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 '@/app/components/base/chat/chat/context'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { Markdown } from '@/app/components/base/markdown'
import { useChatConfigContext } from '../../chat-with-history/context/chat-config-context'
type InitQuestionsProps = {
// config: ChatConfig
chatAnswerContainerInner?: string
// icon:ReactNode
}
const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) => {
// const config = useChatStore(state => state.config)
const { config } = useChatContext()
const questions = useMemo(() => {
const { suggested_questions, initial_message } = config
const suggestedQuestions = suggested_questions
?.filter(q => !!q && q.trim())
.sort(() => Math.random() - 0.5)
.slice(0, 3)
const initQuestions: ChatItem = {
content: initial_message || '',
suggestedQuestions,
isAnswer: true,
id: 'initial_message',
}
return initQuestions
}, [config.initial_message])
if (!questions.content) return null
const { suggested_questions, initial_message } = useChatConfigContext()
if (!suggested_questions) return null
const suggestedQuestions = suggested_questions
.filter(q => !!q && q.trim())
.sort(() => Math.random() - 0.5)
.slice(0, 3)
return (
<div className="mb-2 flex last:mb-0">
<div className="relative h-10 w-10 shrink-0">{<AnswerIcon />}</div>
......@@ -39,8 +27,8 @@ const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) =>
className={cn(
'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary',
)}>
<Markdown content={questions.content} />
<InitSuggest suggestedQuestions={questions.suggestedQuestions} />
{initial_message && <Markdown content={initial_message} />}
<InitSuggest suggestedQuestions={suggestedQuestions} />
</div>
</div>
</div>
......
......@@ -2,22 +2,20 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17
* @LastEditors: limin
* @LastEditTime: 2025-07-15 09:22:21
* @LastEditTime: 2025-07-16 00:00:32
* @FilePath: \ai-assistant\app\components\base\chat\chat\question\init-suggest.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import type { FC } from 'react'
import { memo, useMemo } from 'react'
import type { ChatItem } from '@/app/components/base/chat/types'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { memo } from 'react'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import Button from '@/app/components/base/button/next-button'
import { InputMessageType } from '@/app/components/base/chat/types'
type InitSuggestProps = {
suggestedQuestions?: string[]
}
const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions }) => {
const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions = [] }) => {
const { onSend: sendMessage } = useChatContext()
if (!suggestedQuestions?.length) return null
return (
<div className="w-[fit-content]">
{suggestedQuestions.map((question, index) => (
......@@ -30,8 +28,4 @@ const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions }) => {
)
}
const MemoizedSuggestedQuestions = memo(InitSuggest, (prev, next) => {
return prev.suggestedQuestions?.length === next.suggestedQuestions?.length
})
export default MemoizedSuggestedQuestions
export default memo(InitSuggest)
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import Button from '@/app/components/base/button'
import cn from '@/utils/classnames'
......
......@@ -6,7 +6,7 @@ import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'
import TimePicker from '@/app/components/base/date-and-time-picker/time-picker'
import Checkbox from '@/app/components/base/checkbox'
import Select from '@/app/components/base/select'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
enum DATA_FORMAT {
TEXT = 'text',
......
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import Button from '@/app/components/base/button'
import cn from '@/utils/classnames'
import { isValidUrl } from './utils'
......
......@@ -6,7 +6,7 @@ import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'
import TimePicker from '@/app/components/base/date-and-time-picker/time-picker'
import Checkbox from '@/app/components/base/checkbox'
import Select from '@/app/components/base/select'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { InputMessageType } from '@/app/components/base/chat/types'
enum DATA_FORMAT {
......
......@@ -4,7 +4,7 @@
* Handles special rendering for "abbr:" type links for interactive chat actions.
*/
import React, { useState } from 'react'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { isValidUrl } from './utils'
import ImagePreview from '@/app/components/base/image-uploader/image-preview'
import { InputMessageType } from '@/app/components/base/chat/types'
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!