-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
699 lines (615 loc) · 19.4 KB
/
Copy pathindex.js
File metadata and controls
699 lines (615 loc) · 19.4 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
import OpenAI from 'openai';
import DesktopWindow from '../DesktopWindow/index.js';
const baseChatImagePath = './assets/images/chat-app';
const apiKey = import.meta.env.VITE_OPENAI_API_KEY;
const openai = apiKey ? new OpenAI({ apiKey, dangerouslyAllowBrowser: true }) : null;
/**
* @class ChatApp
* @classdesc A chat application interface that manages user authentication, channel selection, and message handling.
* @augments DesktopWindow
*/
export default class ChatApp extends DesktopWindow {
_state;
_username = localStorage.getItem('chat-app-username') || null;
/**
* Gets the current state of the chat application.
* @returns {string} The current state.
*/
get state () {
return this._state;
}
/**
* Sets the state of the chat application and updates the UI.
* @param {string} value - The new state to set.
*/
set state (value) {
this._state = value;
this.closeConnection();
this.messageListElement = null;
this.inputFieldElement = null;
this.renderBody(value);
}
/**
* Gets the current username.
* @returns {string|null} The current username or null if not set.
*/
get username () {
return this._username || localStorage.getItem('chat-app-username') || null;
}
/**
* Sets the username and optionally remembers it in local storage.
* @param {object | null} value - The username object containing username and rememberMe flag.
*/
set username (value) {
if (value === null || value === undefined) {
this._username = null;
localStorage.removeItem('chat-app-username');
} else {
const { username, rememberMe } = value;
this._username = username;
if (rememberMe) {
localStorage.setItem('chat-app-username', username);
}
}
}
socket;
apiKey = 'eDBE76deU7L0H9mEBgxUKVR0VCnq0XBd';
channel = 'default_channel';
filterProfanity;
messages = [];
messageListElement;
changeChannelButton;
controlPanel;
/**
* Lifecycle method called when the component is added to the DOM.
*/
connectedCallback () {
super.connectedCallback();
this.state = 'username-choice';
}
/**
* Lifecycle method called when the component is removed from the DOM.
*/
disconnectedCallback () {
this.closeConnection();
}
/**
* Creates the control panel for the chat application.
* @returns {HTMLElement} The control panel element.
*/
createControlPanel () {
const controlPanel = document.createElement('div');
controlPanel.classList.add('window__control-panel');
controlPanel.innerHTML = `
<div class="window__dropdown">
<div class="window__dropdown-activator">Settings</div>
<div class="window__dropdown-content">
<div data-action="change-username" class="window__dropdown-choice" style="white-space: nowrap;">Change Username</div>
<div data-action="change-channel" class="window__dropdown-choice" style="white-space: nowrap;">Change Channel</div>
</div>
</div>
`;
this.controlPanel = controlPanel;
this.changeChannelButton = controlPanel.querySelector('[data-action="change-channel"]');
return controlPanel;
}
/**
* Renders the body of the chat application based on the current state.
* @param {string} state - The current state of the application.
*/
renderBody (state) {
this.body.style.width = '250px';
this.body.style.height = '400px';
if (this.username) {
this.changeChannelButton.classList.remove('disabled');
} else {
this.changeChannelButton.classList.add('disabled');
}
if (state === 'username-choice') {
this.body.replaceChildren(this.createUsernameChoiceMenu());
} else if (state === 'channel-choice') {
if (!this.username) {
this.state = 'username-choice';
return;
}
this.body.replaceChildren(this.createChannelChoiceMenu());
} else if (state === 'chat') {
const { messageListElement, chat } = this.createChat();
this.messageListElement = messageListElement;
this.body.replaceChildren(chat);
this.connect();
} else {
throw new Error('Invalid state');
}
}
/**
* Adds event listeners to the chat application.
*/
addEventListeners () {
super.addEventListeners();
this.controlPanel.addEventListener('click', this.handleClick.bind(this));
this.body.addEventListener('submit', this.handleSubmit.bind(this));
}
/**
* Handles click events on the control panel.
* @param {Event} event - The click event.
*/
handleClick (event) {
const action = event.target.dataset.action;
switch (action) {
case 'change-username':
this.username = null;
this.state = 'username-choice';
break;
case 'change-channel':
this.state = 'channel-choice';
break;
}
}
/**
* Handles form submission events.
* @param {Event} event - The submit event.
*/
handleSubmit (event) {
event.preventDefault();
const form = event.target;
switch (form.id) {
case 'auth-form':
this.handleAuthFormSubmit(form);
break;
case 'channel-form':
this.handleChannelChoiceFormSubmit(form);
break;
case 'message-form':
this.handleMessageFormSubmit(form);
break;
default:
throw new Error('Unhandled form submission');
}
}
/**
* Handles the submission of the authentication form.
* @param {HTMLFormElement} form - The authentication form element.
*/
handleAuthFormSubmit (form) {
const formData = new FormData(form);
const username = formData.get('username');
const rememberMe = formData.get('remember-me');
if (username) {
this.username = { username, rememberMe: !!rememberMe };
this.state = 'channel-choice';
}
}
/**
* Handles the submission of the channel choice form.
* @param {HTMLFormElement} form - The channel choice form element.
*/
handleChannelChoiceFormSubmit (form) {
const formData = new FormData(form);
const channel = formData.get('channel');
if (channel) {
this.channel = channel;
this.filterProfanity = !!formData.get('profanity');
this.state = 'chat';
}
}
/**
* Handles the submission of the message form.
* @param {HTMLFormElement} form - The message form element.
*/
handleMessageFormSubmit (form) {
const formData = new FormData(form);
const message = formData.get('message');
if (message) {
this.sendMessage(message);
const inputField = form.querySelector('.input-field');
inputField.value = '';
inputField.dispatchEvent(new Event('input'));
}
}
/**
* Sends a message through the WebSocket connection.
* @param {string} data - The message data to send.
*/
sendMessage (data) {
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
console.error('Cannot send message: WebSocket is not open.');
return;
}
const message = {
type: 'message',
data,
username: this.username,
channel: this.channel,
key: this.apiKey
};
this.socket.send(JSON.stringify(message));
}
/**
* Creates a message element for display in the chat.
* @param {object} message - The message object containing username and data.
* @returns {HTMLElement} The message element.
*/
createMessageElement (message) {
if (message.username.toLowerCase() === 'the server') {
const serverMessageElement = document.createElement('p');
serverMessageElement.classList.add('server-message');
serverMessageElement.textContent = message.data;
return serverMessageElement;
} else {
const messageElement = document.createElement('div');
messageElement.classList.add('message');
const usernameElement = document.createElement('p');
usernameElement.classList.add('username');
usernameElement.textContent = `${message.username}:`;
messageElement.appendChild(usernameElement);
const contentElement = document.createElement('p');
contentElement.classList.add('content');
contentElement.textContent = message.data;
messageElement.appendChild(contentElement);
return messageElement;
}
}
/**
* Creates the username choice menu.
* @returns {HTMLElement} The username choice menu element.
*/
createUsernameChoiceMenu () {
const menu = document.createElement('div');
menu.classList.add('container', 'menu');
const authForm = document.createElement('form');
authForm.id = 'auth-form';
authForm.classList.add('form');
authForm.innerHTML = `
<img src="${baseChatImagePath}/logo.webp" alt="Messenger Logo" />
<label class="form__hint" for="username">Enter your username</label>
<input class="form__input" type="text" name="username" placeholder="Username" required />
<div class="form__checkbox">
<input type="checkbox" id="remember-me" name="remember-me" />
<label for="remember-me">Remember me</label>
</div>
<button class="form__button" type="submit">Sign in</button>
`;
menu.appendChild(authForm);
return menu;
}
/**
* Creates the channel choice menu.
* @returns {HTMLElement} The channel choice menu element.
*/
createChannelChoiceMenu () {
const menu = document.createElement('div');
menu.classList.add('container', 'menu');
const channelChoiceForm = document.createElement('form');
channelChoiceForm.id = 'channel-form';
channelChoiceForm.classList.add('form');
channelChoiceForm.innerHTML = `
<img src="${baseChatImagePath}/logo.webp" alt="Messenger Logo" />
<label for="channel">Enter channel name</label>
<input type="text" name="channel" placeholder="default_channel" value="default_channel" required />
<div class="form__checkbox">
<input type="checkbox" id="profanity" name="profanity" />
<label for="profanity">Profanity filter</label>
</div>
<button type="submit">Connect</button>
`;
menu.appendChild(channelChoiceForm);
return menu;
}
/**
* Creates the chat interface including message list, emoji picker, and input form.
* @returns {object} An object containing the message list element, input form element, and chat container.
*/
createChat () {
const chat = this.createChatContainer();
const messageListElement = this.createMessageList();
const emojiPickerElement = this.createEmojiPicker();
const inputFormElement = this.createInputForm();
chat.appendChild(messageListElement);
chat.appendChild(emojiPickerElement);
chat.appendChild(inputFormElement);
return {
messageListElement,
inputFormElement,
chat
};
}
/**
* Creates the chat container element.
* @returns {HTMLElement} The chat container element.
*/
createChatContainer () {
const chat = document.createElement('div');
chat.classList.add('container', 'chat');
return chat;
}
/**
* Creates the message list element.
* @returns {HTMLElement} The message list element.
*/
createMessageList () {
const messageListElement = document.createElement('div');
messageListElement.classList.add('messages');
return messageListElement;
}
/**
* Creates the emoji picker element.
* @returns {HTMLElement} The emoji picker element.
*/
createEmojiPicker () {
const emojiPicker = document.createElement('div');
emojiPicker.classList.add('emoji-picker');
const emojis = ['😀', '😂', '😍', '😎', '😭', '😡'];
emojis.forEach((emoji, index) => {
const emojiButton = document.createElement('div');
emojiButton.textContent = emoji;
emojiButton.classList.add('emoji-picker__button');
emojiButton.dataset.id = index;
emojiPicker.appendChild(emojiButton);
});
emojiPicker.addEventListener('click', ({ target }) => {
if (!target.classList.contains('emoji-picker__button')) return;
const inputField = this.body.querySelector('.input-field');
inputField.value += emojis[target.dataset.id];
inputField.dispatchEvent(new Event('input'));
});
return emojiPicker;
}
/**
* Creates the input form element for sending messages.
* @returns {HTMLElement} The input form element.
*/
createInputForm () {
const inputFormElement = document.createElement('form');
inputFormElement.id = 'message-form';
inputFormElement.classList.add('input-form');
const inputFieldElement = document.createElement('textarea');
inputFieldElement.classList.add('input-field');
inputFieldElement.name = 'message';
inputFieldElement.required = true;
const sendButton = document.createElement('button');
sendButton.type = 'submit';
sendButton.classList.add('send-btn');
sendButton.innerHTML = '<u>S</u>end';
sendButton.disabled = true;
inputFormElement.appendChild(inputFieldElement);
inputFormElement.appendChild(sendButton);
inputFieldElement.addEventListener('keydown', (event) => {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
inputFormElement.requestSubmit();
}
});
inputFieldElement.addEventListener('input', () => {
sendButton.disabled = !inputFieldElement.value.trim();
});
return inputFormElement;
}
/**
* Establishes a WebSocket connection to the chat server.
*/
connect () {
this.socket = new WebSocket('wss://courselab.lnu.se/message-app/socket');
this.socket.addEventListener('open', this.handleOpen.bind(this));
this.socket.addEventListener('message', this.handleMessage.bind(this));
this.socket.addEventListener('error', this.handleError);
this.socket.addEventListener('close', this.handleClose.bind(this));
window.addEventListener('beforeunload', this.closeConnection.bind(this));
}
/**
* Handles the WebSocket open event.
*/
handleOpen () {
console.log('Connection with the server established.');
const storedMessages = JSON.parse(localStorage.getItem(this.channel));
if (storedMessages) {
storedMessages.forEach((message) => {
this.messages.push(message);
const messageElement = this.createMessageElement(message);
this.messageListElement.appendChild(messageElement);
});
}
}
/**
* Scrolls the message list to the bottom.
*/
scrollToBottom () {
this.messageListElement.scrollTop = this.messageListElement.scrollHeight;
}
/**
* Handles incoming WebSocket messages.
* @param {MessageEvent} event - The message event.
*/
async handleMessage (event) {
const message = JSON.parse(event.data);
if (message.type !== 'heartbeat') {
if (openai && this.filterProfanity) {
const completion = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{
role: 'user',
content:
'Please review the message and respond strictly with "yes" if there is any' +
'inappropriate, offensive, or explicit language, including but not limited' +
'to slurs, sexual content, or abusive language. Otherwise, respond strictly' +
'with "no". Do not provide any other response. Here is the message:\n' +
message.data
}
]
});
if (completion.choices[0].message.content.toLowerCase() === 'yes') {
message.data = '[message removed due to inappropriate language]';
}
}
if (this.messages && this.messageListElement) {
this.messages.push(message);
localStorage.setItem(this.channel, JSON.stringify(this.messages));
const messageElement = this.createMessageElement(message);
this.messageListElement.appendChild(messageElement);
this.scrollToBottom();
}
}
}
/**
* Handles the WebSocket close event.
*/
handleClose () {
console.log('Connection closed.');
this.messages.push({
data: 'You are disconnected!',
type: 'notification',
username: 'The Server'
});
localStorage.setItem(this.channel, JSON.stringify(this.messages));
this.messages = [];
this.socket = null;
}
/**
* Handles WebSocket errors.
* @param {Event} error - The error event.
*/
handleError (error) {
console.error('Connection error:', error);
}
/**
* Closes the WebSocket connection.
* @param {Event} [event] - The event that triggered the closure.
*/
closeConnection (event) {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
if (event) {
event.preventDefault();
}
this.socket.close();
this.socket = null;
}
}
/**
* Gets the styles for the chat application.
* @returns {string} The styles as a string.
*/
getStyles () {
return (
super.getStyles() +
`
<style>
.container {
display: flex;
flex-flow: column nowrap;
min-width: inherit;
width: 100%;
min-height: inherit;
height: 100%;
position: relative;
}
.menu {
align-items: center;
justify-content: center;
}
.chat {
justify-content: space-between;
align-items: stretch;
}
.form {
display: flex;
flex-flow: column nowrap;
align-items: center;
justify-content: center;
gap: 0.5rem;
margin-bottom: 12rem;
}
.form img {
user-select: none;
pointer-events: none;
position: absolute;
bottom: -8%;
right: 0%;
width: 180px;
margin-bottom: 2rem;
opacity: 0.4;
z-index: -1;
}
.form__hint {
font-size: 1rem;
}
.form__button {
width: 100%;
}
.form__checkbox {
width: 100%;
display: flex;
flex-flow: row nowrap;
font-size: 0.8rem;
}
.form__checkbox input {
margin-left: 0;
}
.messages {
overflow-x: hidden;
overflow-y: auto;
flex: 1 1;
}
.messages .server-message,
.messages .username,
.messages .content {
margin: 0;
}
.messages .server-message {
color: #777;
}
.messages .content {
margin-left: 1rem;
}
.emoji-picker {
box-sizing: border-box;
display: flex;
flex-flow: row nowrap;
justify-content: space-around;
align-items: center;
height: 32px;
padding: 4px;
background: #d6dff7;
border-top-left-radius: 0.25rem;
border-top-right-radius: 0.25rem;
font-size: 1rem;
}
.emoji-picker__button {
user-select: none;
cursor: pointer;
}
.input-form {
flex: 0 0;
}
.input-field {
width: 100%;
height: 6em;
resize: none;
padding-right: 64px;
border-top: none;
border-bottom-left-radius: 0.25rem;
border-bottom-right-radius: 0.25rem;
vertical-align: middle;
overflow-y: scroll;
scrollbar-width: none;
-ms-overflow-style: none;
}
.input-field::-webkit-scrollbar {
display: none;
}
.input-field:focus-visible {
outline: none;
}
.send-btn {
width: 52px;
height: 48px;
position: absolute;
right: 9px;
bottom: 9px;
}
</style>`
);
}
}
customElements.define('chat-app', ChatApp);