"use client"; import { Fragment, useRef, ElementRef, use } from "react"; import { format } from "date-fns" import { Member, Message, Profile } from "@prisma/client" import { ChatWelcome } from "./chat-welcome"; import { useChatQuery } from "@/hooks/use-chat-query"; import { Loader2, ServerCrash } from "lucide-react"; import { ChatItem } from "./chat-item"; import { useChatSocket } from "@/hooks/use-chat-socket"; import { useChatScroll } from "@/hooks/use-chat-scroll"; const DATE_FORMAT = "d MMM yyyy, HH:mm"; type MessageWithMemberWithProfile = Message & { member: Member & { profile: Profile } } interface ChatMessagesProps { name: string; member: Member; chatId: string; apiUrl: string; socketUrl: string; socketQuery: Record; paramKey: "channelId" | "conversationId"; paramValue: string; type: "channel" | "conversation"; } export const ChatMessages = ({ name, member, chatId, apiUrl, socketUrl, socketQuery, paramKey, paramValue, type, }: ChatMessagesProps) => { const queryKey = `chat:${chatId}`; const addKey = `chat:${chatId}:messages`; const updateKey = `chat:${chatId}:messages:update`; const chatRef = useRef>(null); const bottomRef = useRef>(null); const { data, fetchNextPage, hasNextPage, isFetchingNextPage, status, } = useChatQuery({ queryKey, apiUrl, paramKey, paramValue, }); useChatSocket({ queryKey, addKey, updateKey}); useChatScroll({ chatRef, bottomRef, loadMore: fetchNextPage, shouldLoadMore: !isFetchingNextPage && !!hasNextPage, count: data?.pages?.[0]?.items?.length ?? 0, }) if (status === "pending") { return (

Loading Messages...

) } if (status === "error") { return (

Something went wrong!

) } return (
{!hasNextPage &&
} {!hasNextPage &&( )} {hasNextPage && (
{isFetchingNextPage ? ( ): ( )}
)}
{data?.pages.map((group, i) => ( {group.items.map((message: MessageWithMemberWithProfile) => ( ))} ))}
) }