99 lines
2.9 KiB
JavaScript

let data = {};
function fetchData() {
fetch('/api/data').then(r => r.json()).then(d => {
data = d;
renderTable();
});
}
function saveData() {
fetch('/api/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
}
function renderTable() {
const container = document.getElementById('attendance-table');
container.innerHTML = '';
const table = document.createElement('table');
// Header row
const thead = document.createElement('thead');
const headRow = document.createElement('tr');
headRow.appendChild(document.createElement('th')).innerText = 'Date';
data.players.forEach((name, i) => {
const th = document.createElement('th');
const input = document.createElement('input');
input.type = 'text';
input.value = name;
input.onchange = e => {
data.players[i] = e.target.value;
saveData();
renderTable();
};
th.appendChild(input);
headRow.appendChild(th);
});
// Guest column
const guestTh = document.createElement('th');
const guestInput = document.createElement('input');
guestInput.type = 'text';
guestInput.value = data.guest;
guestInput.onchange = e => {
data.guest = e.target.value;
saveData();
renderTable();
};
guestTh.appendChild(guestInput);
headRow.appendChild(guestTh);
thead.appendChild(headRow);
table.appendChild(thead);
// Body rows
const tbody = document.createElement('tbody');
data.dates.forEach((date, rowIdx) => {
const tr = document.createElement('tr');
// Date cell
const dateTd = document.createElement('td');
dateTd.innerText = date;
tr.appendChild(dateTd);
// Player attendance
[...data.players, data.guest].forEach((player, colIdx) => {
const td = document.createElement('td');
td.className = 'clickable';
const key = `${date}|${colIdx}`;
if (data.attendance[key]) {
td.innerText = 'Yes';
td.classList.add('yes');
} else {
td.innerText = '';
}
td.onclick = () => {
if (data.attendance[key]) {
delete data.attendance[key];
} else {
data.attendance[key] = true;
}
saveData();
renderTable();
};
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
container.appendChild(table);
}
document.getElementById('add-date').onclick = function() {
const date = prompt('Enter date (DD/MM/YY):');
if (date && !data.dates.includes(date)) {
data.dates.push(date);
saveData();
renderTable();
}
};
window.onload = fetchData;