/* Courtside public board. Renders entirely from the state JSON embedded in the page,
then keeps it fresh over a WebSocket. No framework, no build step. */
(() => {
const app = document.getElementById('app');
let state = JSON.parse(document.getElementById('state').textContent);
const myTeam = app.dataset.team || null;
const display = app.dataset.display === '1';
const seenAlerts = new Set();
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
// every team name on the board links to that team's page (schedule, record, next match)
const teamHref = t => `/t/${state.slug}/teams/${encodeURIComponent(t.id)}`;
const name = t => t ? `${esc(t.name)} ` : 'TBD ';
const clock = ms => new Date(ms).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
const isMine = m => myTeam && (m.a?.id === myTeam || m.b?.id === myTeam);
const phaseLabel = { checkin: 'Registration open', closed: 'Registration closed', live: 'Live', final: 'Final' };
const score = m => m.status === 'final' ? m.sets.map(s => `${s[0]}–${s[1]}`).join(', ')
: m.status === 'forfeit' ? 'forfeit' : m.live ? [...(m.liveSets ?? []), m.live].map(s => `${s[0]}–${s[1]}`).join(', ') : m.status === 'live' ? '0–0' : '';
// score from one team's point of view (their points first)
const scoreFor = (m, teamId) => {
const flip = m.b?.id === teamId;
const pair = ([a, b]) => flip ? `${b}–${a}` : `${a}–${b}`;
if (m.status === 'final') return m.sets.map(pair).join(', ');
if (m.status === 'forfeit') return 'forfeit';
if (m.live) return [...(m.liveSets ?? []), m.live].map(pair).join(', ');
return m.status === 'live' ? '0–0' : '';
};
const rulesLine = r => `${r.teamSize}s · to ${r.pointsTo}, win by ${r.winBy}${r.cap ? `, cap ${r.cap}` : ''}${r.bestOf > 1 ? `, best of ${r.bestOf}` : ''}`;
function render() {
const s = state;
const mine = myTeam ? [...s.teams, ...s.withdrawn].find(t => t.id === myTeam) : null;
const parts = [];
if (!display) parts.push(`${esc(s.date ?? '')} · ${phaseLabel[s.phase]}
${esc(s.name)} ${rulesLine(s.rules)}${s.avgMatchMin ? ` · matches running ~${s.avgMatchMin} min` : ''}
`);
else parts.push(`
${esc(s.name)} ${phaseLabel[s.phase]} `);
if (s.banner) parts.push(`${esc(s.banner)}
`);
if (s.champion) parts.push(`Champion
${esc(s.champion)} `);
if (mine) parts.push(renderMyTeam(mine));
if (s.phase === 'live') { parts.push(renderCourts()); parts.push(renderUpNext()); }
if (s.phase === 'closed' && !s.pools.length) parts.push(`Schedule coming Registration is closed with ${s.teams.length} teams. The organizer is generating pools now; this page will update on its own.
`);
if (s.bracket.length) parts.push(renderBracket());
if (s.pools.length) parts.push(renderPools());
if (!s.pools.length && !s.bracket.length) parts.push(renderRoster());
if (s.withdrawn.length && !display) parts.push(`Withdrawn: ${s.withdrawn.map(t => esc(t.name)).join(', ')}
`);
app.innerHTML = parts.join('');
fitBracket();
notifyMine();
}
function renderMyTeam(t) {
const s = state;
const my = [...s.pools.flatMap(p => p.matches), ...s.bracket].filter(isMine);
const live = my.find(m => m.status === 'live');
const next = s.upNext.find(isMine) ?? my.find(m => m.status === 'on_deck' || (m.status === 'pending' && m.a && m.b));
const played = my.filter(m => m.status === 'final' || m.status === 'forfeit');
const w = played.filter(m => m.winner === t.id).length;
let now;
if (t.status === 'withdrawn') now = `Your team has withdrawn from the tournament.
`;
else if (live) now = `You're on Court ${live.court} now vs ${name(live.a?.id === t.id ? live.b : live.a)}
`;
else if (next) now = `Next: vs ${name(next.a?.id === t.id ? next.b : next.a)}${next.court ? ` on Court ${next.court} ` : ''}${next.etaMin != null ? ` in about ${next.etaMin} min ` : ''}
`;
else if (s.phase === 'final') now = `Tournament over. Thanks for playing.
`;
else if (s.phase === 'live') now = `No match scheduled yet. Waiting on results from other courts.
`;
else now = `Waiting for play to start.
`;
return `Your team
${esc(t.name)} ${now}${played.length ? `Record ${w}–${played.length - w}` : 'No results yet'}${t.poolId ? ` · Pool ${esc(t.poolId)}` : ''}
${my.length ? `${my.map(m => `${m.stage === 'pool' ? `Pool ${m.round}` : (m.label ?? `Bracket R${m.round}`)} vs ${name(m.a?.id === t.id ? m.b : m.a)} ${scoreFor(m, t.id) || (m.court ? `Court ${m.court}` : '')}${m.status === 'final' || m.status === 'forfeit' ? (m.winner === t.id ? ' W' : ' L') : ''} `).join('')} ` : ''}
${!display && 'Notification' in window && Notification.permission === 'default' ? `Alert me when we're up ` : ''}
`;
}
function renderCourts() {
return `${state.courts.map(c => {
const m = c.match;
if (c.status === 'paused') return ``;
if (!m) return ``;
const avg = state.avgMatchMin;
const elapsed = m.startedAt ? Math.max(0, Math.round((Date.now() - m.startedAt) / 60000)) : null;
const left = avg != null && elapsed != null ? Math.max(0, avg - elapsed) : null;
const finish = avg != null && m.startedAt ? clock(Math.max(Date.now(), m.startedAt + avg * 60000)) : null;
const timing = avg != null ? `avg game ${avg} min${elapsed != null ? ` · ${elapsed} min played` : ''}${finish ? ` · est. finish ~${finish}${left ? ` (${left} min)` : ''}` : ''}` : '';
return `Court ${c.court} · ${m.stage === 'pool' ? `Pool ${esc(m.a && state.teams.find(t => t.id === m.a.id)?.poolId || '')} R${m.round}` : (m.label ?? `Bracket R${m.round}`)}
${name(m.a)}
${score(m) || '0–0'}
${name(m.b)}
${timing ? `
${timing}
` : ''}
${nextForCourt(c.court)}
`;
}).join('')} `;
}
// the first queued match predicted for this court, with the clock time it should be ready
function nextForCourt(courtNo) {
const u = state.upNext.find(x => x.court === courtNo);
if (!u) return '';
const ready = clock(state.generatedAt + u.etaMin * 60000);
return `Next up ${name(u.a)} vs ${name(u.b)} ready ~${ready}
`;
}
function renderUpNext() {
if (!state.upNext.length) return '';
return `Up next
${state.upNext.map((u, i) => `${i === 0 ? 'On deck' : 'Then'} ${name(u.a)} vs ${name(u.b)} Court ${u.court} · ~${clock(state.generatedAt + u.etaMin * 60000)} (${u.etaMin} min)
`).join('')} `;
}
function renderPools() {
return `${state.pools.map(p => `Pool ${esc(p.id)}
Team W L Pts +/−
${p.standings.map((r, i) => `${i + 1}. ${name({ id: r.teamId, name: r.name })}${r.decidedBy ? `* ` : ''} ${r.w} ${r.l} ${r.pf}–${r.pa} ${r.pointDiff > 0 ? '+' : ''}${r.pointDiff} `).join('')}
Matches ${p.matches.map(m => `R${m.round} ${name(m.a)} ${score(m) || (m.court ? `C${m.court}` : '·')} ${name(m.b)} `).join('')}
`).join('')} `;
}
// ---- bracket: a real tree with connector lines, plus a list view for small screens ----
// default: full tree on wide screens, scaled-to-fit on phones; the viewer's choice is remembered
let bracketView = window.innerWidth < 700 ? 'fit' : 'tree';
try { bracketView = localStorage.getItem('courtside.bracketView') || bracketView; } catch {}
const BOX_W = 176, BOX_H = 58, COL_GAP = 44, ROW_GAP = 14;
function renderBracket() {
const isDouble = state.bracket.some(m => m.stage === 'losers');
const toggle = display ? '' : `${[['tree', 'Bracket'], ['fit', 'Fit to screen'], ['list', 'List']].map(([v, l]) => `${l} `).join('')}
`;
const stages = [['bracket', isDouble ? 'Winners bracket' : 'Bracket'], ['losers', 'Losers bracket'], ['final', 'Finals']];
const body = stages.map(([stage, title]) => {
const ms = state.bracket.filter(m => m.stage === stage && !(m.conditional && !m.a));
if (!ms.length) return '';
return `${isDouble ? `
${title} ` : ''}${bracketView === 'list' ? bracketList(stage, ms) : bracketTree(stage, ms)}`;
}).join('');
return `
${isDouble ? 'Double elimination' : 'Bracket'} ${toggle}${body}${bracketView === 'tree' && !display ? 'Swipe sideways to see later rounds.
' : ''} `;
}
function bracketTree(stage, ms) {
const third = ms.find(m => m.label === '3rd place');
const tree = ms.filter(m => m !== third);
const rounds = [...new Set(tree.map(m => m.round))].sort((a, b) => a - b);
const pos = new Map();
const feedersOf = m => tree.filter(f => f.feeds === m.id);
rounds.forEach((r, ri) => {
const inRound = tree.filter(m => m.round === r).sort((a, b) => (a.slot ?? 0) - (b.slot ?? 0));
const x = ri * (BOX_W + COL_GAP);
let cursor = 0;
inRound.forEach(m => {
const fs = feedersOf(m).map(f => pos.get(f.id)).filter(Boolean);
let y;
if (fs.length) y = fs.reduce((a, p) => a + p.y, 0) / fs.length;
else y = cursor;
y = Math.max(y, cursor);
pos.set(m.id, { x, y });
cursor = y + BOX_H + ROW_GAP;
});
});
let height = Math.max(...[...pos.values()].map(p => p.y)) + BOX_H;
let width = rounds.length * (BOX_W + COL_GAP) - COL_GAP;
if (third) { const f = pos.get(tree.find(m => m.round === rounds.at(-1))?.id) ?? { x: 0, y: 0 }; pos.set(third.id, { x: f.x, y: height + ROW_GAP * 2 }); height += ROW_GAP * 2 + BOX_H; }
const paths = tree.filter(m => m.feeds && pos.has(m.feeds)).map(m => {
const a = pos.get(m.id), b = pos.get(m.feeds);
const x1 = a.x + BOX_W, y1 = a.y + BOX_H / 2, x2 = b.x, y2 = b.y + BOX_H / 2, xm = x1 + COL_GAP / 2;
const hot = m.winner && isMineId(m.winner);
return ` `;
}).join('');
const boxes = [...pos.entries()].map(([id, p]) => matchBox(ms.find(m => m.id === id), p)).join('');
const labels = rounds.map((r, ri) => `${roundName(stage, r, rounds.length, tree)}
`).join('');
return ``;
}
function matchBox(m, p) {
const row = (t, side) => {
const won = m.winner && t && m.winner === t.id;
const pts = m.sets[0] ? m.sets.map(s => s[side]).join(' ') : (m.live && m.status === 'live' ? m.live[side] : '');
return `${t ? name(t) : `${feedLabel(m, side)} `} ${pts}
`;
};
const tag = m.status === 'live' ? `Court ${m.court} ` : m.status === 'on_deck' ? `On deck${m.court ? ` · C${m.court}` : ''} ` : m.status === 'forfeit' ? 'Forfeit ' : m.label ? `${esc(m.label)} ` : '';
return `${row(m.a, 0)}${row(m.b, 1)}${tag}
`;
}
function feedLabel(m, side) {
// what fills this slot later: winner/loser of which match
const wantSide = side === 0 ? 'A' : 'B';
const w = state.bracket.find(f => f.feeds === m.id && f.feedsSide === wantSide);
if (w) return `W ${shortRef(w)}`;
const l = state.bracket.find(f => f.loserFeeds === m.id && f.loserFeedsSide === wantSide);
if (l) return `L ${shortRef(l)}`;
return 'TBD';
}
const shortRef = m => m.stage === 'losers' ? `LB${m.round}.${m.slot}` : m.stage === 'final' ? 'final' : `R${m.round}.${m.slot}`;
function bracketList(stage, ms) {
const rounds = [...new Set(ms.map(m => m.round))].sort((a, b) => a - b);
return rounds.map(r => `${roundName(stage, r, rounds.length, ms)}
${ms.filter(m => m.round === r).map(m => `
${['a', 'b'].map((k, i) => { const t = m[k]; const won = m.winner && t && m.winner === t.id; return `
${t ? name(t) : `${feedLabel(m, i)} `} ${m.sets[0] ? m.sets.map(s => s[i]).join(' ') : (m.live && m.status === 'live' ? m.live[i] : '')}
`; }).join('')}${m.status === 'live' ? `
Court ${m.court} ` : m.status === 'on_deck' ? `
On deck${m.court ? ` · C${m.court}` : ''} ` : m.status === 'forfeit' ? '
Forfeit ' : m.label ? `
${esc(m.label)} ` : ''}
`).join('')}
`).join('');
}
const isMineId = id => myTeam && id === myTeam;
function fitBracket() {
if (bracketView !== 'fit') return;
document.querySelectorAll('.btree-scroll').forEach(sc => {
const tree = sc.firstElementChild;
const w = parseFloat(tree.style.width), h = parseFloat(tree.style.height);
const scale = Math.min(1, (sc.clientWidth - 2) / w);
tree.style.transform = `scale(${scale})`;
tree.style.transformOrigin = '0 0';
sc.style.height = `${h * scale}px`;
});
}
document.addEventListener('click', e => {
const b = e.target.closest('[data-bview]');
if (!b) return;
bracketView = b.dataset.bview;
try { localStorage.setItem('courtside.bracketView', bracketView); } catch {}
render();
});
window.addEventListener('resize', fitBracket);
function roundName(stage, r, total, ms) {
if (stage === 'final') return r === 1 ? 'Grand final' : 'Bracket reset';
if (stage === 'losers') return `LB round ${r}`;
const left = total - r;
const inRound = ms.filter(m => m.round === r && m.label !== '3rd place').length;
return left === 0 ? 'Final' : left === 1 ? 'Semifinals' : left === 2 ? 'Quarterfinals' : `Round of ${inRound * 2}`;
}
function renderRoster() {
return `Teams (${state.teams.length}) ${state.teams.map(t => `${esc(t.name)} (${t.players}) `).join('')} `;
}
// ---- alerts for the team page ----
function notifyMine() {
if (!myTeam) return;
for (const a of state.recentAlerts) {
const key = `${a.kind}:${a.match ?? a.at}`;
if (seenAlerts.has(key)) continue;
seenAlerts.add(key);
if (!(a.kind === 'broadcast' || a.teams.includes(myTeam))) continue;
if (Date.now() - a.at > 10 * 60 * 1000) continue; // stale on first load
toast(a.text);
try { navigator.vibrate?.([200, 100, 200]); } catch {}
if ('Notification' in window && Notification.permission === 'granted') { try { new Notification('Courtside', { body: a.text, tag: key }); } catch {} }
}
}
function toast(text) {
const el = document.createElement('div'); el.className = 'toast'; el.textContent = text;
document.body.appendChild(el); setTimeout(() => el.remove(), 8000);
}
document.addEventListener('click', e => {
if (e.target.id === 'notify') Notification.requestPermission().then(render);
});
// first paint: skip toasts for alerts that already happened
for (const a of state.recentAlerts) seenAlerts.add(`${a.kind}:${a.match ?? a.at}`);
// ---- live updates ----
let retry = 1000;
function connect() {
const ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws/${state.slug}`);
ws.onmessage = ev => { state = JSON.parse(ev.data); retry = 1000; render(); };
ws.onclose = () => { setTimeout(connect, retry); retry = Math.min(retry * 2, 15000); };
ws.onerror = () => ws.close();
}
render();
connect();
// belt and braces: a full refresh every 2 minutes in case a proxy drops the socket silently
setInterval(() => fetch(`/t/${state.slug}/state.json`).then(r => r.json()).then(s => { state = s; render(); }).catch(() => {}), 120000);
if (display) setInterval(() => document.documentElement.scrollTo({ top: (Date.now() / 1000 | 0) % 2 ? 0 : document.body.scrollHeight, behavior: 'smooth' }), 15000);
})();