Built: units/movements/reports/send/expansion screens, alliance/messages/rankings screens, ws client + server /ws push (docs/PROTOCOL.md), Internet exchange trade, backbone endgame + world end, shared reports, buildDone relative levels. Tested: npm test 175/175. Two adversarial reviews found issues (trade-leg recall exploit, __proto__ via validate.js, rankings DoS, static headers, ...): fixes follow in the next commit. NOT done: bots/balance, e2e suite, real-device checks. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
491 lines
22 KiB
JavaScript
491 lines
22 KiB
JavaScript
'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
|
|
* navGroup: 'main' | 'more', // bar button (default) or behind the "More" sheet
|
|
* 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.
|
|
* The bar holds 5 slots; with any 'more' screen the 5th is the More button (see "Bottom nav with overflow" below).
|
|
* App.setBadge(screenId, n, 'alert'|'info') puts a count on a screen's nav button (the More button sums its screens).
|
|
* 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); };
|
|
App.alertKinds = {}; // notification type -> describer, see screens/alerts.js
|
|
App.popSections = []; // extra cards of the POP screen: { slot: 'top' | 'main', render(townData) -> Node | null }
|
|
|
|
// Bottom nav with overflow. A screen picks where it lives with `navGroup`:
|
|
// 'main' (default) one of the primary screens in the bar (registration order)
|
|
// 'more' behind the "More" button, which opens a sheet listing these screens
|
|
// The bar holds NAV_SLOTS buttons. If any 'more' screen exists, or there are more 'main' screens than slots, the last slot
|
|
// becomes "More" and the surplus 'main' screens go into the sheet in front of the 'more' ones. Keep it to about 4 primary
|
|
// screens. Badges: App.setBadge(screenId, n, 'alert'|'info') shows a count on the screen's button; the More button
|
|
// shows the sum of its screens' badges (red if any of them is an alert). Add the screen's script tag and you are done.
|
|
const NAV_SLOTS = 5;
|
|
const badges = new Map(); // screen id -> { n, kind }
|
|
function navSplit() {
|
|
const all = Array.from(App.screens.values()).filter((d) => d.nav !== false);
|
|
const main = all.filter((d) => d.navGroup !== 'more'), more = all.filter((d) => d.navGroup === 'more');
|
|
if (!more.length && main.length <= NAV_SLOTS) return { bar: main, over: [] };
|
|
return { bar: main.slice(0, NAV_SLOTS - 1), over: main.slice(NAV_SLOTS - 1).concat(more) };
|
|
}
|
|
|
|
function navButton(def, onclick) {
|
|
const badge = h('span', { class: 'nav-badge', hidden: true, 'aria-hidden': 'true' });
|
|
return h('button', { class: 'nav-btn', type: 'button', dataset: { screen: def.id }, onclick },
|
|
h('span', { class: 'nav-ic' }, icon(def.icon), badge), h('span', { class: 'nav-lbl', text: App.t(def.navKey || def.titleKey) }));
|
|
}
|
|
|
|
function buildNav() {
|
|
const nav = elNav();
|
|
clear(nav);
|
|
nav.setAttribute('aria-label', App.t('nav.label'));
|
|
const { bar, over } = navSplit();
|
|
for (const def of bar) nav.appendChild(navButton(def, () => App.go(def.id)));
|
|
if (over.length) {
|
|
const btn = navButton({ id: 'more', icon: 'more', navKey: 'nav.more' }, () => openMore());
|
|
btn.setAttribute('aria-haspopup', 'dialog');
|
|
nav.appendChild(btn);
|
|
}
|
|
markCurrent();
|
|
updateBadges();
|
|
}
|
|
|
|
function markCurrent() {
|
|
const id = App.current ? App.current.id : null;
|
|
const { over } = navSplit();
|
|
const inMore = over.some((d) => d.id === id);
|
|
for (const b of elNav().children) {
|
|
const on = b.dataset.screen === id || (b.dataset.screen === 'more' && inMore);
|
|
if (on) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current');
|
|
}
|
|
}
|
|
|
|
function openMore() {
|
|
const { over } = navSplit();
|
|
const list = h('div', { class: 'more-list' });
|
|
const sheet = UI.openSheet({ title: App.t('nav.more'), icon: 'more', closeLabel: App.t('common.close'), body: list });
|
|
for (const def of over) {
|
|
const bd = badges.get(def.id);
|
|
list.appendChild(h('button', { class: 'row-btn', type: 'button', onclick: () => { sheet.close(true); App.go(def.id); } },
|
|
h('span', { class: 'row-ic' }, icon(def.icon)),
|
|
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: App.t(def.navKey || def.titleKey) }))),
|
|
bd && bd.n ? h('span', { class: 'pill ' + (bd.kind === 'alert' ? 'amber' : 'accent'), text: String(bd.n) }) : null));
|
|
}
|
|
}
|
|
|
|
function paintBadge(btn, n, kind, label) {
|
|
const b = btn.querySelector('.nav-badge');
|
|
if (!b) return;
|
|
b.hidden = !n;
|
|
b.textContent = n > 9 ? '9+' : String(n);
|
|
b.classList.toggle('is-alert', kind === 'alert');
|
|
const lbl = btn.querySelector('.nav-lbl');
|
|
btn.setAttribute('aria-label', (lbl ? lbl.textContent : label || '') + (n ? ' (' + n + ')' : ''));
|
|
}
|
|
|
|
function updateBadges() {
|
|
const { over } = navSplit();
|
|
const overIds = new Set(over.map((d) => d.id));
|
|
let sum = 0, kind = 'info';
|
|
for (const [id, bd] of badges) {
|
|
if (overIds.has(id)) { sum += bd.n; if (bd.kind === 'alert' && bd.n) kind = 'alert'; }
|
|
}
|
|
for (const btn of elNav().children) {
|
|
const id = btn.dataset.screen;
|
|
if (id === 'more') paintBadge(btn, sum, kind);
|
|
else { const bd = badges.get(id); paintBadge(btn, bd ? bd.n : 0, bd ? bd.kind : 'info'); }
|
|
}
|
|
}
|
|
|
|
App.setBadge = (id, n, kind) => {
|
|
const prev = badges.get(id);
|
|
n = Math.max(0, Math.floor(n) || 0);
|
|
if (prev && prev.n === n && prev.kind === (kind || 'info')) return;
|
|
badges.set(id, { n, kind: kind || 'info' });
|
|
updateBadges();
|
|
};
|
|
const updateBadge = () => App.setBadge('alerts', App.state.unread, 'info'); // alerts feed unread count
|
|
|
|
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;
|
|
markCurrent();
|
|
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 td = App.state.townData;
|
|
if (!td || !App.state.world) return null;
|
|
if (rulesCache && rulesCache.src === td) return rulesCache.town;
|
|
const town = App.rulesTownFrom(td, App.fetchedServerTime || 0);
|
|
rulesCache = { src: td, town };
|
|
return town;
|
|
};
|
|
// Same for any POP payload of GET /towns/:id fetched at server time `at` (the send dialog looks at other POPs too).
|
|
App.rulesTownFrom = (td, at) => {
|
|
const st = App.state;
|
|
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: at,
|
|
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 || {},
|
|
};
|
|
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 = {};
|
|
App.on('towns', () => renderHud(true)); // POP list changed (founded / conquered / lost / renamed)
|
|
App.on('townchange', () => renderHud(true)); // the switcher shows the selected POP
|
|
|
|
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);
|
|
// POP switcher (only with more than one POP): every screen with the resource bar gets it
|
|
if (App.state.towns.length > 1) {
|
|
hud.appendChild(h('label', { class: 'hud-town' }, icon('pop'),
|
|
h('select', { 'aria-label': App.t('screen.pop'), onchange: (e) => App.setTown(Number(e.target.value)) },
|
|
App.state.towns.map((x) => h('option', { value: x.id, selected: x.id === App.state.townId, text: x.name + (x.isCapital ? ' ★' : '') })))));
|
|
}
|
|
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);
|
|
}());
|