-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
210 lines (194 loc) · 5.99 KB
/
Copy pathscript.js
File metadata and controls
210 lines (194 loc) · 5.99 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
203
204
205
206
207
208
209
210
/* TEXTBORED CLIENT */
// 📋 VARIABLES
let currentURL = new URL(window.location.href);
let params = new URLSearchParams(currentURL.search);
const ws = new WebSocket(params.get('server') || 'ws://localhost:8000');
const thisUrl = new URL(window.location.href)
const chat = document.getElementById('chat');
const msgBar = document.getElementById('usrMessage');
const settings = {
wrapper: document.getElementById('settings').parentElement,
name: document.getElementById('usrName'),
col: document.getElementById('usrCol'),
opened: false,
openClose() {
if (this.opened) {
this.wrapper.style.display = 'none';
this.opened = false;
} else {
this.wrapper.style.display = 'block';
this.opened = true;
}
},
save() {
const old = [un, col];
un = this.name.value || un;
col = this.col.value || col;
localStorage.setItem("username", un);
localStorage.setItem("colour", col);
ws.send(JSON.stringify({
type: "change",
oldName: old[0],
oldCol: old[1],
username: un,
colour: col,
timestamp: new Date().toUTCString()
}))
console.log('Settings saved!');
this.openClose();
}
}
let un;
let col;
// 🛠️ FUNCTIONS
// get a random colour
function getRandomColour() {
const letters = '0123456789ABCDEF';
let colour = '#';
for (let i = 0; i < 6; i++) {
colour += letters[Math.floor(Math.random() * 16)];
}
return colour;
}
// parse json to html
function j2hparse(jsonMsg) {
const msg = (()=>{
try {
return JSON.parse(jsonMsg);
} catch (error) {
return {
type: "unable"
};
}
})();
// const time = convertTo12Hr(msg.timestamp);
const time = new Date(msg.time).toLocaleTimeString("en-US", {hour: '2-digit', minute:'2-digit'});
const messages = {
join: `<div class="message jl">
<strong class="username" style="border-color: ${msg.colour};">${msg.username}</strong>
<div class="content">has joined the chat.</div>
<small class="timestamp">${time}</small>
</div>`,
leave: `<div class="message jl">
<strong class="username" style="border-color: ${msg.colour};">${msg.username}</strong>
<div class="content">has left the chat.</div>
<small class="timestamp">${time}</small>
</div>`,
normal: `<div class="message">
<strong class="username" style="border-color: ${msg.colour};">${msg.username}</strong>
<small class="timestamp">${time}</small>
<div class="content">${msg.message}</div>
</div>`,
change: `<div class="message jl">
<strong class="username" style="border-color: ${msg.oldCol};">${msg.oldName}</strong>
<div class="content">is now <strong class="username" style="border-color: ${msg.colour};">${msg.username}</strong>.</div>
<small class="timestamp">10:48 AM</small>
</div>`,
unable: `<p style='color: red;'>Unable to parse received message...</p>`
}
switch (msg.type.toUpperCase()) {
case "NORMAL":
return messages.normal;
case "JOIN":
return messages.join;
case "LEAVE":
return messages.leave;
case "CHANGE":
return messages.change;
default:
console.error('Unable to parse message: ' + jsonMsg)
return messages.unable;
}
}
// add a message to chat div
function addMessage(jsonMsg) {
chat.insertAdjacentHTML('beforeend', j2hparse(jsonMsg));
}
// send a message to the websocket server
function sendMessage() {
if (msgBar.value != "") {
const msg = JSON.stringify({
type: 'normal',
username: un,
colour: col,
message: msgBar.value,
time: new Date().toUTCString()
});
ws.send(msg);
msgBar.value = "";
}
// rate limit
let lastTime = new Date();
return ()=>{
const now = new Date();
if ((now - lastTime) < 10000) return;
lastTime = now;
}
}
// change the websocket server
function customServer() {
const input = prompt("Enter your server URL (eg wss://echo.websocket.org/)");
if (!input) return;
let url;
try {
url = new URL(input);
} catch (e) {
try {
url = new URL('ws://' + input);
} catch (e2) {
alert('Invalid server URL');
return;
}
}
params.set("server", url.toString());
currentURL.search = params.toString();
window.location.href = currentURL.toString();
}
// 🔌 WEBSOCKET STUFF
// send a join message on connection open
ws.onopen = () => {
console.log("Connection initialised!")
chat.insertAdjacentHTML('beforeend', '<h2>Connection initialised!</h2>');
ws.send(JSON.stringify({
type: 'join',
username: un,
colour: col,
time: new Date().toUTCString()
}));
}
// add message to dom on message
ws.onmessage = (event) => {
addMessage(event.data);
}
// connection error and close handler
ws.onerror = (event) => {
alert('Error!');
console.error(event);
}
ws.onclose = (event) => {
alert('Connection has closed.');
chat.insertAdjacentHTML('beforeend', '<h2>Connection has closed.</h2>');
console.error(event);
}
// 🧩 OTHER STUFF
// random username and colour on page load, or load from local storage
window.onload = () => {
const storedName = localStorage.getItem("username");
const storedCol = localStorage.getItem("colour");
if (storedName && storedCol) {
un = storedName;
col = storedCol;
} else {
un = `user${Math.floor(Math.random() * 999)}0`;
col = getRandomColour();
localStorage.setItem("username", un);
localStorage.setItem("username", col);
}
};
// send message on enter key in message bar
msgBar.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
sendMessage();
}
});