mirror of
https://gitlab.com/animath/si/plateforme.git
synced 2025-06-21 09:18:23 +02:00
Initialize chat interface
Signed-off-by: Emmy D'Anello <emmy.danello@animath.fr>
This commit is contained in:
52
chat/static/chat.js
Normal file
52
chat/static/chat.js
Normal file
@ -0,0 +1,52 @@
|
||||
(async () => {
|
||||
// check notification permission
|
||||
// This is useful to alert people that they should do something
|
||||
await Notification.requestPermission()
|
||||
})()
|
||||
|
||||
/**
|
||||
* Display a new notification with the given title and the given body.
|
||||
* @param title The title of the notification
|
||||
* @param body The body of the notification
|
||||
* @param timeout The time (in milliseconds) after that the notification automatically closes. 0 to make indefinite. Default to 5000 ms.
|
||||
* @return Notification
|
||||
*/
|
||||
function showNotification(title, body, timeout = 5000) {
|
||||
let notif = new Notification(title, {'body': body, 'icon': "/static/tfjm.svg"})
|
||||
if (timeout)
|
||||
setTimeout(() => notif.close(), timeout)
|
||||
return notif
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
/**
|
||||
* Process the received data from the server.
|
||||
* @param data The received message
|
||||
*/
|
||||
function processMessage(data) {
|
||||
// TODO Implement chat protocol
|
||||
}
|
||||
|
||||
function setupSocket(nextDelay = 1000) {
|
||||
// Open a global websocket
|
||||
socket = new WebSocket(
|
||||
(document.location.protocol === 'https:' ? 'wss' : 'ws') + '://' + window.location.host + '/ws/chat/'
|
||||
)
|
||||
|
||||
// Listen on websockets and process messages from the server
|
||||
socket.addEventListener('message', e => {
|
||||
// Parse received data as JSON
|
||||
const data = JSON.parse(e.data)
|
||||
|
||||
processMessage(data)
|
||||
})
|
||||
|
||||
// Manage errors
|
||||
socket.addEventListener('close', e => {
|
||||
console.error('Chat socket closed unexpectedly, restarting…')
|
||||
setTimeout(() => setupSocket(2 * nextDelay), nextDelay)
|
||||
})
|
||||
}
|
||||
|
||||
setupSocket()
|
||||
})
|
Reference in New Issue
Block a user