Spaces:
Running
Running
(() => { | |
const params = new URLSearchParams(window.location.search); | |
const room = params.get("room"); | |
const socket = io(); | |
const chatBox = document.getElementById("chat"); | |
const msgInput = document.getElementById("msg"); | |
const sendBtn = document.getElementById("send"); | |
const leaveBtn = document.getElementById("leave"); | |
const chatroomTitle = document.getElementById("chatroom-title"); | |
let mySid = null; | |
let partnerSid = null; | |
let currentRoom = null; | |
// On connect, store my SID | |
socket.on("connect", () => { | |
mySid = socket.id; | |
}); | |
socket.on("matched", data => { | |
currentRoom = data.room; | |
const sid1 = data.sid1; | |
const sid2 = data.sid2; | |
partnerSid = (mySid === sid1) ? sid2 : sid1; | |
chatroomTitle.textContent = `Chatroom of ${sid1} and ${sid2}`; | |
appendSystemMsg("Matched! Start chatting."); | |
}); | |
socket.on("chat", data => { | |
const cls = data.sid === mySid ? "me" : "other"; | |
appendChat(data.sid + ": " + data.msg, cls); | |
}); | |
sendBtn.onclick = () => { | |
const txt = msgInput.value.trim(); | |
if (!txt || !currentRoom) return; | |
socket.emit("chat", { room: currentRoom, msg: txt, sid: mySid }); | |
msgInput.value = ""; | |
}; | |
function appendChat(msg, cls) { | |
const div = document.createElement("div"); | |
div.textContent = msg; | |
div.classList.add(cls); | |
chatBox.append(div); | |
chatBox.scrollTop = chatBox.scrollHeight; | |
} | |
function appendSystemMsg(msg) { | |
appendChat(msg, "status"); | |
} | |
socket.on("status", data => { | |
const s = document.createElement("div"); | |
s.style.fontStyle = "italic"; | |
s.textContent = data.msg; | |
chatDiv.append(s); | |
chatDiv.scrollTop = chatDiv.scrollHeight; | |
}); | |
leaveBtn.onclick = () => { | |
if (confirm("Leave chat?")) { | |
socket.emit("leave", { room }); | |
} | |
}; | |
socket.on("left", () => { | |
window.location = "/"; | |
}); | |
socket.on("matched", data => { | |
// If you ever get matched here, you can handle it, but in this flow | |
// matching happens before navigation. | |
}); | |
})(); |