Skip to content

Instantly share code, notes, and snippets.

@steadylearner
Last active May 16, 2019 16:10
Show Gist options
  • Save steadylearner/ccf298bc946d194cc51dd2d3996fe4f2 to your computer and use it in GitHub Desktop.
Save steadylearner/ccf298bc946d194cc51dd2d3996fe4f2 to your computer and use it in GitHub Desktop.
// 1.
const emoji = require("node-emoji");
const hasEmoji = require("has-emoji");
const socket = new WebSocket("ws://127.0.0.1:7777/ws");
// 2.
function getDateTime() {
const today = new Date();
const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
const payload = date + ' ' + time;
return payload;
}
function removeMessages() { // remove child elements from its parent element
const messages = document.getElementById("messages");
while (messages.firstChild) {
messages.removeChild(messages.firstChild);
}
}
let open = false;
let userId = "";
let userInputs = [];
let server = []
socket.addEventListener('open', function (event) {
// socket.send('Start to chat');
console.log("Start to chat");
});
// 3.
const clear = document.getElementById("clear");
clear.onclick = removeMessages;
const exit = document.getElementById("exit");
exit.onclick = function () {
socket.close();
}
// 4.
const form = document.getElementById("form");
form.onsubmit = function (event) {
event.preventDefault();
const input = document.getElementById("msg");
if (input.value === "") {
return;
}
if (input.value === "!clear") {
removeMessages()
input.value = "";
return;
}
if (input.value === "!exit") {
socket.close();
return;
}
const userInputWithTime = `${userId} typed ${input.value} at ${getDateTime()}`;
userInputs.push(userInputWithTime);
socket.send(`${userId}: ${input.value}`);
input.value = "";
// Comment it and find the difference(It scroll down the window when user type)
setTimeout(() => window.scrollTo({ top: window.innerHeight, behavior: "auto" }), 10);
};
socket.onmessage = function (event) {
// To save what server sent to localStorage, use database in production
const messagefromServer = `Server ${event.origin} sent ${event.data} at ${getDateTime()}`
server.push(messagefromServer);
// if (userInputs[userInputs.length - 1] === "!warn") {
// alert("You sent warning to the other users");
// }
if (event.data.includes("!clearall")) {
removeMessages();
return;
}
if (event.data.includes("!exitall")) {
socket.close();
return;
}
if (event.data.includes("!x-opacity")) {
const messages = document.getElementById("messages");
if (messages.className === "x-opacity") { messages.className = ""; } else { messages.className = "x-opacity" }
return;
}
// 5.
if (!open) {
// To give id to user and verify the maximum number, only work once
// See the Rust code we defined before and find that they are relevant.
// We pick the first(id for user and will be You with JavaScript)
// and the last part(number of connection) from
// open_message variable with JavaScript
// fn on_open(&mut self, handshake: Handshake) -> Result<()> {
// self.count.set(self.count.get() + 1);
// let number_of_connection = self.count.get();
// let open_message = format!("{} entered and the number of live connections is {}", &handshake.peer_addr.unwrap(), &number_of_connection);
// self.out.broadcast(open_message); -> becomes event.data
// Ok(())
// }
let separate = event.data.split(" ");
userId = separate[0];
const messages = document.getElementById("messages");
const li = document.createElement("li");
const p = document.createElement("p");
let totalNumber = separate[separate.length - 1];
// 6.
if (totalNumber > 5) {
p.textContent = `${totalNumber - 1} is maximum user allowed. Wait for others exit the chat.`;
p.className = "red-white";
li.append(p)
messages.append(li);
socket.close();
return;
}
open = true;
p.textContent = `Your id is ${userId} and "You" will be used in this page instead`;
p.className = "blue";
li.append(p)
messages.append(li);
return;
} else {
let fromServer = event.data;
const beforePayload = fromServer.split(" ")[0];
const authorOfMessage = beforePayload.slice(0, beforePayload.length - 1); // to get the id part of the message
// if (authorOfMessage !== userId && fromServer.includes(`!exclude ${userId}`)) {
if (fromServer.includes(`!exclude ${userId}`)) {
socket.close();
return;
}
const messages = document.getElementById("messages");
const li = document.createElement("li");
// Give color and "You" for a user when author of the messages is the user.
if (authorOfMessage === userId) {
li.className = "red-white";
fromServer = fromServer.replace(userId, "You");
}
// 7.
const includeEmoji = hasEmoji(emoji.emojify(fromServer));
afterEmoji = includeEmoji ? emoji.emojify(fromServer) : fromServer;
const p = document.createElement("p");
p.append(afterEmoji)
li.append(p);
messages.append(li);
return;
}
};
// 8.
socket.onclose = function (event) {
const closeMessage = event.data === undefined ? "Server, You or another user closed the connection." : "WebSocket is closed now."
const messages = document.getElementById("messages");
const li = document.createElement("li");
li.append(closeMessage)
li.className = "blue";
messages.append(li);
localStorage.setItem("userInputs", `[${userInputs}]`);
localStorage.setItem("server", `[${server}]`);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment