MAJOR FIX: Chat Latency Fixed
This commit is contained in:
@@ -27,7 +27,6 @@ const ListItem: React.FC<ListItemProps> = ({
|
||||
thumbnail,
|
||||
onItemClick,
|
||||
}) => {
|
||||
console.log(title, "thumbnail", thumbnail);
|
||||
return (
|
||||
<div
|
||||
className="flex flex-col bg-gray-800 rounded-lg overflow-hidden cursor-pointer hover:bg-gray-700 transition-colors"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import { io, Socket } from "socket.io-client";
|
||||
import Input from "../Layout/Input";
|
||||
import { useAuth } from "../../context/AuthContext";
|
||||
import { useSocket } from "../../context/SocketContext";
|
||||
|
||||
interface ChatMessage {
|
||||
chatter_id: string;
|
||||
@@ -16,81 +16,60 @@ interface ChatPanelProps {
|
||||
const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [inputMessage, setInputMessage] = useState("");
|
||||
const [socket, setSocket] = useState<Socket | null>(null);
|
||||
const chatContainerRef = useRef<HTMLDivElement>(null);
|
||||
const { isLoggedIn, username } = useAuth();
|
||||
const { socket, isConnected } = useSocket();
|
||||
|
||||
// Initialize socket connection
|
||||
// Join chat room when component mounts
|
||||
useEffect(() => {
|
||||
const newSocket = io("/", {
|
||||
path: "/api/socket.io",
|
||||
withCredentials: true
|
||||
});
|
||||
setSocket(newSocket);
|
||||
if (socket && isConnected) {
|
||||
socket.emit("join", { stream_id: streamId });
|
||||
|
||||
newSocket.on("connect", () => {
|
||||
console.log("Socket Connection established!");
|
||||
// Join the stream's chat room
|
||||
newSocket.emit("join", { stream_id: streamId });
|
||||
});
|
||||
// Load initial chat history
|
||||
fetch(`/api/chat/${streamId}`)
|
||||
.then((response) => {
|
||||
if (!response.ok) throw new Error("Failed to fetch chat history");
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
if (data.chat_history) {
|
||||
setMessages(data.chat_history);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error loading chat history:", error);
|
||||
});
|
||||
|
||||
newSocket.on("new_message", (data: ChatMessage) => {
|
||||
setMessages(prev => [...prev, data]);
|
||||
});
|
||||
// Handle incoming messages
|
||||
socket.on("new_message", (data: ChatMessage) => {
|
||||
setMessages((prev) => [...prev, data]);
|
||||
});
|
||||
|
||||
newSocket.on("connect_error", (error) => {
|
||||
console.error("Socket connection error:", error);
|
||||
});
|
||||
|
||||
newSocket.on("connect_timeout", () => {
|
||||
console.error("Socket connection timeout");
|
||||
});
|
||||
|
||||
newSocket.on("error", (error) => {
|
||||
console.error("Socket error:", error);
|
||||
});
|
||||
|
||||
// Cleanup on unmount
|
||||
return () => {
|
||||
newSocket.emit("leave", { stream_id: streamId });
|
||||
newSocket.close();
|
||||
};
|
||||
}, [streamId]);
|
||||
|
||||
// Load initial chat history
|
||||
useEffect(() => {
|
||||
const loadPastChat = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/chat/${streamId}`);
|
||||
if (!response.ok) throw new Error("Failed to fetch chat history");
|
||||
const data = await response.json();
|
||||
if (data.chat_history) {
|
||||
setMessages(data.chat_history);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading chat history:", error);
|
||||
}
|
||||
};
|
||||
|
||||
loadPastChat();
|
||||
}, [streamId]);
|
||||
// Cleanup
|
||||
return () => {
|
||||
socket.emit("leave", { stream_id: streamId });
|
||||
socket.off("new_message");
|
||||
};
|
||||
}
|
||||
}, [socket, isConnected, streamId]);
|
||||
|
||||
// Auto-scroll to bottom when new messages arrive
|
||||
useEffect(() => {
|
||||
if (chatContainerRef.current) {
|
||||
chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
|
||||
chatContainerRef.current.scrollTop =
|
||||
chatContainerRef.current.scrollHeight;
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
const sendChat = () => {
|
||||
if (!inputMessage.trim() || !socket) {
|
||||
console.log("No message to send or socket not initialized!");
|
||||
if (!inputMessage.trim() || !socket || !isConnected) {
|
||||
console.log("Invalid message or socket not connected");
|
||||
return;
|
||||
};
|
||||
}
|
||||
|
||||
socket.emit("send_message", {
|
||||
stream_id: streamId,
|
||||
message: inputMessage.trim()
|
||||
message: inputMessage.trim(),
|
||||
});
|
||||
|
||||
setInputMessage("");
|
||||
@@ -102,7 +81,7 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
|
||||
sendChat();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<div id="chat-panel" className="h-full flex flex-col rounded-lg p-4">
|
||||
<h2 className="text-xl font-bold mb-4 text-white">Stream Chat</h2>
|
||||
@@ -113,11 +92,21 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
|
||||
className="flex-grow w-full max-h-[50vh] overflow-y-auto mb-4 space-y-2"
|
||||
>
|
||||
{messages.map((msg, index) => (
|
||||
<div key={index} className="grid grid-cols-[8%_minmax(15%,_100px)_1fr] items-center bg-gray-700 rounded p-2 text-white">
|
||||
<div
|
||||
key={index}
|
||||
className="grid grid-cols-[8%_minmax(15%,_100px)_1fr] items-center bg-gray-700 rounded p-2 text-white"
|
||||
>
|
||||
<span className="text-gray-400 text-sm">
|
||||
{new Date(msg.time_sent).toLocaleTimeString()}
|
||||
</span>
|
||||
<span className={`font-bold ${msg.chatter_id === username ? "text-blue-400" : "text-green-400"}`}> {msg.chatter_id}: </span>
|
||||
<span
|
||||
className={`font-bold ${
|
||||
msg.chatter_id === username ? "text-blue-400" : "text-green-400"
|
||||
}`}
|
||||
>
|
||||
{" "}
|
||||
{msg.chatter_id}:{" "}
|
||||
</span>
|
||||
<span>{msg.message}</span>
|
||||
</div>
|
||||
))}
|
||||
@@ -145,4 +134,4 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
|
||||
);
|
||||
};
|
||||
|
||||
export default ChatPanel;
|
||||
export default ChatPanel;
|
||||
|
||||
Reference in New Issue
Block a user