// App controller: loads data, keeps the event log in sync with the server, routes between views. // // Every user action becomes an event ({id, t, type, ...}). Events go to a local outbox first // (localStorage), are applied immediately, and are flushed to the server in the background, // so a pick made on a flaky phone connection is never lost. Ratings are always recomputed by // replaying server events (in server order) followed by not-yet-acknowledged local ones. import { replay, ranking, pairKey } from './elo.js'; import { nextPair } from './pairing.js'; import { DEFAULT_SETTINGS, shortName } from './metrics.js'; import { html, toast, newId, local, ICONS } from './ui.js'; import * as duelView from './views/duel.js'; import * as rankView from './views/rank.js'; import * as schoolView from './views/school.js'; import * as triageView from './views/triage.js'; import * as settingsView from './views/settings.js'; class ApiError extends Error { constructor(status, message) { super(message); this.status = status; } } async function api(path, { method = 'GET', body } = {}) { let res; try { res = await fetch(path, { method, credentials: 'same-origin', headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body), }); } catch { throw new ApiError(0, 'offline'); } const data = await res.json().catch(() => null); if (!res.ok) throw new ApiError(res.status, data?.error ?? res.statusText); return data; } const ROUTES = { '': duelView, rank: rankView, triage: triageView, settings: settingsView, school: schoolView, }; const app = { config: null, data: null, byCode: new Map(), bySlug: new Map(), serverEvents: [], seq: 0, outbox: local.get('outbox', []), notes: {}, settings: { ...DEFAULT_SETTINGS }, state: null, ctx: null, recent: local.get('recent', []), pair: local.get('pair', null), positions: new Map(), flushing: false, retryDelay: 2000, lastRoute: null, /* ---------- derived state ---------- */ recompute() { const known = new Set(this.serverEvents.map((e) => e.id)); this.outbox = this.outbox.filter((e) => !known.has(e.id)); const events = [...this.serverEvents, ...this.outbox]; const elo = { initial: this.config.elo.initial, kMax: this.config.elo.kMax, kMin: this.config.elo.kMin }; this.state = replay(events, this.data.schools.map((s) => s.code), elo); this.positions = new Map(ranking(this.state.stats).map((s, i) => [s.code, i + 1])); this.ctx = { settings: this.settings, data: this.data }; }, rankOf(code) { return this.positions.get(code) ?? null; }, currentPair() { const ok = (c) => this.state.stats.get(c) && !this.state.stats.get(c).dropped; if (!(this.pair && this.pair.length === 2 && this.pair[0] !== this.pair[1] && this.pair.every(ok))) { this.pair = nextPair(this.state.stats, { mode: this.settings.pairing, recent: this.recent, pairCounts: this.state.pairCounts, }); local.set('pair', this.pair); } return this.pair; }, /* ---------- actions ---------- */ record(fields) { const ev = { id: newId(), t: new Date().toISOString(), ...fields }; this.outbox.push(ev); local.set('outbox', this.outbox); this.recompute(); this.flush(); return ev; }, rememberPair(a, b) { this.recent = [...this.recent, pairKey(a, b)].slice(-40); local.set('recent', this.recent); }, pick(a, b, r) { const before = { a: this.state.stats.get(a).rating, b: this.state.stats.get(b).rating }; this.record({ type: 'match', a, b, r }); this.rememberPair(a, b); this.pair = null; const da = Math.round(this.state.stats.get(a).rating - before.a); const db = Math.round(this.state.stats.get(b).rating - before.b); const fmt = (code, d) => `${shortName(this.byCode.get(code))} ${d >= 0 ? '+' : ''}${d}`; toast(r === 'draw' ? `Tie · ${fmt(a, da)} · ${fmt(b, db)}` : `${fmt(a, da)} · ${fmt(b, db)}`, { label: 'Undo', run: () => this.undo() }); this.render(); }, skip() { if (this.pair) this.rememberPair(...this.pair); this.pair = null; this.render(); }, undo() { const target = this.state.lastUndoable; if (!target) return toast('Nothing to undo'); this.record({ type: 'undo', target: target.id }); if (target.type === 'match') { this.pair = [target.a, target.b]; local.set('pair', this.pair); } const what = target.type === 'match' ? 'pick' : target.type; toast(`Undid the last ${what}`); this.render(); }, drop(code) { this.record({ type: 'drop', code }); if (this.pair?.includes(code)) this.pair = null; toast(`Dropped ${shortName(this.byCode.get(code))}`, { label: 'Undo', run: () => this.undo() }); this.render(); }, restore(code) { this.record({ type: 'restore', code }); toast(`${shortName(this.byCode.get(code))} is back in the race`); this.render(); }, review(code) { this.record({ type: 'review', code }); this.render(); }, duelWith(code) { const me = this.state.stats.get(code); const others = [...this.state.stats.values()] .filter((s) => !s.dropped && s.code !== code) .sort((x, y) => Math.abs(x.rating - me.rating) - Math.abs(y.rating - me.rating)) .slice(0, 5); if (!others.length) return toast('No opponent available'); const opp = others[Math.floor(Math.random() * others.length)].code; this.pair = Math.random() < 0.5 ? [code, opp] : [opp, code]; local.set('pair', this.pair); this.navigate('#/'); }, async saveNote(code, text) { const res = await api(`api/notes/${encodeURIComponent(code)}`, { method: 'PUT', body: { text } }); if (res.note) this.notes[code] = res.note; else delete this.notes[code]; }, async updateSettings(patch) { const previous = this.settings; this.settings = { ...this.settings, ...patch }; if ('pairing' in patch) this.pair = null; this.recompute(); this.render(); try { await api('api/settings', { method: 'PUT', body: patch }); } catch (err) { this.settings = previous; this.recompute(); this.render(); toast(err.status === 0 ? 'Offline: setting not saved' : `Setting not saved: ${err.message}`); } }, async importBackup(file) { let data; try { data = JSON.parse(await file.text()); } catch { return toast('That file is not valid JSON'); } const n = Array.isArray(data?.events) ? data.events.length : 0; if (!confirm(`Replace ALL current picks, notes and settings with this backup (${n} events)?\nThe server keeps a copy of the current state in DATA_DIR/backups.`)) return; try { await api('api/import', { method: 'POST', body: data }); this.outbox = []; local.set('outbox', []); await this.sync({ full: true }); toast('Backup imported'); } catch (err) { toast(`Import failed: ${err.message}`); } }, async logout() { await api('api/logout', { method: 'POST', body: {} }).catch(() => {}); location.reload(); }, /* ---------- server sync ---------- */ /** Pull server state. Returns how many new events came from elsewhere (not our outbox). */ async sync({ full = false } = {}) { const res = await api(`api/state${full ? '' : `?since=${this.seq}`}`); const mine = new Set(this.outbox.map((e) => e.id)); let incoming; if (full || res.seq < this.seq) { // First load, or the server state was replaced (import): take it wholesale. this.serverEvents = full ? res.events : (await api('api/state')).events; incoming = this.serverEvents; } else { incoming = res.events.filter((e) => e.seq > this.seq); this.serverEvents.push(...incoming); } this.seq = res.seq; this.notes = res.notes; this.settings = { ...DEFAULT_SETTINGS, stayMonths: this.config.defaults.stayMonths, ...res.settings }; this.recompute(); local.set('outbox', this.outbox); return incoming.filter((e) => !mine.has(e.id)).length; }, async flush() { if (this.flushing || !this.outbox.length) return; this.flushing = true; const batch = this.outbox.slice(); let sent = false; try { await api('api/events', { method: 'POST', body: { events: batch } }); sent = true; } catch (err) { if (err.status === 401) { this.flushing = false; return this.showLogin(); } // 400 = the server refused something in the batch; find and discard just that event. if (err.status === 400) sent = await this.discardRejected(batch); if (!sent) { setTimeout(() => this.flush(), this.retryDelay); this.retryDelay = Math.min(this.retryDelay * 2, 60000); } } this.flushing = false; if (!sent) return; this.retryDelay = 2000; const foreign = await this.sync().catch(() => 0); if (foreign) this.render(); // another device changed something meanwhile if (this.outbox.length) this.flush(); }, /** Resend events one by one; drop those refused (e.g. undo of something already undone elsewhere). */ async discardRejected(batch) { const rejected = []; for (const ev of batch) { try { await api('api/events', { method: 'POST', body: { events: [ev] } }); } catch (err) { if (err.status !== 400) return false; // connection trouble: retry everything later rejected.push(ev); } } this.outbox = this.outbox.filter((e) => !rejected.includes(e)); local.set('outbox', this.outbox); if (rejected.length) toast(`${rejected.length} change(s) refused by the server and discarded`); return true; }, /* ---------- routing & rendering ---------- */ navigate(hash) { location.hash = hash; }, back() { if (history.length > 1) history.back(); else this.navigate('#/rank'); }, applyTheme() { const theme = local.get('theme', 'system'); if (theme === 'system') delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = theme; }, route() { const [, name = '', param] = location.hash.match(/^#\/?([a-z]*)\/?(.*)$/) ?? []; return { name: ROUTES[name] ? name : '', param: decodeURIComponent(param ?? '') }; }, render() { const { name, param } = this.route(); const view = document.getElementById('view'); const key = `${name}/${param}`; // Don't yank the notes box away from someone typing in it during a background sync. if (key === this.lastRoute && view.contains(document.activeElement) && document.activeElement.matches('textarea, input[type=search]')) return; view.onclick = view.onchange = view.oninput = null; ROUTES[name].render(view, this, param); for (const a of document.querySelectorAll('.tabs a')) a.classList.toggle('active', a.dataset.route === (name === 'school' ? 'rank' : name)); document.getElementById('picks').textContent = `${this.state.matches.length} picks`; if (key !== this.lastRoute) { window.scrollTo(0, 0); this.lastRoute = key; } }, showLogin(message = '') { const view = document.getElementById('view'); document.body.classList.add('logged-out'); view.innerHTML = String(html`

