display incoming username if username sended message

This commit is contained in:
slawk0
2024-09-10 22:43:50 +02:00
parent 20899cfa23
commit e85dcb8487

View File

@@ -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