buster/web/src/context/Chats/ChatProvider/useChatSelectors.ts

49 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-02-11 11:15:32 +08:00
import { type MutableRefObject, useCallback } from 'react';
import type { IBusterChat, IBusterChatMessage } from '../interfaces';
2025-02-11 07:43:38 +08:00
import { useMemoizedFn } from 'ahooks';
2025-02-09 13:41:08 +08:00
export const useChatSelectors = ({
isPending,
chatsRef,
chatsMessagesRef
}: {
isPending: boolean;
chatsRef: MutableRefObject<Record<string, IBusterChat>>;
chatsMessagesRef: MutableRefObject<Record<string, IBusterChatMessage>>;
}) => {
2025-02-12 03:32:12 +08:00
const getChatMemoized = useMemoizedFn((chatId: string): IBusterChat | undefined => {
2025-02-11 07:43:38 +08:00
return chatsRef.current[chatId];
});
2025-02-09 13:41:08 +08:00
const getChatMessages = useCallback(
(chatId: string): IBusterChatMessage[] => {
2025-02-12 06:02:02 +08:00
return getChatMessagesMemoized(chatId);
2025-02-09 13:41:08 +08:00
},
[chatsMessagesRef, isPending, chatsRef]
);
const getChatMessage = useCallback(
2025-02-12 03:32:12 +08:00
(messageId: string): IBusterChatMessage | undefined => {
2025-02-12 06:02:02 +08:00
return getChatMessageMemoized(messageId);
2025-02-09 13:41:08 +08:00
},
[chatsMessagesRef, isPending]
);
2025-02-11 07:43:38 +08:00
const getChatMessagesMemoized = useMemoizedFn((chatId: string) => {
2025-02-12 08:09:12 +08:00
const chatMessageIds = chatsRef.current[chatId]?.messages || [];
2025-02-12 06:02:02 +08:00
return chatMessageIds.map((messageId) => chatsMessagesRef.current[messageId]);
2025-02-11 07:43:38 +08:00
});
const getChatMessageMemoized = useMemoizedFn((messageId: string) => {
2025-02-12 06:02:02 +08:00
return chatsMessagesRef.current[messageId];
2025-02-11 07:43:38 +08:00
});
return {
getChatMemoized,
getChatMessages,
getChatMessage,
getChatMessagesMemoized,
getChatMessageMemoized
};
2025-02-09 13:41:08 +08:00
};