From f9f7da6ffcca68ed0f147a0b379b29732efcb842 Mon Sep 17 00:00:00 2001 From: Russell Ballestrini Date: Sat, 23 Nov 2024 09:39:39 -0500 Subject: [PATCH] incremental progress modified: app.py modified: templates/chat.html --- app.py | 5 +++++ templates/chat.html | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/app.py b/app.py index d9e9004..aa9e2b5 100644 --- a/app.py +++ b/app.py @@ -479,6 +479,11 @@ def on_join(data): {"id": None, "content": f"{data['username']} has joined the room."}, room=room.name, ) + emit( + "user_joined", + {"username": data["username"]}, + room=room.name, + ) emit( "chat_message", { diff --git a/templates/chat.html b/templates/chat.html index 62db5f1..3ac528d 100644 --- a/templates/chat.html +++ b/templates/chat.html @@ -111,6 +111,43 @@ function updateQueryString() { window.history.replaceState({}, '', newUrl); } +// Object to keep track of active users +let activeUsers = {}; + +// Function to update the active user list in the DOM +function updateActiveUserList() { + const userListElement = document.getElementById("active-users"); + userListElement.innerHTML = ''; // Clear the current list + + // Populate the list with active users + for (const username in activeUsers) { + const userItem = document.createElement("li"); + userItem.textContent = username; + userListElement.appendChild(userItem); + } +} + +// Socket event when a user joins +socket.on("user_joined", (data) => { + activeUsers[data.username] = true; // Add user to the active list + updateActiveUserList(); // Update the DOM +}); + +// Socket event when a user leaves +socket.on("user_left", (data) => { + delete activeUsers[data.username]; // Remove user from the active list + updateActiveUserList(); // Update the DOM +}); + +// Handle socket disconnection to update the user list +socket.on("disconnect", () => { + // Optionally, clear the active users list or handle specific user disconnection + // For example, you might want to remove the current user from the list + delete activeUsers[username]; // Remove the current user + updateActiveUserList(); // Update the DOM +}); + + // Function to handle sending the message function sendMessage() { const message = document.getElementById("message").value;