ft_transcendence/frontend/static/js/views/Chat.js

57 lines
1.2 KiB
JavaScript
Raw Normal View History

2023-11-30 07:05:46 -05:00
import AbstractAuthentifiedView from "./AbstractAuthentifiedView.js";
2023-11-27 08:35:11 -05:00
2023-11-30 07:05:46 -05:00
export default class extends AbstractAuthentifiedView {
2023-11-27 08:35:11 -05:00
constructor(params) {
2023-11-30 07:05:46 -05:00
super(params, "Chat");
2023-11-27 08:35:11 -05:00
2023-11-29 13:20:12 -05:00
let url = `wss://${window.location.host}/ws/socket-server/`
2023-11-27 08:35:11 -05:00
this.chatSocket = new WebSocket(url)
this.chatSocket.onmessage = function(e){
let data = JSON.parse(e.data)
console.log('Data:', data)
2023-11-27 09:10:06 -05:00
if (data.type === 'chat') {
let messages = document.getElementById('messages')
2023-11-27 17:31:31 -05:00
let username = data.username === null || data.username.length <= 0 ? "NoName" : data.username;
2023-11-27 09:10:06 -05:00
messages.insertAdjacentHTML('beforeend', `
2023-11-27 09:47:00 -05:00
<div><p>${username}: ${data.message}</p></div>
2023-11-27 09:10:06 -05:00
`)
}
2023-11-27 08:35:11 -05:00
}
}
async postInit() {
let form = document.getElementById('form')
form.addEventListener('submit', (e)=> {
e.preventDefault()
let message = e.target.message.value
this.chatSocket.send(JSON.stringify({
'message':message
}))
form.reset()
})
2023-11-27 09:47:00 -05:00
2023-11-27 08:35:11 -05:00
}
2023-11-27 15:59:41 -05:00
async leavePage() {
this.chatSocket.close();
}
2023-11-27 08:35:11 -05:00
async getHtml() {
return `
<h1>Chat</h1>
<form id="form">
<input type="text" name="message" />
</form>
<div id="messages">
</div>
`;
}
}