Spaces:
Running
Running
Update static/chat.js
Browse files- static/chat.js +51 -20
static/chat.js
CHANGED
@@ -1,30 +1,61 @@
|
|
1 |
(() => {
|
2 |
const params = new URLSearchParams(window.location.search);
|
3 |
const room = params.get("room");
|
4 |
-
const socket = io();
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
|
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
const leaveBtn= document.getElementById("leave");
|
14 |
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
input.value = "";
|
20 |
-
};
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
socket.on("status", data => {
|
30 |
const s = document.createElement("div");
|
|
|
1 |
(() => {
|
2 |
const params = new URLSearchParams(window.location.search);
|
3 |
const room = params.get("room");
|
|
|
4 |
|
5 |
+
const socket = io();
|
6 |
+
const chatBox = document.getElementById("chat");
|
7 |
+
const msgInput = document.getElementById("msg");
|
8 |
+
const sendBtn = document.getElementById("send");
|
9 |
+
const leaveBtn = document.getElementById("leave");
|
10 |
+
const chatroomTitle = document.getElementById("chatroom-title");
|
11 |
|
12 |
+
let mySid = null;
|
13 |
+
let partnerSid = null;
|
14 |
+
let currentRoom = null;
|
|
|
15 |
|
16 |
+
// On connect, store my SID
|
17 |
+
socket.on("connect", () => {
|
18 |
+
mySid = socket.id;
|
19 |
+
});
|
|
|
|
|
20 |
|
21 |
+
socket.on("matched", data => {
|
22 |
+
currentRoom = data.room;
|
23 |
+
const sid1 = data.sid1;
|
24 |
+
const sid2 = data.sid2;
|
25 |
+
partnerSid = (mySid === sid1) ? sid2 : sid1;
|
26 |
+
|
27 |
+
chatroomTitle.textContent = `Chatroom of ${sid1} and ${sid2}`;
|
28 |
+
appendSystemMsg("Matched! Start chatting.");
|
29 |
+
});
|
30 |
+
|
31 |
+
socket.on("chat", data => {
|
32 |
+
const cls = data.sid === mySid ? "me" : "other";
|
33 |
+
appendChat(data.sid + ": " + data.msg, cls);
|
34 |
+
});
|
35 |
+
|
36 |
+
sendBtn.onclick = () => {
|
37 |
+
const txt = msgInput.value.trim();
|
38 |
+
if (!txt || !currentRoom) return;
|
39 |
+
socket.emit("chat", { room: currentRoom, msg: txt, sid: mySid });
|
40 |
+
msgInput.value = "";
|
41 |
+
};
|
42 |
+
|
43 |
+
|
44 |
+
|
45 |
+
function appendChat(msg, cls) {
|
46 |
+
const div = document.createElement("div");
|
47 |
+
div.textContent = msg;
|
48 |
+
div.classList.add(cls);
|
49 |
+
chatBox.append(div);
|
50 |
+
chatBox.scrollTop = chatBox.scrollHeight;
|
51 |
+
}
|
52 |
+
|
53 |
+
function appendSystemMsg(msg) {
|
54 |
+
appendChat(msg, "status");
|
55 |
+
}
|
56 |
+
|
57 |
+
|
58 |
+
|
59 |
|
60 |
socket.on("status", data => {
|
61 |
const s = document.createElement("div");
|