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

57 lines
1.2 KiB
JavaScript
Raw Normal View History

2023-12-12 04:04:46 -05:00
import AbstractView from "./AbstractView.js";
2023-11-27 08:35:11 -05:00
2023-12-12 04:04:46 -05:00
export default class extends AbstractView {
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-30 10:36:21 -05:00
let url = `ws://${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">
2023-11-30 10:36:21 -05:00
<input type="text" name="message" placeholder="message"/>
2023-11-27 08:35:11 -05:00
</form>
<div id="messages">
</div>
`;
}
}