'use strict'; /* * The shell: session, screen registry, bottom nav, resource bar (HUD), ticker, language. Screens live in * js/screens/*.js and register themselves: * * App.registerScreen({ * id: 'pop', titleKey: 'screen.pop', navKey: 'nav.pop', icon: 'pop', // nav: false hides it from the nav * hud: true, // show the resource bar above it * render(container) {}, // once, when the screen is first shown: build the persistent DOM * onShow(params) {}, // every time it becomes visible * onHide() {}, * onLang() {}, // optional: language changed while visible (default: onShow again) * }); * * Later stages add screens (units, reports, ...) the same way: one file, one registerScreen call, one script tag. * Everything time-based is computed from api.serverNow() (server clock), never from the device clock alone. */ (function () { const { h, clear, icon, toast, safeStore } = UI; const I = UpstreamI18n; const R = UpstreamRules; const D = UpstreamData; const api = UpstreamApi.createApi({ fetch: window.fetch.bind(window), storage: (function () { try { return window.localStorage; } catch (e) { return null; } }()), }); const LANG_KEY = 'upstream.lang'; const TOWN_KEY = 'upstream.town'; const SEEN_KEY = 'upstream.alerts.seen.'; const App = { api, state: { user: null, operators: [], operator: null, world: null, towns: [], townId: null, townData: null, townFetchedAt: 0, lang: 'en', unread: 0 }, screens: new Map(), current: null, params: null, }; window.App = App; // ------------------------------------------------------------------ tiny event bus (town, session, lang) const bus = {}; App.on = (evt, fn) => { (bus[evt] = bus[evt] || new Set()).add(fn); return () => bus[evt].delete(fn); }; App.emit = (evt, data) => { if (bus[evt]) for (const fn of Array.from(bus[evt])) { try { fn(data); } catch (e) { console.error(e); } } }; // ------------------------------------------------------------------ i18n helpers App.t = (key, vars) => I.t(App.state.lang, key, vars); App.fmt = { num: (n) => I.fmtNum(App.state.lang, n), dec: (n, signed) => I.fmtDec(App.state.lang, n, signed), dur: (ms, parts) => I.fmtDuration(App.state.lang, ms, parts), clock: (ms) => I.fmtClock(ms), ago: (ms) => I.fmtAgo(App.state.lang, ms), compact: (n) => (Math.abs(n) >= 1000 ? I.fmtDec(App.state.lang, n / 1000) + 'k' : I.fmtNum(App.state.lang, n)), }; App.errMsg = (err) => { const code = err && err.code; if (code && Object.prototype.hasOwnProperty.call(I.strings.en, 'err.' + code)) return App.t('err.' + code); return (err && err.message) || App.t('err.unknown'); }; App.resName = (r) => App.t('res.' + r); App.buildingName = (type) => (I.strings.en['building.' + type + '.name'] ? App.t('building.' + type + '.name') : type); App.buildingDesc = (type) => (I.strings.en['building.' + type + '.desc'] ? App.t('building.' + type + '.desc') : ''); App.setLang = (lang) => { if (!I.LANGS.includes(lang)) return; App.state.lang = lang; safeStore.set(LANG_KEY, lang); document.documentElement.lang = lang; buildNav(); renderHud(true); if (App.current) { setTitle(App.current); if (App.current.onLang) App.current.onLang(); else if (App.current.onShow) App.current.onShow(App.params || {}); } App.emit('lang', lang); }; // ------------------------------------------------------------------ server clock + ticker App.now = () => api.serverNow(); const tickers = new Set(); App.onTick = (fn) => { tickers.add(fn); return () => tickers.delete(fn); }; setInterval(() => { if (document.hidden) return; const now = api.serverNow(); tickHud(now); for (const fn of Array.from(tickers)) { try { fn(now); } catch (e) { console.error(e); } } }, 250); // ------------------------------------------------------------------ screens + nav const elView = () => document.getElementById('view'); const elNav = () => document.getElementById('nav'); const elApp = () => document.getElementById('app'); App.registerScreen = (def) => { App.screens.set(def.id, def); }; function buildNav() { const nav = elNav(); clear(nav); nav.setAttribute('aria-label', App.t('nav.label')); for (const def of App.screens.values()) { if (def.nav === false) continue; const badge = h('span', { class: 'nav-badge', hidden: true, 'aria-hidden': 'true' }); const btn = h('button', { class: 'nav-btn', type: 'button', dataset: { screen: def.id }, onclick: () => App.go(def.id) }, h('span', { class: 'nav-ic' }, icon(def.icon), badge), h('span', { class: 'nav-lbl', text: App.t(def.navKey || def.titleKey) })); if (App.current && App.current.id === def.id) btn.setAttribute('aria-current', 'page'); nav.appendChild(btn); } updateBadge(); } function updateBadge() { const n = App.state.unread; const b = elNav().querySelector('[data-screen="alerts"] .nav-badge'); if (!b) return; b.hidden = !n; b.textContent = n > 9 ? '9+' : String(n); const btn = b.closest('button'); if (btn) btn.setAttribute('aria-label', App.t('nav.alerts') + (n ? ' (' + App.t('alerts.count', { n }) + ')' : '')); } function setTitle(def) { document.getElementById('title').textContent = def.id === 'auth' ? App.t('app.name') : App.t(def.titleKey); document.title = (def.id === 'auth' ? '' : App.t(def.titleKey) + ' ยท ') + 'UPSTREAM'; } // Navigate. Sets the hash (so back/forward work); hashchange does the actual switch. App.go = (id, params) => { App.nextParams = params || null; const want = '#/' + id; if (location.hash === want) show(id, App.nextParams); else location.hash = want; }; function show(id, params) { if (!App.state.user && id !== 'auth') id = 'auth'; if (App.state.user && id === 'auth') id = 'pop'; const def = App.screens.get(id) || App.screens.get(App.state.user ? 'pop' : 'auth'); if (!def) return; if (App.current && App.current !== def && App.current.onHide) App.current.onHide(); const view = elView(); for (const s of view.children) s.hidden = s.dataset.screen !== def.id; let box = view.querySelector('[data-screen="' + def.id + '"]'); if (!box) { box = h('section', { class: 'screen screen-' + def.id, dataset: { screen: def.id }, tabindex: '-1' }); view.appendChild(box); if (def.render) def.render(box); } box.hidden = false; App.current = def; App.params = params || {}; const app = elApp(); app.dataset.screen = def.id; app.dataset.state = App.state.user ? 'in' : 'out'; elNav().hidden = !App.state.user; for (const b of elNav().children) { if (b.dataset.screen === def.id) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current'); } setTitle(def); renderHud(false); if (def.onShow) def.onShow(App.params); if (App.state.user && def.nav !== false) safeStore.set('upstream.screen', def.id); } window.addEventListener('hashchange', () => { const id = (location.hash.match(/^#\/(\w+)/) || [])[1] || 'pop'; const p = App.nextParams; App.nextParams = null; show(id, p); }); // ------------------------------------------------------------------ session // Accepts the operators array of /me or of an auth response. App.setSession = (user, operators) => { const st = App.state; st.user = user; st.operators = operators || []; st.operator = st.operators[0] || null; // v1: one world per account st.world = st.operator ? st.operator.world : null; st.towns = st.operator ? st.operator.towns : []; const saved = Number(safeStore.get(TOWN_KEY)); const pick = st.towns.find((t) => t.id === saved) || st.towns.find((t) => t.isCapital) || st.towns[0] || null; st.townId = pick ? pick.id : null; st.townData = null; st.unread = 0; App.emit('session', st); }; App.clearSession = () => { const st = App.state; st.user = null; st.operators = []; st.operator = null; st.world = null; st.towns = []; st.townId = null; st.townData = null; st.unread = 0; api.clearToken(); renderHud(true); App.emit('session', st); }; App.loadMe = async () => { const me = await api.get('/me'); App.setSession(me.user, me.operators); return me; }; App.setTown = (id) => { if (App.state.townId === id) return; App.state.townId = id; App.state.townData = null; safeStore.set(TOWN_KEY, String(id)); App.refreshTown().catch(() => {}); App.emit('townchange', id); }; let townInflight = null; App.refreshTown = () => { const st = App.state; if (!st.townId) return Promise.resolve(null); if (townInflight) return townInflight; const id = st.townId; townInflight = api.get('/towns/' + id).then((r) => { if (st.townId !== id) return null; st.townData = r.town; st.townFetchedAt = Date.now(); App.fetchedServerTime = r.serverTime; // the instant the amounts in r.town are exact for rulesCache = null; renderHud(true); App.emit('town', r.town); return r.town; }).finally(() => { townInflight = null; }); return townInflight; }; // ------------------------------------------------------------------ rules.js view of the current POP (previews + ticking) let rulesCache = null; // The rules.js town shape from the API response: same function the server settles with, so the numbers agree. App.rulesTown = () => { const st = App.state, td = st.townData; if (!td || !st.world) return null; if (rulesCache && rulesCache.src === td) return rulesCache.town; const buildings = {}; let bdraw = 0; for (const b of td.buildings) { if (b.level <= 0) continue; buildings[b.key] = { type: b.type, level: b.level }; const def = D.BUILDINGS[b.type]; if (def && def.kind === 'infra') bdraw += def.draw * b.level; } const town = { id: td.id, speed: st.world.speed, updatedAt: App.fetchedServerTime || 0, res: { fiber: td.resources.fiber.amount, hardware: td.resources.hardware.amount, capital: td.resources.capital.amount, battery: td.power.buffer }, footprint: td.footprint, buildings, unitDraw: Math.max(0, Math.round(td.power.draw - bdraw)), bonus: td.bonus || {}, }; rulesCache = { src: td, town }; return town; }; // Current amounts at server time `now`. Falls back to the fetched values if the rules cannot be applied. App.resourcesNow = (now) => { const td = App.state.townData; if (!td) return null; try { const rt = App.rulesTown(); const cur = R.resourcesAt(rt, now === undefined ? api.serverNow() : now); return { amounts: cur.amounts, caps: cur.caps, rates: cur.rates }; } catch (e) { const amounts = { battery: td.power.buffer }, caps = { battery: td.power.bufferCap }; for (const r of D.RESOURCES) { amounts[r] = td.resources[r].amount; caps[r] = td.resources[r].cap; } return { amounts, caps, rates: { fiber: td.resources.fiber.rate, hardware: td.resources.hardware.rate, capital: td.resources.capital.rate, powerOut: td.power.out, powerDraw: td.power.draw, powerNet: td.power.net } }; } }; // ------------------------------------------------------------------ resource bar const hudRefs = {}; function renderHud(rebuild) { const hud = document.getElementById('hud'); const def = App.current; const td = App.state.townData; const want = !!(def && def.hud && td && App.state.user); hud.hidden = !want; if (!want) return; if (!rebuild && hud.firstChild) return; clear(hud); for (const r of D.RESOURCES.concat(['power'])) { const refs = { val: h('b', { class: 'val' }), cap: h('span', { class: 'cap' }), rate: h('span', { class: 'rate' }), fill: h('i'), }; hudRefs[r] = refs; hud.appendChild(h('div', { class: 'hud-chip ' + r, role: 'group', dataset: { res: r } }, h('div', { class: 'hud-top' }, icon(r), refs.val, refs.cap), h('div', { class: 'hud-sub' }, refs.rate), h('div', { class: 'bar', 'aria-hidden': 'true' }, refs.fill))); } tickHud(api.serverNow(), true); } const lastText = new WeakMap(); function setText(el, s) { if (lastText.get(el) !== s) { lastText.set(el, s); el.textContent = s; } } function tickHud(now, force) { const hud = document.getElementById('hud'); if (hud.hidden && !force) return; const cur = App.resourcesNow(now); if (!cur || !hudRefs.fiber) return; const f = App.fmt; for (const r of D.RESOURCES) { const refs = hudRefs[r]; const amt = cur.amounts[r], cap = cur.caps[r], rate = cur.rates[r]; const full = amt >= cap - 0.01; setText(refs.val, f.num(amt)); setText(refs.cap, '/' + f.compact(cap)); setText(refs.rate, full ? 'FULL' : f.dec(rate, true) + App.t('common.perHour')); refs.fill.style.setProperty('--p', String(cap > 0 ? Math.min(1, amt / cap) : 0)); const chip = refs.val.closest('.hud-chip'); chip.classList.toggle('full', full); if (force) chip.setAttribute('aria-label', App.resName(r) + ': ' + f.num(amt) + ' / ' + f.num(cap) + ', ' + f.dec(rate, true) + App.t('common.perHour')); } const p = hudRefs.power; const net = cur.rates.powerNet, buf = cur.amounts.battery, bcap = cur.caps.battery; setText(p.val, f.dec(net, true)); setText(p.cap, App.t('power.unit')); setText(p.rate, buf <= 0 && net < 0 ? App.t('power.empty').split(':')[0] : f.num(buf) + '/' + f.compact(bcap)); p.fill.style.setProperty('--p', String(bcap > 0 ? Math.min(1, buf / bcap) : 0)); const pc = p.val.closest('.hud-chip'); pc.classList.toggle('bad', net < 0); pc.classList.toggle('empty', buf <= 0 && net < 0); if (force) pc.setAttribute('aria-label', App.t('res.power') + ': ' + f.dec(net, true) + ', ' + App.t('res.battery') + ' ' + f.num(buf) + ' / ' + f.num(bcap)); } // ------------------------------------------------------------------ alerts badge (unread count from the notification feed) const seenKey = () => SEEN_KEY + (App.state.user ? App.state.user.id : '0'); App.getSeen = () => Number(safeStore.get(seenKey())) || 0; App.markSeen = (id) => { if (id > App.getSeen()) safeStore.set(seenKey(), String(id)); App.state.unread = 0; updateBadge(); }; App.checkAlerts = async () => { if (!App.state.user) return; try { const after = App.getSeen(); const r = await api.get('/notifications', { after, limit: 50 }); if (App.current && App.current.id === 'alerts') { App.state.unread = 0; } else App.state.unread = r.items.length; updateBadge(); } catch (e) { /* badge is a convenience */ } }; // ------------------------------------------------------------------ connection state let backTimer = null; api.on('offline', () => { const el = document.getElementById('netstate'); el.textContent = App.t('common.offline'); el.hidden = false; el.classList.remove('ok'); clearTimeout(backTimer); }); api.on('online', () => { const el = document.getElementById('netstate'); if (el.hidden) return; el.textContent = App.t('common.online'); el.classList.add('ok'); backTimer = setTimeout(() => { el.hidden = true; }, 1800); if (App.state.user) App.refreshTown().catch(() => {}); }); api.on('unauthorized', () => { App.clearSession(); App.authNotice = App.t('auth.expired'); App.go('auth'); }); document.addEventListener('visibilitychange', () => { if (document.hidden || !App.state.user) return; if (Date.now() - App.state.townFetchedAt > 20000) App.refreshTown().catch(() => {}); App.checkAlerts(); }); setInterval(() => { if (!document.hidden && App.state.user) App.checkAlerts(); }, 60000); // After login or boot: load the POP and go to the screen the hash asks for. App.enter = async (wantScreen) => { buildNav(); const id = wantScreen || (location.hash.match(/^#\/(\w+)/) || [])[1] || safeStore.get('upstream.screen') || 'pop'; App.go(App.screens.has(id) && id !== 'auth' ? id : 'pop'); App.checkAlerts(); try { await App.refreshTown(); } catch (e) { toast(App.errMsg(e), 'error'); } }; // ------------------------------------------------------------------ boot async function boot() { const saved = safeStore.get(LANG_KEY); App.state.lang = I.LANGS.includes(saved) ? saved : I.detectLang(navigator.language); document.documentElement.lang = App.state.lang; buildNav(); if (!api.hasToken()) { App.go('auth'); return; } const view = elView(); const status = h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') })); view.appendChild(status); try { await App.loadMe(); status.remove(); await App.enter(); } catch (e) { status.remove(); if (e.code === 'network_error') { const retry = h('button', { class: 'btn primary', type: 'button', onclick: () => { card.remove(); boot(); } }, icon('refresh'), App.t('common.retry')); const card = h('div', { class: 'boot' }, h('p', { text: App.errMsg(e) }), retry); view.appendChild(card); } else if (e.code !== 'unauthorized') { toast(App.errMsg(e), 'error'); App.go('auth'); } } } document.addEventListener('DOMContentLoaded', boot); }());