Stage 3-5 server (military, expansion, social), web client for stages 1-2, ops/deploy
Built: units/research/training, movements (scan, raid, attack, takeover, reinforce, settle, transport), deterministic combat resolved in the event queue, reports, power/offline units, founding + conquest + incumbent sites; alliances, roles, diplomacy (24h pact cancel via events), messages, rankings; vanilla-JS phone-first client (auth, POP, map, alerts, settings, en/nb); systemd units, backup timer, DEPLOY.md, tools/admin.js. Tested: npm test 96/96 (fake clock, in-memory db, a few real-HTTP tests); client checked with headless Chromium screenshots only. NOT done: marketplace/transport trade, client screens for military/social, WebSocket push, bots/balance, e2e suite. All unit stats and costs are unbalanced first guesses. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
parent
b56b13880e
commit
249818a7aa
111 changed files with 17472 additions and 13 deletions
84
public/js/screens/alerts.js
Normal file
84
public/js/screens/alerts.js
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
'use strict';
|
||||
/* Alerts: the durable notification feed (GET /notifications). Newest first; what arrived since you last looked is marked. */
|
||||
(function () {
|
||||
const { h, clear, icon } = UI;
|
||||
const PAGE = 100, MAX_PAGES = 5;
|
||||
|
||||
let box, listEl, statusEl, items = [], seenAtOpen = 0, loading = false, offTick = null;
|
||||
|
||||
function townName(id) {
|
||||
const t = App.state.towns.find((x) => x.id === id);
|
||||
return t ? t.name : '#' + id;
|
||||
}
|
||||
|
||||
// One entry per notification type: icon + title + detail. Unknown types still show something readable.
|
||||
function describe(n) {
|
||||
const p = n.payload || {};
|
||||
if (n.type === 'build_done') {
|
||||
return { icon: 'b-' + p.type, title: App.t('alerts.build_done', { name: App.buildingName(p.type), level: p.level }), detail: App.t('alerts.build_done.in', { town: townName(p.townId) }), go: 'pop' };
|
||||
}
|
||||
return { icon: 'bell', title: App.t('alerts.unknown', { type: n.type }), detail: '', go: null };
|
||||
}
|
||||
|
||||
function draw() {
|
||||
clear(listEl);
|
||||
if (!items.length) { listEl.appendChild(h('p', { class: 'empty pad', text: App.t('alerts.empty') })); return; }
|
||||
const now = App.now();
|
||||
for (const n of items.slice().reverse()) {
|
||||
const d = describe(n);
|
||||
const isNew = n.id > seenAtOpen;
|
||||
listEl.appendChild(h('li', null,
|
||||
h('button', { class: 'alert' + (isNew ? ' new' : ''), type: 'button', onclick: () => { if (d.go) App.go(d.go); } },
|
||||
h('span', { class: 'row-ic' }, icon(d.icon)),
|
||||
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: d.title }), isNew ? h('span', { class: 'pill accent', text: App.t('alerts.new') }) : null),
|
||||
d.detail ? h('span', { class: 'row-sub', text: d.detail }) : null),
|
||||
h('span', { class: 'when mono', dataset: { at: n.createdAt }, text: App.fmt.ago(now - n.createdAt) }))));
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (loading) return;
|
||||
loading = true;
|
||||
statusEl.hidden = true;
|
||||
try {
|
||||
let after = items.length ? items[items.length - 1].id : 0;
|
||||
for (let page = 0; page < MAX_PAGES; page++) {
|
||||
const r = await App.api.get('/notifications', { after, limit: PAGE });
|
||||
items = items.concat(r.items);
|
||||
if (r.next === null || !r.items.length) break;
|
||||
after = r.next;
|
||||
}
|
||||
draw();
|
||||
if (items.length) App.markSeen(items[items.length - 1].id); else App.markSeen(0);
|
||||
} catch (e) {
|
||||
statusEl.textContent = App.t('alerts.error') + ' ' + App.errMsg(e);
|
||||
statusEl.hidden = false;
|
||||
} finally { loading = false; }
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'alerts', titleKey: 'screen.alerts', navKey: 'nav.alerts', icon: 'bell', hud: false,
|
||||
render(container) {
|
||||
box = container;
|
||||
listEl = h('ul', { class: 'alert-list' });
|
||||
statusEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
box.appendChild(h('div', { class: 'page' },
|
||||
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.alerts') }),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load() }, icon('refresh'))),
|
||||
statusEl, listEl));
|
||||
App.on('session', () => { items = []; });
|
||||
},
|
||||
onShow() {
|
||||
seenAtOpen = App.getSeen();
|
||||
box.querySelector('h1').textContent = App.t('screen.alerts');
|
||||
draw();
|
||||
load();
|
||||
if (offTick) offTick();
|
||||
offTick = App.onTick(() => {
|
||||
const now = App.now();
|
||||
for (const el of listEl.querySelectorAll('.when')) { const s = App.fmt.ago(now - Number(el.dataset.at)); if (el.textContent !== s) el.textContent = s; }
|
||||
});
|
||||
},
|
||||
onHide() { if (offTick) offTick(); offTick = null; },
|
||||
});
|
||||
}());
|
||||
100
public/js/screens/auth.js
Normal file
100
public/js/screens/auth.js
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
'use strict';
|
||||
/* Login / signup. Not in the nav. The invite field appears when the server answers signup_closed. */
|
||||
(function () {
|
||||
const { h, icon, clear } = UI;
|
||||
let box, mode = 'login', needInvite = false, busy = false;
|
||||
let refs = {};
|
||||
|
||||
function deviceName() {
|
||||
const ua = navigator.userAgent || '';
|
||||
const browser = /Edg\//.test(ua) ? 'Edge' : /OPR\//.test(ua) ? 'Opera' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Browser';
|
||||
const os = /Android/.test(ua) ? 'Android' : /iPhone|iPad|iPod/.test(ua) ? 'iOS' : /Windows/.test(ua) ? 'Windows' : /Mac OS/.test(ua) ? 'macOS' : /Linux/.test(ua) ? 'Linux' : '';
|
||||
return (browser + (os ? ' on ' + os : '')).slice(0, 40);
|
||||
}
|
||||
|
||||
function showError(msg) { refs.err.textContent = msg || ''; refs.err.hidden = !msg; }
|
||||
|
||||
function validationMessage(err) {
|
||||
const list = err.details && err.details.errors;
|
||||
const base = App.t('err.validation_failed');
|
||||
if (Array.isArray(list) && list.length) {
|
||||
const f = list[0];
|
||||
const path = String(f.path || '').replace(/^\$?\.?/, '');
|
||||
return base + (path ? ' (' + path + ')' : '');
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
async function submit(ev) {
|
||||
ev.preventDefault();
|
||||
if (busy) return;
|
||||
showError('');
|
||||
const username = refs.user.value.trim(), password = refs.pass.value;
|
||||
if (!username || !password) { showError(App.t('err.validation_failed')); return; }
|
||||
busy = true; refs.go.disabled = true; refs.goText.textContent = App.t('auth.working');
|
||||
try {
|
||||
let r;
|
||||
if (mode === 'signup') {
|
||||
const body = { username, password, device: deviceName() };
|
||||
if (needInvite && refs.invite.value.trim()) body.invite = refs.invite.value.trim();
|
||||
r = await App.api.post('/auth/signup', body, { auth: false });
|
||||
} else {
|
||||
r = await App.api.post('/auth/login', { username, password, device: deviceName() }, { auth: false });
|
||||
}
|
||||
App.api.setToken(r.token);
|
||||
App.setSession(r.user, r.operators);
|
||||
refs.pass.value = '';
|
||||
App.authNotice = null;
|
||||
await App.enter('pop');
|
||||
} catch (e) {
|
||||
if (e.code === 'signup_closed') { needInvite = true; draw(); refs.invite.focus(); showError(App.t('auth.invite.hint')); }
|
||||
else if (e.code === 'validation_failed') showError(validationMessage(e));
|
||||
else showError(App.errMsg(e));
|
||||
} finally {
|
||||
busy = false;
|
||||
if (refs.go) { refs.go.disabled = false; refs.goText.textContent = App.t(mode === 'signup' ? 'auth.signup' : 'auth.login'); }
|
||||
}
|
||||
}
|
||||
|
||||
function field(id, label, input, hint) {
|
||||
return h('label', { class: 'field', for: id }, h('span', { class: 'field-lbl', text: label }), input, hint ? h('span', { class: 'field-hint', text: hint }) : null);
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const keep = { u: refs.user ? refs.user.value : '', p: refs.pass ? refs.pass.value : '', i: refs.invite ? refs.invite.value : '', e: refs.err ? refs.err.textContent : '' };
|
||||
clear(box);
|
||||
const signup = mode === 'signup';
|
||||
refs.user = h('input', { id: 'f-user', name: 'username', type: 'text', autocomplete: 'username', autocapitalize: 'none', autocorrect: 'off', spellcheck: 'false', required: true, minlength: signup ? '3' : null, maxlength: '20', pattern: signup ? '[A-Za-z0-9_\\-]{3,20}' : null, enterkeyhint: 'next' });
|
||||
refs.pass = h('input', { id: 'f-pass', name: 'password', type: 'password', autocomplete: signup ? 'new-password' : 'current-password', required: true, minlength: signup ? '8' : null, maxlength: '128', enterkeyhint: needInvite && signup ? 'next' : 'go' });
|
||||
refs.invite = h('input', { id: 'f-invite', name: 'invite', type: 'text', autocomplete: 'off', autocapitalize: 'none', spellcheck: 'false', maxlength: '64', enterkeyhint: 'go' });
|
||||
refs.user.value = keep.u; refs.pass.value = keep.p; refs.invite.value = keep.i;
|
||||
refs.err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
refs.goText = h('span', { text: App.t(signup ? 'auth.signup' : 'auth.login') });
|
||||
refs.go = h('button', { class: 'btn primary wide', type: 'submit' }, icon('check'), refs.goText);
|
||||
const notice = App.authNotice ? h('p', { class: 'notice', text: App.authNotice }) : null;
|
||||
|
||||
const form = h('form', { class: 'auth-form', novalidate: false, onsubmit: submit },
|
||||
h('h1', { class: 'auth-h', text: App.t(signup ? 'auth.signup' : 'auth.login') }),
|
||||
notice,
|
||||
field('f-user', App.t('auth.username'), refs.user, signup ? App.t('auth.username.hint') : null),
|
||||
field('f-pass', App.t('auth.password'), refs.pass, signup ? App.t('auth.password.hint') : null),
|
||||
signup && needInvite ? field('f-invite', App.t('auth.invite'), refs.invite) : null,
|
||||
refs.err, refs.go,
|
||||
h('button', { class: 'linklike', type: 'button', onclick: () => { mode = signup ? 'login' : 'signup'; draw(); } }, App.t(signup ? 'auth.toLogin' : 'auth.toSignup')));
|
||||
|
||||
box.appendChild(h('div', { class: 'auth-card' },
|
||||
h('div', { class: 'auth-logo' }, h('span', { class: 'brand-mark big', 'aria-hidden': 'true' }), h('span', { class: 'auth-name', text: App.t('app.name') })),
|
||||
h('p', { class: 'auth-tag', text: App.t('app.tagline') }),
|
||||
form,
|
||||
h('div', { class: 'lang-switch', role: 'group', 'aria-label': App.t('settings.language') },
|
||||
...['en', 'nb'].map((l) => h('button', { class: 'chip-btn', type: 'button', 'aria-pressed': String(App.state.lang === l), onclick: () => App.setLang(l) }, l === 'en' ? 'EN' : 'NB')))));
|
||||
if (keep.e) showError(keep.e);
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'auth', titleKey: 'app.name', nav: false, hud: false,
|
||||
render(container) { box = container; },
|
||||
onShow() { draw(); if (window.matchMedia('(pointer: fine)').matches) setTimeout(() => { if (refs.user) refs.user.focus({ preventScroll: true }); }, 50); },
|
||||
onLang() { draw(); },
|
||||
});
|
||||
}());
|
||||
220
public/js/screens/map.js
Normal file
220
public/js/screens/map.js
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Map screen: owns the canvas (render.js draws it), fetches GET /map by viewport into a chunk cache, and shows the
|
||||
* tile info sheet. One /map request returns at most a 81 x 81 window (r <= 40), so the world is cut into 40 x 40
|
||||
* chunks and only the chunks the viewport touches are fetched, again when the camera stops moving. Land tiles are
|
||||
* implied by the API (only rural areas, incumbent sites and POPs are listed).
|
||||
*/
|
||||
(function () {
|
||||
const { h, icon, openSheet, closeSheet, toast } = UI;
|
||||
const R = UpstreamRules;
|
||||
const F = UpstreamData.FORMULAS;
|
||||
|
||||
const CHUNK = 40, STALE_MS = 60000, RETRY_MS = 6000, MAX_PARALLEL = 2;
|
||||
|
||||
// ------------------------------------------------------------------ chunk store
|
||||
class Store {
|
||||
constructor() { this.chunks = new Map(); this.active = 0; this.errShown = 0; this.onChange = null; }
|
||||
reset() { this.chunks.clear(); }
|
||||
key(i, j) { return i + ',' + j; }
|
||||
|
||||
// Make sure every chunk touching the rect is loaded and fresh.
|
||||
ensure(v, radius) {
|
||||
const i0 = Math.floor(v.x0 / CHUNK), i1 = Math.floor(v.x1 / CHUNK), j0 = Math.floor(v.y0 / CHUNK), j1 = Math.floor(v.y1 / CHUNK);
|
||||
const want = [];
|
||||
for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
|
||||
if (i * CHUNK > radius || (i + 1) * CHUNK - 1 < -radius || j * CHUNK > radius || (j + 1) * CHUNK - 1 < -radius) continue;
|
||||
const c = this.chunks.get(this.key(i, j));
|
||||
const now = Date.now();
|
||||
if (!c || (c.state === 'ok' && now - c.at > STALE_MS) || (c.state === 'error' && now - c.at > RETRY_MS)) want.push([i, j]);
|
||||
}
|
||||
// nearest to the view centre first
|
||||
want.sort((a, b) => Math.hypot((a[0] + 0.5) * CHUNK - v.cx, (a[1] + 0.5) * CHUNK - v.cy) - Math.hypot((b[0] + 0.5) * CHUNK - v.cx, (b[1] + 0.5) * CHUNK - v.cy));
|
||||
for (const [i, j] of want) this.fetch(i, j);
|
||||
}
|
||||
|
||||
async fetch(i, j) {
|
||||
const k = this.key(i, j);
|
||||
const prev = this.chunks.get(k);
|
||||
if (prev && prev.state === 'loading') return;
|
||||
if (this.active >= MAX_PARALLEL) { setTimeout(() => this.fetch(i, j), 120); return; }
|
||||
const rec = prev || { specials: [], towns: [], map: new Map(), at: 0 };
|
||||
rec.state = 'loading';
|
||||
this.chunks.set(k, rec);
|
||||
this.active++;
|
||||
const x0 = i * CHUNK, y0 = j * CHUNK;
|
||||
try {
|
||||
const r = await App.api.get('/map', { x: x0 + CHUNK / 2, y: y0 + CHUNK / 2, r: CHUNK / 2 });
|
||||
const inChunk = (o) => o.x >= x0 && o.x < x0 + CHUNK && o.y >= y0 && o.y < y0 + CHUNK;
|
||||
rec.specials = r.specials.filter(inChunk);
|
||||
rec.map = new Map(rec.specials.map((s) => [s.x * 4096 + s.y, s]));
|
||||
rec.towns = r.towns.filter(inChunk);
|
||||
rec.state = 'ok'; rec.at = Date.now();
|
||||
} catch (e) {
|
||||
rec.state = prev && prev.at ? 'ok' : 'error'; rec.at = Date.now(); // keep showing old data when a refresh fails
|
||||
if (Date.now() - this.errShown > 8000) { this.errShown = Date.now(); toast(App.t('map.error'), 'error'); }
|
||||
} finally {
|
||||
this.active--;
|
||||
if (this.onChange) this.onChange();
|
||||
}
|
||||
}
|
||||
|
||||
chunkAt(x, y) { return this.chunks.get(this.key(Math.floor(x / CHUNK), Math.floor(y / CHUNK))); }
|
||||
special(x, y) { const c = this.chunkAt(x, y); return c ? c.map.get(x * 4096 + y) : undefined; }
|
||||
townAt(x, y) { const c = this.chunkAt(x, y); return c ? c.towns.find((t) => t.x === x && t.y === y) : undefined; }
|
||||
loaded(x, y) { const c = this.chunkAt(x, y); return !!c && c.state === 'ok'; }
|
||||
|
||||
forEachSpecial(x0, y0, x1, y1, fn) {
|
||||
for (const c of this.chunks.values()) for (const s of c.specials) if (s.x >= x0 && s.x <= x1 && s.y >= y0 && s.y <= y1) fn(s);
|
||||
}
|
||||
townsInRect(x0, y0, x1, y1) {
|
||||
const out = [];
|
||||
for (const c of this.chunks.values()) for (const t of c.towns) if (t.x >= x0 && t.x <= x1 && t.y >= y0 && t.y <= y1) out.push(t);
|
||||
return out;
|
||||
}
|
||||
// After a rename the capital on the map must not show a stale name.
|
||||
patchTown(id, patch) { for (const c of this.chunks.values()) for (const t of c.towns) if (t.id === id) Object.assign(t, patch); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ screen
|
||||
let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own';
|
||||
const store = new Store();
|
||||
let infoSheet = null;
|
||||
|
||||
const ownOperatorId = () => (App.state.operator ? App.state.operator.id : null);
|
||||
const capital = () => App.state.towns.find((t) => t.isCapital) || App.state.towns[0] || null;
|
||||
|
||||
function updateCoords() {
|
||||
if (!coordsEl || !view) return;
|
||||
coordsEl.textContent = 'x ' + Math.round(view.cx) + ' · y ' + Math.round(view.cy);
|
||||
}
|
||||
|
||||
function centreOnOwn() {
|
||||
const c = App.state.towns.find((t) => t.id === App.state.townId) || capital();
|
||||
if (!c) return;
|
||||
view.setView(c.x, c.y, 30);
|
||||
}
|
||||
|
||||
function setup() {
|
||||
if (ready) return;
|
||||
ready = true;
|
||||
canvas = h('canvas', { class: 'map-canvas', tabindex: '0', role: 'application', 'aria-label': App.t('map.label') });
|
||||
coordsEl = h('div', { class: 'map-coords mono', 'aria-hidden': 'true' });
|
||||
legendEl = h('ul', { class: 'map-legend', 'aria-hidden': 'true' });
|
||||
const zoomBtn = (name, label, f) => h('button', { class: 'map-btn', type: 'button', 'aria-label': label, onclick: f }, icon(name));
|
||||
const controls = h('div', { class: 'map-controls' },
|
||||
zoomBtn('plus', App.t('map.zoomIn'), () => view.zoomAt(view.w / 2, view.h / 2, 1.5)),
|
||||
zoomBtn('minus', App.t('map.zoomOut'), () => view.zoomAt(view.w / 2, view.h / 2, 1 / 1.5)),
|
||||
zoomBtn('locate', App.t('map.centre'), centreOnOwn));
|
||||
controls.dataset.role = 'controls';
|
||||
box.appendChild(canvas); box.appendChild(legendEl); box.appendChild(coordsEl); box.appendChild(controls);
|
||||
|
||||
const source = {
|
||||
forEachSpecial: (a, b, c, d, fn) => store.forEachSpecial(a, b, c, d, fn),
|
||||
townsInRect: (a, b, c, d) => store.townsInRect(a, b, c, d),
|
||||
isOwn: (t) => t.owner.id === ownOperatorId(),
|
||||
};
|
||||
view = new MapRender.MapView(canvas, source, {
|
||||
onTap: onTap,
|
||||
onMoveEnd: (v) => { updateCoords(); store.ensure(v, App.state.world ? App.state.world.mapRadius : 50); },
|
||||
});
|
||||
view.labelFn = (t, own) => (own ? t.name : t.owner.name);
|
||||
view.reachTiles = F.ruralReach;
|
||||
store.onChange = () => view.invalidate();
|
||||
new ResizeObserver(() => { if (visible && view.resize()) updateCoords(); }).observe(box);
|
||||
// The camera moves are frequent; keep the coords chip in step cheaply.
|
||||
canvas.addEventListener('pointermove', () => updateCoords());
|
||||
canvas.addEventListener('wheel', () => updateCoords(), { passive: true });
|
||||
drawLegend();
|
||||
}
|
||||
|
||||
function drawLegend() {
|
||||
UI.clear(legendEl);
|
||||
const item = (cls, text) => h('li', null, h('span', { class: 'lg ' + cls }), text);
|
||||
legendEl.appendChild(item('you', App.t('map.legend.you')));
|
||||
legendEl.appendChild(item('rival', App.t('map.legend.rival')));
|
||||
legendEl.appendChild(item('rural', App.t('map.legend.rural')));
|
||||
legendEl.appendChild(item('incumbent', App.t('map.legend.incumbent')));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tile info
|
||||
function onTap(x, y) {
|
||||
const w = App.state.world;
|
||||
if (!w) return;
|
||||
if (Math.abs(x) > w.mapRadius || Math.abs(y) > w.mapRadius) return;
|
||||
showTile(x, y);
|
||||
}
|
||||
|
||||
function showTile(x, y) {
|
||||
view.setSelected(x, y);
|
||||
const town = store.townAt(x, y);
|
||||
const special = store.special(x, y);
|
||||
const known = store.loaded(x, y);
|
||||
const type = town ? 'pop' : special ? special.type : 'land';
|
||||
const cap = capital();
|
||||
const body = [];
|
||||
const row = (label, value) => h('div', { class: 'kv' }, h('span', { class: 'k', text: label }), h('span', { class: 'v', text: value }));
|
||||
|
||||
if (town) {
|
||||
const own = town.owner.id === ownOperatorId();
|
||||
body.push(h('div', { class: 'pill-row' },
|
||||
own ? h('span', { class: 'pill accent', text: App.t('map.info.yours') }) : h('span', { class: 'pill', text: App.t('map.info.rival') }),
|
||||
town.isCapital ? h('span', { class: 'pill', text: App.t('map.info.capital') }) : null,
|
||||
town.owner.protected ? h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')) : null));
|
||||
body.push(row(App.t('map.info.operator'), town.owner.name));
|
||||
body.push(row(App.t('map.info.as'), UpstreamI18n.fmtAs(town.owner.asNumber)));
|
||||
} else if (special && special.type === 'rural') {
|
||||
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.rural', { n: F.ruralReach, p: Math.round(F.ruralBonus * 100), res: App.resName(special.bonus) }) }));
|
||||
body.push(h('div', { class: 'pill-row' }, h('span', { class: 'pill res-' + special.bonus }, icon(special.bonus), '+' + Math.round(F.ruralBonus * 100) + '% ' + App.resName(special.bonus))));
|
||||
} else if (special && special.type === 'incumbent') {
|
||||
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.incumbent') }));
|
||||
} else if (!known) {
|
||||
body.push(h('p', { class: 'detail-desc dimmer', text: App.t('map.scanning') }));
|
||||
} else {
|
||||
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
|
||||
}
|
||||
body.push(row('', App.t('map.info.coords', { x, y })));
|
||||
if (cap && !(town && town.id === cap.id)) body.push(row('', App.t('map.info.distance', { d: App.fmt.dec(R.distance(cap.x, cap.y, x, y)) })));
|
||||
if (town && town.owner.id === ownOperatorId() && App.state.towns.some((t) => t.id === town.id)) {
|
||||
body.push(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { closeSheet(); App.setTown(town.id); App.go('pop'); } }, icon('pop'), App.t('map.info.open')));
|
||||
}
|
||||
const title = town ? town.name : App.t('tile.' + type);
|
||||
infoSheet = openSheet({
|
||||
title, icon: town ? 'pop' : type === 'rural' ? 'fiber' : type === 'incumbent' ? 'b-core_router' : 'map', iconClass: special && special.type === 'rural' ? 'res-' + special.bonus : (town && town.owner.id === ownOperatorId() ? 'own' : ''),
|
||||
closeLabel: App.t('common.close'), body: h('div', { class: 'detail' }, body),
|
||||
onClose: () => { if (view) view.setSelected(null); infoSheet = null; },
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ screen registration
|
||||
App.registerScreen({
|
||||
id: 'map', titleKey: 'screen.map', navKey: 'nav.map', icon: 'map', hud: true,
|
||||
render(container) {
|
||||
box = container;
|
||||
App.on('session', () => { store.reset(); pendingFocus = 'own'; });
|
||||
App.on('town', () => { const t = App.state.townData; if (t) store.patchTown(t.id, { name: t.name }); });
|
||||
},
|
||||
onShow(params) {
|
||||
visible = true;
|
||||
if (!App.state.world) { UI.clear(box); box.appendChild(h('p', { class: 'empty pad', text: App.t('map.noWorld') })); ready = false; return; }
|
||||
setup();
|
||||
view.setWorld(App.state.world.mapRadius);
|
||||
const apply = () => {
|
||||
if (params && Number.isFinite(params.x)) view.setView(params.x, params.y, params.zoom || 40);
|
||||
else if (pendingFocus) { centreOnOwn(); pendingFocus = null; }
|
||||
else view.setView(view.cx, view.cy);
|
||||
updateCoords();
|
||||
};
|
||||
// the container was display:none until now: measure after layout
|
||||
requestAnimationFrame(() => { if (view.resize()) apply(); else setTimeout(() => { view.resize(); apply(); }, 60); });
|
||||
},
|
||||
onHide() { visible = false; closeSheet(); },
|
||||
onLang() {
|
||||
if (!ready) return;
|
||||
canvas.setAttribute('aria-label', App.t('map.label'));
|
||||
drawLegend();
|
||||
const labels = ['map.zoomIn', 'map.zoomOut', 'map.centre'];
|
||||
box.querySelectorAll('.map-controls .map-btn').forEach((b, i) => b.setAttribute('aria-label', App.t(labels[i])));
|
||||
},
|
||||
});
|
||||
}());
|
||||
495
public/js/screens/pop.js
Normal file
495
public/js/screens/pop.js
Normal file
|
|
@ -0,0 +1,495 @@
|
|||
'use strict';
|
||||
/*
|
||||
* POP screen: header, build queue, power, resource fields (grouped by type), infrastructure; tap a building for
|
||||
* the detail sheet. All numbers come from GET /towns/:id (the server's "next" plan decides what is buildable); the
|
||||
* client only ticks values forward with rules.js and re-checks affordability live, so a button wakes up the moment
|
||||
* the resources are there. Countdowns come from the server clock (App.now()).
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet, closeSheet } = UI;
|
||||
const R = UpstreamRules;
|
||||
const D = UpstreamData;
|
||||
const F = D.FORMULAS;
|
||||
|
||||
let box = null, dirty = true, visible = false;
|
||||
let refs = { tiles: new Map(), rows: new Map(), queue: [] };
|
||||
let offTick = null;
|
||||
let prevQueue = null;
|
||||
const refetchTries = new Map(); // queue event id -> refetch attempts after it came due
|
||||
let sheetCtl = null;
|
||||
|
||||
const td = () => App.state.townData;
|
||||
const find = (key) => (td() ? td().buildings.find((b) => b.key === key) : null);
|
||||
const resOf = (type) => D.FIELD_PRODUCES[type] || null;
|
||||
|
||||
// ------------------------------------------------------------------ building state (live)
|
||||
// 'queued' | 'ready' | 'locked' | 'max' | 'wait'. `code` is the reason it cannot be built now (null = can).
|
||||
function stateOf(b, cur) {
|
||||
const t = td();
|
||||
if (t.queue.some((q) => q.key === b.key)) return { st: 'queued', code: 'already_queued' };
|
||||
if (b.level >= b.maxLevel) return { st: 'max', code: 'max_level' };
|
||||
const n = b.next;
|
||||
let code = n.code;
|
||||
if (code === 'not_enough_resources' && cur && n.cost) {
|
||||
let ok = true;
|
||||
for (const r of D.RESOURCES) if (cur.amounts[r] + 1e-6 < n.cost[r]) ok = false;
|
||||
if (ok) code = null;
|
||||
}
|
||||
if (code === null) return { st: 'ready', code: null };
|
||||
if (code === 'requirements_not_met') return { st: 'locked', code };
|
||||
return { st: 'wait', code };
|
||||
}
|
||||
|
||||
// How long until the resources for `cost` are there (ms), or null if never (rate 0) / Infinity if above the storage cap.
|
||||
function etaFor(cost, cur) {
|
||||
let worst = 0;
|
||||
for (const r of D.RESOURCES) {
|
||||
const need = cost[r] - cur.amounts[r];
|
||||
if (need <= 0) continue;
|
||||
if (cost[r] > cur.caps[r]) return Infinity;
|
||||
const rate = cur.rates[r];
|
||||
if (rate <= 0) return null;
|
||||
worst = Math.max(worst, need / rate * D.HOUR_MS);
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ pieces
|
||||
function costChips(cost, cur, withHave) {
|
||||
return h('div', { class: 'costs' }, D.RESOURCES.map((r) => {
|
||||
const short = cur && cur.amounts[r] + 1e-6 < cost[r];
|
||||
return h('span', { class: 'cost ' + r + (short ? ' short' : ''), dataset: { res: r } }, icon(r),
|
||||
h('b', { text: App.fmt.num(cost[r]) }),
|
||||
withHave && cur ? h('small', { text: App.t('sheet.have', { n: App.fmt.num(cur.amounts[r]) }) }) : null);
|
||||
}));
|
||||
}
|
||||
|
||||
const fmt2 = (x) => x.toFixed(2).replace('.', App.state.lang === 'nb' ? ',' : '.');
|
||||
|
||||
function levelPreview(b, toLevel) {
|
||||
// [{ text }] lines describing what the next level changes, from rules.js.
|
||||
const t = td(), rt = App.rulesTown(), world = App.state.world;
|
||||
const lines = [];
|
||||
const fmt = App.fmt;
|
||||
const withLevel = (lvl) => {
|
||||
const bb = Object.assign({}, rt.buildings);
|
||||
bb[b.key] = { type: b.type, level: lvl };
|
||||
return Object.assign({}, rt, { buildings: bb });
|
||||
};
|
||||
if (b.kind === 'field') {
|
||||
const res = resOf(b.type);
|
||||
const mult = res === 'power' ? 1 : (world.speed || 1) * (1 + ((t.bonus && t.bonus[res]) || 0));
|
||||
const a = R.fieldOutputPerHour(b.level) * mult, c = R.fieldOutputPerHour(toLevel) * mult;
|
||||
lines.push(App.t('sheet.preview.output', { a: fmt.dec(a), b: fmt.dec(c) }) + ' ' + App.resName(res));
|
||||
} else if (b.type === 'rack_hall') {
|
||||
lines.push(App.t('sheet.preview.storage', { a: fmt.num(R.storageCap(withLevel(b.level))), b: fmt.num(R.storageCap(withLevel(toLevel))) }));
|
||||
} else if (b.type === 'battery_bank') {
|
||||
lines.push(App.t('sheet.preview.battery', { a: fmt.num(R.batteryCap(withLevel(b.level))), b: fmt.num(R.batteryCap(withLevel(toLevel))) }));
|
||||
} else if (b.type === 'core_router') {
|
||||
const k = (l) => fmt2(1 / (1 + F.coreSpeedPerLevel * l));
|
||||
lines.push(App.t('sheet.preview.core', { a: k(b.level), b: k(toLevel) }));
|
||||
if (toLevel === F.secondQueueCoreLevel) lines.push(App.t('sheet.preview.core2', { n: toLevel }));
|
||||
} else if (b.type === 'firewall') {
|
||||
lines.push(App.t('sheet.preview.firewall', { a: fmt2(1 + F.firewallPerLevel * b.level), b: fmt2(1 + F.firewallPerLevel * toLevel) }));
|
||||
}
|
||||
const def = D.BUILDINGS[b.type];
|
||||
if (def && def.draw > 0) lines.push(App.t('sheet.preview.draw', { n: def.draw }));
|
||||
return lines;
|
||||
}
|
||||
|
||||
function requirementList(b) {
|
||||
const def = D.BUILDINGS[b.type];
|
||||
const levels = {};
|
||||
for (const x of td().buildings) if (x.kind === 'infra') levels[x.type] = x.level;
|
||||
return (def.requires || []).map((rq) => {
|
||||
const have = levels[rq.type] || 0, ok = have >= rq.level;
|
||||
return h('li', { class: ok ? 'ok' : 'miss' }, icon(ok ? 'check' : 'lock'),
|
||||
h('span', { text: App.buildingName(rq.type) + ' ' + App.t('pop.level', { n: rq.level }) }),
|
||||
h('small', { text: App.t('sheet.have', { n: have }) }));
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ detail sheet
|
||||
function openBuilding(key, opts) {
|
||||
const first = find(key);
|
||||
if (!first) return;
|
||||
const R_ = { cur: null };
|
||||
const body = h('div', { class: 'detail' });
|
||||
const ctl = openSheet({
|
||||
title: App.buildingName(first.type), icon: 'b-' + first.type, iconClass: first.kind === 'field' ? 'res-' + resOf(first.type) : '',
|
||||
closeLabel: App.t('common.close'), body,
|
||||
onClose: () => { if (offSheetTick) offSheetTick(); offSheetTick = null; sheetCtl = null; },
|
||||
});
|
||||
sheetCtl = ctl;
|
||||
let offSheetTick = null;
|
||||
|
||||
const els = {};
|
||||
function build() {
|
||||
for (const k of Object.keys(els)) delete els[k];
|
||||
const b = find(key);
|
||||
if (!b) { ctl.close(); return; }
|
||||
const cur = App.resourcesNow();
|
||||
clear(body);
|
||||
body.appendChild(h('p', { class: 'detail-desc', text: App.buildingDesc(b.type) }));
|
||||
body.appendChild(h('div', { class: 'detail-level' },
|
||||
h('span', { class: 'lvl-now', text: b.level > 0 ? App.t('sheet.level', { n: b.level }) : App.t('pop.notBuilt') }),
|
||||
b.level < b.maxLevel ? h('span', { class: 'lvl-next' }, icon('up'), App.t('sheet.nextLevel', { n: b.level + 1 })) : h('span', { class: 'lvl-next', text: App.t('sheet.maxed') })));
|
||||
|
||||
const queued = td().queue.find((q) => q.key === key);
|
||||
if (queued) {
|
||||
els.qbar = h('i');
|
||||
els.qtime = h('b', { class: 'mono' });
|
||||
body.appendChild(h('div', { class: 'detail-queue' },
|
||||
h('div', { class: 'row' }, h('span', { text: App.t('sheet.underway') + ' · ' + App.t('pop.queue.to', { n: queued.toLevel }) }), els.qtime),
|
||||
h('div', { class: 'bar' }, els.qbar)));
|
||||
els.cancel = h('button', { class: 'btn danger wide', type: 'button', onclick: () => confirmCancel(queued) }, icon('x'), App.t('sheet.cancel'));
|
||||
body.appendChild(els.cancel);
|
||||
updateQueueEls(queued, App.now());
|
||||
return;
|
||||
}
|
||||
if (b.level >= b.maxLevel) return;
|
||||
|
||||
const to = b.level + 1;
|
||||
const next = b.next;
|
||||
for (const text of levelPreview(b, to)) body.appendChild(h('p', { class: 'preview', text }));
|
||||
els.costs = costChips(next.cost, cur, true);
|
||||
body.appendChild(h('h3', { class: 'sub', text: App.t('sheet.cost') }));
|
||||
body.appendChild(els.costs);
|
||||
body.appendChild(h('div', { class: 'row meta' }, icon('clock'), h('span', { text: App.t('sheet.time') + ': ' }), h('b', { text: App.fmt.dur(next.durationMs) })));
|
||||
const reqs = requirementList(b);
|
||||
if (reqs.length) { body.appendChild(h('h3', { class: 'sub', text: App.t('sheet.requires') })); body.appendChild(h('ul', { class: 'reqs' }, reqs)); }
|
||||
els.reason = h('p', { class: 'reason', 'aria-live': 'polite' });
|
||||
els.btn = h('button', { class: 'btn primary wide', type: 'button', onclick: () => doBuild(b.key) }, icon('up'), h('span', { text: App.t(b.level > 0 ? 'sheet.upgrade' : 'sheet.build', { n: to }) }));
|
||||
body.appendChild(els.reason);
|
||||
body.appendChild(els.btn);
|
||||
updateLive();
|
||||
}
|
||||
|
||||
function updateQueueEls(q, now) {
|
||||
const left = q.dueAt - now;
|
||||
els.qtime.textContent = App.fmt.clock(left);
|
||||
els.qbar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))));
|
||||
}
|
||||
|
||||
let busy = false;
|
||||
function updateLive() {
|
||||
const b = find(key);
|
||||
if (!b || !els.btn) return;
|
||||
const cur = App.resourcesNow();
|
||||
const s = stateOf(b, cur);
|
||||
for (const chip of els.costs.children) chip.classList.toggle('short', cur.amounts[chip.dataset.res] + 1e-6 < b.next.cost[chip.dataset.res]);
|
||||
const can = s.code === null && !busy;
|
||||
els.btn.disabled = !can;
|
||||
let reason = '';
|
||||
if (s.code) {
|
||||
reason = App.t('err.' + s.code);
|
||||
if (s.code === 'not_enough_resources') {
|
||||
const eta = etaFor(b.next.cost, cur);
|
||||
if (eta === Infinity) reason = App.t('sheet.capTooLow', { cap: App.fmt.num(cur.caps.fiber) });
|
||||
else if (eta !== null) reason = App.t('sheet.affordableIn', { t: App.fmt.dur(Math.max(1000, eta)) });
|
||||
}
|
||||
}
|
||||
els.reason.textContent = reason;
|
||||
els.reason.hidden = !reason;
|
||||
}
|
||||
|
||||
async function doBuild(k) {
|
||||
if (busy) return;
|
||||
busy = true; els.btn.disabled = true;
|
||||
els.btn.querySelector('span').textContent = App.t('sheet.building');
|
||||
const t = td();
|
||||
try {
|
||||
const b = find(k);
|
||||
await App.api.post('/towns/' + t.id + '/build', { key: k }, { intent: 'build:' + t.id + ':' + k });
|
||||
toast(App.t('sheet.built', { name: App.buildingName(b.type), n: b.level + 1 }), 'ok');
|
||||
ctl.close();
|
||||
await App.refreshTown();
|
||||
} catch (e) {
|
||||
toast(App.errMsg(e), 'error');
|
||||
busy = false;
|
||||
try { await App.refreshTown(); } catch (e2) { /* shown by the offline chip */ }
|
||||
if (sheetCtl === ctl) build();
|
||||
}
|
||||
}
|
||||
|
||||
function confirmCancel(q) {
|
||||
clear(body);
|
||||
const b = find(key);
|
||||
body.appendChild(h('p', { class: 'detail-desc', text: App.t('sheet.cancel.confirm', { name: App.buildingName(b.type), n: q.toLevel }) }));
|
||||
body.appendChild(h('p', { class: 'preview', text: App.t('sheet.cancel.refund') }));
|
||||
body.appendChild(h('div', { class: 'btn-row' },
|
||||
h('button', { class: 'btn', type: 'button', onclick: () => build() }, App.t('sheet.cancel.keep')),
|
||||
h('button', { class: 'btn danger', type: 'button', onclick: async (ev) => {
|
||||
ev.currentTarget.disabled = true;
|
||||
try {
|
||||
await App.api.del('/towns/' + td().id + '/queue/' + q.id);
|
||||
toast(App.t('sheet.cancelled'), 'ok');
|
||||
} catch (e) { toast(App.errMsg(e), 'error'); }
|
||||
ctl.close();
|
||||
App.refreshTown().catch(() => {});
|
||||
} }, icon('x'), App.t('sheet.cancel'))));
|
||||
}
|
||||
|
||||
offSheetTick = App.onTick((now) => {
|
||||
const q = td() && td().queue.find((x) => x.key === key);
|
||||
if (q && els.qtime) updateQueueEls(q, now); else if (els.btn) updateLive();
|
||||
});
|
||||
const offTown = App.on('town', () => { if (sheetCtl === ctl) build(); });
|
||||
const prevClose = offSheetTick;
|
||||
offSheetTick = () => { prevClose(); offTown(); };
|
||||
build();
|
||||
if (opts && opts.cancel) { const q = td().queue.find((x) => x.key === key); if (q) confirmCancel(q); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ main drawing
|
||||
function tileLabel(b, s) {
|
||||
const status = s.st === 'queued' ? App.t('pop.inQueue') : s.st === 'ready' ? App.t('pop.upgradeReady') : s.st === 'max' ? App.t('pop.max') : s.st === 'locked' ? App.t('pop.locked') : '';
|
||||
return App.buildingName(b.type) + ', ' + (b.level > 0 ? App.t('pop.level', { n: b.level }) : App.t('pop.notBuilt')) + (status ? ', ' + status : '');
|
||||
}
|
||||
|
||||
function fieldTile(b) {
|
||||
const res = resOf(b.type);
|
||||
const lvl = h('b', { class: 'tile-lvl', text: String(b.level) });
|
||||
const badge = h('span', { class: 'tile-badge', 'aria-hidden': 'true' });
|
||||
const bar = h('i');
|
||||
const el = h('button', { class: 'tile res-' + res, type: 'button', dataset: { key: b.key }, onclick: () => openBuilding(b.key) },
|
||||
icon('b-' + b.type, 'tile-ic'), lvl, badge, h('span', { class: 'tile-bar', 'aria-hidden': 'true' }, bar));
|
||||
refs.tiles.set(b.key, { el, badge, bar, b });
|
||||
return el;
|
||||
}
|
||||
|
||||
function infraRow(b) {
|
||||
const status = h('span', { class: 'pill' });
|
||||
const sub = h('span', { class: 'row-sub' });
|
||||
const bar = h('i');
|
||||
const el = h('button', { class: 'row-btn', type: 'button', dataset: { key: b.key }, onclick: () => openBuilding(b.key) },
|
||||
h('span', { class: 'row-ic' }, icon('b-' + b.type)),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: App.buildingName(b.type) }), h('span', { class: 'lv', text: b.level > 0 ? App.t('pop.level', { n: b.level }) : App.t('pop.notBuilt') })),
|
||||
sub),
|
||||
status, h('span', { class: 'tile-bar', 'aria-hidden': 'true' }, bar));
|
||||
refs.rows.set(b.key, { el, status, sub, bar, b });
|
||||
return el;
|
||||
}
|
||||
|
||||
function header(t) {
|
||||
const st = App.state;
|
||||
const bonus = D.RESOURCES.filter((r) => (t.bonus && t.bonus[r] > 0)).map((r) => h('span', { class: 'pill res-' + r }, icon(r), '+' + Math.round(t.bonus[r] * 100) + '% ' + App.resName(r)));
|
||||
const title = st.towns.length > 1
|
||||
? h('select', { class: 'town-select', 'aria-label': App.t('screen.pop'), onchange: (e) => App.setTown(Number(e.target.value)) },
|
||||
st.towns.map((x) => h('option', { value: x.id, selected: x.id === t.id, text: x.name })))
|
||||
: h('h1', { class: 'town-name', text: t.name });
|
||||
return h('section', { class: 'card pop-head' },
|
||||
h('div', { class: 'pop-title' }, title,
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('pop.rename'), onclick: openRename }, icon('pencil'))),
|
||||
h('div', { class: 'pop-meta' },
|
||||
h('span', { text: App.t('pop.coords', { x: t.x, y: t.y }) }),
|
||||
t.isCapital ? h('span', { class: 'pill accent', text: App.t('pop.capital') }) : null,
|
||||
h('span', { class: 'pill' }, icon('shield'), App.t('pop.loyalty') + ' ' + App.fmt.num(t.loyalty)),
|
||||
h('span', { class: 'pill', text: App.t('pop.footprint') + ' ' + App.fmt.num(t.footprint) + ' (' + App.t('pop.footprintPerDay', { n: App.fmt.num(t.footprintPerDay) }) + ')' }),
|
||||
bonus.length ? bonus : h('span', { class: 'pill dim', text: App.t('pop.bonus.none') })));
|
||||
}
|
||||
|
||||
function openRename() {
|
||||
const t = td();
|
||||
const input = h('input', { type: 'text', value: t.name, maxlength: '40', minlength: '2', 'aria-label': App.t('pop.rename.label'), autocomplete: 'off', enterkeyhint: 'done' });
|
||||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const save = h('button', { class: 'btn primary wide', type: 'submit' }, icon('check'), App.t('common.save'));
|
||||
const form = h('form', { class: 'detail', onsubmit: async (ev) => {
|
||||
ev.preventDefault();
|
||||
const name = input.value.trim();
|
||||
if (name.length < 2) { err.textContent = App.t('err.validation_failed'); err.hidden = false; return; }
|
||||
save.disabled = true;
|
||||
try {
|
||||
const r = await App.api.post('/towns/' + t.id + '/rename', { name });
|
||||
const known = App.state.towns.find((x) => x.id === t.id);
|
||||
if (known) known.name = r.name;
|
||||
toast(App.t('pop.rename.done'), 'ok');
|
||||
sheet.close();
|
||||
await App.refreshTown();
|
||||
} catch (e) { err.textContent = App.errMsg(e); err.hidden = false; save.disabled = false; }
|
||||
} }, h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('pop.rename.label') }), input), err, save);
|
||||
const sheet = openSheet({ title: App.t('pop.rename'), icon: 'pencil', closeLabel: App.t('common.close'), body: form });
|
||||
setTimeout(() => { input.focus(); input.select(); }, 60);
|
||||
}
|
||||
|
||||
function queueCard(t) {
|
||||
refs.queue = [];
|
||||
const slots = h('span', { class: 'pill', text: App.t('pop.queue.slots', { used: t.queue.length, total: t.queueSlots }) });
|
||||
const list = h('div', { class: 'queue' });
|
||||
for (const q of t.queue) {
|
||||
const time = h('b', { class: 'mono' }), bar = h('i');
|
||||
const name = App.buildingName(q.type);
|
||||
list.appendChild(h('div', { class: 'q-item' },
|
||||
h('button', { class: 'q-main', type: 'button', onclick: () => openBuilding(q.key), 'aria-label': name + ' ' + App.t('pop.queue.to', { n: q.toLevel }) },
|
||||
h('span', { class: 'row-ic' }, icon('b-' + q.type)),
|
||||
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: name }), h('span', { class: 'lv', text: App.t('pop.queue.to', { n: q.toLevel }) })),
|
||||
h('span', { class: 'bar' }, bar)),
|
||||
time),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('pop.queue.cancel') + ': ' + name, onclick: () => openBuilding(q.key, { cancel: true }) }, icon('x'))));
|
||||
refs.queue.push({ q, time, bar });
|
||||
}
|
||||
if (!t.queue.length) list.appendChild(h('p', { class: 'empty', text: App.t('pop.queue.empty') }));
|
||||
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.queue.title') }), slots), list);
|
||||
}
|
||||
|
||||
function powerCard() {
|
||||
refs.power = { out: h('b'), draw: h('b'), net: h('b'), buf: h('span', { class: 'mono' }), bar: h('i'), status: h('p', { class: 'power-status' }) };
|
||||
const p = refs.power;
|
||||
return h('section', { class: 'card power-card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('power'), App.t('power.title'))),
|
||||
h('div', { class: 'stat-row' },
|
||||
h('div', { class: 'stat' }, h('small', { text: App.t('power.out') }), p.out),
|
||||
h('div', { class: 'stat' }, h('small', { text: App.t('power.draw') }), p.draw),
|
||||
h('div', { class: 'stat' }, h('small', { text: App.t('power.net') }), p.net)),
|
||||
h('div', { class: 'row' }, h('span', { class: 'dimmer', text: App.t('power.buffer') }), p.buf),
|
||||
h('div', { class: 'bar power-bar', 'aria-hidden': 'true' }, p.bar), p.status);
|
||||
}
|
||||
|
||||
function fieldsCard(t) {
|
||||
const fields = t.buildings.filter((b) => b.kind === 'field');
|
||||
const world = App.state.world;
|
||||
const groups = h('div', { class: 'groups' });
|
||||
for (const type of D.FIELD_TYPES) {
|
||||
const list = fields.filter((b) => b.type === type);
|
||||
if (!list.length) continue;
|
||||
const res = resOf(type);
|
||||
const mult = res === 'power' ? 1 : (world.speed || 1) * (1 + ((t.bonus && t.bonus[res]) || 0));
|
||||
const total = list.reduce((s, b) => s + R.fieldOutputPerHour(b.level) * mult, 0);
|
||||
groups.appendChild(h('div', { class: 'group res-' + res },
|
||||
h('div', { class: 'group-head' }, icon(res), h('b', { text: App.buildingName(type) }), h('span', { class: 'dimmer', text: '×' + list.length }),
|
||||
h('span', { class: 'group-rate', text: App.fmt.dec(total, true) + ' ' + App.resName(res) + App.t('common.perHour') })),
|
||||
h('div', { class: 'tiles' }, list.map(fieldTile))));
|
||||
}
|
||||
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.fields.title') })), groups);
|
||||
}
|
||||
|
||||
function infraCard(t) {
|
||||
const list = t.buildings.filter((b) => b.kind === 'infra');
|
||||
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.infra.title') })), h('div', { class: 'rows' }, list.map(infraRow)));
|
||||
}
|
||||
|
||||
function draw() {
|
||||
dirty = false;
|
||||
refs = { tiles: new Map(), rows: new Map(), queue: [] };
|
||||
clear(box);
|
||||
const t = td();
|
||||
if (!App.state.townId) { box.appendChild(h('p', { class: 'empty pad', text: App.t('pop.noTown') })); return; }
|
||||
if (!t) { box.appendChild(h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') }))); return; }
|
||||
box.appendChild(h('div', { class: 'cols' },
|
||||
h('div', { class: 'col' }, header(t), queueCard(t), powerCard()),
|
||||
h('div', { class: 'col' }, fieldsCard(t), infraCard(t))));
|
||||
tick(App.now());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ ticking
|
||||
function tick(now) {
|
||||
const t = td();
|
||||
if (!t || !refs.power) return;
|
||||
const cur = App.resourcesNow(now);
|
||||
const f = App.fmt;
|
||||
|
||||
// queue countdowns + the refetch when something comes due
|
||||
for (const e of refs.queue) {
|
||||
const q = e.q, left = q.dueAt - now;
|
||||
const time = f.clock(left);
|
||||
if (e.time.textContent !== time) e.time.textContent = time;
|
||||
e.bar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))));
|
||||
if (left <= -300) {
|
||||
const tries = refetchTries.get(q.id) || { n: 0, at: 0 };
|
||||
if (Date.now() >= tries.at) {
|
||||
refetchTries.set(q.id, { n: tries.n + 1, at: Date.now() + Math.min(10000, 1500 * (tries.n + 1)) });
|
||||
App.refreshTown().catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tiles and rows
|
||||
const queueByKey = new Map(t.queue.map((q) => [q.key, q]));
|
||||
for (const [key, e] of refs.tiles) {
|
||||
const s = stateOf(e.b, cur);
|
||||
if (e.el.dataset.st !== s.st) {
|
||||
e.el.dataset.st = s.st;
|
||||
e.badge.textContent = '';
|
||||
if (s.st === 'queued') e.badge.appendChild(icon('clock'));
|
||||
else if (s.st === 'ready') e.badge.appendChild(icon('up'));
|
||||
else if (s.st === 'locked') e.badge.appendChild(icon('lock'));
|
||||
e.el.setAttribute('aria-label', tileLabel(e.b, s));
|
||||
}
|
||||
const q = queueByKey.get(key);
|
||||
e.bar.style.setProperty('--p', q ? String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))) : '0');
|
||||
}
|
||||
for (const [key, e] of refs.rows) {
|
||||
const s = stateOf(e.b, cur);
|
||||
const q = queueByKey.get(key);
|
||||
let pill = '', pillCls = 'pill', sub = '';
|
||||
if (s.st === 'queued') { pill = f.clock(q.dueAt - now); pillCls += ' amber mono'; sub = App.buildingDesc(e.b.type); }
|
||||
else if (s.st === 'ready') { pill = App.t(e.b.level > 0 ? 'pop.upgradeReady' : 'sheet.build', { n: e.b.level + 1 }); pillCls += ' green'; sub = App.buildingDesc(e.b.type); }
|
||||
else if (s.st === 'max') { pill = App.t('pop.max'); sub = App.buildingDesc(e.b.type); }
|
||||
else if (s.st === 'locked') {
|
||||
const m = (e.b.next.missing || [])[0];
|
||||
pill = m ? App.buildingName(m.type) + ' ' + App.t('pop.level', { n: m.level }) : App.t('pop.locked'); pillCls += ' dim';
|
||||
sub = App.buildingDesc(e.b.type);
|
||||
} else sub = App.buildingDesc(e.b.type);
|
||||
if (e.status.textContent !== pill) e.status.textContent = pill;
|
||||
e.status.className = pillCls;
|
||||
e.status.hidden = !pill;
|
||||
if (e.sub.textContent !== sub) e.sub.textContent = sub;
|
||||
e.el.dataset.st = s.st;
|
||||
e.bar.style.setProperty('--p', q ? String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))) : '0');
|
||||
}
|
||||
|
||||
// power
|
||||
const p = refs.power, net = cur.rates.powerNet, buf = cur.amounts.battery, bcap = cur.caps.battery;
|
||||
p.out.textContent = f.dec(cur.rates.powerOut);
|
||||
p.draw.textContent = f.dec(cur.rates.powerDraw);
|
||||
p.net.textContent = f.dec(net, true);
|
||||
p.net.className = net < 0 ? 'bad' : 'good';
|
||||
p.buf.textContent = f.num(buf) + ' / ' + f.num(bcap) + ' ' + App.t('power.unit');
|
||||
p.bar.style.setProperty('--p', String(bcap > 0 ? Math.min(1, buf / bcap) : 0));
|
||||
const speed = App.state.world.speed || 1;
|
||||
let status, cls = '';
|
||||
if (net < 0) {
|
||||
if (buf <= 0) { status = App.t('power.empty'); cls = 'bad'; }
|
||||
else { status = App.t('power.draining', { t: f.dur(buf / (-net * speed) * D.HOUR_MS) }); cls = 'warn'; }
|
||||
} else if (net > 0 && buf < bcap - 0.01) status = App.t('power.charging', { t: f.dur((bcap - buf) / (net * speed) * D.HOUR_MS) });
|
||||
else status = buf >= bcap - 0.01 && bcap > 0 ? App.t('power.full') : App.t('power.ok');
|
||||
if (p.status.textContent !== status) p.status.textContent = status;
|
||||
p.status.className = 'power-status ' + cls;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ town changed
|
||||
function onTown(t) {
|
||||
// toast for levels that finished since the last fetch
|
||||
if (prevQueue && prevQueue.townId === t.id) {
|
||||
const nowIds = new Set(t.queue.map((q) => q.id));
|
||||
for (const q of prevQueue.items) {
|
||||
if (nowIds.has(q.id)) continue;
|
||||
const b = t.buildings.find((x) => x.key === q.key);
|
||||
if (b && b.level >= q.toLevel) toast(App.t('alerts.build_done', { name: App.buildingName(q.type), level: b.level }), 'ok');
|
||||
refetchTries.delete(q.id);
|
||||
App.checkAlerts();
|
||||
}
|
||||
}
|
||||
prevQueue = { townId: t.id, items: t.queue.slice() };
|
||||
if (visible) draw(); else dirty = true;
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'pop', titleKey: 'screen.pop', navKey: 'nav.pop', icon: 'pop', hud: true,
|
||||
render(container) {
|
||||
box = container;
|
||||
App.on('town', onTown);
|
||||
App.on('session', () => { dirty = true; prevQueue = null; });
|
||||
App.on('townchange', () => { dirty = true; if (visible) draw(); });
|
||||
},
|
||||
onShow() {
|
||||
visible = true;
|
||||
draw();
|
||||
if (offTick) offTick();
|
||||
offTick = App.onTick(tick);
|
||||
if (td() && Date.now() - App.state.townFetchedAt > 15000) App.refreshTown().catch(() => {});
|
||||
},
|
||||
onHide() { visible = false; if (offTick) offTick(); offTick = null; closeSheet(); },
|
||||
});
|
||||
}());
|
||||
84
public/js/screens/settings.js
Normal file
84
public/js/screens/settings.js
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
'use strict';
|
||||
/* Settings: language, account info, device tokens (list + revoke) and logout. */
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet } = UI;
|
||||
const I = UpstreamI18n;
|
||||
|
||||
let box, devicesEl, tokens = null, tokenErr = null;
|
||||
|
||||
function kv(label, value) { return h('div', { class: 'kv' }, h('span', { class: 'k', text: label }), h('span', { class: 'v', text: value })); }
|
||||
|
||||
async function loadTokens() {
|
||||
try { tokens = (await App.api.get('/auth/tokens')).tokens; tokenErr = null; } catch (e) { tokenErr = App.errMsg(e); }
|
||||
drawDevices();
|
||||
}
|
||||
|
||||
function drawDevices() {
|
||||
if (!devicesEl) return;
|
||||
clear(devicesEl);
|
||||
if (tokenErr) { devicesEl.appendChild(h('p', { class: 'form-error', role: 'alert', text: tokenErr })); return; }
|
||||
if (!tokens) { devicesEl.appendChild(h('p', { class: 'empty', text: App.t('common.loading') })); return; }
|
||||
const now = App.now();
|
||||
for (const t of tokens) {
|
||||
devicesEl.appendChild(h('li', { class: 'device' },
|
||||
h('span', { class: 'row-ic' }, icon('device')),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: t.device || App.t('settings.device.unnamed') }), t.current ? h('span', { class: 'pill accent', text: App.t('settings.device.current') }) : null),
|
||||
h('span', { class: 'row-sub', text: App.t('settings.device.created', { t: App.fmt.ago(now - t.createdAt) }) + ' · ' + App.t('settings.device.lastUsed', { t: App.fmt.ago(now - t.lastUsedAt) }) })),
|
||||
t.current ? null : h('button', { class: 'btn small danger', type: 'button', onclick: (ev) => revoke(t, ev.currentTarget) }, App.t('settings.device.revoke'))));
|
||||
}
|
||||
}
|
||||
|
||||
async function revoke(t, btn) {
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await App.api.del('/auth/tokens/' + t.id);
|
||||
toast(App.t('settings.device.revoked'), 'ok');
|
||||
} catch (e) { if (e.code !== 'not_found') toast(App.errMsg(e), 'error'); }
|
||||
loadTokens();
|
||||
}
|
||||
|
||||
function confirmLogout() {
|
||||
const sheet = openSheet({
|
||||
title: App.t('settings.logout'), icon: 'logout', closeLabel: App.t('common.close'),
|
||||
body: h('div', { class: 'detail' }, h('p', { class: 'detail-desc', text: App.t('settings.logout.confirm') }),
|
||||
h('div', { class: 'btn-row' },
|
||||
h('button', { class: 'btn', type: 'button', onclick: () => sheet.close() }, App.t('common.cancel')),
|
||||
h('button', { class: 'btn danger', type: 'button', onclick: async () => {
|
||||
try { await App.api.post('/auth/logout', {}, { retries: 1 }); } catch (e) { /* the token may already be gone */ }
|
||||
sheet.close();
|
||||
App.clearSession();
|
||||
App.authNotice = null;
|
||||
App.go('auth');
|
||||
} }, icon('logout'), App.t('settings.logout')))),
|
||||
});
|
||||
}
|
||||
|
||||
function draw() {
|
||||
clear(box);
|
||||
const st = App.state;
|
||||
const op = st.operator, w = st.world;
|
||||
devicesEl = h('ul', { class: 'device-list' });
|
||||
box.appendChild(h('div', { class: 'page' },
|
||||
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.language') })),
|
||||
h('div', { class: 'seg', role: 'group', 'aria-label': App.t('settings.language') },
|
||||
I.LANGS.map((l) => h('button', { class: 'seg-btn', type: 'button', 'aria-pressed': String(st.lang === l), onclick: () => App.setLang(l) }, App.t('settings.lang.' + l))))),
|
||||
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.account') })),
|
||||
st.user ? kv(App.t('settings.username'), st.user.username) : null,
|
||||
op ? kv(App.t('settings.operator'), op.name) : null,
|
||||
op ? kv(App.t('settings.as'), I.fmtAs(op.asNumber)) : null,
|
||||
w ? kv(App.t('settings.world'), App.t('settings.worldInfo', { name: w.name, speed: w.speed, r: w.mapRadius })) : null,
|
||||
h('button', { class: 'btn danger wide', type: 'button', onclick: confirmLogout }, icon('logout'), App.t('settings.logout'))),
|
||||
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.devices') })),
|
||||
h('p', { class: 'dimmer small', text: App.t('settings.devices.hint') }), devicesEl),
|
||||
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.about') })),
|
||||
h('p', { class: 'dimmer small', text: App.t('settings.about.text') }))));
|
||||
drawDevices();
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'settings', titleKey: 'screen.settings', navKey: 'nav.settings', icon: 'gear', hud: false,
|
||||
render(container) { box = container; App.on('session', () => { tokens = null; }); },
|
||||
onShow() { draw(); loadTokens(); },
|
||||
});
|
||||
}());
|
||||
Loading…
Add table
Add a link
Reference in a new issue