import React, { PropsWithChildren } from 'react'; import { ContextSelector, createContext, useContextSelector } from '@fluentui/react-context-selector'; import type { SelectedFile } from '../interfaces'; import { useAutoChangeLayout } from './useAutoChangeLayout'; import { useMessageIndividual } from '@/context/Chats'; import { useSubscribeIndividualChat } from './useSubscribeIndividualChat'; export const useChatIndividualContext = ({ chatId, defaultSelectedFile, onSetSelectedFile }: { chatId?: string; defaultSelectedFile?: SelectedFile; onSetSelectedFile: (file: SelectedFile) => void; }) => { const selectedFileId = defaultSelectedFile?.id; const selectedFileType = defaultSelectedFile?.type; //CHAT const chat = useSubscribeIndividualChat({ chatId, defaultSelectedFile }); const hasChat = !!chatId && !!chat; const chatTitle = chat?.title; const chatMessageIds = chat?.messages ?? []; //FILE const hasFile = !!defaultSelectedFile?.id; //MESSAGES const currentMessageId = chatMessageIds[chatMessageIds.length - 1]; const message = useMessageIndividual(currentMessageId); const isLoading = !message?.isCompletedStream; useAutoChangeLayout({ lastMessageId: currentMessageId, onSetSelectedFile }); return { hasChat, hasFile, selectedFileId, currentMessageId, chatTitle, selectedFileType, chatMessageIds, chatId, isLoading }; }; export const IndividualChatContext = createContext>( {} as ReturnType ); export const ChatContextProvider = React.memo( ({ value, children }: PropsWithChildren<{ value: ReturnType }>) => { return ( {children} ); } ); ChatContextProvider.displayName = 'ChatContextProvider'; export const useChatIndividualContextSelector = ( selector: ContextSelector, T> ) => useContextSelector(IndividualChatContext, selector);