-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
202 lines (169 loc) · 6.25 KB
/
Copy pathscript.js
File metadata and controls
202 lines (169 loc) · 6.25 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
document.addEventListener('DOMContentLoaded', function() {
var msg = document.getElementById("msg"); // Message input field
var nme = document.getElementById("nme"); // Username input field
var log = document.getElementById("log"); // Log container for messages
var pick = document.getElementById("colorpicker"); // Username's Colorpicker
var ws = new WebSocket("ws://" + document.location.host + "/ws"); // Establish a WebSocket connection to the server
var message = document.getElementById("message");
// A map to store usernames and their assigned colors
var userColors = {};
var userNames = {};
// Function to generate a random color
function getRandomColor() {
return "#" + Math.random().toString(16).slice(2, 8).padStart(6, "0");
}
// Random digit
function getRandomDigit() {
return Math.floor(Math.random() * 9999) + 1;
}
// Function to set background-color and text color
function setColor(element, color) {
element.style.backgroundColor = color;
}
// Function to set username
function setName(element, string) {
nme.value = string;
}
// Function to set a cookie
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); // Convert days to milliseconds
const expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
// Function to get a cookie by name
function getCookie(name) {
const cookies = document.cookie.split(";"); // Split cookies into an array
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim(); // Trim whitespace
if (cookie.startsWith(name + "=")) {
return cookie.substring((name + "=").length); // Return the value of the cookie
}
}
return null; // Return null if the cookie is not found
}
// Check if a username is stored in cookies
var userName = getCookie("nme");
if (!userName) {
// Generate a random color if no cookie exists
var userName = "Guest" + getRandomDigit();
setCookie("nme", userName); // Store the username in a cookie
}
// Apply the stored or newly generated name
setName(nme, userName);
// Add event listener to change the username
nme.addEventListener('input', function() {
var newName = this.value;
setCookie("nme", newName); // Update the cookie with the new username
setName(nme, newName); // Apply the new username
console.log(`New Name: ${newName}`);
});
// Check if a color is stored in cookies
var userColor = getCookie("color");
if (!userColor) {
// Generate a random color if no cookie exists
var userColor = getRandomColor();
setCookie("color", userColor); // Store the color in a cookie
}
// Apply the stored or newly generated color
setColor(pick, userColor);
// Add click event listener to change the color
pick.onclick = function() {
const newColor = getRandomColor(); // Generate a new random color
setCookie("color", newColor, 365); // Update the cookie with the new color
setColor(pick, newColor); // Apply the new color
console.log(`New Color: ${newColor}`);
};
// Function to append messages to the log
function appendLog(item) {
var doScroll = log.scrollTop > log.scrollHeight - log.clientHeight - 1;
log.appendChild(item);
if (doScroll) {
log.scrollTop = log.scrollHeight - log.clientHeight;
}
}
// Handle the form submission for sending messages
message.onsubmit = function() {
if (!ws) {
return false;
}
if (!msg.value) {
return false;
}
// Send username and message as JSON to the server
const fullMessage = {
username: nme.value,
color: getComputedStyle(pick).backgroundColor,
text: msg.value,
};
// Debug sent text
// console.log("Sending message:", JSON.stringify(fullMessage));
ws.send(JSON.stringify(fullMessage));
// Clear the message input field
msg.value = "";
return false;
};
// Check if the browser supports WebSocket
if (window["WebSocket"]) {
function establishConnection() {
ws = new WebSocket("ws://" + document.location.host + "/ws");
// Event handler when open
ws.onopen = function(evt) {
console.log("%c Connection established to chat", "color: lightgreen");
};
// Event handler for when the WebSocket connection is closed
ws.onclose = function(evt) {
console.log("%c Connection closed, reconnecting...", "color: red");
setTimeout(reconnect, 2000); // Reconnect after a delay
};
// Event handler for when a message is received from the server
ws.onmessage = function(evt) {
// Log raw data for debugging
// console.log("Raw data received:", evt.data);
// Parse the incoming JSON string into a JavaScript object
const data = JSON.parse(evt.data);
// Log parsed data for debugging
// console.log("Parsed data:", data);
// Ensure `data` has both `username` and `text`
/* if (!data.username || !data.text) {
console.error("Parsed data is missing username or text:", data);
return;
} */
// Display username and message
const item = document.createElement("div");
item.id = 'box';
// Create a span for the username with bold styling
const nameDiv = document.createElement("div");
nameDiv.textContent = data.username + ": ";
nameDiv.style.color = data.color; // Make the color received from server
// Create a div for the message text (on a new line)
const messageDiv = document.createElement("div");
messageDiv.textContent = data.text;
// Append elements to display the message in the chat log
item.appendChild(nameDiv); // Add username span
item.appendChild(messageDiv); // Add message div
// Append the constructed item to the chat log
appendLog(item);
};
// Append log function implementation (ensure this exists)
function appendLog(item) {
if (!log) {
console.error("Chat log container not found!");
return;
}
log.prepend(item);
}
}
// Function to reconnect
function reconnect() {
console.log('Reconnecting...');
establishConnection(); // Attempt to reconnect
reconnectDelay = 2000; // Increase delay for next attempt
}
// Establish the initial connection
establishConnection();
} else {
// If WebSockets are not supported by the browser, show an error message in console log
console.error("%c Your browser does not support WebSockets.", "color: red");
}
});