Upstream/public/js/screens/units.js
jvanvik b18645dca1 Phase 2: client military/social screens, WebSocket push, trade + endgame, review findings pending
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
2026-10-11 19:05:03 +02:00

368 lines
20 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/*
* Units: what stands in this POP (home, reinforcements from others, your units standing elsewhere), the training queue
* with a train form, research, and the power/offline status. Everything comes from GET /towns/:id (town.military); the
* client previews cost/time with rules.trainPlan / researchPlan (same functions the server runs) and the server decides.
*/
(function () {
const { h, clear, icon, toast, openSheet, closeSheet } = UI;
const R = UpstreamRules;
const D = UpstreamData;
const Mil = UpstreamMil;
const td = () => App.state.townData;
const mi = () => (td() ? td().military : null);
const mil = () => App.mil;
let box, bodyEl, visible = false, dirty = true, offTick = null;
const refetch = new Map(); // training/research event id -> { n, at }
const num = (n) => App.fmt.num(n);
const val = (x) => (Number.isInteger(x) ? num(x) : App.fmt.dec(x));
// ------------------------------------------------------------------ pieces
function statLine(unit, levels) {
const def = D.UNITS[unit];
const a = R.unitStat(unit, 'attack', levels), d = R.unitStat(unit, 'defence', levels);
return App.t('unit.stats', { a: val(a), d: val(d), s: def.speed || 0, c: def.carry || 0 }) + (def.fixed ? ' · ' + App.t('unit.fixed') : '');
}
function unitRow(unit, count, levels, right) {
return h('li', { class: 'mil-row unit' },
h('span', { class: 'row-ic' }, mil().unitIcon(unit)),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: mil().unitName(unit) }), count !== null ? h('span', { class: 'lv mono', text: '× ' + num(count) }) : null),
h('span', { class: 'row-sub wrap', text: statLine(unit, levels) })),
right || null);
}
function unitList(units, levels) {
const rows = D.UNIT_ORDER.filter((u) => units && units[u] > 0).map((u) => unitRow(u, units[u], levels));
return rows.length ? h('ul', { class: 'mil-list' }, rows) : null;
}
// ------------------------------------------------------------------ status
function statusCard(m) {
const t = td();
if (!m.units.online) {
const until = Mil.decommissionAt(m.units.offlineSince || App.now(), App.state.world.speed);
return h('section', { class: 'card warn-card', role: 'alert' },
h('div', { class: 'card-head' }, h('h2', null, icon('power'), App.t('units.offline.title'))),
h('p', { class: 'detail-desc', text: App.t('units.offline.body') }),
h('p', { class: 'row-sub wrap' }, App.t('units.offline.decom') + ' ', mil().countdown(until)));
}
return h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('units'), App.t('units.status')),
h('span', { class: 'pill green', text: App.t('units.online') })),
h('p', { class: 'row-sub wrap', text: App.t('units.powerNet', { n: App.fmt.dec(t.power.net, true) }) }));
}
// ------------------------------------------------------------------ home / stationed
function homeCard(m) {
const levels = m.research.levels;
const list = unitList(m.units.home, levels);
return h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('units'), App.t('units.home')),
h('button', { class: 'btn small primary', type: 'button', disabled: !list, onclick: () => App.openSend({ fromTownId: td().id }) }, icon('target'), App.t('mov.send'))),
list || h('p', { class: 'empty', text: App.t('units.home.empty') }));
}
async function withdraw(hostTownId, ownerTownId, btn) {
btn.disabled = true;
try {
await App.api.post('/towns/' + hostTownId + '/withdraw', { ownerTownId }, { intent: 'withdraw:' + hostTownId + ':' + ownerTownId });
toast(App.t('units.withdrawn'), 'ok');
} catch (e) { toast(App.errMsg(e), 'error'); }
App.refreshMovements().catch(() => {});
App.refreshTown().catch(() => {});
}
function stationedCards(m) {
const out = [];
if (m.units.stationedHere.length) {
out.push(h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('shield'), App.t('units.hosted'))),
h('ul', { class: 'mil-list' }, m.units.stationedHere.map((g) => h('li', { class: 'mil-group' },
h('div', { class: 'row' },
h('span', null, h('b', { text: g.ownerTownName || '#' + g.ownerTownId }), g.owner ? h('span', { class: 'dimmer', text: ' · ' + g.owner.name }) : null),
h('button', { class: 'btn small', type: 'button', onclick: (ev) => withdraw(td().id, g.ownerTownId, ev.currentTarget) }, icon('return'), App.t('units.sendHome'))),
h('p', { class: 'row-sub wrap', text: mil().unitsText(g.units) }))))));
}
if (m.units.stationedAway.length) {
out.push(h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('flag'), App.t('units.away'))),
h('ul', { class: 'mil-list' }, m.units.stationedAway.map((g) => h('li', { class: 'mil-group' },
h('div', { class: 'row' },
h('span', null, h('b', { text: g.hostTownName || '#' + g.hostTownId })),
h('button', { class: 'btn small', type: 'button', onclick: (ev) => withdraw(g.hostTownId, td().id, ev.currentTarget) }, icon('return'), App.t('units.callBack'))),
h('p', { class: 'row-sub wrap', text: mil().unitsText(g.units) }))))));
}
return out;
}
// ------------------------------------------------------------------ training
const tailFor = (m, building) => m.training.filter((b) => b.building === building).reduce((t, b) => Math.max(t, b.dueAt), 0);
function trainingCard(m) {
const queue = h('ul', { class: 'mil-list queue' });
for (const b of m.training) {
const bar = h('i');
const li = h('li', { class: 'mil-row batch' },
h('span', { class: 'row-ic' }, mil().unitIcon(b.unit)),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: mil().unitName(b.unit) }), h('span', { class: 'lv mono', text: '× ' + num(b.count) }), h('span', { class: 'lv', text: App.buildingName(b.building) })),
h('span', { class: 'bar mil-bar', 'aria-hidden': 'true' }, bar)),
h('span', { class: 'mil-when' }, mil().countdown(b.dueAt)));
li._bar = bar; li._b = b;
queue.appendChild(li);
}
const trainable = h('ul', { class: 'mil-list' }, m.trainable.map((u) => {
const def = D.UNITS[u.unit];
const row = h('button', { class: 'row-btn mil-train' + (u.locked ? ' locked' : ''), type: 'button', dataset: { unit: u.unit }, onclick: () => openTrain(u.unit) },
h('span', { class: 'row-ic' }, mil().unitIcon(u.unit)),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: mil().unitName(u.unit) }), h('span', { class: 'lv', text: App.buildingName(def.building) })),
u.locked
? h('span', { class: 'row-sub wrap', text: App.t('units.needs') + ' ' + u.missing.map((x) => App.buildingName(x.type) + ' ' + App.t('pop.level', { n: x.level })).join(', ') })
: h('span', { class: 'row-sub wrap', text: App.t('units.perUnit', { t: App.fmt.dur(u.timeMs) }) })),
u.locked ? h('span', { class: 'pill dim' }, icon('lock')) : mil().resChips(u.cost));
return h('li', null, row);
}));
return h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('clock'), App.t('units.training')), h('span', { class: 'pill', text: String(m.training.length) })),
m.training.length ? queue : h('p', { class: 'empty', text: App.t('units.training.empty') }),
h('h3', { class: 'sub', text: App.t('units.train') }), trainable);
}
function openTrain(unit) {
const body = h('div', { class: 'detail' });
let off = null;
const ctl = openSheet({ title: mil().unitName(unit), icon: 'units', closeLabel: App.t('common.close'), body, onClose: () => { if (off) off(); } });
const els = {};
let count = 1, busy = false;
const def = D.UNITS[unit];
function plan() {
const t = td(), m = mi();
const rt = App.rulesTown();
if (!t || !rt) return null;
const p = R.trainPlan(rt, unit, count, App.now(), tailFor(m, def.building));
if (p.ok && m.training.filter((b) => b.building === def.building).length >= D.MILITARY.maxTrainQueue) return Object.assign(p, { ok: false, code: 'queue_full' });
return p;
}
function maxAffordable() {
const cur = App.resourcesNow();
if (!cur) return 1;
let n = D.MILITARY.maxBatch;
for (const r of D.RESOURCES) if (def.cost[r] > 0) n = Math.min(n, Math.floor(cur.amounts[r] / def.cost[r] + 1e-6));
return Math.max(0, n);
}
body.appendChild(h('p', { class: 'detail-desc', text: mil().unitDesc(unit) }));
body.appendChild(h('p', { class: 'preview', text: statLine(unit, mi().research.levels) + ' · ' + App.t('unit.draw', { n: def.draw }) }));
els.input = h('input', { type: 'number', inputmode: 'numeric', min: '1', max: String(D.MILITARY.maxBatch), value: '1', class: 'mil-num', 'aria-label': App.t('units.count') });
const step = (d) => { count = Math.max(1, Math.min(D.MILITARY.maxBatch, count + d)); els.input.value = String(count); live(); };
els.input.addEventListener('input', () => { const v = Math.floor(Number(els.input.value)); count = Number.isFinite(v) && v >= 1 ? Math.min(v, D.MILITARY.maxBatch) : 1; live(); });
body.appendChild(h('div', { class: 'stepper' },
h('button', { class: 'btn', type: 'button', 'aria-label': '-10', onclick: () => step(-10) }, '−10'),
h('button', { class: 'btn', type: 'button', 'aria-label': '-1', onclick: () => step(-1) }, '−'),
els.input,
h('button', { class: 'btn', type: 'button', 'aria-label': '+1', onclick: () => step(1) }, '+'),
h('button', { class: 'btn', type: 'button', 'aria-label': '+10', onclick: () => step(10) }, '+10')));
body.appendChild(h('button', { class: 'btn small wide', type: 'button', onclick: () => { count = Math.max(1, maxAffordable()); els.input.value = String(count); live(); } }, App.t('units.max')));
els.costs = h('div', { class: 'costs' });
els.time = h('b');
els.done = h('span', { class: 'dimmer' });
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('units.time') + ': ' }), els.time, els.done));
els.reason = h('p', { class: 'reason', 'aria-live': 'polite' });
els.btn = h('button', { class: 'btn primary wide', type: 'button', onclick: go }, icon('units'), h('span', { text: App.t('units.trainBtn') }));
body.appendChild(els.reason); body.appendChild(els.btn);
function live() {
const p = plan();
if (!p) return;
const cur = App.resourcesNow();
clear(els.costs);
for (const r of D.RESOURCES) {
const short = cur && cur.amounts[r] + 1e-6 < p.cost[r];
els.costs.appendChild(h('span', { class: 'cost ' + r + (short ? ' short' : '') }, icon(r), h('b', { text: num(p.cost[r]) }), cur ? h('small', { text: App.t('sheet.have', { n: num(cur.amounts[r]) }) }) : null));
}
els.time.textContent = App.fmt.dur(p.durationMs);
els.done.textContent = ' · ' + App.t('units.readyAt', { t: mil().clockTime(p.dueAt) });
let reason = '';
if (!p.ok) {
reason = App.t('err.' + p.code);
if (p.code === 'requirements_not_met' && p.missing && p.missing.length) reason += ' ' + p.missing.map((x) => App.buildingName(x.type) + ' ' + App.t('pop.level', { n: x.level })).join(', ');
}
els.reason.textContent = reason; els.reason.hidden = !reason;
els.btn.disabled = !p.ok || busy;
}
async function go() {
if (busy) return;
busy = true; els.btn.disabled = true;
const t = td();
try {
await App.api.post('/towns/' + t.id + '/train', { unit, count }, { intent: 'train:' + t.id + ':' + unit + ':' + count });
toast(App.t('units.queued', { n: num(count), unit: mil().unitName(unit) }), 'ok');
ctl.close();
await App.refreshTown();
} catch (e) {
toast(App.errMsg(e), 'error');
busy = false;
App.refreshTown().catch(() => {});
live();
}
}
off = App.onTick(() => { if (!busy) live(); });
live();
}
// ------------------------------------------------------------------ research
function researchCard(m) {
const levels = m.research.levels;
const q = m.research.queue;
const head = h('div', { class: 'card-head' }, h('h2', null, icon('flask'), App.t('units.research')),
m.research.speedBonus > 0 ? h('span', { class: 'pill green', text: App.t('units.research.speed', { p: Math.round(m.research.speedBonus * 100) }) }) : null);
const busy = q ? h('div', { class: 'detail-queue' },
h('div', { class: 'row' }, h('span', { text: App.t('units.research.busy', { unit: mil().unitName(q.unit), stat: App.t('stat.' + q.stat), level: q.toLevel }) }), mil().countdown(q.dueAt)),
h('div', { class: 'bar' }, h('i', { dataset: { rs: '1' } }))) : null;
const rows = D.UNIT_ORDER.filter((u) => D.UNITS[u].attack > 0 || D.UNITS[u].defence > 0).map((u) => {
const a = levels[R.researchKey(u, 'attack')] || 0, d = levels[R.researchKey(u, 'defence')] || 0;
return h('li', null, h('button', { class: 'row-btn', type: 'button', onclick: () => openResearch(u) },
h('span', { class: 'row-ic' }, mil().unitIcon(u)),
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: mil().unitName(u) })),
h('span', { class: 'row-sub wrap', text: App.t('stat.attack') + ' ' + a + ' · ' + App.t('stat.defence') + ' ' + d })),
h('span', { class: 'pill', text: '+' + Math.round((a + d) * D.MILITARY.researchPerLevel * 100) + '%' })));
});
return h('section', { class: 'card' }, head, busy, h('ul', { class: 'mil-list' }, rows));
}
function openResearch(unit) {
const body = h('div', { class: 'detail' });
let off = null;
const ctl = openSheet({ title: mil().unitName(unit), icon: 'flask', closeLabel: App.t('common.close'), body, onClose: () => { if (off) off(); } });
let busy = false;
const def = D.UNITS[unit];
const parts = {};
function build() {
clear(body);
const m = mi();
body.appendChild(h('p', { class: 'detail-desc', text: App.t('units.research.hint', { p: Math.round(D.MILITARY.researchPerLevel * 100), max: D.RESEARCH.maxLevel }) }));
for (const stat of D.RESEARCH.stats) {
if (!(def[stat] > 0)) continue;
const level = m.research.levels[R.researchKey(unit, stat)] || 0;
const sec = h('section', { class: 'card inner' });
sec.appendChild(h('div', { class: 'card-head' }, h('h2', { text: App.t('stat.' + stat) }),
h('span', { class: 'pill', text: App.t('units.research.level', { n: level, max: D.RESEARCH.maxLevel }) })));
if (level >= D.RESEARCH.maxLevel) { sec.appendChild(h('p', { class: 'empty', text: App.t('sheet.maxed') })); body.appendChild(sec); continue; }
const costs = h('div', { class: 'costs' }), reason = h('p', { class: 'reason', 'aria-live': 'polite' }), time = h('b');
const btn = h('button', { class: 'btn primary wide', type: 'button', onclick: () => go(stat, btn) }, icon('flask'), h('span', { text: App.t('units.research.start', { n: level + 1 }) }));
sec.appendChild(h('p', { class: 'preview', text: App.t('units.research.effect', { a: val(def[stat] * R.researchMult(level)), b: val(def[stat] * R.researchMult(level + 1)) }) }));
sec.appendChild(costs);
sec.appendChild(h('div', { class: 'row meta' }, icon('clock'), h('span', { text: App.t('units.research.time') + ': ' }), time));
sec.appendChild(reason); sec.appendChild(btn);
parts[stat] = { level, costs, reason, time, btn };
body.appendChild(sec);
}
live();
}
function live() {
const m = mi(), rt = App.rulesTown();
if (!m || !rt) return;
const cur = App.resourcesNow();
for (const stat of Object.keys(parts)) {
const p = parts[stat];
const plan = R.researchPlan(rt, unit, stat, p.level, !!m.research.queue, App.now(), m.research.speedBonus);
clear(p.costs);
for (const r of D.RESOURCES) p.costs.appendChild(h('span', { class: 'cost ' + r + (cur && cur.amounts[r] + 1e-6 < plan.cost[r] ? ' short' : '') }, icon(r), h('b', { text: num(plan.cost[r]) })));
p.time.textContent = App.fmt.dur(plan.durationMs);
let reason = '';
if (!plan.ok) {
reason = App.t('err.' + plan.code);
if (plan.code === 'requirements_not_met' && plan.missing && plan.missing.length) reason += ' ' + plan.missing.map((x) => App.buildingName(x.type) + ' ' + App.t('pop.level', { n: x.level })).join(', ');
}
p.reason.textContent = reason; p.reason.hidden = !reason;
p.btn.disabled = !plan.ok || busy;
}
}
async function go(stat, btn) {
if (busy) return;
busy = true; btn.disabled = true;
const t = td();
try {
await App.api.post('/towns/' + t.id + '/research', { unit, stat }, { intent: 'research:' + t.id + ':' + unit + ':' + stat });
toast(App.t('units.research.queued'), 'ok');
ctl.close();
await App.refreshTown();
} catch (e) {
toast(App.errMsg(e), 'error');
busy = false;
App.refreshTown().then(() => build()).catch(() => {});
}
}
build();
off = App.onTick(live);
}
// ------------------------------------------------------------------ screen
function head() {
return h('div', { class: 'card-head page-head units-head' }, h('h1', { text: App.t('screen.units') }),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => App.refreshTown().catch((e) => toast(App.errMsg(e), 'error')) }, icon('refresh')));
}
function draw() {
dirty = false;
clear(bodyEl);
const t = td(), m = mi();
if (!App.state.townId) { bodyEl.appendChild(h('p', { class: 'empty pad', text: App.t('pop.noTown') })); return; }
if (!t || !m) { bodyEl.appendChild(h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') }))); return; }
bodyEl.appendChild(head());
bodyEl.appendChild(h('div', { class: 'cols' },
h('div', { class: 'col' }, statusCard(m), homeCard(m), stationedCards(m)),
h('div', { class: 'col' }, trainingCard(m), researchCard(m))));
tick(App.now());
}
function tick(now) {
const m = mi();
if (!m || !bodyEl) return;
for (const li of bodyEl.querySelectorAll('li.batch')) {
const b = li._b;
if (!b) continue;
li._bar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - b.startAt) / Math.max(1, b.dueAt - b.startAt)))));
}
const rs = bodyEl.querySelector('[data-rs]');
if (rs && m.research.queue) rs.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - m.research.queue.startedAt) / Math.max(1, m.research.queue.dueAt - m.research.queue.startedAt)))));
// something came due: refetch (with a gentle retry, like the build queue)
const items = m.training.map((b) => ({ id: 't' + b.id, due: b.dueAt })).concat(m.research.queue ? [{ id: 'r' + m.research.queue.id, due: m.research.queue.dueAt }] : []);
for (const it of items) {
if (now - it.due < 300) continue;
const tries = refetch.get(it.id) || { n: 0, at: 0 };
if (Date.now() >= tries.at) { refetch.set(it.id, { n: tries.n + 1, at: Date.now() + Math.min(10000, 1500 * (tries.n + 1)) }); App.refreshTown().catch(() => {}); }
}
}
App.registerScreen({
id: 'units', titleKey: 'screen.units', navKey: 'nav.units', icon: 'units', hud: true,
render(container) {
box = container;
bodyEl = h('div', { class: 'units-body' });
box.appendChild(bodyEl);
App.on('town', () => { if (visible) draw(); else dirty = true; });
App.on('townchange', () => { dirty = true; if (visible) draw(); });
App.on('session', () => { dirty = true; refetch.clear(); });
App.on('towns', () => { if (visible) draw(); else dirty = true; });
},
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(); },
});
}());