${this.config?.title ?? 'Elorasmus'}

Enter the password set in AUTH_PASSWORD.

`); view.querySelector('form').onsubmit = async (e) => { e.preventDefault(); try { await api('api/login', { method: 'POST', body: { password: e.target.password.value } }); location.reload(); } catch (err) { this.showLogin(err.status === 401 ? 'Wrong password' : err.message); } }; }, async start() { this.applyTheme(); document.querySelector('.tabs').innerHTML = String(html` ${ICONS.duel}Compare ${ICONS.rank}Ranking ${ICONS.triage}Triage ${ICONS.settings}Settings`); try { this.config = await api('api/config'); document.title = this.config.title; if (this.config.authRequired && !this.config.authenticated) return this.showLogin(); this.data = await api('data/schools.json'); if (this.config.eurCzk) this.data.fx = { ...this.data.fx, EURCZK: this.config.eurCzk }; } catch (err) { if (err.status === 401) return this.showLogin(); document.getElementById('view').innerHTML = String(html`

Can't load the app

${err.message}

`); return; } for (const s of this.data.schools) { this.byCode.set(s.code, s); this.bySlug.set(s.slug, s); } try { await this.sync({ full: true }); } catch (err) { if (err.status === 401) return this.showLogin(); // Offline: run on the local outbox only; sync when back. this.recompute(); toast('Offline: your picks are kept on this device and sent later'); } this.render(); this.flush(); addEventListener('hashchange', () => this.render()); addEventListener('online', () => this.flush()); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') this.sync().then((n) => n && this.render()).catch(() => {}); }); setInterval(() => { if (document.visibilityState === 'visible') this.sync().then((n) => n && this.render()).catch(() => {}); }, 60000); document.addEventListener('keydown', (e) => { if (this.route().name === '' && duelView.onKey(e, this)) e.preventDefault(); }); }, }; app.start();