Commit 5b99a30e by liimin

refactor(chat): 重构聊天页面

- 优化了 ChatWrapper 组件的结构和逻辑
- 移除了未使用的 InputsForm 组件
- 简化了 ChatWithHistoryContext 的定义
- 删除了未使用的 HeaderInMobile 组件
- 优化了 page.tsx 中的导出
1 parent b75fd32d
......@@ -8,4 +8,4 @@ const Chat = () => {
)
}
export default React.memo(Chat)
export default React.memo(Chat, () => true)
......@@ -5,7 +5,6 @@ import { createContext, useContext } from "use-context-selector";
import type { Callback, ChatConfig, ChatItemInTree, Feedback } from "../types";
import type { ThemeBuilder } from "../embedded-chatbot/theme/theme-context";
import type {
AppConversationData,
AppData,
AppMeta,
ConversationItem,
......@@ -22,43 +21,22 @@ export type ChatWithHistoryContextValue = {
currentConversationId: string;
currentConversationItem?: ConversationItem;
appPrevChatTree: ChatItemInTree[];
// pinnedConversationList: AppConversationData["data"];
// conversationList: AppConversationData["data"];
newConversationInputs: Record<string, any>;
newConversationInputsRef: RefObject<Record<string, any>>;
// handleNewConversationInputsChange: (v: Record<string, any>) => void;
// inputsForms: any[];
handleNewConversation: (v?: Record<string, any>,skipClear?:boolean) => void;
// handleStartChat: (callback?: any) => void;
handleChangeConversation: (conversationId: string) => void;
// handlePinConversation: (conversationId: string) => void;
// handleUnpinConversation: (conversationId: string) => void;
// handleDeleteConversation: (
// conversationId: string,
// callback: Callback
// ) => void;
// conversationRenaming: boolean;
// handleRenameConversation: (
// conversationId: string,
// newName: string,
// callback: Callback
// ) => void;
handleNewConversationCompleted: (newConversationId: string) => void;
chatShouldReloadKey: string;
isMobile: boolean;
handleNewConversationCompleted?: (newConversationId: string) => void;
chatShouldReloadKey?: string;
isMobile?: boolean;
isInstalledApp: boolean;
appId?: string;
handleFeedback: (messageId: string, feedback: Feedback) => void;
currentChatInstanceRef: RefObject<{ handleStop: () => void }>;
themeBuilder?: ThemeBuilder;
// sidebarCollapseState?: boolean;
// handleSidebarCollapse: (state: boolean) => void;
clearChatList?: boolean;
setClearChatList: (state: boolean) => void;
setClearChatList?: (state: boolean) => void;
isResponding?: boolean;
setIsResponding: (state: boolean) => void;
currentConversationInputs: Record<string, any> | null;
// setCurrentConversationInputs: (v: Record<string, any>) => void;
currentConversationInputs?: Record<string, any> | null;
isShowPracticeButton: boolean;
};
......@@ -66,34 +44,20 @@ export const ChatWithHistoryContext =
createContext<ChatWithHistoryContextValue>({
currentConversationId: "",
appPrevChatTree: [],
// pinnedConversationList: [],
// conversationList: [],
newConversationInputs: {},
newConversationInputsRef: { current: {} },
// handleNewConversationInputsChange: noop,
// inputsForms: [],
handleNewConversation: noop,
// handleStartChat: noop,
handleChangeConversation: noop,
// handlePinConversation: noop,
// handleUnpinConversation: noop,
// handleDeleteConversation: noop,
// conversationRenaming: false,
// handleRenameConversation: noop,
handleNewConversationCompleted: noop,
chatShouldReloadKey: "",
isMobile: false,
isInstalledApp: false,
handleFeedback: noop,
currentChatInstanceRef: { current: { handleStop: noop } },
// sidebarCollapseState: false,
// handleSidebarCollapse: noop,
clearChatList: false,
setClearChatList: noop,
isResponding: false,
setIsResponding: noop,
currentConversationInputs: {},
// setCurrentConversationInputs: noop,
isShowPracticeButton: false,
});
export const useChatWithHistoryContext = () =>
......
import type { FC } from 'react'
import { useEffect, useState, useCallback, useRef } from 'react'
import { useEffect, useState, useCallback, useRef, memo } from 'react'
import { useAsyncEffect } from 'ahooks'
import { useThemeContext } from '../embedded-chatbot/theme/theme-context'
import { ChatWithHistoryContext, useChatWithHistoryContext } from './context'
......@@ -50,11 +50,14 @@ const getQueryParams = function (): urlProps {
}
}
const inputs = getQueryParams()
const { avatar, domain, presuppositionProblem, practice_status, ...newInputs } = inputs
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 avatarUrl: string = avatar ?? AVATAR_USER_URL
const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {
const { appInfoError, appInfoLoading, appChatListDataLoading, chatShouldReloadKey, isMobile, handleNewConversation } = useChatWithHistoryContext()
const { appInfoError, appInfoLoading, appChatListDataLoading, chatShouldReloadKey, isMobile, handleNewConversation } =
useChatWithHistoryContext()
if (appInfoLoading) {
return <Loading type="app" />
......@@ -72,6 +75,7 @@ const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {
<ChatWrapper
presuppositionQuestion={presuppositionProblem}
// doClear={doClear}
// hasAutoSended={hasAutoSended}
key={chatShouldReloadKey}
avatar={avatarUrl}
aiAvatar={AVATAR_AI_URL}
......@@ -84,27 +88,48 @@ const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {
}
export type ChatWithHistoryWrapProps = {
installedAppInfo?: any//InstalledApp
installedAppInfo?: any //InstalledApp
className?: string
}
const ChatWithHistoryWrap: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, className }) => {
const media = useBreakpoints()
const isMobile = media === MediaType.mobile
const themeBuilder = useThemeContext()
const { appInfoError, appInfoLoading, appData, appParams, appMeta, appChatListDataLoading, currentConversationId, appPrevChatTree, newConversationInputs, newConversationInputsRef, handleNewConversation, handleChangeConversation, handleNewConversationCompleted, chatShouldReloadKey, isInstalledApp, appId, handleFeedback, currentChatInstanceRef, clearChatList, setClearChatList, isResponding, setIsResponding} =
useChatWithHistory(installedAppInfo,newInputs)
// const media = useBreakpoints()
// const isMobile = media === MediaType.mobile
// const themeBuilder = useThemeContext()
const {
// appInfoError,
// appInfoLoading,
// appData,
appParams,
// appMeta,
// appChatListDataLoading,
currentConversationId,
appPrevChatTree,
newConversationInputs,
newConversationInputsRef,
handleNewConversation,
// handleChangeConversation,
handleNewConversationCompleted,
// chatShouldReloadKey,
isInstalledApp,
// appId,
handleFeedback,
currentChatInstanceRef,
// clearChatList,
// setClearChatList,
isResponding,
setIsResponding,
} = useChatWithHistory(installedAppInfo, newInputs)
return (
<ChatWithHistoryContext.Provider
value={{
appInfoError,
appInfoLoading,
appData,
// appInfoError,
// appInfoLoading,
// appData,
appParams,
appMeta,
appChatListDataLoading,
// appMeta,
// appChatListDataLoading,
currentConversationId,
currentConversationItem:undefined,
currentConversationItem: undefined,
appPrevChatTree,
// pinnedConversationList,
// conversationList,
......@@ -114,29 +139,29 @@ const ChatWithHistoryWrap: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, c
// inputsForms,
handleNewConversation,
// handleStartChat,
handleChangeConversation,
// handleChangeConversation,
// handlePinConversation,
// handleUnpinConversation,
// handleDeleteConversation,
// conversationRenaming,
// handleRenameConversation,
handleNewConversationCompleted,
chatShouldReloadKey,
isMobile,
// chatShouldReloadKey,
// isMobile,
isInstalledApp,
appId,
// appId,
handleFeedback,
currentChatInstanceRef,
themeBuilder,
// themeBuilder,
// sidebarCollapseState,
// handleSidebarCollapse,
clearChatList,
setClearChatList,
// clearChatList,
// setClearChatList,
isResponding,
setIsResponding,
currentConversationInputs:null,
currentConversationInputs: null,
// setCurrentConversationInputs,
isShowPracticeButton
isShowPracticeButton,
}}>
<ChatWithHistory className={className} />
</ChatWithHistoryContext.Provider>
......@@ -147,7 +172,6 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta
const [initialized, setInitialized] = useState(false)
const [appUnavailable, setAppUnavailable] = useState<boolean>(false)
const [isUnknownReason, setIsUnknownReason] = useState<boolean>(false)
useAsyncEffect(async () => {
if (!initialized) {
if (!installedAppInfo) {
......@@ -164,13 +188,10 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta
}
setInitialized(true)
}
}, [])
}, [initialized, installedAppInfo]) // 添加正确依赖
if (!initialized) return null
if (appUnavailable) return <AppUnavailable isUnknownReason={isUnknownReason} />
return <ChatWithHistoryWrap installedAppInfo={installedAppInfo} className={className} />
else if (appUnavailable) return <AppUnavailable isUnknownReason={isUnknownReason} />
else return <ChatWithHistoryWrap installedAppInfo={installedAppInfo} className={className} />
}
export default ChatWithHistoryWrapWithCheckToken
......@@ -7,31 +7,16 @@ import cn from '@/utils/classnames'
type BasicContentProps = {
item: ChatItem
}
const BasicContent: FC<BasicContentProps> = ({
item,
}) => {
const {
annotation,
content,
} = item
if (annotation?.logAnnotation)
return <Markdown content={annotation?.logAnnotation.content || ''} />
const BasicContent: FC<BasicContentProps> = ({ item }) => {
const { id, annotation, content } = item
// console.log(content)
if (annotation?.logAnnotation) return <Markdown content={annotation?.logAnnotation.content || ''} />
return (
<Markdown
className={cn(
item.isError && '!text-[#F04438]',
)}
content={content}
/>
)
return <Markdown className={cn(item.isError && '!text-[#F04438]')} content={content} id={id} />
}
const MemoizedBasicContent = memo(BasicContent, (prev, next) => {
return (
prev.item.content === next.item.content &&
prev.item.annotation?.logAnnotation?.content === next.item.annotation?.logAnnotation?.content
)
return prev.item.content === next.item.content
})
export default MemoizedBasicContent
export default memo(MemoizedBasicContent)
......@@ -28,15 +28,29 @@ type AnswerProps = {
isLast?: boolean
chatAnswerContainerInner?: string
hideProcessDetail?: boolean
appData?: AppData
// appData?: AppData
noChatInput?: boolean
switchSibling?: (siblingMessageId: string) => void
}
const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, responding, showPromptLog, isLast, chatAnswerContainerInner, hideProcessDetail, appData, noChatInput, switchSibling }) => {
const Answer: FC<AnswerProps> = ({
item,
question,
index,
config,
answerIcon,
responding,
showPromptLog,
isLast,
chatAnswerContainerInner,
hideProcessDetail,
// appData,
noChatInput,
switchSibling,
}) => {
const { t } = useTranslation()
const { content, citation, agent_thoughts, more, annotation, workflowProcess, allFiles, message_files } = item
const hasAgentThoughts = !!agent_thoughts?.length
// console.log(content)
const [containerWidth, setContainerWidth] = useState(0)
const [contentWidth, setContentWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
......@@ -68,7 +82,6 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re
resizeObserver.disconnect()
}
}, [])
return (
<div className="mb-2 flex last:mb-0">
<div className="relative h-10 w-10 shrink-0">
......@@ -81,8 +94,25 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re
</div>
<div className="chat-answer-container group ml-4 w-0 grow pb-2" ref={containerRef}>
<div className={cn('group relative pr-14', chatAnswerContainerInner)}>
<div ref={contentRef} className={cn('body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary', workflowProcess && 'w-full')}>
{!responding && <Operation hasWorkflowProcess={!!workflowProcess} maxSize={containerWidth - contentWidth - 4} contentWidth={contentWidth} item={item} isLast={isLast} question={question} index={index} showPromptLog={showPromptLog} noChatInput={noChatInput} />}
<div
ref={contentRef}
className={cn(
'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary',
workflowProcess && 'w-full',
)}>
{!responding && (
<Operation
hasWorkflowProcess={!!workflowProcess}
maxSize={containerWidth - contentWidth - 4}
contentWidth={contentWidth}
item={item}
isLast={isLast}
question={question}
index={index}
showPromptLog={showPromptLog}
noChatInput={noChatInput}
/>
)}
{/** Render the normal steps */}
{/* {workflowProcess && !hideProcessDetail && (
<WorkflowProcessItem
......@@ -107,8 +137,12 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re
)}
{content && !hasAgentThoughts && <BasicContent item={item} />}
{hasAgentThoughts && <AgentContent item={item} responding={responding} content={content} />}
{!!allFiles?.length && <FileList className="my-1" files={allFiles} showDeleteAction={false} showDownloadAction canPreview />}
{!!message_files?.length && <FileList className="my-1" files={message_files} showDeleteAction={false} showDownloadAction canPreview />}
{!!allFiles?.length && (
<FileList className="my-1" files={allFiles} showDeleteAction={false} showDownloadAction canPreview />
)}
{!!message_files?.length && (
<FileList className="my-1" files={message_files} showDeleteAction={false} showDownloadAction canPreview />
)}
{/* {annotation?.id && annotation.authorName && (
<EditTitle
className="mt-1"
......@@ -118,7 +152,9 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re
/>
)} */}
{/* <SuggestedQuestions item={item} /> */}
{!!citation?.length && !responding && <Citation data={citation} showHitInfo={config?.supportCitationHitInfo} />}
{!!citation?.length && !responding && (
<Citation data={citation} showHitInfo={config?.supportCitationHitInfo} />
)}
{/* {item.siblingCount && item.siblingCount > 1 && item.siblingIndex !== undefined && (
<div className="flex items-center justify-center pt-3.5 text-sm">
<button className={`${item.prevSibling ? 'opacity-100' : 'opacity-30'}`} disabled={!item.prevSibling} onClick={() => item.prevSibling && switchSibling?.(item.prevSibling)}>
......@@ -140,11 +176,14 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re
)
}
const AnswerMemo = memo(Answer,(prevProps: AnswerProps, nextProps: AnswerProps) => {
return (
prevProps.item.content === nextProps.item.content &&
prevProps.isLast === nextProps.isLast &&
prevProps.responding === nextProps.responding
)
})
export default AnswerMemo
// const AnswerMemo = memo(Answer, (prevProps: AnswerProps, nextProps: AnswerProps) => {
// return true
// // return (
// // !nextProps.item.content ||
// // (prevProps.item.content === nextProps.item.content &&
// // prevProps.isLast === nextProps.isLast &&
// // prevProps.responding === nextProps.responding)
// // )
// })
export default memo(Answer)
......@@ -29,9 +29,9 @@ type ChatInputAreaProps = {
speechToTextConfig?: EnableType
onSend?: OnSend
onRestart: () => void
inputs?: Record<string, any>
inputsForm?: InputForm[]
theme?: Theme | null
// inputs?: Record<string, any>
// inputsForm?: InputForm[]
// theme?: Theme | null
isResponding?: boolean
disabled?: boolean
}
......@@ -43,11 +43,11 @@ const ChatInputArea = ({
visionConfig,
speechToTextConfig = { enabled: true },
onRestart,
inputs = {},
inputsForm = [],
theme,
// inputs = {},
// inputsForm = [],
// theme,
isResponding,
disabled,
// disabled,
}: ChatInputAreaProps) => {
const { t } = useTranslation()
const { notify } = useToastContext()
......@@ -183,7 +183,7 @@ const ChatInputArea = ({
onShowVoiceInput={handleShowVoiceInput}
onRestart={handleRestart}
onSend={handleSend}
theme={theme}
// theme={theme}
/>
)
// const clear = <Operation ref={holdSpaceRef} onSend={handleClear} imgUrl={CLEAR_BUTTON} />
......
......@@ -25,14 +25,14 @@ type FooterProps = {
onRestart: () => void
inputs?: Record<string, any>
inputsForm?: InputForm[]
themeBuilder?: ThemeBuilder
// themeBuilder?: ThemeBuilder
config?: ChatConfig
chatFooterRef: React.RefObject<HTMLDivElement>
chatFooterInnerRef: React.RefObject<HTMLDivElement>
isResponding?: boolean
}
const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName, onSend, noStopResponding, onStopResponding, noChatInput, isMobile, inputDisabled, showFeatureBar, showFileUpload, onFeatureBarClick, onRestart, inputs, inputsForm, 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, config, suggestedQuestions, isShowPracticeButton, chatFooterRef, chatFooterInnerRef, isResponding }) => {
const { t } = useTranslation()
const hasTryToAsk = config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length && onSend
return (
......@@ -43,7 +43,7 @@ const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName
{isResponding && !noStopResponding && <StopResponding onStopResponding={onStopResponding} />}
</div>
{hasTryToAsk && <TryToAsk suggestedQuestions={suggestedQuestions} onSend={onSend} isMobile={isMobile} />}
{!noChatInput && <ChatInputArea disabled={inputDisabled} showFeatureBar={showFeatureBar} showFileUpload={showFileUpload} featureBarDisabled={isResponding} onFeatureBarClick={onFeatureBarClick} visionConfig={config?.file_upload} speechToTextConfig={config?.speech_to_text} onSend={onSend} onRestart={onRestart} 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} isResponding={isResponding} />}
</div>
</div>
)
......
......@@ -44,7 +44,8 @@ export const useChat = (
prevChatTree?: ChatItemInTree[],
stopChat?: (taskId: string) => void,
clearChatList?: boolean,
clearChatListCallback?: (state: boolean) => void
clearChatListCallback?: (state: boolean) => void,
currentConversationId?: string,
) => {
const { t } = useTranslation();
const { formatTime } = useTimestamp();
......@@ -306,7 +307,7 @@ export const useChat = (
const { query, files, inputs, ...restData } = data;
const bodyParams = {
response_mode: "streaming",
conversation_id: conversationId.current,
conversation_id:currentConversationId, //conversationId.current,
files: getProcessedFiles(files || []),
query,
inputs: getProcessedInputs(
......@@ -315,39 +316,39 @@ export const useChat = (
),
...restData,
};
if (bodyParams?.files?.length) {
bodyParams.files = bodyParams.files.map((item) => {
if (item.transfer_method === TransferMethod.local_file) {
return {
...item,
url: "",
};
}
return item;
});
}
// if (bodyParams?.files?.length) {
// bodyParams.files = bodyParams.files.map((item) => {
// if (item.transfer_method === TransferMethod.local_file) {
// return {
// ...item,
// url: "",
// };
// }
// return item;
// });
// }
let isAgentMode = false;
let hasSetResponseId = false;
let ttsUrl = "";
let ttsIsPublic = false;
if (params.token) {
ttsUrl = "/text-to-audio";
ttsIsPublic = true;
} else if (params.appId) {
if (pathname.search("explore/installed") > -1)
ttsUrl = `/installed-apps/${params.appId}/text-to-audio`;
else ttsUrl = `/apps/${params.appId}/text-to-audio`;
}
const player = AudioPlayerManager.getInstance().getAudioPlayer(
ttsUrl,
ttsIsPublic,
uuidV4(),
"none",
"none",
(_: any): any => {}
);
// let ttsUrl = "";
// let ttsIsPublic = false;
// if (params.token) {
// ttsUrl = "/text-to-audio";
// ttsIsPublic = true;
// } else if (params.appId) {
// if (pathname.search("explore/installed") > -1)
// ttsUrl = `/installed-apps/${params.appId}/text-to-audio`;
// else ttsUrl = `/apps/${params.appId}/text-to-audio`;
// }
// const player = AudioPlayerManager.getInstance().getAudioPlayer(
// ttsUrl,
// ttsIsPublic,
// uuidV4(),
// "none",
// "none",
// (_: any): any => {}
// );
ssePost(
url,
{
......
......@@ -2,7 +2,7 @@
* @Author: liimin 17653212@qq.com
* @Date: 2025-04-16 18:17:38
* @LastEditors: limin
* @LastEditTime: 2025-06-29 02:06:50
* @LastEditTime: 2025-07-02 20:51:53
* @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
*/
......@@ -27,7 +27,7 @@ import chatStyles from './chat.module.css'
import { FileEntity } from '../../file-uploader/types'
export type ChatProps = {
appData?: AppData
// appData?: AppData
chatList: ChatItem[]
config?: ChatConfig
isResponding?: boolean
......@@ -47,7 +47,7 @@ export type ChatProps = {
// showPromptLog?: boolean
questionIcon?: ReactNode
answerIcon?: ReactNode
allToolIcons?: Record<string, string | Emoji>
// allToolIcons?: Record<string, string | Emoji>
// onAnnotationEdited?: (question: string, answer: string, index: number) => void
// onAnnotationAdded?: (
// annotationId: string,
......@@ -57,7 +57,7 @@ export type ChatProps = {
// index: number,
// ) => void
// onAnnotationRemoved?: (index: number) => void
chatNode?: ReactNode
// chatNode?: ReactNode
onFeedback?: (messageId: string, feedback: Feedback) => void
chatAnswerContainerInner?: string
// hideProcessDetail?: boolean
......@@ -75,7 +75,7 @@ export type ChatProps = {
}
const Chat: FC<ChatProps> = ({
appData,
// appData,
config,
onSend,
onRestart,
......@@ -88,9 +88,9 @@ const Chat: FC<ChatProps> = ({
onStopResponding,
noChatInput,
chatContainerClassName,
chatContainerInnerClassName,
chatFooterClassName,
chatFooterInnerClassName,
// chatContainerInnerClassName,
// chatFooterClassName,
// chatFooterInnerClassName,
suggestedQuestions,
// showPromptLog,
questionIcon,
......@@ -98,7 +98,7 @@ const Chat: FC<ChatProps> = ({
// onAnnotationAdded,
// onAnnotationEdited,
// onAnnotationRemoved,
chatNode,
// chatNode,
onFeedback,
chatAnswerContainerInner,
// hideProcessDetail,
......@@ -189,7 +189,9 @@ const Chat: FC<ChatProps> = ({
// })
// }
// })
const chatContainerInnerClassName=`mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}`
const chatFooterClassName="pb-4"
const chatFooterInnerClassName=`mx-auto w-full max-w-[800px] ${isMobile ? 'px-2' : 'px-4'}`
// 使用 MutationObserver 监听 DOM 变化
useEffect(() => {
const container = chatContainerRef.current
......@@ -279,16 +281,11 @@ const Chat: FC<ChatProps> = ({
config={config}
chatList={chatList}
isResponding={isResponding}
// showPromptLog={showPromptLog}
questionIcon={questionIcon}
answerIcon={answerIcon}
onSend={handleSend}
onRegenerate={onRegenerate}
onRestart={onRestart}
// onStopResponding={onStopResponding}
// onAnnotationAdded={onAnnotationAdded}
// onAnnotationEdited={onAnnotationEdited}
// onAnnotationRemoved={onAnnotationRemoved}
onFeedback={onFeedback}>
<div className="relative h-full">
<div
......@@ -298,7 +295,7 @@ const Chat: FC<ChatProps> = ({
chatContainerClassName,
chatStyles.chatContainer,
)}>
{chatNode}
{/* {chatNode} */}
<div ref={chatContainerInnerRef} className={cn('w-full', !noSpacing && 'px-8', chatContainerInnerClassName)}>
{config?.initial_message && (
<InitQuestions
......@@ -312,7 +309,6 @@ const Chat: FC<ChatProps> = ({
const isLast = item.id === chatList[chatList.length - 1]?.id
return (
<Answer
appData={appData}
key={item.id}
item={item}
question={chatList[index - 1]?.content}
......@@ -321,9 +317,7 @@ const Chat: FC<ChatProps> = ({
answerIcon={answerIcon}
isLast={isLast}
responding={isLast && isResponding}
// showPromptLog={showPromptLog}
chatAnswerContainerInner={chatAnswerContainerInner}
// hideProcessDetail={hideProcessDetail}
noChatInput={noChatInput}
switchSibling={switchSibling}
/>
......@@ -341,7 +335,7 @@ const Chat: FC<ChatProps> = ({
chatFooterInnerClassName={chatFooterInnerClassName}
onSend={handleSend}
inputs={inputs}
inputsForm={inputsForm}
// inputsForm={inputsForm}
onRestart={onRestart}
noStopResponding={noStopResponding}
onStopResponding={onStopResponding}
......
......@@ -2,29 +2,34 @@ import { useChatContext } from '@/app/components/base/chat/chat/context'
import Button from '@/app/components/base/button'
import cn from '@/utils/classnames'
import { isValidUrl } from './utils'
const MarkdownButton = ({ node }: any) => {
import { InputMessageType } from '@/app/components/base/chat/types'
const MarkdownButton = ({ node, messageId }:any) => {
const { onSend } = useChatContext()
const variant = node.properties.dataVariant
const message = node.properties.dataMessage
const link = node.properties.dataLink
const size = node.properties.dataSize
return <Button
variant={variant}
size={size}
className={cn('!h-auto min-h-8 select-none whitespace-normal !px-3')}
onClick={() => {
if (isValidUrl(link)) {
window.open(link, '_blank')
return
}
if(!message)
return
onSend?.(message)
}}
>
<span className='text-[13px]'>{node.children[0]?.value || ''}</span>
</Button>
return (
<Button
variant={variant}
size={size}
className={cn('!h-auto min-h-8 select-none whitespace-normal !px-3')}
onClick={() => {
if (isValidUrl(link || '')) {
window.open(link, '_blank')
return
}
if (message) {
onSend?.({ message: message, type: InputMessageType.SYSTEM })
if (messageId) {
document.getElementById(messageId)?.classList.add('pointer-events-none', 'opacity-50')
}
return
}
}}>
<span className="text-[13px]">{node.children[0]?.value || ''}</span>
</Button>
)
}
MarkdownButton.displayName = 'MarkdownButton'
......
/**
* @fileoverview Paragraph component for rendering <p> tags in Markdown.
* Extracted from the main markdown renderer for modularity.
* Handles special rendering for paragraphs that directly contain an image.
*/
import React from 'react'
const Div = (paragraph: any) => {
console.log(paragraph)
return <div>{paragraph.children}</div>
}
export default Div
......@@ -7,21 +7,23 @@ import React from 'react'
import ImageGallery from '@/app/components/base/image-gallery'
const Paragraph = (paragraph: any) => {
const { node }: any = paragraph
const { node,messageId,children }: any = paragraph
const children_node = node.children
if (children_node && children_node[0] && 'tagName' in children_node[0] && children_node[0].tagName === 'img') {
return (
<div className="markdown-img-wrapper">
<ImageGallery srcs={[children_node[0].properties.src]} />
{
Array.isArray(paragraph.children) && paragraph.children.length > 1 && (
<div className="mt-2">{paragraph.children.slice(1)}</div>
Array.isArray(children) && children.length > 1 && (
<div className="mt-2">{children.slice(1)}</div>
)
}
</div>
)
}
return <p>{paragraph.children}</p>
if(node.properties.dataDisable==='disable' && messageId){
return <div id={messageId}>{children}</div>
}
return <p>{children}</p>
}
export default Paragraph
.chatContainer {
scroll-behavior: smooth;
overflow-y: auto;
height: 100%;
}
.streaming_text {
transition: opacity 3s ease, transform 3s ease;
}
......@@ -19,7 +19,13 @@ import { useMemo } from 'react'
* are noted in their respective files if applicable.
*/
export function Markdown(props: { content: string; className?: string; customDisallowedElements?: string[] }) {
type MarkdownProps = {
content: string
className?: string
customDisallowedElements?: string[]
id?: string
}
export function Markdown(props: MarkdownProps) {
const markdown = useMemo(() => {
const latexContent = flow([preprocessThinkTag, preprocessLaTeX])(props.content)
return (
......@@ -47,15 +53,24 @@ export function Markdown(props: { content: string; className?: string; customDis
},
]}
urlTransform={customUrlTransform}
disallowedElements={['iframe', 'head', 'html', 'meta', 'link', 'style', 'body', ...(props.customDisallowedElements || [])]}
disallowedElements={[
'iframe',
'head',
'html',
'meta',
'link',
'style',
'body',
...(props.customDisallowedElements || []),
]}
components={{
code: Code,
img: Img,
video: Video,
audio: Audio,
a: Link,
p: Paragraph,
button: MarkdownButton,
p: properties => <Paragraph {...properties} messageId={props.id} />,
button: properties => <MarkdownButton {...properties} messageId={props.id} />,
form: MarkdownForm,
script: Script as any,
details: Think,
......@@ -66,5 +81,5 @@ export function Markdown(props: { content: string; className?: string; customDis
</div>
)
}, [props.content])
return (markdown)
return markdown
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!