From e85dcb8487dc72f089d6d9f8375d8d75abbea41e Mon Sep 17 00:00:00 2001 From: slawk0 Date: Tue, 10 Sep 2024 22:43:50 +0200 Subject: [PATCH] display incoming username if username sended message --- frontend/js/chat.js | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/frontend/js/chat.js b/frontend/js/chat.js index e7ddca5..b767637 100644 --- a/frontend/js/chat.js +++ b/frontend/js/chat.js @@ -64,20 +64,16 @@ async function initializeSocket() { document.getElementById('input').placeholder = `Send message as: ${username}`; }) + // Set for not displaying same contact multiple times + const addedContacts = new Set(); + // Main socket connection, it is displaying all messages in real time socket.on('chat message', (msg) => { console.log('Received message:', msg); const { username, content, recipient } = msg; - // username is sender username! + // username is sender username!!! - // Add and display contact/incoming messages whatever - if(recipient !== currentRecipient && username !== currentUsername) { - const contact = document.createElement('li'); - contact.textContent = username; - contacts.appendChild(contact); - console.log('created contact') - } // Display messages if (recipient === currentRecipient || username === currentRecipient) { const item = document.createElement('li'); @@ -85,6 +81,27 @@ async function initializeSocket() { messages.appendChild(item); window.scrollTo(0, document.body.scrollHeight); } + + // Add and display contact/incoming messages + if (recipient !== currentRecipient && username !== currentUsername) { + // Check if the contact has already been added + const contact = document.createElement('li'); + contact.textContent = username; + + contact.addEventListener('click', () => { + currentRecipient = username; + recipientInput.value = username; + localStorage.setItem('currentRecipient', currentRecipient); + socket.emit('get messages', username); + }) + // If not found contact that is already in set (so should not be displayed) it display it in contact sidebar + if (!addedContacts.has(username)) { + contacts.appendChild(contact); + console.log('Created contact:', username); + // Add the username to the Set of added contacts + addedContacts.add(username); + } + } }); // If not previous messages found on backend