added SpinningWheel.tsx, infinite scrolling is fully working

This commit is contained in:
slawk0
2024-11-11 22:40:54 +01:00
parent d54d28de9e
commit ab4569f312
2 changed files with 26 additions and 8 deletions

View File

@@ -0,0 +1,8 @@
function SpinningWheel() {
return (
<div className="flex items-center justify-center min-h-screen bg-[#121212]">
<div className="animate-spin rounded-full h-12 w-12 border-4 border-green-500 border-t-transparent"></div>
</div>
);
}
export default SpinningWheel;

View File

@@ -1,4 +1,4 @@
import { useEffect, useRef } from 'react';
import { useEffect, useRef, useState } from 'react';
import { socket } from '../../socket/socket.tsx';
import { useOutletContext } from 'react-router-dom';
import { UsernameType } from '../../utils/ProtectedRoutes.tsx';
@@ -45,12 +45,14 @@ function MessagesArea({
const messagesEndRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const { username }: UsernameType = useOutletContext();
let scrollPosition = 0;
const prevScrollHeight = useRef(0);
const [isFetchingHistory, setIsFetchingHistory] = useState(false);
const handleScroll = () => {
const container = containerRef.current;
if (container && container.scrollTop < 30) {
scrollPosition = container.scrollTop;
prevScrollHeight.current = container.scrollHeight;
setIsFetchingHistory(true);
fetchPreviousMessages(currentContact).catch((e) =>
console.error('Failed to fetch messages: ', e),
);
@@ -68,10 +70,9 @@ function MessagesArea({
socket.on('chat message', (msg: ChatMessages) => {
console.log('Received message: ', msg);
if (msg.sender !== currentContact && msg.sender !== username) {
// Add contact to list
setContactsList((prevContacts) => {
if (!prevContacts.some((c) => c.usernamecontact === msg.sender)) {
sendContact(msg.sender); // Send contact to server
sendContact(msg.sender);
return [
...prevContacts,
{ usernamecontact: msg.sender, read: false },
@@ -79,12 +80,11 @@ function MessagesArea({
}
return prevContacts;
});
// Set contact status on client and server site
updateContactStatus(
{ usernamecontact: msg.sender, read: false },
false,
);
console.log('changed status to false', currentContact);
console.log('changed status to false for: ', msg.sender);
}
if (msg.sender == currentContact || msg.sender == username) {
messageHandler(msg);
@@ -106,7 +106,17 @@ function MessagesArea({
}, [currentContact, username, setContactsList, updateContactStatus]);
useEffect(() => {
messagesEndRef.current?.scrollIntoView();
const container = containerRef.current;
if (container && isFetchingHistory) {
container.scrollTop = container.scrollHeight - prevScrollHeight.current;
setIsFetchingHistory(false);
}
}, [messages]);
useEffect(() => {
if (!isFetchingHistory) {
messagesEndRef.current?.scrollIntoView();
}
}, [messages]);
const messageList = messages.map((msg: ChatMessages) => (