/* 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])); const name = t => t ? esc(t.name) : 'TBD'; 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.live[0]}–${m.live[1]}` : 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(``); 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 ? `` : ''} ${!display && 'Notification' in window && Notification.permission === 'default' ? `` : ''}
`; } function renderCourts() { return `
${state.courts.map(c => { const m = c.match; if (c.status === 'paused') return `
Court ${c.court}
Paused
`; if (!m) return `
Court ${c.court}
Open
`; 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)}
`; }).join('')}
`; } 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} · ~${u.etaMin} min
`).join('')}
`; } function renderPools() { return `
${state.pools.map(p => `

Pool ${esc(p.id)}

${p.standings.map((r, i) => ``).join('')}
TeamWLPts+/−
${i + 1}. ${esc(r.name)}${r.decidedBy ? `*` : ''}${r.w}${r.l}${r.pf}–${r.pa}${r.pointDiff > 0 ? '+' : ''}${r.pointDiff}
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]) => ``).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 `
${labels}
${boxes}
`; } 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 ? esc(t.name) : `${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 ? esc(t.name) : `${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 => `
  1. ${esc(t.name)} (${t.players})
  2. `).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); })();