plateforme-tfjm2/draw/static/draw.js

73 lines
2.5 KiB
JavaScript

const tournaments = JSON.parse(document.getElementById('tournaments_list').textContent)
const sockets = {}
const messages = document.getElementById('messages')
document.addEventListener('DOMContentLoaded', () => {
if (document.location.hash) {
document.querySelectorAll('button[data-bs-toggle="tab"]').forEach(elem => {
if ('#' + elem.innerText.toLowerCase() === document.location.hash.toLowerCase()) {
elem.click()
}
})
}
document.querySelectorAll('button[data-bs-toggle="tab"]').forEach(
elem => elem.addEventListener(
'click', () => document.location.hash = '#' + elem.innerText.toLowerCase()))
for (let tournament of tournaments) {
let socket = new WebSocket(
'ws://' + window.location.host + '/ws/draw/' + tournament.id + '/'
)
sockets[tournament.id] = socket
function addMessage(message, type, timeout = 0) {
const wrapper = document.createElement('div')
wrapper.innerHTML = [
`<div class="alert alert-${type} alert-dismissible" role="alert">`,
`<div>${message}</div>`,
'<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
].join('\n')
messages.append(wrapper)
if (timeout)
setTimeout(() => wrapper.remove(), timeout)
}
function draw_start(data) {
document.getElementById(`banner-not-started-${tournament.id}`).classList.add('d-none')
document.getElementById(`draw-content-${tournament.id}`).classList.remove('d-none')
}
socket.addEventListener('message', e => {
const data = JSON.parse(e.data)
console.log(data)
switch (data.type) {
case 'alert':
addMessage(data.message, data.alert_type)
break
case 'draw_start':
draw_start(data)
}
})
socket.addEventListener('close', e => {
console.error('Chat socket closed unexpectedly')
})
socket.addEventListener('open', e => {})
document.getElementById('format-form-' + tournament.id)
.addEventListener('submit', function (e) {
e.preventDefault()
socket.send(JSON.stringify({
'type': 'start_draw',
'fmt': document.getElementById('format-' + tournament.id).value
}))
})
}
})