'use strict'; const byId = id => document.getElementById(id); const letters = ['A', 'B', 'C', 'D']; const route = new URL(location.href); const code = (route.searchParams.get('room') || '').trim().toUpperCase(); const validCode = /^[2-9A-HJ-NP-Z]{16}$/; const isHost = route.searchParams.get('host') === '1'; const role = isHost ? 'host' : 'player'; const roomPath = '/api/rooms/' + encodeURIComponent(code); const sessionKey = (roomCode, kind) => 'oops.rooms.' + roomCode + '.' + kind; const roomUrl = (roomCode, host = false) => { const url = new URL('/rooms.html', location.origin); url.searchParams.set('room', roomCode); if (host) url.searchParams.set('host', '1'); return url.href; }; function stores() { const available = []; for (const name of ['localStorage', 'sessionStorage']) { try { available.push(window[name]); } catch {} } return available; } function readSaved(key) { for (const storage of stores()) { try { const value = storage.getItem(key); if (value) return value; } catch {} } return null; } function save(key, value) { for (const storage of stores()) { try { storage.setItem(key, value); return; } catch {} } throw new Error('Allow browser storage to join a room and keep your place when you refresh.'); } function forget(key) { for (const storage of stores()) { try { storage.removeItem(key); } catch {} } } function checkStorage() { const key = sessionKey('test', 'storage'); save(key, '1'); forget(key); } function show(id, visible) { byId(id).hidden = !visible; } function write(id, value) { const element = byId(id); if (element.textContent !== value) element.textContent = value; } function notice(id, message = '') { write(id, message); show(id, Boolean(message)); } function view(id) { for (const panel of ['landing', 'join', 'room']) show(panel, panel === id); } async function request(path, {method = 'GET', token, body} = {}) { if (window.OopsPeerRooms) { return window.OopsPeerRooms.request(path, {method, token, body}); } const headers = {Accept: 'application/json'}; if (token) headers.Authorization = 'Bearer ' + token; if (body) headers['Content-Type'] = 'application/json'; const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 12000); try { const res = await fetch(path, { method, headers, body: body ? JSON.stringify(body) : undefined, cache: 'no-store', signal: controller.signal }); let data; try { data = await res.json(); } catch {} if (!res.ok || data === undefined) { const error = new Error(typeof data?.error === 'string' ? data.error : 'The game server could not complete this request.'); error.status = res.status; throw error; } return data; } catch (error) { if (error.name === 'AbortError' || error instanceof TypeError) { throw new Error('The game server could not be reached. Check your connection.'); } throw error; } finally { clearTimeout(timeout); } } let rounds = null; let token = readSaved(sessionKey(code, role)); let room = null; let epoch = 0; let busy = false; let reading = false; let pollTimer; let pollDelay = 1200; function schedule(delay) { clearTimeout(pollTimer); if (token) pollTimer = setTimeout(refresh, delay); } async function loadRounds() { const data = await request('/api/rounds'); if (!Array.isArray(data) || !data.length) throw new Error('The round list could not be loaded.'); rounds = data; } async function refresh() { if (!token || busy || reading) return; const ticket = epoch; reading = true; try { if (!rounds) await loadRounds(); const snapshot = await request(roomPath, {token}); if (ticket !== epoch) return; render(snapshot); notice('connection'); pollDelay = 1200; } catch (error) { if (ticket !== epoch) return; if ([401, 403, 404, 410].includes(error.status)) { token = null; forget(sessionKey(code, role)); if (isHost) { view('join'); byId('join-form').hidden = true; notice('error', 'This host session is unavailable. Open the host link on the device that created the room.'); const link = byId('player-tab'); link.href = roomUrl(code); link.textContent = 'Open the player link'; byId('join').append(link); } else { view('join'); write('join-code', code); notice('error', error.status === 404 || error.status === 410 ? 'This room is unavailable. Check the code with the host.' : 'Your player session has expired. Enter your name to rejoin.'); } notice('connection'); return; } notice('connection', 'Reconnecting to the game… ' + error.message); pollDelay = Math.min(pollDelay * 2, 6000); } finally { reading = false; schedule(pollDelay); } } async function action(button, run) { if (busy) return; busy = true; epoch++; clearTimeout(pollTimer); notice('error'); button.disabled = true; if (room) updateButtons(); try { await run(); } catch (error) { notice('error', error.message); } finally { busy = false; button.disabled = false; if (room) updateButtons(); schedule(0); } } byId('create-room').onclick = event => action(event.currentTarget, async () => { checkStorage(); const created = await request('/api/rooms', {method: 'POST', body: {}}); save(sessionKey(created.code, 'host'), created.hostToken); location.assign(roomUrl(created.code, true)); }); byId('find-form').onsubmit = event => { event.preventDefault(); const input = byId('room-code'); const entered = input.value.trim().toUpperCase(); if (!validCode.test(entered)) { notice('error', 'Enter the 16-character code from the host.'); input.focus(); return; } location.assign(roomUrl(entered)); }; byId('join-form').onsubmit = event => { event.preventDefault(); action(byId('join-room'), async () => { const name = byId('player-name').value.trim(); if (!name) throw new Error('Enter the name you want on the scoreboard.'); const pendingKey = sessionKey(code, 'pending'); let joinKey = readSaved(pendingKey); if (!joinKey) { joinKey = Array.from(crypto.getRandomValues(new Uint8Array(24)), byte => byte.toString(16).padStart(2, '0')).join(''); save(pendingKey, joinKey); } save(sessionKey(code, 'pending-name'), name); const joined = await request(roomPath + '/players', {method: 'POST', body: {name, joinKey}}); save(sessionKey(code, 'player'), joined.playerToken); token = joined.playerToken; forget(pendingKey); forget(sessionKey(code, 'pending-name')); view(null); notice('connection', 'Connecting to the room…'); }); }; byId('copy-invite').onclick = async () => { const input = byId('invite-url'); try { await navigator.clipboard.writeText(input.value); write('copy-status', 'Player link copied.'); } catch { input.focus(); input.select(); write('copy-status', 'Select Copy to share the highlighted link.'); } }; function vote(choice) { if (busy || isHost || room.phase !== 'voting') return; const roundIndex = room.roundIndex; action(byId('choices').children[choice], async () => { render(await request(roomPath + '/vote', {method: 'POST', token, body: {roundIndex, choice}})); notice('connection'); }); } byId('advance').onclick = () => { if (!room || !isHost || room.phase === 'finished') return; const {roundIndex, phase} = room; action(byId('advance'), async () => { render(await request(roomPath + '/advance', {method: 'POST', token, body: {roundIndex, phase}})); notice('connection'); }); }; let choiceKey; function renderChoices(round) { const voting = room.phase === 'voting'; write('question', voting ? round.question : ''); const key = voting ? String(room.roundIndex) : ''; if (choiceKey !== key) { choiceKey = key; const choices = byId('choices'); choices.replaceChildren(); if (voting) { round.options.forEach((option, index) => { const item = document.createElement(isHost ? 'div' : 'button'); item.className = 'choice'; if (!isHost) { item.type = 'button'; item.onclick = () => vote(index); } const letter = document.createElement('b'); letter.textContent = letters[index]; const label = document.createElement('span'); label.textContent = option; item.append(letter, label); choices.append(item); }); } } if (!isHost && voting) { Array.from(byId('choices').children).forEach((element, index) => { element.setAttribute('aria-pressed', String(room.myVote === index)); }); } } let scoreKey; function renderScores() { const players = [...room.players].sort((a, b) => b.score - a.score); const key = JSON.stringify(players); if (scoreKey === key) return; scoreKey = key; byId('scores').replaceChildren(...players.map(player => { const row = document.createElement('li'); row.className = 'score-row'; const name = document.createElement('span'); name.textContent = player.name; const score = document.createElement('strong'); score.textContent = player.score + ' pts'; row.append(name, score); return row; })); show('no-players', !players.length); } const clip = byId('clip'); let mediaKey = ''; function mediaNotice(message = '', retry = false) { write('media-status', message); show('media-notice', Boolean(message)); show('retry-media', retry); } async function renderMedia(round, force = false) { const active = !['lobby', 'finished'].includes(room.phase); const part = room.phase === 'result' ? 'reveal' : 'setup'; const key = active ? room.roundIndex + '/' + part : ''; show('media', active); if (mediaKey === key && !force) return; mediaKey = key; clip.oncanplay = null; clip.onerror = null; clip.pause(); clip.removeAttribute('src'); clip.load(); mediaNotice(); if (!active) return; clip.poster = round.poster; write('task', round.task); const source = byId('source'); source.textContent = round.sourceTitle; source.href = round.sourceUrl; write('source-credit', round.shortCredit || ''); mediaNotice('Loading clip…'); try { const url = await window.ClipStore.load(round[part]); if (key !== mediaKey) return; clip.onerror = () => { if (key === mediaKey) mediaNotice('The clip could not play.', true); }; clip.oncanplay = () => { if (key === mediaKey) mediaNotice(); }; clip.src = url; clip.muted = true; clip.playbackRate = round[part + 'Rate'] || 1; clip.load(); try { await clip.play(); } catch (error) { if (key === mediaKey && error.name !== 'AbortError') { mediaNotice(error.name === 'NotAllowedError' ? 'Press play to watch the clip.' : 'The clip could not play.', error.name !== 'NotAllowedError'); } } } catch { if (key === mediaKey) mediaNotice('The clip could not load. Check your connection.', true); } } byId('retry-media').onclick = () => renderMedia(rounds[room.roundIndex], true); function updateButtons() { byId('advance').disabled = busy; for (const button of byId('choices').querySelectorAll('button')) button.disabled = busy; } function render(snapshot) { room = snapshot; byId('room').dataset.phase = room.phase; byId('room').dataset.role = role; const round = rounds[room.roundIndex]; const active = !['lobby', 'finished'].includes(room.phase); const lastRound = room.roundIndex === rounds.length - 1; const phase = room.phase; view('room'); write('room-pin', code); write('identity', isHost ? 'Host view' : 'Playing as ' + room.myName); write('round-label', active ? 'Round ' + (room.roundIndex + 1) + ' of ' + rounds.length : 'Live room'); write('round-title', active ? round.title : phase === 'lobby' ? 'The lobby.' : 'Final scores.'); show('invite', isHost && phase !== 'finished'); show('host-online', Boolean(window.OopsPeerRooms) && isHost); const invite = roomUrl(code); if (byId('invite-url').value !== invite) { byId('invite-url').value = invite; byId('player-tab').href = invite; } const titles = { lobby: 'Waiting for the game', setup: 'Watch the setup', voting: isHost ? 'Voting is open' : 'Make your prediction', result: 'The reveal', finished: 'Game complete' }; const descriptions = { lobby: isHost ? 'Share the player link, then start when everyone is here.' : 'You’re in. The first clip starts when the host is ready.', setup: isHost ? 'Open voting when everyone has seen the setup.' : 'Watch closely. The host will open voting.', voting: isHost ? 'Reveal the answer when everyone has had a chance to vote.' : 'Tap an answer before the host reveals the outcome.', result: isHost ? 'Each correct prediction earns two points.' : 'The scoreboard includes this round.', finished: 'The highest score wins. Players who tie share the win.' }; write('phase-title', titles[phase]); write('phase-copy', descriptions[phase]); renderChoices(round); let status = ''; if (!isHost && Number.isInteger(room.myVote) && phase === 'voting') { status = 'Your vote is ' + letters[room.myVote] + '. You can change it until the reveal.'; } else if (!isHost && phase === 'result') { status = Number.isInteger(room.myVote) ? 'You picked ' + letters[room.myVote] + '. ' + (room.myVote === round.answerIndex ? '+2 points.' : '0 points this round.') : 'You didn’t vote this round.'; } notice('vote-status', status); const votingCounts = phase === 'voting' || phase === 'result'; show('vote-count', votingCounts); if (votingCounts) write('vote-count', room.votesCast + ' of ' + room.playerCount + ' voted'); show('result', phase === 'result'); if (phase === 'result') write('correct-answer', letters[round.answerIndex] + '. ' + (round.answer || round.options[round.answerIndex])); const nextLabels = {lobby: 'Start first round', setup: 'Open voting', voting: 'Reveal answer', result: lastRound ? 'See final scores' : 'Next round'}; show('advance', isHost && phase !== 'finished'); if (phase !== 'finished') write('advance', nextLabels[phase]); show('new-game', phase === 'finished'); renderScores(); renderMedia(round); updateButtons(); } function start() { if (!code) { view('landing'); loadRounds().then(() => { byId('hero-image').src = rounds[0].poster; show('hero', true); }).catch(() => {}); return; } if (!validCode.test(code)) { view('landing'); notice('error', 'That room code is invalid. Enter the code from your host.'); return; } write('join-code', code); if (token) { notice('connection', 'Connecting to the room…'); refresh(); } else if (isHost) { location.replace(roomUrl(code)); } else { byId('player-name').value = readSaved(sessionKey(code, 'pending-name')) || ''; view('join'); } } document.addEventListener('visibilitychange', () => { if (!document.hidden) schedule(0); }); window.addEventListener('online', () => schedule(0)); start();