Skip to content

Commit

Permalink
docs(examples): Improve the chat example with more ES6 features (#3240)
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiolenza committed Jan 14, 2021
1 parent b55892a commit 6b1d790
Showing 1 changed file with 39 additions and 43 deletions.
82 changes: 39 additions & 43 deletions examples/chat/public/main.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
$(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
const FADE_TIME = 150; // ms
const TYPING_TIMER_LENGTH = 400; // ms
const COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];

// Initialize variables
var $window = $(window);
var $usernameInput = $('.usernameInput'); // Input for username
var $messages = $('.messages'); // Messages area
var $inputMessage = $('.inputMessage'); // Input message input box
const $window = $(window);
const $usernameInput = $('.usernameInput'); // Input for username
const $messages = $('.messages'); // Messages area
const $inputMessage = $('.inputMessage'); // Input message input box

var $loginPage = $('.login.page'); // The login page
var $chatPage = $('.chat.page'); // The chatroom page
const $loginPage = $('.login.page'); // The login page
const $chatPage = $('.chat.page'); // The chatroom page

// Prompt for setting a username
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
const socket = io();

var socket = io();
// Prompt for setting a username
let username;
let connected = false;
let typing = false;
let lastTypingTime;
let $currentInput = $usernameInput.focus();

const addParticipantsMessage = (data) => {
var message = '';
let message = '';
if (data.numUsers === 1) {
message += "there's 1 participant";
message += `there's 1 participant`;
} else {
message += "there are " + data.numUsers + " participants";
message += `there are ${data.numUsers} participants`;
}
log(message);
}
Expand All @@ -53,45 +53,41 @@ $(function() {

// Sends a chat message
const sendMessage = () => {
var message = $inputMessage.val();
let message = $inputMessage.val();
// Prevent markup from being injected into the message
message = cleanInput(message);
// if there is a non-empty message and a socket connection
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
addChatMessage({ username, message });
// tell server to execute 'new message' and send along one parameter
socket.emit('new message', message);
}
}

// Log a message
const log = (message, options) => {
var $el = $('<li>').addClass('log').text(message);
const log = (message, options) => {
const $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}

// Adds the visual chat message to the message list
const addChatMessage = (data, options) => {
// Don't fade the message in if there is an 'X was typing'
var $typingMessages = getTypingMessages(data);
options = options || {};
const $typingMessages = getTypingMessages(data);
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}

var $usernameDiv = $('<span class="username"/>')
const $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
const $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);

var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
const typingClass = data.typing ? 'typing' : '';
const $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
Expand Down Expand Up @@ -119,8 +115,7 @@ $(function() {
// options.prepend - If the element should prepend
// all other messages (default = false)
const addMessageElement = (el, options) => {
var $el = $(el);

const $el = $(el);
// Setup default options
if (!options) {
options = {};
Expand All @@ -141,6 +136,7 @@ $(function() {
} else {
$messages.append($el);
}

$messages[0].scrollTop = $messages[0].scrollHeight;
}

Expand All @@ -159,8 +155,8 @@ $(function() {
lastTypingTime = (new Date()).getTime();

setTimeout(() => {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
const typingTimer = (new Date()).getTime();
const timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
Expand All @@ -179,12 +175,12 @@ $(function() {
// Gets the color of a username through our hash function
const getUsernameColor = (username) => {
// Compute hash code
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
let hash = 7;
for (let i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// Calculate color
var index = Math.abs(hash % COLORS.length);
const index = Math.abs(hash % COLORS.length);
return COLORS[index];
}

Expand Down Expand Up @@ -229,7 +225,7 @@ $(function() {
socket.on('login', (data) => {
connected = true;
// Display the welcome message
var message = "Welcome to Socket.IO Chat – ";
const message = 'Welcome to Socket.IO Chat – ';
log(message, {
prepend: true
});
Expand All @@ -243,13 +239,13 @@ $(function() {

// Whenever the server emits 'user joined', log it in the chat body
socket.on('user joined', (data) => {
log(data.username + ' joined');
log(`${data.username} joined`);
addParticipantsMessage(data);
});

// Whenever the server emits 'user left', log it in the chat body
socket.on('user left', (data) => {
log(data.username + ' left');
log(`${data.username} left`);
addParticipantsMessage(data);
removeChatTyping(data);
});
Expand Down

0 comments on commit 6b1d790

Please sign in to comment.