import { useEffect, useMemo, useRef } from "react";
import ProfileImage from "@/Element/User/ProfileImage";
import DM from "@/Element/Chat/DM";
import useLogin from "@/Hooks/useLogin";
import WriteMessage from "@/Element/Chat/WriteMessage";
import { Chat, createEmptyChatObject, useChatSystem } from "@/chat";
import { FormattedMessage } from "react-intl";
import { ChatParticipantProfile } from "./ChatParticipant";
export default function DmWindow({ id }: { id: string }) {
const dms = useChatSystem();
const chat = dms.find(a => a.id === id) ?? createEmptyChatObject(id);
function sender() {
if (chat.participants.length === 1) {
return ;
} else {
return (
{chat.participants.map(v => (
))}
{chat.title ??
}
);
}
}
return (
);
}
function DmChatSelected({ chat }: { chat: Chat }) {
const { publicKey: myPubKey } = useLogin(s => ({ publicKey: s.publicKey }));
const messagesContainerRef = useRef(null);
const messagesEndRef = useRef(null);
const sortedDms = useMemo(() => {
const myDms = chat?.messages;
if (myPubKey && myDms) {
// filter dms in this chat, or dms to self
return [...myDms].sort((a, b) => a.created_at - b.created_at);
}
return [];
}, [chat, myPubKey]);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "instant" });
};
useEffect(() => {
const observer = new ResizeObserver(() => {
scrollToBottom();
});
// Start observing the element that you want to keep in view
if (messagesContainerRef.current) {
observer.observe(messagesContainerRef.current);
}
// Make sure to scroll to bottom on initial load
scrollToBottom();
// Clean up the observer on component unmount
return () => {
if (messagesContainerRef.current) {
observer.unobserve(messagesContainerRef.current);
}
};
}, [sortedDms]);
return (
{sortedDms.map(a => (
))}
);
}