buster/web/src/context/Chats/ChatProvider/ChatProvider.tsx

64 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-02-09 13:41:08 +08:00
import React, { useRef, useTransition } from 'react';
2025-02-07 10:08:40 +08:00
import {
createContext,
ContextSelector,
useContextSelector
} from '@fluentui/react-context-selector';
import type { BusterChat } from '@/api/asset_interfaces';
2025-02-11 11:15:32 +08:00
import type { IBusterChat, IBusterChatMessage } from '../interfaces';
2025-02-07 10:08:40 +08:00
import { useChatSubscriptions } from './useChatSubscriptions';
import { useChatAssosciations } from './useChatAssosciations';
2025-02-09 13:41:08 +08:00
import { useChatSelectors } from './useChatSelectors';
import { useChatUpdate } from './useChatUpdate';
2025-02-07 10:08:40 +08:00
export const useBusterChat = () => {
const [isPending, startTransition] = useTransition();
const chatsRef = useRef<Record<string, IBusterChat>>({});
2025-02-09 13:41:08 +08:00
const chatsMessagesRef = useRef<Record<string, IBusterChatMessage>>({});
2025-02-07 10:08:40 +08:00
2025-02-09 13:41:08 +08:00
const chatSubscriptions = useChatSubscriptions({
2025-02-07 10:08:40 +08:00
chatsRef,
2025-02-09 13:41:08 +08:00
chatsMessagesRef,
2025-02-07 10:08:40 +08:00
startTransition
});
2025-02-09 13:41:08 +08:00
const chatAssociations = useChatAssosciations();
const chatSelectors = useChatSelectors({
chatsRef,
chatsMessagesRef,
isPending
});
const chatUpdate = useChatUpdate({
chatsRef,
chatsMessagesRef,
startTransition
});
2025-02-07 10:08:40 +08:00
return {
chats: chatsRef.current,
2025-02-09 13:41:08 +08:00
chatsMessages: chatsMessagesRef.current,
...chatSubscriptions,
...chatAssociations,
...chatSelectors,
...chatUpdate
2025-02-07 10:08:40 +08:00
};
};
const BusterChat = createContext<ReturnType<typeof useBusterChat>>(
{} as ReturnType<typeof useBusterChat>
);
2025-02-09 12:13:42 +08:00
export const ChatProvider: React.FC<{
2025-02-07 10:08:40 +08:00
children: React.ReactNode;
}> = ({ children }) => {
const value = useBusterChat();
return <BusterChat.Provider value={value}>{children}</BusterChat.Provider>;
};
export const useBusterChatContextSelector = <T,>(
selector: ContextSelector<ReturnType<typeof useBusterChat>, T>
) => useContextSelector(BusterChat, selector);