Upstream/public/js/milstate.js
jvanvik 9104480463 Add POST /me/join and a join card: accounts survive a world reset
Found while resetting the live test world: joinWorld's comment promised POST /worlds/:id/join but no route existed, so after reset-world (accounts kept) nobody could found a POP again. Added POST /me/join (default: first running world; 409 if already joined), a join card on the POP screen, en/nb strings, API.md + openapi. Client no longer polls /movements while it has no operator (that 404ed).

Tested: npm test 209/209 (new test/me-join.test.js incl. response contract), openapi check, npm run e2e (new check: account without a POP sees the join card and founds one). NOT tested: joining a second/other world (only the default-world path in the browser), nb text of the card visually.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-11 22:43:15 +02:00

168 lines
11 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';
/*
* Shared state and small view helpers of the military / expansion screens (browser only; loads after main.js).
*
* App.mil.moves { outgoing, incoming, at }: the last GET /movements, the single source for the nav badge,
* the POP banner, the movements screen and the map lines. Emits App.emit('movements').
* App.refreshMovements() refetch it (coalesced). Called by the ticker when something arrived, by push, by the poll.
* App.refreshReportsUnread() refetch the unread count of reports (nav badge on Reports).
* App.refreshTowns() refetch /me and update the POP list WITHOUT resetting the session (after a settle/takeover).
* App.mil.* helpers unitName, unitsText, typeLabel, coordLink, countdown, chips ...
*
* Countdowns are elements with data-cd = server-clock deadline in ms; one ticker keeps all of them current, so screens
* only create them (mil.countdown) and never run their own timers for display.
*/
(function () {
const { h, icon } = UI;
const D = UpstreamData;
const Mil = UpstreamMil;
const api = App.api;
const mil = App.mil = { moves: { outgoing: [], incoming: [], alliedIncoming: [], at: 0, loaded: false }, reportsUnread: 0 };
// ------------------------------------------------------------------ names and small pieces
mil.unitName = (id) => (UpstreamI18n.strings.en['unit.' + id + '.name'] ? App.t('unit.' + id + '.name') : id);
mil.unitDesc = (id) => (UpstreamI18n.strings.en['unit.' + id + '.desc'] ? App.t('unit.' + id + '.desc') : '');
mil.typeLabel = (type) => (UpstreamI18n.strings.en['move.type.' + type] ? App.t('move.type.' + type) : type);
mil.reportTypeLabel = (type) => (UpstreamI18n.strings.en['report.type.' + type] ? App.t('report.type.' + type) : type);
mil.unitIcon = (id) => icon(Mil.ROLE_ICON[(D.UNITS[id] || {}).role] || 'units');
mil.townName = (id) => { const t = App.state.towns.find((x) => x.id === id); return t ? t.name : null; };
mil.ownTown = (id) => App.state.towns.find((x) => x.id === id) || null;
// "3 × Script crew, 2 × Botnet"
mil.unitsText = (units) => {
const parts = [];
for (const u of D.UNIT_ORDER) if (units && units[u] > 0) parts.push(App.fmt.num(units[u]) + ' × ' + mil.unitName(u));
return parts.length ? parts.join(', ') : '—';
};
// Clock time (local) at server time `ms`.
mil.clockTime = (ms) => {
try { return new Date(ms).toLocaleTimeString(App.state.lang === 'nb' ? 'nb-NO' : 'en-GB', { hour: '2-digit', minute: '2-digit' }); } catch (e) { return ''; }
};
mil.dayTime = (ms) => {
try { return new Date(ms).toLocaleString(App.state.lang === 'nb' ? 'nb-NO' : 'en-GB', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }); } catch (e) { return ''; }
};
// A link that jumps to the map at (x, y). Closes any sheet first.
mil.coordLink = (x, y, label) => h('button', { class: 'mil-coord mono', type: 'button', 'aria-label': App.t('mil.showOnMap', { x, y }), onclick: () => { UI.closeSheet(); App.go('map', { x, y, zoom: 40 }); } },
icon('map'), label || (x + ', ' + y));
// A movement endpoint ({ townId, x, y, name, owner? }) as text + coordinates link.
mil.endLink = (end) => h('span', { class: 'mil-end' }, end.name ? h('span', { class: 'mil-end-name', text: end.name }) : null, mil.coordLink(end.x, end.y));
// Resource chips: { fiber, hardware, capital } (zero entries are skipped).
mil.resChips = (res, signed) => {
const out = [];
for (const r of D.RESOURCES) if (res && res[r]) out.push(h('span', { class: 'cost ' + r }, icon(r), h('b', { text: (signed ? '+' : '') + App.fmt.num(res[r]) })));
return h('div', { class: 'costs' }, out.length ? out : h('span', { class: 'dimmer', text: '—' }));
};
// <b class="mono" data-cd="<deadline ms>">m:ss</b>, kept current by the ticker below.
mil.countdown = (deadline, opts) => {
const el = h('b', { class: 'mono mil-cd' + (opts && opts.cls ? ' ' + opts.cls : ''), dataset: { cd: String(deadline) } });
el.textContent = App.fmt.clock(deadline - App.now());
return el;
};
// Progress 0..1 of a movement.
mil.progress = (m, now) => Math.max(0, Math.min(1, (now - m.departAt) / Math.max(1, m.arriveAt - m.departAt)));
// ------------------------------------------------------------------ the ticker: countdowns + "something arrived" refetch
let lastMovesFetch = 0;
App.onTick((now) => {
for (const el of document.querySelectorAll('[data-cd]')) {
const s = App.fmt.clock(Number(el.dataset.cd) - now);
if (el.textContent !== s) el.textContent = s;
}
if (!App.state.user || !mil.moves.loaded) return;
// a movement is over (arrived / returned): the server dropped it, so refetch (retry no more often than every 3 s)
const due = mil.moves.outgoing.concat(mil.moves.incoming, mil.moves.alliedIncoming || []).some((m) => m.arriveAt - now < -600);
if (due && Date.now() - lastMovesFetch > 3000) { lastMovesFetch = Date.now(); App.refreshMovements().catch(() => {}); }
});
// ------------------------------------------------------------------ refetchers
let movesFlight = null;
App.refreshMovements = () => {
if (!App.state.user || !App.state.operator) return Promise.resolve(null);
if (movesFlight) return movesFlight;
lastMovesFetch = Date.now();
movesFlight = api.get('/movements').then((r) => {
// a settle that is no longer on the wire has resolved: the POP list changed (the push-less path to the same refresh)
const settled = mil.moves.loaded && mil.moves.outgoing.some((m) => m.type === 'settle' && !(r.outgoing || []).some((n) => n.id === m.id));
if (settled) App.refreshTowns().catch(() => {});
mil.moves = { outgoing: r.outgoing || [], incoming: r.incoming || [], alliedIncoming: r.alliedIncoming || [], at: r.serverTime, loaded: true };
App.setBadge('movements', mil.moves.incoming.length, 'alert');
App.emit('movements', mil.moves);
return mil.moves;
}).finally(() => { movesFlight = null; });
return movesFlight;
};
let reportsFlight = null;
App.refreshReportsUnread = () => {
if (!App.state.user) return Promise.resolve(null);
if (reportsFlight) return reportsFlight;
reportsFlight = api.get('/reports', { limit: 1 }).then((r) => {
mil.reportsUnread = r.unread || 0;
App.setBadge('reports', mil.reportsUnread, 'info');
App.emit('reportsUnread', mil.reportsUnread);
return mil.reportsUnread;
}).finally(() => { reportsFlight = null; });
return reportsFlight;
};
// The POP list changed (founded, conquered, lost): refresh /me without the destructive parts of setSession.
let townsFlight = null;
const townSig = (list) => list.map((t) => t.id + ':' + t.name + ':' + (t.isCapital ? 1 : 0)).join('|');
App.refreshTowns = () => {
const st = App.state;
if (!st.user) return Promise.resolve();
if (townsFlight) return townsFlight;
townsFlight = (async () => {
const me = await api.get('/me');
const op = (me.operators || [])[0] || null;
if (!op) return;
const before = townSig(st.towns);
st.operators = me.operators; st.operator = op; st.world = op.world; st.towns = op.towns;
if (App.checkWorld) App.checkWorld(); // the world may have ended while we were away
let gone = false;
if (!st.towns.some((t) => t.id === st.townId)) {
const pick = st.towns.find((t) => t.isCapital) || st.towns[0] || null;
st.townId = pick ? pick.id : null; st.townData = null; gone = true;
}
// only a real change rebuilds the screens (a redraw resets the scroll position, and this runs on every poll)
if (gone) { App.emit('townchange', st.townId); if (st.townId) App.refreshTown().catch(() => {}); }
if (gone || townSig(st.towns) !== before) App.emit('towns', st.towns);
})().finally(() => { townsFlight = null; });
return townsFlight;
};
// Another of the player's POPs (GET /towns/:id), for the send dialog. -> { town, serverTime }
mil.loadTown = (id) => api.get('/towns/' + id);
App.on('session', (st) => {
if (st && st.user) { App.refreshMovements().catch(() => {}); App.refreshReportsUnread().catch(() => {}); return; }
mil.moves = { outgoing: [], incoming: [], alliedIncoming: [], at: 0, loaded: false };
mil.reportsUnread = 0;
App.setBadge('movements', 0, 'alert'); App.setBadge('reports', 0, 'info');
});
// ------------------------------------------------------------------ the notification feed (screens/alerts.js) learns our types
const kinds = App.alertKinds;
const townTxt = (id) => mil.townName(id) || '#' + id;
kinds.incoming = (n, p) => ({ icon: 'alert', title: App.t('alerts.incoming'), detail: App.t('alerts.incoming.at', { town: townTxt(p.toTownId), time: mil.clockTime(p.arriveAt) }), go: 'movements' });
kinds.report = (n, p) => ({ icon: 'report', title: App.t('alerts.report', { type: mil.reportTypeLabel(p.type) }), detail: '', go: 'reports', params: { open: p.reportId } });
kinds.train_done = (n, p) => ({ icon: 'units', title: App.t('alerts.train_done', { n: App.fmt.num(p.count), unit: mil.unitName(p.unit) }), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' });
kinds.research_done = (n, p) => ({ icon: 'flask', title: App.t('alerts.research_done', { unit: mil.unitName(p.unit), stat: App.t('stat.' + p.stat), level: p.level }), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' });
kinds.movement_returned = (n, p) => ({ icon: 'return', title: App.t('alerts.movement_returned'), detail: [mil.unitsText(p.units)].concat(D.RESOURCES.some((r) => p.cargo && p.cargo[r]) ? [Object.keys(p.cargo).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', ')] : []).join(' · '), go: 'movements' });
kinds.movement_lost = () => ({ icon: 'alert', title: App.t('alerts.movement_lost'), detail: '', go: 'movements' });
kinds.transport_arrived = (n, p) => ({ icon: 'box', title: App.t('alerts.transport_arrived', { town: townTxt(p.townId) }), detail: Object.keys(p.cargo || {}).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', '), go: 'movements' });
kinds.transport_delivered = (n, p) => ({ icon: 'box', title: App.t('alerts.transport_delivered'), detail: Object.keys(p.cargo || {}).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', '), go: 'movements' });
kinds.units_offline = (n, p) => ({ icon: 'power', title: App.t('alerts.units_offline'), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' });
kinds.units_decommissioned = (n, p) => ({ icon: 'power', title: App.t('alerts.units_decommissioned'), detail: mil.unitsText(p.units), go: 'units' });
kinds.town_lost = (n, p) => ({ icon: 'alert', title: App.t('alerts.town_lost', { name: p.name }), detail: p.by ? App.t('alerts.town_lost.by', { name: p.by.name }) : '', go: 'pop' });
kinds.town_gained = (n, p) => ({ icon: 'pop', title: App.t('alerts.town_gained', { name: p.name }), detail: '', go: 'pop' });
kinds.reinforcements_sent_home = (n, p) => ({ icon: 'return', title: App.t('alerts.reinforcements_home'), detail: mil.unitsText(p.units), go: 'units' });
}());