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

80 lines
2.1 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-02-18 07:25:31 +08:00
import { useMessageIndividual } from '@/context/Chats';
import { useSubscribeIndividualChat } from './useSubscribeIndividualChat';
2025-02-07 10:08:40 +08:00
export const useChatIndividualContext = ({
chatId,
2025-02-09 13:41:08 +08:00
defaultSelectedFile,
onSetSelectedFile
}: {
chatId?: string;
defaultSelectedFile?: SelectedFile;
2025-02-09 13:41:08 +08:00
onSetSelectedFile: (file: SelectedFile) => void;
}) => {
const selectedFileId = defaultSelectedFile?.id;
const selectedFileType = defaultSelectedFile?.type;
//CHAT
2025-02-09 13:41:08 +08:00
const chat = useSubscribeIndividualChat({
chatId,
2025-02-07 06:06:37 +08:00
defaultSelectedFile
});
2025-02-11 11:15:32 +08:00
2025-02-05 13:04:26 +08:00
const hasChat = !!chatId && !!chat;
const chatTitle = chat?.title;
2025-02-09 13:41:08 +08:00
const chatMessageIds = chat?.messages ?? [];
//FILE
const hasFile = !!defaultSelectedFile?.id;
2025-02-05 13:04:26 +08:00
//MESSAGES
2025-02-09 13:41:08 +08:00
const currentMessageId = chatMessageIds[chatMessageIds.length - 1];
2025-02-18 07:25:31 +08:00
const message = useMessageIndividual(currentMessageId);
const isLoading = !message?.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
return {
2025-02-05 13:04:26 +08:00
hasChat,
hasFile,
selectedFileId,
2025-02-05 13:04:26 +08:00
currentMessageId,
chatTitle,
2025-01-28 08:08:52 +08:00
selectedFileType,
2025-02-09 13:41:08 +08:00
chatMessageIds,
chatId,
2025-02-11 11:15:32 +08:00
isLoading
};
};
2025-02-07 10:08:40 +08:00
export const IndividualChatContext = createContext<ReturnType<typeof useChatIndividualContext>>(
{} 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);