File size: 1,961 Bytes
6423a65
 
b350e4b
bb32923
1c177a3
 
 
 
 
 
e571f09
1c177a3
 
 
3474c3f
1c177a3
 
 
 
3474c3f
1c177a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c1fbc1
3474c3f
 
 
 
 
 
 
e571f09
3474c3f
 
 
e571f09
3474c3f
 
 
 
b350e4b
 
 
 
 
6423a65
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
(() => {
  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.
  });
})();