buster/web/src/layouts/ChatLayout/ChatContext/ChatContext.tsx

88 lines
2.2 KiB
TypeScript
Raw Normal View History

import React, { PropsWithChildren } from 'react';
import {
ContextSelector,
createContext,
useContextSelector
} from '@fluentui/react-context-selector';
import type { SelectedFile } from '../interfaces';
2025-02-09 13:41:08 +08:00
import { useAutoChangeLayout } from './useAutoChangeLayout';
2025-03-06 01:13:24 +08:00
import { useGetChat } from '@/api/buster_rest/chats';
2025-03-06 08:05:34 +08:00
import { useMessageIndividual } from '@/context/Chats';
2025-02-07 10:08:40 +08:00
export const useChatIndividualContext = ({
chatId,
selectedFile,
2025-02-09 13:41:08 +08:00
onSetSelectedFile
}: {
chatId?: string;
selectedFile?: SelectedFile;
2025-02-09 13:41:08 +08:00
onSetSelectedFile: (file: SelectedFile) => void;
}) => {
const selectedFileId = selectedFile?.id;
const selectedFileType = selectedFile?.type;
//CHAT
2025-03-06 02:17:28 +08:00
const { data: chat } = useGetChat({ id: chatId || '' });
2025-02-05 13:04:26 +08:00
const hasChat = !!chatId && !!chat;
const chatTitle = chat?.title;
2025-03-06 01:13:24 +08:00
const chatMessageIds = chat?.message_ids ?? [];
//FILE
const hasFile = !!selectedFileId;
2025-02-05 13:04:26 +08:00
//MESSAGES
2025-02-09 13:41:08 +08:00
const currentMessageId = chatMessageIds[chatMessageIds.length - 1];
2025-03-06 08:05:34 +08:00
const isStreamingMessage = useMessageIndividual(currentMessageId, (x) => !x?.isCompletedStream);
2025-02-09 13:41:08 +08:00
2025-02-12 07:46:22 +08:00
useAutoChangeLayout({
lastMessageId: currentMessageId,
onSetSelectedFile
});
2025-02-05 13:04:26 +08:00
2025-03-06 02:17:28 +08:00
return React.useMemo(
() => ({
hasChat,
hasFile,
selectedFileId,
currentMessageId,
chatTitle,
selectedFileType,
chatMessageIds,
chatId,
2025-03-06 08:05:34 +08:00
isStreamingMessage
2025-03-06 02:17:28 +08:00
}),
[
hasChat,
hasFile,
2025-03-06 08:05:34 +08:00
isStreamingMessage,
2025-03-06 02:17:28 +08:00
selectedFileId,
currentMessageId,
chatTitle,
selectedFileType,
chatMessageIds,
2025-03-06 08:05:34 +08:00
chatId
2025-03-06 02:17:28 +08:00
]
);
};
2025-03-06 08:05:34 +08:00
const IndividualChatContext = createContext<ReturnType<typeof useChatIndividualContext>>(
2025-02-07 10:08:40 +08:00
{} as ReturnType<typeof useChatIndividualContext>
);
export const ChatContextProvider = React.memo(
2025-02-07 10:08:40 +08:00
({
value,
children
}: PropsWithChildren<{ value: ReturnType<typeof useChatIndividualContext> }>) => {
return (
<IndividualChatContext.Provider value={value}>{children}</IndividualChatContext.Provider>
);
}
);
ChatContextProvider.displayName = 'ChatContextProvider';
2025-02-07 10:08:40 +08:00
export const useChatIndividualContextSelector = <T,>(
selector: ContextSelector<ReturnType<typeof useChatIndividualContext>, T>
) => useContextSelector(IndividualChatContext, selector);