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
This commit is contained in:
jvanvik 2026-10-11 19:05:03 +02:00
parent 249818a7aa
commit b18645dca1
87 changed files with 10201 additions and 71 deletions

View file

@ -109,6 +109,10 @@
editNotes: ['leader', 'diplomat', 'officer'],
broadcast: ['leader', 'diplomat', 'officer', 'member'],
disband: ['leader'],
shareReport: ['leader', 'diplomat', 'officer', 'member'], // put one of YOUR reports into the alliance folder
viewSharedReports: ['leader', 'diplomat', 'officer', 'member'],
unshareReport: ['leader', 'officer'], // plus whoever shared it
backboneBuild: ['leader', 'diplomat', 'officer', 'member'], // start the next Backbone node level on a held landing site
},
allianceBaseSize: 10, // size cap = base + perLevel * Peering office level (best POP of the leader)
allianceSizePerLevel: 2,
@ -235,6 +239,34 @@
researchSpeedMax: 0.5,
};
return { UNITS, UNIT_ORDER, MILITARY, RESEARCH, EXPANSION, TRANSPORT, MOVE_ROLES, INCUMBENT, HOUR_MS, RESOURCES, FORMULAS, FIELD_SLOTS, FIELD_TYPES, FIELD_PRODUCES, FIELDS_PER_TYPE, WILD_SLOTS,
// Trade at the Internet exchange. Offers are "give X of A for Y of B, max distance Z"; each side must fit one transport
// link (TRANSPORT.capacityPerLink). The exchange level sets how far you see and trade (reachPerLevel tiles per level)
// and how many offers you may keep open per POP together with running transports (links).
const TRADE = {
ratioMax: 2, // give/want must lie in [1/ratioMax, ratioMax] (pump-feeding guard)
ttlHours: 48, // an offer expires after this long, divided by world speed
reachPerLevel: 10, // tiles
maxDistance: 300, // upper bound of an offer's max distance
scanChunk: 200, // offers read per round trip when listing (the range filter runs in JS)
};
// End game (backbone race). World age is in WORLD days: real days * world speed.
const ENDGAME = {
openDay: 100, // the landing sites appear at this world age
sites: 7,
graceDays: 2, // after level maxLevel is reached the world ends this long after (divided by world speed)
siteRingMin: 0.35, siteRingMax: 0.8, // landing sites sit between these fractions of the map radius
siteMinSpacing: 6, // tiles between two sites
defenceMult: 12, // incumbent site defence x this = the heavy defence of a landing site
defencePerLevel: 0.03, // + 3% per built Backbone node level (the node is a bigger target)
scanStrength: 40, // a landing site counts as this many scanners when scanned
maxLevel: 100, // = BUILDINGS.backbone_node.maxLevel
costGrowth: 1.045, // level L costs BUILDINGS.backbone_node.cost * costGrowth^(L-1) of each resource
timeGrowth: 1.025, // level L takes BUILDINGS.backbone_node.time * timeGrowth^(L-1) seconds at 1x
notifyEvery: 10, // alliance members hear about every n-th level (and the last one)
rankingTop: 100, // final snapshot: entries per list
};
return { UNITS, UNIT_ORDER, MILITARY, RESEARCH, EXPANSION, TRANSPORT, MOVE_ROLES, INCUMBENT, TRADE, ENDGAME, HOUR_MS, RESOURCES, FORMULAS, FIELD_SLOTS, FIELD_TYPES, FIELD_PRODUCES, FIELDS_PER_TYPE, WILD_SLOTS,
SOCIAL, BUILDINGS, START, TILE, PROTECTION_HOURS, AS_RANGE, WORLD_DEFAULTS };
}));

View file

@ -372,5 +372,17 @@
// Fictional AS numbers come from the private 32-bit range; shown as "AS4200000123".
const fmtAs = (n) => 'AS' + n;
return { LANGS, strings, t, fill, detectLang, fmtNum, fmtDec, fmtDuration, fmtClock, fmtAgo, fmtAs };
// Screens added by later stages bring their own strings: public/js/strings/<area>.js calls
// UpstreamI18n.extend({ en: {...}, nb: {...} }). Duplicate keys are an error (loud, not last-one-wins).
function extend(dicts) {
for (const l of LANGS) {
const d = dicts[l] || {};
for (const k of Object.keys(d)) {
if (Object.prototype.hasOwnProperty.call(strings[l], k)) throw new Error('duplicate i18n key ' + k + ' (' + l + ')');
strings[l][k] = d[k];
}
}
}
return { LANGS, strings, extend, t, fill, detectLang, fmtNum, fmtDec, fmtDuration, fmtClock, fmtAgo, fmtAs };
}));

View file

@ -5,6 +5,7 @@
*
* 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
@ -13,6 +14,8 @@
* });
*
* 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 () {
@ -94,32 +97,102 @@
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'));
for (const def of App.screens.values()) {
if (def.nav === false) continue;
const badge = h('span', { class: 'nav-badge', hidden: true, 'aria-hidden': 'true' });
const btn = h('button', { class: 'nav-btn', type: 'button', dataset: { screen: def.id }, onclick: () => App.go(def.id) },
h('span', { class: 'nav-ic' }, icon(def.icon), badge), h('span', { class: 'nav-lbl', text: App.t(def.navKey || def.titleKey) }));
if (App.current && App.current.id === def.id) btn.setAttribute('aria-current', 'page');
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);
}
updateBadge();
markCurrent();
updateBadges();
}
function updateBadge() {
const n = App.state.unread;
const b = elNav().querySelector('[data-screen="alerts"] .nav-badge');
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);
const btn = b.closest('button');
if (btn) btn.setAttribute('aria-label', App.t('nav.alerts') + (n ? ' (' + App.t('alerts.count', { 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.
@ -150,7 +223,7 @@
app.dataset.screen = def.id;
app.dataset.state = App.state.user ? 'in' : 'out';
elNav().hidden = !App.state.user;
for (const b of elNav().children) { if (b.dataset.screen === def.id) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current'); }
markCurrent();
setTitle(def);
renderHud(false);
if (def.onShow) def.onShow(App.params);
@ -225,9 +298,16 @@
let rulesCache = null;
// The rules.js town shape from the API response: same function the server settles with, so the numbers agree.
App.rulesTown = () => {
const st = App.state, td = st.townData;
if (!td || !st.world) return null;
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) {
@ -237,11 +317,10 @@
if (def && def.kind === 'infra') bdraw += def.draw * b.level;
}
const town = {
id: td.id, speed: st.world.speed, updatedAt: App.fetchedServerTime || 0,
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 || {},
};
rulesCache = { src: td, town };
return town;
};
@ -262,6 +341,8 @@
// ------------------------------------------------------------------ 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');
@ -272,6 +353,12 @@
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'),

121
public/js/milcore.js Normal file
View file

@ -0,0 +1,121 @@
'use strict';
/*
* Pure helpers of the military / expansion screens (no DOM, no storage, no clock): what can be sent where, which units go
* on which movement, report perspective, reconnect backoff. Loads as a browser script (window.UpstreamMil) and as a Node
* module (test/client-mil.test.js). The SERVER decides everything; this only hides choices that can never work, so the
* sheet is short, and says why the rest is greyed out.
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory(require('./data.js'), require('./rules.js'));
else root.UpstreamMil = factory(root.UpstreamData, root.UpstreamRules);
}(typeof self !== 'undefined' ? self : this, function (D, R) {
const TYPES = ['scan', 'raid', 'attack', 'takeover', 'reinforce', 'settle', 'transport'];
const HOSTILE = ['raid', 'attack', 'takeover'];
const ROLE_ICON = { scout: 'eye', defender: 'shield', attacker: 'target', siege: 'alert', settler: 'flag', conquest: 'handshake' };
const TYPE_ICON = { scan: 'eye', raid: 'target', attack: 'target', takeover: 'handshake', reinforce: 'shield', settle: 'flag', transport: 'box', return: 'return', unknown: 'alert' };
// Units of `home` ({id: n}) that may go on a movement of `type`: [{ unit, have }] in display order.
function unitsForType(type, home) {
const roles = D.MOVE_ROLES[type];
if (!roles) return [];
const out = [];
for (const unit of D.UNIT_ORDER) {
const def = D.UNITS[unit];
const have = (home && home[unit]) || 0;
if (have > 0 && !def.fixed && roles.indexOf(def.role) >= 0) out.push({ unit, have });
}
return out;
}
/*
* What can be sent to a tile. c = {
* tile: GET /map/tile response,
* home: units at the sending POP, transport: { links, active } of the sending POP,
* allianceId: my alliance id or null, crews: number of rollout crews at home
* } -> [{ type, ok, reason }] (reason is a code the sheet turns into text; null when ok)
* Hidden (not even greyed): types that make no sense for this kind of tile. Pact rules (NAP, confederation) are not
* known to the client: the server refuses those and the sheet shows its message.
*/
function moveOptions(c) {
const t = c.tile, home = c.home || {};
const out = [];
if (!t) return out;
const has = (type) => unitsForType(type, home).length > 0;
const add = (type, ok, reason) => out.push({ type, ok: !!ok, reason: ok ? null : reason });
if (t.town) {
if (t.town.mine) {
add('reinforce', has('reinforce'), 'no_units');
const links = (c.transport && c.transport.links) || 0, active = (c.transport && c.transport.active) || 0;
add('transport', links > active, links === 0 ? 'no_link' : 'links_busy');
} else {
add('scan', has('scan'), 'no_units');
const prot = !!(t.town.owner && t.town.owner.protected);
for (const type of HOSTILE) {
let ok = !prot && has(type), reason = prot ? 'target_protected' : 'no_units';
if (ok && type === 'takeover' && !(home[D.EXPANSION.conquestUnit] > 0)) { ok = false; reason = 'needs_ma_team'; }
add(type, ok, reason);
}
if (c.allianceId && t.town.owner && t.town.owner.allianceId === c.allianceId) add('reinforce', has('reinforce'), 'no_units');
}
} else if (t.type === 'incumbent') {
add('scan', has('scan'), 'no_units');
add('attack', has('attack'), 'no_units');
} else if (t.type === 'land') {
const s = t.settle || {};
if (!s.possible) add('settle', false, 'settle:' + (s.code || 'invalid_target'));
else add('settle', (c.crews || 0) >= D.EXPANSION.crews, 'needs_crews');
}
return out;
}
// Default selection when a type is picked: settle takes exactly the crews, everything else starts empty.
function defaultUnits(type, home) {
if (type === 'settle') { const o = {}; o[D.EXPANSION.settleUnit] = D.EXPANSION.crews; return o; }
return {};
}
// Drop zero entries and clamp to what is at home.
function cleanSelection(sel, home) {
const out = {};
for (const k of Object.keys(sel || {})) {
const n = Math.max(0, Math.min(Math.floor(sel[k] || 0), (home && home[k]) || 0));
if (n > 0) out[k] = n;
}
return out;
}
// Preview of a movement: distance, latency (ms), carry capacity, slowest unit.
function preview(type, from, to, units, cargo, worldSpeed) {
const dist = R.distance(from.x, from.y, to.x, to.y);
const ms = type === 'transport' ? R.transportMs(dist, worldSpeed) : R.movementMs(dist, units, worldSpeed);
const s = R.slowestSpeed(units);
return { dist, ms, carry: R.carryOf(units), slowest: isFinite(s) ? s : null };
}
const isHostile = (type) => HOSTILE.indexOf(type) >= 0;
// Report perspective: did *I* win? role is the recipient role of the report.
function perspective(role, outcome) {
const attackerSide = role === 'attacker';
const attackerWon = outcome === 'attacker_won';
return attackerSide === attackerWon ? 'victory' : 'defeat';
}
// When units that went offline are decommissioned (ms, server clock).
const decommissionAt = (offlineSince, speed) => offlineSince + R.decommissionMs(speed);
// Reconnect delay for the WebSocket: exponential from 1 s, capped at 60 s, +-25% jitter (rnd in [0,1)).
function backoffMs(attempt, rnd) {
const base = Math.min(60000, 1000 * Math.pow(2, Math.min(attempt, 10)));
return Math.round(base * (0.75 + 0.5 * (rnd === undefined ? Math.random() : rnd)));
}
const sumUnits = (u) => Object.keys(u || {}).reduce((s, k) => s + (u[k] || 0), 0);
// Exploit-kit target choices: infrastructure types (the server also takes f1..f18 slots; the client does not know them).
function siegeTargets() {
return Object.keys(D.BUILDINGS).filter((k) => D.BUILDINGS[k].kind === 'infra' && !D.BUILDINGS[k].special);
}
return { TYPES, HOSTILE, ROLE_ICON, TYPE_ICON, unitsForType, moveOptions, defaultUnits, cleanSelection, preview, isHostile, perspective, decommissionAt, backoffMs, sumUnits, siegeTargets };
}));

167
public/js/milstate.js Normal file
View file

@ -0,0 +1,167 @@
'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) 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;
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' });
}());

View file

@ -6,6 +6,8 @@
* source.forEachSpecial(x0, y0, x1, y1, fn(special)) rural + incumbent tiles in the rect
* source.townsInRect(x0, y0, x1, y1) -> [town] POPs in the rect
* source.isOwn(town) -> bool
* source.movements() -> [{ from: {x,y}, to: {x,y}, kind: 'out' | 'in' | 'ret' | 'ally', p: 0..1 }] optional: lines with a marker at progress p
* source.threatened(town) -> bool optional: an incoming movement is heading for this own POP (red ring)
* onTap(x, y) a finger lift / click that was not a drag or a pinch (act on lift)
* onMoveEnd(view) debounced after the camera stopped; view = { x0, y0, x1, y1, cx, cy, zoom }
*
@ -292,6 +294,7 @@
}
ctx.restore();
}
if (this.src.movements) this._movements(this.src.movements());
for (const t of towns) this._pop(t);
// world border
@ -365,6 +368,10 @@
ctx.beginPath(); ctx.arc(s.x, s.y, Math.max(1.5, rad * (t.isCapital ? 0.38 : 0.22)), 0, Math.PI * 2); ctx.fill();
if (t.isCapital) { ctx.strokeStyle = col.stroke; ctx.lineWidth = 1; this._hex(s.x, s.y, rad * 0.68); ctx.stroke(); }
}
if (own && this.src.threatened && this.src.threatened(t)) {
ctx.strokeStyle = '#ff6b87'; ctx.lineWidth = Math.max(2, z * 0.08);
this._hex(s.x, s.y, rad + Math.max(4, z * 0.2)); ctx.stroke();
}
if (z >= 18 && t.owner.protected) {
ctx.strokeStyle = COLORS.select; ctx.lineWidth = Math.max(1, z * 0.05); ctx.setLineDash([3, 3]);
this._hex(s.x, s.y, rad + z * 0.12); ctx.stroke(); ctx.setLineDash([]);
@ -380,6 +387,35 @@
}
}
// Movement lines: dashed, cyan outgoing, red incoming, dim return legs, green allied traffic; a marker sits at progress p.
_movements(list) {
const { ctx, zoom: z } = this;
const col = { out: COLORS.own, in: '#ff6b87', ret: 'rgba(155,178,214,0.8)', ally: '#35e0a1' };
ctx.save();
ctx.lineCap = 'round';
for (const m of list) {
const a = this.toScreen(m.from.x, m.from.y), b = this.toScreen(m.to.x, m.to.y);
if (Math.max(a.x, b.x) < -20 || Math.min(a.x, b.x) > this.w + 20 || Math.max(a.y, b.y) < -20 || Math.min(a.y, b.y) > this.h + 20) continue;
const c = col[m.kind] || COLORS.own;
ctx.strokeStyle = c; ctx.fillStyle = c;
ctx.globalAlpha = m.kind === 'ret' ? 0.55 : 0.85;
ctx.lineWidth = m.kind === 'in' ? 2.4 : 1.6;
ctx.setLineDash(m.kind === 'in' ? [3, 5] : [7, 6]);
ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
ctx.setLineDash([]);
const p = Math.max(0, Math.min(1, m.p));
const px = a.x + (b.x - a.x) * p, py = a.y + (b.y - a.y) * p;
const ang = Math.atan2(b.y - a.y, b.x - a.x), r = Math.max(4, Math.min(8, z * 0.3));
ctx.globalAlpha = 1;
ctx.beginPath();
ctx.moveTo(px + Math.cos(ang) * r, py + Math.sin(ang) * r);
ctx.lineTo(px + Math.cos(ang + 2.5) * r, py + Math.sin(ang + 2.5) * r);
ctx.lineTo(px + Math.cos(ang - 2.5) * r, py + Math.sin(ang - 2.5) * r);
ctx.closePath(); ctx.fill();
}
ctx.restore();
}
_selection(sel) {
const { ctx, zoom: z } = this;
const s = this.toScreen(sel.x, sel.y);

View file

@ -52,7 +52,19 @@
// ------------------------------------------------------------------ the map
// Pure function of the world seed: 'land' | 'rural' | 'incumbent' | 'void' (outside the map). A rural tile also
// says which resource it boosts. Towns are not part of this; they live in the database.
function tileAt(seed, radius, x, y) {
// `ageDays` (optional, world days) adds the end game: from D.ENDGAME.openDay on, the landing sites report 'backbone'
// (with `site`: its index). Without it (old callers, previews without a clock) the map is the plain terrain.
// Terrain never changes: a landing site is always a land tile underneath, see backboneSites.
function tileAt(seed, radius, x, y, ageDays) {
const t = terrainAt(seed, radius, x, y);
if (t.type === 'land' && ageDays !== undefined && ageDays >= D.ENDGAME.openDay) {
const s = backboneSiteAt(seed, radius, x, y);
if (s) return { type: 'backbone', site: s.index };
}
return t;
}
function terrainAt(seed, radius, x, y) {
if (Math.abs(x) > radius || Math.abs(y) > radius) return { type: 'void' };
if (Math.abs(x) <= 2 && Math.abs(y) <= 2) return { type: 'land' }; // keep the centre free
const h = hash(seed, x, y) / 4294967296;
@ -64,6 +76,54 @@
return { type: 'land' };
}
// The backbone landing sites: D.ENDGAME.sites fixed positions, a pure function of (seed, radius). One per sector of the
// circle (jittered), on plain land tiles between siteRingMin and siteRingMax of the radius, never in the free centre and
// at least siteMinSpacing apart. They exist from the start (spawn and settling refuse them) but only SHOW from openDay.
// -> [{ index, x, y }]
const siteCache = new Map();
function backboneSites(seed, radius) {
const key = seed + '|' + radius;
if (siteCache.has(key)) return siteCache.get(key);
const E = D.ENDGAME;
const out = [];
for (let k = 0; k < E.sites; k++) {
const rand = rng(hash(seed, k, 0xb4cb));
const ang = (k + 0.15 + 0.7 * rand()) * 2 * Math.PI / E.sites;
const rr = radius * (E.siteRingMin + (E.siteRingMax - E.siteRingMin) * rand());
const cx = Math.round(Math.cos(ang) * rr), cy = Math.round(Math.sin(ang) * rr);
let found = null;
for (let d = 0; d <= radius && !found; d++) { // spiral outwards until a free land tile turns up
for (let dy = -d; dy <= d && !found; dy++) {
for (let dx = -d; dx <= d && !found; dx++) {
if (Math.max(Math.abs(dx), Math.abs(dy)) !== d) continue;
const x = cx + dx, y = cy + dy;
if (terrainAt(seed, radius, x, y).type !== 'land') continue;
if (Math.abs(x) <= 2 && Math.abs(y) <= 2) continue;
if (out.some((s) => distance(s.x, s.y, x, y) < E.siteMinSpacing)) continue;
found = { index: k, x, y };
}
}
}
if (found) out.push(found);
}
if (siteCache.size > 64) siteCache.clear();
siteCache.set(key, out);
return out;
}
function backboneSiteAt(seed, radius, x, y) {
for (const s of backboneSites(seed, radius)) if (s.x === x && s.y === y) return s;
return null;
}
const isBackboneSite = (seed, radius, x, y) => !!backboneSiteAt(seed, radius, x, y);
// World age in world days (real days * speed). Negative ages are 0.
function worldAgeDays(startAt, now, speed) { return Math.max(0, (now - startAt) / DAY * (speed || 1)); }
// 'running' | 'backbone_open' | 'ended'.
function worldPhase(status, ageDays) {
if (status === 'ended') return 'ended';
return ageDays >= D.ENDGAME.openDay ? 'backbone_open' : 'running';
}
// Rural areas within reach of (x, y): the tiles whose bonus a POP there enjoys. Biggest bonus counts max 3.
function ruralNear(seed, radius, x, y) {
const out = [];
@ -101,7 +161,7 @@
const ang = rand() * Math.PI * 2;
const rr = lo + rand() * (hi - lo);
const x = Math.round(Math.cos(ang) * rr), y = Math.round(Math.sin(ang) * rr);
if (tileAt(seed, radius, x, y).type !== 'land') continue;
if (tileAt(seed, radius, x, y).type !== 'land' || isBackboneSite(seed, radius, x, y)) continue;
if (near(x, y)) continue;
return { x, y };
}
@ -577,6 +637,7 @@
// Founding a POP: info about the target tile and the operator. Codes: invalid_target, out_of_range, footprint_too_low.
function settleCheck(o) {
if (o.backbone) return { ok: false, code: 'invalid_target', reason: 'backbone_site' }; // landing sites are taken, never settled
if (o.tileType !== 'land' || o.occupied) return { ok: false, code: 'invalid_target', reason: o.occupied ? 'occupied' : 'not_empty_land' };
if (!(o.nearestOwnDist <= D.EXPANSION.maxDistance)) return { ok: false, code: 'out_of_range', max: D.EXPANSION.maxDistance, have: o.nearestOwnDist };
const g = footprintGate(o.ownedCount, o.footprint);
@ -654,8 +715,62 @@
return { ok: true, total };
}
// ---- trade (Internet exchange offers: give X of A for Y of B, max distance Z)
// How far (tiles) a POP with this Internet exchange level sees and trades. Level 0 = no exchange = 0.
const tradeReach = (level) => (level > 0 ? level * D.TRADE.reachPerLevel : 0);
// Is the exchange rate within the 1:ratioMax band (give/want in [1/ratioMax, ratioMax])?
const tradeRatioOk = (give, want) => give > 0 && want > 0 && give <= want * D.TRADE.ratioMax && want <= give * D.TRADE.ratioMax;
// Validate the terms of a new offer. `o` = { giveRes, giveAmount, wantRes, wantAmount, maxDistance }. Codes: validation_failed,
// trade_ratio, capacity_exceeded. Does not look at the town (resources, links) - the command does.
function tradeTermsCheck(o) {
const bad = (path, message) => ({ ok: false, code: 'validation_failed', errors: [{ path, message }] });
if (D.RESOURCES.indexOf(o.giveRes) < 0) return bad('giveRes', 'must be one of ' + D.RESOURCES.join(', '));
if (D.RESOURCES.indexOf(o.wantRes) < 0) return bad('wantRes', 'must be one of ' + D.RESOURCES.join(', '));
if (o.giveRes === o.wantRes) return bad('wantRes', 'must differ from giveRes');
if (!Number.isInteger(o.giveAmount) || o.giveAmount < 1) return bad('giveAmount', 'must be a whole number >= 1');
if (!Number.isInteger(o.wantAmount) || o.wantAmount < 1) return bad('wantAmount', 'must be a whole number >= 1');
if (!Number.isInteger(o.maxDistance) || o.maxDistance < 1 || o.maxDistance > D.TRADE.maxDistance) return bad('maxDistance', 'must be a whole number of tiles 1..' + D.TRADE.maxDistance);
const cap = D.TRANSPORT.capacityPerLink;
if (o.giveAmount > cap || o.wantAmount > cap) return { ok: false, code: 'capacity_exceeded', capacity: cap };
if (!tradeRatioOk(o.giveAmount, o.wantAmount)) return { ok: false, code: 'trade_ratio', max: D.TRADE.ratioMax };
return { ok: true };
}
// May a POP at `dist` tiles with Internet exchange `level` take an offer (max distance `maxDistance`)? Both the offer's own
// limit and the taker's reach apply.
const tradeInRange = (dist, maxDistance, level) => level >= 1 && dist <= maxDistance && dist <= tradeReach(level);
// ---- end game: backbone landing sites
// Heavy static defence of a landing site: the incumbent's site defence x defenceMult, plus defencePerLevel per node level.
function backboneDefence(seed, x, y, ageDays, level) {
return Math.round(incumbentDefence(seed, x, y, ageDays) * D.ENDGAME.defenceMult * (1 + D.ENDGAME.defencePerLevel * Math.max(0, level || 0)));
}
// Cost to build the Backbone node UP TO `level` (1..maxLevel), per resource.
function backboneCost(level) {
const def = D.BUILDINGS.backbone_node;
const out = {};
for (const r of D.RESOURCES) out[r] = Math.round(def.cost[r] * Math.pow(D.ENDGAME.costGrowth, level - 1));
return out;
}
function backboneTimeMs(level, speed) {
return Math.max(F.minBuildMs, Math.round(D.BUILDINGS.backbone_node.time * Math.pow(D.ENDGAME.timeGrowth, level - 1) / (speed || 1) * 1000));
}
// Can the holder alliance start the next level? site = { level, build (null | { to }), pool: { fiber, hardware, capital } }. Codes: max_level, already_queued, not_enough_resources.
function backbonePlan(site, speed) {
const toLevel = site.level + 1;
const base = { ok: false, fromLevel: site.level, toLevel };
if (toLevel > D.ENDGAME.maxLevel) return Object.assign(base, { code: 'max_level' });
base.cost = backboneCost(toLevel);
base.durationMs = backboneTimeMs(toLevel, speed);
if (site.build) return Object.assign(base, { code: 'already_queued' });
for (const r of D.RESOURCES) if ((site.pool[r] || 0) + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' });
base.ok = true;
return base;
}
return {
unitDef, unitCount, costValue, unitValue, researchKey, researchLevel, researchMult, unitStat, unitCost, trainTimeMs, unitMissing, trainPlan, researchCost, researchTimeMs, researchSpeedBonus, researchPlan, slowestSpeed, movementMs, transportMs, checkUnitsForType, isProtected, firewallMult, effectiveFirewall, attackPower, defencePower, applyLoss, resolveBattle, battlePoints, cacheFraction, lootSplit, carryOf, siegeLevels, loyaltyDrop, takeoverBlock, footprintGate, settleCheck, cleanWild, newTownBuildings, scanStrength, resolveScan, incumbentDefence, decommissionMs, decommissionPlan, transportLinks, transportPlan, rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn,
terrainAt, backboneSites, backboneSiteAt, isBackboneSite, worldAgeDays, worldPhase, tradeReach, tradeRatioOk, tradeTermsCheck, tradeInRange,
backboneDefence, backboneCost, backboneTimeMs, backbonePlan,
buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, queueSlots, storageCap, batteryCap,
fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt,
allianceCap, allianceCan, roleRank, outranks, diplomacyMove, pactCancelMs,

View file

@ -17,6 +17,9 @@
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' };
}
// Other screens describe their own notification types: App.alertKinds[type] = (n, p) => ({ icon, title, detail, go, params })
const ext = App.alertKinds && App.alertKinds[n.type];
if (ext) return ext(n, p);
return { icon: 'bell', title: App.t('alerts.unknown', { type: n.type }), detail: '', go: null };
}
@ -28,7 +31,7 @@
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('button', { class: 'alert' + (isNew ? ' new' : ''), type: 'button', onclick: () => { if (d.go) App.go(d.go, d.params); } },
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),
@ -57,7 +60,7 @@
}
App.registerScreen({
id: 'alerts', titleKey: 'screen.alerts', navKey: 'nav.alerts', icon: 'bell', hud: false,
id: 'alerts', titleKey: 'screen.alerts', navKey: 'nav.alerts', icon: 'bell', hud: false, navGroup: 'more',
render(container) {
box = container;
listEl = h('ul', { class: 'alert-list' });

View file

@ -0,0 +1,542 @@
'use strict';
/*
* Alliance screen. Not in an alliance: found one (Peering office needed) and answer invitations. In one: overview with pinned
* notes, members (role changes, kick, transfer, invite), diplomacy. What is offered follows data.js SOCIAL.permissions through
* rules.js allianceCan/outranks (via UpstreamSocial); the server re-checks everything and its error codes are translated.
* Every player-controlled string is set with textContent.
*/
(function () {
const { h, clear, icon, toast, openSheet } = UI;
const Soc = UpstreamSocial;
const R = UpstreamRules;
const D = UpstreamData;
const S = D.SOCIAL;
const X = () => window.SocUI;
let box, body, tabsEl, content;
let mine = null; // GET /alliances/mine
let members = null; // GET /alliances/:id/members items
let tab = 'overview';
let gen = 0; // bumped on every load: stale async results are dropped
let offTick = null;
const cache = {}; // per-tab data
const myRole = () => (mine ? mine.role : null);
const acts = () => Soc.selfActions(myRole(), members ? members.length : (mine && mine.alliance ? mine.alliance.memberCount : 0));
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
// ------------------------------------------------------------------ load
async function load() {
const my = ++gen;
const had = !!mine;
if (!had) { clear(body); body.appendChild(X().loading()); }
try {
const m = await App.api.get('/alliances/mine');
if (my !== gen) return;
mine = m;
const al = m.alliance;
const cur = X().myAlliance();
if ((al && (!cur || cur.id !== al.id)) || (!al && cur)) X().refreshOperator().catch(() => {});
if (al) {
const r = await App.api.get('/alliances/' + al.id + '/members');
if (my !== gen) return;
members = r.items;
for (const k of Object.keys(cache)) delete cache[k];
drawIn();
} else {
members = null;
const inv = await App.api.get('/alliance-invites');
if (my !== gen) return;
cache.invites = inv.items;
drawNone();
}
} catch (e) {
if (my !== gen) return;
clear(body);
body.appendChild(X().errorBox(e, load));
}
}
// Reload after a change of membership (found, join, leave, kick...).
function reload() { mine = null; members = null; tab = 'overview'; return load(); }
// ------------------------------------------------------------------ not in an alliance
function drawNone() {
clear(body);
stopTick();
const have = mine.peeringLevel, need = S.minPeeringLevel, ok = have >= need;
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
const nameIn = h('input', { type: 'text', maxlength: String(S.nameLen[1] * 2), autocomplete: 'off', autocapitalize: 'words', spellcheck: 'false', id: 'soc-name' });
const tagIn = h('input', { type: 'text', maxlength: String(S.tagLen[1]), autocomplete: 'off', autocapitalize: 'characters', spellcheck: 'false', id: 'soc-tag' });
const create = h('button', { class: 'btn primary wide', type: 'button' }, icon('plus'), App.t('soc.create.go'));
const valid = () => {
const n = Array.from(Soc.cleanName(nameIn.value)).length, t = tagIn.value.trim();
return ok && n >= S.nameLen[0] && n <= S.nameLen[1] && /^[A-Za-z0-9]+$/.test(t) && t.length >= S.tagLen[0] && t.length <= S.tagLen[1];
};
const sync = () => { create.disabled = !valid(); };
nameIn.addEventListener('input', sync); tagIn.addEventListener('input', sync);
create.addEventListener('click', () => X().guard(create, async () => {
err.hidden = true;
try {
await App.api.post('/alliances', { name: Soc.cleanName(nameIn.value), tag: tagIn.value.trim() }, { intent: 'ally:create' });
toast(App.t('soc.create.done'), 'ok');
await reload();
} catch (e) {
err.textContent = e.code === 'validation_failed' ? App.t('soc.create.invalid', { n1: S.nameLen[0], n2: S.nameLen[1], t1: S.tagLen[0], t2: S.tagLen[1] }) : X().err(e);
err.hidden = false;
}
}));
sync();
body.appendChild(h('div', { class: 'card soc-card' },
h('div', { class: 'card-head' }, h('h2', null, icon('users'), App.t('soc.create.title'))),
h('p', { class: 'detail-desc', text: App.t('soc.create.intro') }),
h('ul', { class: 'reqs soc-req' }, h('li', { class: ok ? 'ok' : 'miss' }, icon(ok ? 'check' : 'lock'),
h('span', { text: App.buildingName('peering_office') + ' ' + App.t('pop.level', { n: need }) }), h('small', { text: App.t('sheet.have', { n: have }) }))),
ok ? null : h('p', { class: 'reason', text: App.t('soc.create.needOffice', { building: App.buildingName('peering_office'), n: need }) }),
h('label', { class: 'field', for: 'soc-name' }, h('span', { class: 'field-lbl', text: App.t('soc.create.name') }), nameIn,
h('span', { class: 'field-hint', text: App.t('soc.create.nameHint', { a: S.nameLen[0], b: S.nameLen[1] }) })),
h('label', { class: 'field', for: 'soc-tag' }, h('span', { class: 'field-lbl', text: App.t('soc.create.tag') }), tagIn,
h('span', { class: 'field-hint', text: App.t('soc.create.tagHint', { a: S.tagLen[0], b: S.tagLen[1] }) })),
err, create));
const invCard = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('mail'), App.t('soc.invites.title')),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load() }, icon('refresh'))));
const items = cache.invites || [];
if (!items.length) invCard.appendChild(h('p', { class: 'empty', text: App.t('soc.invites.none') }));
else {
if (!ok) invCard.appendChild(h('p', { class: 'reason', text: App.t('soc.invites.needOffice', { building: App.buildingName('peering_office') }) }));
const list = h('ul', { class: 'soc-list' });
const now = App.now();
for (const inv of items) {
const e2 = h('p', { class: 'form-error', role: 'alert', hidden: true });
const acc = h('button', { class: 'btn small primary', type: 'button', text: App.t('soc.invites.accept') });
const dec = h('button', { class: 'btn small', type: 'button', text: App.t('soc.invites.decline') });
const answer = (accept) => X().guard(accept ? acc : dec, async () => {
e2.hidden = true;
try {
await App.api.post('/alliance-invites/' + inv.id + (accept ? '/accept' : '/decline'), {}, { intent: 'ally:invite:' + inv.id });
toast(App.t(accept ? 'soc.invites.accepted' : 'soc.invites.declined'), 'ok');
await reload();
} catch (e) { e2.textContent = X().err(e); e2.hidden = false; }
});
acc.addEventListener('click', () => answer(true));
dec.addEventListener('click', () => answer(false));
list.appendChild(h('li', { class: 'soc-item soc-invite' },
h('div', { class: 'row-main' },
h('span', { class: 'row-title' }, X().tagPill(inv.alliance.tag), h('b', { text: inv.alliance.name })),
h('span', { class: 'row-sub', text: App.t('soc.invites.from', { name: inv.invitedBy.name }) + ' · ' + App.t('soc.invites.expires', { t: App.fmt.dur(Math.max(0, inv.expiresAt - now), 2) }) })),
h('div', { class: 'soc-actions' }, dec, acc), e2));
}
invCard.appendChild(list);
}
body.appendChild(invCard);
}
// ------------------------------------------------------------------ in an alliance
function drawIn() {
clear(body);
stopTick();
const a = mine.alliance;
const sizeP = a.sizeCap > 0 ? Math.min(1, a.memberCount / a.sizeCap) : 0;
body.appendChild(h('div', { class: 'card soc-card soc-head' },
h('div', { class: 'soc-title' }, X().tagPill(a.tag), h('h2', { class: 'soc-name', text: a.name })),
h('div', { class: 'pill-row' }, X().rolePill(mine.role),
h('span', { class: 'pill', text: App.t('soc.size', { n: a.memberCount, cap: a.sizeCap }) }),
h('span', { class: 'pill', text: App.t('soc.leaderIs', { name: a.leader ? a.leader.name : '-' }) })),
h('div', { class: 'bar', 'aria-hidden': 'true', style: { '--p': String(sizeP) } }, h('i'))));
const tabs = [['overview', 'soc.tab.overview'], ['members', 'soc.tab.members'], ['diplomacy', 'soc.tab.diplomacy']];
tabsEl = h('div', { class: 'seg soc-tabs', role: 'group', 'aria-label': App.t('soc.tab.label') },
tabs.map(([id, key]) => h('button', { class: 'seg-btn', type: 'button', dataset: { tab: id }, 'aria-pressed': String(tab === id), text: App.t(key), onclick: () => setTab(id) })));
content = h('div', { class: 'soc-content' });
body.appendChild(tabsEl);
body.appendChild(content);
drawTab();
}
function setTab(id) {
tab = id;
for (const b of tabsEl.children) b.setAttribute('aria-pressed', String(b.dataset.tab === id));
drawTab();
}
function drawTab() {
stopTick();
clear(content);
if (tab === 'members') drawMembers();
else if (tab === 'diplomacy') drawDiplomacy();
else drawOverview();
}
// ---------------------------------------------------------------- overview: notes, leave / disband
const nameOf = (id) => { const m = (members || []).find((x) => x.operatorId === id); return m ? m.name : '#' + id; };
async function drawOverview() {
const my = gen;
const A = acts();
const notesCard = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('pencil'), App.t('soc.notes.title')),
h('span', { class: 'pill dim mono', id: 'soc-notes-count' })));
const notesList = h('ul', { class: 'soc-list' });
notesCard.appendChild(notesList);
content.appendChild(notesCard);
function drawNotes(items) {
clear(notesList);
notesCard.querySelector('#soc-notes-count').textContent = items.length + '/' + S.maxNotes;
if (!items.length) notesList.appendChild(h('li', { class: 'empty', text: App.t('soc.notes.none') }));
for (const n of items) {
const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.notes.remove'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
await App.api.del('/alliances/' + mine.alliance.id + '/notes/' + n.id);
cache.notes = cache.notes.filter((x) => x.id !== n.id);
drawNotes(cache.notes);
}) }, icon('x'));
notesList.appendChild(h('li', { class: 'soc-item soc-note' },
h('div', { class: 'row-main' }, h('p', { class: 'soc-text-out', text: n.text }),
h('span', { class: 'row-sub', text: nameOf(n.authorId) + ' · ' + App.fmt.ago(App.now() - n.createdAt) })),
A.editNotes ? del : null));
}
}
if (A.editNotes) {
const ta = h('textarea', { class: 'soc-text', rows: 2, maxlength: String(S.noteMax * 2), 'aria-label': App.t('soc.notes.add'), placeholder: App.t('soc.notes.placeholder') });
const cnt = h('span', { class: 'soc-count mono' });
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
const add = h('button', { class: 'btn small primary', type: 'button' }, icon('plus'), App.t('soc.notes.add'));
const sync = () => {
const st = Soc.composeState(ta.value, S.noteMax);
cnt.textContent = st.n + '/' + S.noteMax; cnt.classList.toggle('over', st.over);
add.disabled = st.empty || st.over || (cache.notes && cache.notes.length >= S.maxNotes);
};
ta.addEventListener('input', sync);
add.addEventListener('click', () => X().guard(add, async () => {
err.hidden = true;
try {
const r = await App.api.post('/alliances/' + mine.alliance.id + '/notes', { text: ta.value });
cache.notes = (cache.notes || []).concat([r.note]);
ta.value = '';
drawNotes(cache.notes); sync();
} catch (e) { err.textContent = X().err(e); err.hidden = false; }
}));
notesCard.appendChild(h('div', { class: 'soc-addnote' }, ta, h('div', { class: 'soc-composer-bar' }, cnt, add), err));
sync();
}
// leave / disband
const danger = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('shield'), App.t('soc.manage.title'))));
const row = h('div', { class: 'btn-row soc-stack' });
if (A.leaveNeedsTransfer) {
danger.appendChild(h('p', { class: 'reason', text: App.t('soc.leave.mustTransfer') }));
row.appendChild(h('button', { class: 'btn', type: 'button', onclick: () => setTab('members') }, icon('users'), App.t('soc.leave.goTransfer')));
} else {
row.appendChild(h('button', { class: 'btn danger', type: 'button', onclick: confirmLeave }, icon('logout'), App.t('soc.leave.go')));
}
if (A.disband) row.appendChild(h('button', { class: 'btn danger', type: 'button', onclick: confirmDisband }, icon('x'), App.t('soc.disband.go')));
danger.appendChild(row);
content.appendChild(danger);
if (cache.notes) { drawNotes(cache.notes); return; }
notesList.appendChild(X().loading());
try {
const r = await App.api.get('/alliances/' + mine.alliance.id + '/notes');
if (my !== gen) return;
cache.notes = r.items;
if (tab === 'overview') drawNotes(cache.notes);
} catch (e) { if (my === gen && tab === 'overview') { clear(notesList); notesList.appendChild(X().errorBox(e, drawTab)); } }
}
function confirmLeave() {
const alone = members && members.length <= 1;
X().confirmSheet({
title: App.t('soc.leave.go'), icon: 'logout', danger: true, ok: App.t('soc.leave.go'),
text: App.t(alone ? 'soc.leave.confirmAlone' : 'soc.leave.confirm', { name: mine.alliance.name }),
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/leave', {}, { intent: 'ally:leave' }); toast(App.t('soc.leave.done'), 'ok'); await reload(); },
});
}
function confirmDisband() {
X().confirmSheet({
title: App.t('soc.disband.go'), icon: 'alert', danger: true, ok: App.t('soc.disband.go'),
text: App.t('soc.disband.confirm', { name: mine.alliance.name }),
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/disband', {}, { intent: 'ally:disband' }); toast(App.t('soc.disband.done'), 'ok'); await reload(); },
});
}
// ---------------------------------------------------------------- members
function drawMembers() {
const A = acts();
const now = App.now();
const card = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('users'), App.t('soc.members')),
h('span', { class: 'pill dim mono', text: App.t('soc.size', { n: members.length, cap: mine.alliance.sizeCap }) })));
const list = h('ul', { class: 'soc-list' });
for (const m of members) {
const you = m.operatorId === X().myOperatorId();
list.appendChild(h('li', null, h('button', { class: 'row-btn soc-member', type: 'button', onclick: () => openMember(m) },
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: m.name }), you ? h('span', { class: 'pill accent', text: App.t('soc.you') }) : null, X().rolePill(m.role)),
h('span', { class: 'row-sub', text: App.t('soc.member.stats', { towns: m.towns, fp: App.fmt.dec(m.footprint) }) + ' · ' + (m.lastOnline ? App.t('soc.member.online', { t: App.fmt.ago(now - m.lastOnline) }) : App.t('soc.member.never')) })))));
}
card.appendChild(list);
content.appendChild(card);
if (A.invite) drawInvite();
}
async function drawInvite() {
const my = gen;
const card = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('mail'), App.t('soc.invite.title'))));
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
const nameIn = h('input', { type: 'text', maxlength: '40', autocomplete: 'off', spellcheck: 'false', 'aria-label': App.t('soc.invite.name'), placeholder: App.t('soc.invite.name'), enterkeyhint: 'send' });
const go = h('button', { class: 'btn primary', type: 'button' }, icon('up'), App.t('soc.invite.go'));
const pend = h('ul', { class: 'soc-list' });
const sync = () => { go.disabled = !Soc.cleanName(nameIn.value); };
nameIn.addEventListener('input', sync);
nameIn.addEventListener('keydown', (ev) => { if (ev.key === 'Enter' && !go.disabled) go.click(); });
go.addEventListener('click', () => X().guard(go, async () => {
err.hidden = true;
const name = Soc.cleanName(nameIn.value);
try {
const r = await App.api.post('/alliances/' + mine.alliance.id + '/invite', { name }, { intent: 'ally:invite:' + name.toLowerCase() });
toast(App.t(r.changed ? 'soc.invite.sent' : 'soc.invite.already', { name }), 'ok');
nameIn.value = ''; sync();
loadPending();
} catch (e) { err.textContent = e.code === 'not_found' ? App.t('soc.invite.unknown', { name }) : X().err(e); err.hidden = false; }
}));
sync();
card.appendChild(h('div', { class: 'soc-inline' }, nameIn, go));
card.appendChild(err);
if (acts().viewInvites) { card.appendChild(h('div', { class: 'sub', text: App.t('soc.invite.pending') })); card.appendChild(pend); }
content.appendChild(card);
async function loadPending() {
if (!acts().viewInvites) return;
try {
const r = await App.api.get('/alliances/' + mine.alliance.id + '/invites');
if (my !== gen || tab !== 'members') return;
clear(pend);
if (!r.items.length) pend.appendChild(h('li', { class: 'empty', text: App.t('soc.invite.none') }));
const now = App.now();
for (const inv of r.items) {
const cancel = h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.invite.cancel'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
await App.api.del('/alliances/' + mine.alliance.id + '/invites/' + inv.id);
loadPending();
}) }, icon('x'));
pend.appendChild(h('li', { class: 'soc-item' }, h('div', { class: 'row-main' }, h('b', { text: inv.operator.name }),
h('span', { class: 'row-sub', text: App.t('soc.invites.from', { name: inv.invitedBy.name }) + ' · ' + App.t('soc.invites.expires', { t: App.fmt.dur(Math.max(0, inv.expiresAt - now), 2) }) })),
acts().cancelInvite ? cancel : null));
}
} catch (e) { if (my === gen && tab === 'members') { clear(pend); pend.appendChild(X().errorBox(e, loadPending)); } }
}
loadPending();
}
// Member sheet: message, role (leader), transfer (leader), kick (outranking).
function openMember(m) {
const act = Soc.memberActions(myRole(), m, X().myOperatorId());
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
const bodyEl = h('div', { class: 'detail' });
const sheet = openSheet({ title: m.name, icon: 'users', closeLabel: App.t('common.close'), body: bodyEl });
const after = async () => { sheet.close(); await load(); };
const run = (btn, fn) => X().guard(btn, async () => { err.hidden = true; try { await fn(); } catch (e) { err.textContent = X().err(e); err.hidden = false; } });
bodyEl.appendChild(h('div', { class: 'pill-row' }, X().rolePill(m.role), h('span', { class: 'pill mono', text: 'AS' + m.asNumber })));
bodyEl.appendChild(h('div', null,
kv(App.t('soc.member.pops'), String(m.towns)), kv(App.t('soc.footprint'), App.fmt.dec(m.footprint)),
kv(App.t('soc.member.lastOnline'), m.lastOnline ? App.fmt.ago(App.now() - m.lastOnline) : App.t('soc.member.never')),
kv(App.t('soc.member.joined'), App.fmt.ago(App.now() - m.joinedAt))));
if (act.message) bodyEl.appendChild(h('button', { class: 'btn wide', type: 'button', onclick: () => { sheet.close(); X().openCompose({ operator: { operatorId: m.operatorId, name: m.name } }); } }, icon('mail'), App.t('soc.member.message')));
if (act.roles.length) {
bodyEl.appendChild(h('div', { class: 'sub', text: App.t('soc.member.setRole') }));
bodyEl.appendChild(h('div', { class: 'seg' }, act.roles.map((r) => h('button', { class: 'seg-btn', type: 'button', text: X().role(r), onclick: (ev) => run(ev.currentTarget, async () => {
await App.api.post('/alliances/' + mine.alliance.id + '/role', { operatorId: m.operatorId, role: r }, { intent: 'ally:role:' + m.operatorId + ':' + r });
toast(App.t('soc.member.roleSet', { name: m.name, role: X().role(r) }), 'ok');
await after();
}) }))));
bodyEl.appendChild(h('p', { class: 'field-hint', text: App.t('soc.member.roleHint') }));
}
const row = h('div', { class: 'btn-row soc-stack' });
if (act.transfer) row.appendChild(h('button', { class: 'btn', type: 'button', onclick: () => {
sheet.close();
X().confirmSheet({ title: App.t('soc.transfer.go'), icon: 'shield', ok: App.t('soc.transfer.go'), text: App.t('soc.transfer.confirm', { name: m.name }),
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/transfer', { operatorId: m.operatorId }, { intent: 'ally:transfer:' + m.operatorId }); toast(App.t('soc.transfer.done', { name: m.name }), 'ok'); await load(); } });
} }, icon('shield'), App.t('soc.transfer.go')));
if (act.kick) row.appendChild(h('button', { class: 'btn danger', type: 'button', onclick: () => {
sheet.close();
X().confirmSheet({ title: App.t('soc.kick.go'), icon: 'alert', danger: true, ok: App.t('soc.kick.go'), text: App.t('soc.kick.confirm', { name: m.name }),
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/kick', { operatorId: m.operatorId }, { intent: 'ally:kick:' + m.operatorId }); toast(App.t('soc.kick.done', { name: m.name }), 'ok'); await load(); } });
} }, icon('x'), App.t('soc.kick.go')));
if (row.children.length) bodyEl.appendChild(row);
bodyEl.appendChild(err);
}
// ---------------------------------------------------------------- diplomacy
async function drawDiplomacy() {
const my = gen;
const A = acts();
const card = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('shield'), App.t('soc.dip.title')),
A.diplomacy ? h('button', { class: 'btn small primary', type: 'button', onclick: openPicker }, icon('plus'), App.t('soc.dip.new')) : null));
const holder = h('div', { class: 'soc-dip' }, X().loading());
card.appendChild(holder);
if (!A.diplomacy) card.appendChild(h('p', { class: 'field-hint', text: App.t('soc.dip.readOnly') }));
content.appendChild(card);
const draw = (d) => {
cache.dip = d;
clear(holder);
stopTick();
if (d.proposalsIn.length) holder.appendChild(proposalBlock('soc.dip.incoming', d.proposalsIn, 'in'));
holder.appendChild(h('div', { class: 'sub', text: App.t('soc.dip.relations') }));
if (!d.relations.length) holder.appendChild(h('p', { class: 'empty', text: App.t('soc.dip.none') }));
const list = h('ul', { class: 'soc-list' });
for (const r of d.relations) list.appendChild(relationRow(r));
holder.appendChild(list);
if (d.proposalsOut.length) holder.appendChild(proposalBlock('soc.dip.outgoing', d.proposalsOut, 'out'));
const cds = holder.querySelectorAll('[data-eff]');
if (cds.length) {
offTick = App.onTick((now) => {
for (const el of cds) {
if (!el.isConnected) continue;
const left = Math.max(0, Number(el.dataset.eff) - now);
const s = left > 0 ? App.t('soc.dip.in', { t: App.fmt.dur(left, 2) }) : App.t('soc.dip.applying');
if (el.textContent !== s) el.textContent = s;
}
});
}
};
const refetch = async () => {
try {
const d = await App.api.get('/alliances/' + mine.alliance.id + '/diplomacy');
if (my !== gen || tab !== 'diplomacy') return;
draw(d);
} catch (e) { if (my === gen && tab === 'diplomacy') { clear(holder); holder.appendChild(X().errorBox(e, drawTab)); } }
};
refreshDip = refetch;
if (cache.dip) draw(cache.dip);
refetch();
}
let refreshDip = () => {};
function allianceLabel(other) {
return h('span', { class: 'row-title' }, other.tag ? X().tagPill(other.tag) : null, h('b', { text: other.name || '#' + other.id }));
}
function relationRow(r) {
const A = acts();
const now = App.now();
const p = r.pending;
const eta = p ? h('span', { class: 'soc-eta mono', dataset: { eff: p.effectiveAt }, text: App.t('soc.dip.in', { t: App.fmt.dur(Math.max(0, p.effectiveAt - now), 2) }) }) : null;
const revoke = p && p.byUs && A.diplomacy
? h('button', { class: 'btn small', type: 'button', text: App.t('soc.dip.revoke'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
await App.api.del('/alliances/' + mine.alliance.id + '/diplomacy/' + r.other.id + '/pending');
toast(App.t('soc.dip.revoked'), 'ok'); refreshDip();
}) }) : null;
return h('li', { class: 'soc-item soc-rel' },
h('div', { class: 'row-main' }, allianceLabel(r.other),
h('span', { class: 'row-sub' }, h('span', { class: 'pill soc-state soc-state-' + r.state, text: X().state(r.state) }),
p ? h('span', { class: 'soc-pending' }, ' → ', h('b', { text: X().state(p.to) }), ' · ', eta, ' · ', p.byUs ? App.t('soc.dip.byUs') : App.t('soc.dip.byThem')) : null)),
revoke);
}
function proposalBlock(titleKey, items, dir) {
const A = acts();
const wrap = h('div', null, h('div', { class: 'sub', text: App.t(titleKey) }));
const list = h('ul', { class: 'soc-list' });
const now = App.now();
for (const pr of items) {
const mk = (label, cls, path, method) => h('button', { class: 'btn small ' + cls, type: 'button', text: label, onclick: (ev) => X().guard(ev.currentTarget, async () => {
try {
if (method === 'del') await App.api.del(path); else await App.api.post(path, {}, { intent: 'dip:' + path });
refreshDip();
} catch (e) { toast(X().err(e), 'error'); refreshDip(); }
}) });
const btns = !A.diplomacy ? [] : dir === 'in'
? [mk(App.t('soc.dip.decline'), '', '/diplomacy/proposals/' + pr.id + '/decline'), mk(App.t('soc.dip.accept'), 'primary', '/diplomacy/proposals/' + pr.id + '/accept')]
: [mk(App.t('soc.dip.withdraw'), '', '/diplomacy/proposals/' + pr.id, 'del')];
list.appendChild(h('li', { class: 'soc-item soc-rel' },
h('div', { class: 'row-main' }, allianceLabel(pr.other),
h('span', { class: 'row-sub' }, h('span', { class: 'pill soc-state soc-state-' + pr.state, text: X().state(pr.state) }), h('span', { text: App.t('soc.dip.expires', { t: App.fmt.dur(Math.max(0, pr.expiresAt - now), 2) }) }))),
h('div', { class: 'soc-actions' }, btns)));
}
wrap.appendChild(list);
return wrap;
}
// Pick another alliance (directory search), then the move.
function openPicker() {
const results = h('ul', { class: 'soc-list' });
const q = h('input', { type: 'text', maxlength: '40', autocomplete: 'off', spellcheck: 'false', placeholder: App.t('soc.dip.search'), 'aria-label': App.t('soc.dip.search'), enterkeyhint: 'search' });
const more = h('button', { class: 'btn small wide', type: 'button', hidden: true, text: App.t('soc.more') });
let items = [], next = null, seq = 0, timer = null;
const sheet = openSheet({ title: App.t('soc.dip.pick'), icon: 'shield', closeLabel: App.t('common.close'), onClose: () => clearTimeout(timer),
body: h('div', { class: 'detail' }, q, results, more) });
function drawResults() {
clear(results);
const rows = items.filter((x) => x.id !== mine.alliance.id);
if (!rows.length) results.appendChild(h('li', { class: 'empty', text: App.t('soc.dip.noResults') }));
for (const a of rows) {
results.appendChild(h('li', null, h('button', { class: 'row-btn', type: 'button', onclick: () => { sheet.close(); openMove(a); } },
h('span', { class: 'row-main' }, allianceLabel(a), h('span', { class: 'row-sub', text: App.t('soc.size', { n: a.memberCount, cap: a.sizeCap }) })))));
}
more.hidden = next === null;
}
async function search(append) {
const my = ++seq;
try {
const r = await App.api.get('/alliances', { q: q.value.trim() || undefined, after: append ? next : undefined, limit: 30 });
if (my !== seq) return;
items = append ? items.concat(r.items) : r.items; next = r.next;
drawResults();
} catch (e) { if (my === seq) { clear(results); results.appendChild(X().errorBox(e, () => search(false))); } }
}
q.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(() => search(false), 250); });
more.addEventListener('click', () => search(true));
search(false);
}
function openMove(other) {
const d = cache.dip || { relations: [] };
const cur = Soc.relationTo(d.relations, other.id);
const opts = Soc.diplomacyOptions(cur.state, cur.pending);
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
const list = h('div', { class: 'soc-moves' });
const sheet = openSheet({ title: other.name, icon: 'shield', closeLabel: App.t('common.close'),
body: h('div', { class: 'detail' },
h('div', { class: 'pill-row' }, X().tagPill(other.tag), h('span', { class: 'pill soc-state soc-state-' + cur.state, text: App.t('soc.dip.current', { state: X().state(cur.state) }) })),
cur.pending ? h('p', { class: 'reason', text: App.t('soc.dip.locked') }) : null,
!opts.length && !cur.pending ? h('p', { class: 'empty', text: App.t('soc.dip.noMoves') }) : null,
list, err) });
for (const o of opts) {
const hint = o.kind === 'delayed' ? App.t('soc.kind.delayed.hint', { t: App.fmt.dur(R.pactCancelMs(App.state.world ? App.state.world.speed : 1), 2) }) : App.t('soc.kind.' + o.kind + '.hint');
list.appendChild(h('button', { class: 'row-btn soc-move', type: 'button', onclick: (ev) => X().guard(ev.currentTarget, async () => {
err.hidden = true;
try {
const r = await App.api.post('/alliances/' + mine.alliance.id + '/diplomacy', { targetId: other.id, state: o.state }, { intent: 'dip:' + other.id + ':' + o.state });
toast(App.t('soc.dip.result.' + r.result, { state: X().state(r.state), name: other.name }), 'ok');
sheet.close();
cache.dip = null;
if (tab === 'diplomacy') drawTab();
} catch (e) { err.textContent = X().err(e); err.hidden = false; }
}) },
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('span', { class: 'pill soc-state soc-state-' + o.state, text: X().state(o.state) }), h('b', { text: App.t('soc.kind.' + o.kind) })), h('span', { class: 'row-sub soc-wrap', text: hint }))));
}
}
function stopTick() { if (offTick) { offTick(); offTick = null; } }
App.registerScreen({
id: 'alliance', titleKey: 'screen.alliance', navKey: 'nav.alliance', icon: 'users', hud: false, navGroup: 'more',
render(container) {
box = container;
body = h('div', { class: 'soc-body' });
box.appendChild(h('div', { class: 'page soc-page' },
h('div', { class: 'card-head page-head' }, h('h1', { id: 'soc-alliance-h', text: App.t('screen.alliance') }),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load() }, icon('refresh'))),
body));
App.on('session', () => { mine = null; members = null; tab = 'overview'; for (const k of Object.keys(cache)) delete cache[k]; });
},
onShow() { box.querySelector('#soc-alliance-h').textContent = App.t('screen.alliance'); load(); },
onHide() { stopTick(); gen++; },
});
}());

View file

@ -0,0 +1,50 @@
'use strict';
/*
* Expansion on the POP screen (App.popSections, slot 'main'): your POPs (switch between them), and what founding the next
* one takes: rollout crews at home, the footprint gate, a shortcut to the map to pick a site (the map tile sheet then offers
* "Send" -> Settle with the wild-slot choice, see send.js). The founding itself is a settle movement; the settle report has
* an "Open POP" button. The POP switcher in the resource bar lives in main.js.
*/
(function () {
const { h, icon, toast } = UI;
const R = UpstreamRules;
const D = UpstreamData;
const mil = () => App.mil;
function popsList(t) {
const st = App.state;
return h('ul', { class: 'mil-list' }, st.towns.map((x) => h('li', { class: 'mil-row' + (x.id === t.id ? ' current' : '') },
h('span', { class: 'row-ic' }, icon('pop')),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: x.name }), x.isCapital ? h('span', { class: 'pill accent', text: App.t('pop.capital') }) : null),
h('span', { class: 'row-sub' }, mil().coordLink(x.x, x.y))),
x.id === t.id ? h('span', { class: 'pill green', text: App.t('exp.current') })
: h('button', { class: 'btn small', type: 'button', onclick: () => { App.setTown(x.id); } }, App.t('exp.open')))));
}
function card(t) {
const m = t.military;
const owned = App.state.towns.length;
const need = R.footprintNeeded(owned);
const crews = m ? (m.units.home[D.EXPANSION.settleUnit] || 0) : 0;
const canTrain = m && m.trainable.some((u) => u.unit === D.EXPANSION.settleUnit && !u.locked);
const rows = [
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('exp.crews') }), h('span', { class: 'v mono' + (crews >= D.EXPANSION.crews ? ' good' : ''), text: crews + ' / ' + D.EXPANSION.crews })),
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('exp.footprint') }), h('span', { class: 'v mono', text: App.t('exp.footprint.v', { have: App.fmt.num(t.footprint), need: App.fmt.num(need) }) })),
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('exp.range') }), h('span', { class: 'v mono', text: D.EXPANSION.maxDistance + ' ' + App.t('common.tiles') })),
];
const actions = [];
if (crews >= D.EXPANSION.crews) {
actions.push(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { App.go('map', { x: t.x, y: t.y, zoom: 24 }); toast(App.t('exp.pick'), 'ok'); } }, icon('flag'), App.t('exp.found')));
} else {
actions.push(h('p', { class: 'row-sub wrap', text: canTrain ? App.t('exp.needCrews', { n: D.EXPANSION.crews - crews, unit: mil().unitName(D.EXPANSION.settleUnit) }) : App.t('exp.needDepot') }));
if (canTrain) actions.push(h('button', { class: 'btn wide', type: 'button', onclick: () => App.go('units') }, icon('units'), App.t('exp.train')));
}
return h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('flag'), App.t('exp.title')), h('span', { class: 'pill', text: App.t('exp.count', { n: owned }) })),
rows, h('p', { class: 'row-sub wrap', text: App.t('exp.hint') }), actions,
owned > 1 ? [h('h3', { class: 'sub', text: App.t('exp.pops') }), popsList(t)] : null);
}
App.popSections.push({ slot: 'main', render: card });
}());

View file

@ -77,7 +77,7 @@
}
// ------------------------------------------------------------------ screen
let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own';
let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own', offMoveTick = null;
const store = new Store();
let infoSheet = null;
@ -113,6 +113,8 @@
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(),
movements: () => moveLines(),
threatened: (t) => App.mil.moves.incoming.some((m) => m.to && m.to.townId === t.id),
};
view = new MapRender.MapView(canvas, source, {
onTap: onTap,
@ -128,6 +130,21 @@
drawLegend();
}
// Lines for the movements of the shared cache (App.mil.moves): yours, incoming and allied ones, with progress at draw time.
function moveLines() {
const mv = App.mil && App.mil.moves;
if (!mv) return [];
const now = App.now(), out = [];
const add = (m, kind) => {
if (!m.from || !m.to || m.from.x === undefined || m.to.x === undefined) return;
out.push({ from: m.from, to: m.to, kind, p: (now - m.departAt) / Math.max(1, m.arriveAt - m.departAt) });
};
for (const m of mv.outgoing) add(m, m.type === 'return' ? 'ret' : 'out');
for (const m of mv.incoming) add(m, 'in');
for (const m of mv.alliedIncoming || []) add(m, 'ally');
return out;
}
function drawLegend() {
UI.clear(legendEl);
const item = (cls, text) => h('li', null, h('span', { class: 'lg ' + cls }), text);
@ -135,6 +152,8 @@
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')));
legendEl.appendChild(item('mv-out', App.t('map.legend.out')));
legendEl.appendChild(item('mv-in', App.t('map.legend.in')));
}
// ------------------------------------------------------------------ tile info
@ -174,6 +193,9 @@
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
}
body.push(row('', App.t('map.info.coords', { x, y })));
if (App.openSend && App.state.towns.length && (town || (special && special.type === 'incumbent') || (!special && known))) {
body.push(h('button', { class: 'btn wide' + (town && town.owner.id === ownOperatorId() ? '' : ' primary'), type: 'button', onclick: () => App.openSend({ x, y }) }, icon('target'), App.t('send.open')));
}
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')));
@ -192,10 +214,19 @@
render(container) {
box = container;
App.on('session', () => { store.reset(); pendingFocus = 'own'; });
App.on('movements', () => { if (visible && view) view.invalidate(); });
App.on('towns', () => { if (view) view.invalidate(); });
App.on('town', () => { const t = App.state.townData; if (t) store.patchTown(t.id, { name: t.name }); });
},
onShow(params) {
visible = true;
// marker positions move with the clock: redraw about once a second while any movement is on the wire
if (offMoveTick) offMoveTick();
let lastSec = 0;
offMoveTick = App.onTick((now) => {
const sec = Math.floor(now / 1000), mv = App.mil.moves;
if (sec !== lastSec && view && (mv.outgoing.length || mv.incoming.length || (mv.alliedIncoming || []).length)) { lastSec = sec; view.invalidate(); }
});
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);
@ -208,7 +239,7 @@
// 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(); },
onHide() { visible = false; if (offMoveTick) offMoveTick(); offMoveTick = null; closeSheet(); },
onLang() {
if (!ready) return;
canvas.setAttribute('aria-label', App.t('map.label'));

View file

@ -0,0 +1,334 @@
'use strict';
/*
* Messages: inbox, sent, alliance broadcast feed, blocked operators, one thread per operator, compose. Message text is
* plain text and only ever set with textContent (the CSS keeps line breaks). Lists are newest first and paged with
* `after` = the last id (the next page holds OLDER ids). The unread count of the inbox is polled in the background and
* shown through App.setBadge on the nav entry (or the "More" button).
*/
(function () {
const { h, clear, icon, toast, openSheet } = UI;
const Soc = UpstreamSocial;
const D = UpstreamData;
const X = () => window.SocUI;
const PAGE = 30;
let box, tabsEl, listBox, tab = 'inbox';
let thread = null; // { peer: {operatorId, name}, items, next, loading } while a conversation is open
let blocked = null; // Map operatorId -> name (loaded lazily)
let unreadOnly = false;
let offTick = null, gen = 0;
const feeds = { inbox: blank(), sent: blank(), alliance: blank() };
let blocks = { items: null, err: null };
function blank() { return { items: [], next: null, loaded: false, loading: false, err: null }; }
const inAlliance = () => !!X().myAlliance();
const urls = { inbox: '/messages/inbox', sent: '/messages/outbox', alliance: '/messages/alliance' };
// ------------------------------------------------------------------ unread badge (works without the screen being open)
const badge = { n: 0, polling: false };
async function pollUnread() {
if (!App.state.user || badge.polling || document.hidden) return;
badge.polling = true;
try { const r = await App.api.get('/messages/inbox', { limit: 1 }); setUnread(r.unread || 0); } catch (e) { /* a badge is a convenience */ } finally { badge.polling = false; }
}
// App.setBadge (main.js) shows it on this screen's nav button, or summed on the "More" button when the screen lives there.
function setUnread(n) { badge.n = n; App.state.unreadMsgs = n; App.setBadge('messages', n, 'info'); }
setInterval(pollUnread, 60000);
document.addEventListener('visibilitychange', () => { if (!document.hidden) pollUnread(); });
App.on('session', () => { setUnread(0); for (const k of Object.keys(feeds)) feeds[k] = blank(); blocks = { items: null, err: null }; thread = null; setTimeout(pollUnread, 800); });
// ------------------------------------------------------------------ loading
async function loadFeed(kind, more) {
const f = feeds[kind];
if (f.loading) return;
f.loading = true; f.err = null;
const my = gen;
if (kind === tab && !thread) drawList();
try {
const q = { limit: PAGE };
if (more && f.next) q.after = f.next;
if (kind === 'inbox' && unreadOnly) q.unread = true;
const r = await App.api.get(urls[kind], q);
f.items = more ? Soc.mergeMessages(f.items, r.items) : r.items;
f.next = r.next; f.loaded = true;
if (kind === 'inbox' && typeof r.unread === 'number') setUnread(r.unread);
} catch (e) { f.err = e; if (kind === 'alliance' && e.code === 'not_in_alliance') { f.items = []; f.next = null; f.loaded = true; f.err = null; } } finally {
f.loading = false;
if (my === gen && kind === tab && !thread) drawList();
}
}
async function loadBlocks() {
blocks.err = null;
try { blocks.items = (await App.api.get('/messages/blocks')).items; blocked = new Map(blocks.items.map((b) => [b.operatorId, b.name])); } catch (e) { blocks.err = e; }
if (tab === 'blocked' && !thread) drawList();
}
async function markRead(ids) {
if (!ids.length) return;
try {
await App.api.post('/messages/read', { ids: ids.slice(0, 100) });
const now = App.now(), set = new Set(ids);
for (const k of Object.keys(feeds)) for (const m of feeds[k].items) if (set.has(m.id) && !m.readAt) m.readAt = now;
if (thread) for (const m of thread.items) if (set.has(m.id) && !m.readAt) m.readAt = now;
pollUnread();
} catch (e) { /* unread state only */ }
}
async function deleteMessage(m, btn) {
await X().guard(btn, async () => {
await App.api.del('/messages/' + m.id);
for (const k of Object.keys(feeds)) feeds[k].items = feeds[k].items.filter((x) => x.id !== m.id);
if (thread) thread.items = thread.items.filter((x) => x.id !== m.id);
toast(App.t('soc.msg.deleted'), 'ok');
pollUnread();
thread ? drawThread() : drawList();
});
}
// ------------------------------------------------------------------ list view
const ago = (at) => h('span', { class: 'when mono', dataset: { at }, text: App.fmt.ago(App.now() - at) });
function msgRow(m) {
const out = m.direction === 'out';
const unread = !out && !m.readAt;
const alliance = m.kind === 'alliance';
const who = out ? (alliance ? App.t('soc.msg.allianceFeed') : App.t('soc.msg.toShort', { name: m.to ? m.to.name : '?' })) : m.from.name;
const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.msg.delete'), onclick: (ev) => deleteMessage(m, ev.currentTarget) }, icon('x'));
return h('li', { class: 'soc-msgrow' },
h('button', { class: 'row-btn soc-msg' + (unread ? ' unread' : ''), type: 'button', onclick: () => openMessage(m) },
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: who }), alliance && m.alliance ? X().tagPill(m.alliance.tag) : null, unread ? h('span', { class: 'pill accent', text: App.t('soc.msg.new') }) : null),
h('span', { class: 'soc-preview', text: m.text })),
ago(m.createdAt)),
del);
}
function openMessage(m) {
if (m.kind === 'alliance') {
if (m.direction === 'in' && !m.readAt) markRead([m.id]);
if (tab !== 'alliance') setTab('alliance'); else drawList();
return;
}
const peer = Soc.peerOf(m);
openThread({ operatorId: peer.operatorId, name: peer.name });
}
function drawList() {
if (!listBox) return;
clear(listBox);
if (thread) return;
tabsEl.hidden = !!thread;
for (const b of tabsEl.children) b.setAttribute('aria-pressed', String(b.dataset.tab === tab));
const inb = tabsEl.querySelector('[data-tab="inbox"] .soc-tabn');
if (inb) { inb.textContent = badge.n ? String(badge.n) : ''; inb.hidden = !badge.n; }
const allyBtn = tabsEl.querySelector('[data-tab="alliance"]');
if (allyBtn) allyBtn.hidden = !inAlliance();
if (tab === 'blocked') { drawBlocked(); return; }
const f = feeds[tab];
if (tab === 'inbox') {
listBox.appendChild(h('div', { class: 'soc-toolbar' },
h('button', { class: 'chip-btn', type: 'button', 'aria-pressed': String(unreadOnly), text: App.t('soc.msg.unreadOnly'), onclick: () => { unreadOnly = !unreadOnly; feeds.inbox = blank(); loadFeed('inbox'); } }),
h('button', { class: 'btn small', type: 'button', disabled: !badge.n, text: App.t('soc.msg.markAll'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
await App.api.post('/messages/read', { all: true });
const now = App.now();
for (const m of feeds.inbox.items) if (!m.readAt) m.readAt = now;
setUnread(0); drawList();
}) })));
}
if (tab === 'alliance') drawBroadcast();
if (f.err) { listBox.appendChild(X().errorBox(f.err, () => loadFeed(tab))); return; }
if (!f.loaded && f.loading) { listBox.appendChild(X().loading()); return; }
if (!f.items.length) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.msg.empty.' + tab) })); return; }
const ul = h('ul', { class: 'soc-list' });
for (const m of f.items) ul.appendChild(tab === 'alliance' ? feedItem(m) : msgRow(m));
listBox.appendChild(ul);
if (f.next !== null) listBox.appendChild(h('button', { class: 'btn small wide', type: 'button', disabled: f.loading, text: App.t('soc.more'), onclick: () => loadFeed(tab, true) }));
}
// One alliance broadcast shown in full.
function feedItem(m) {
const out = m.direction === 'out';
const unread = !out && !m.readAt;
return h('li', { class: 'soc-item soc-feed' + (unread ? ' unread' : '') },
h('div', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: m.from.name }), unread ? h('span', { class: 'pill accent', text: App.t('soc.msg.new') }) : null, ago(m.createdAt)),
h('p', { class: 'soc-msg-body', text: m.text })),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.msg.delete'), onclick: (ev) => deleteMessage(m, ev.currentTarget) }, icon('x')));
}
let bc = null;
function drawBroadcast() {
if (!bc) {
bc = X().composer({
label: App.t('soc.msg.toAlliance'), placeholder: App.t('soc.msg.broadcastPlaceholder'), sendLabel: App.t('soc.msg.broadcast'), rows: 2,
onSend: async (text) => { await App.api.post('/messages', { text, toAlliance: true }, { retries: 0 }); toast(App.t('soc.msg.sent'), 'ok'); feeds.alliance = blank(); loadFeed('alliance'); },
});
}
listBox.appendChild(h('div', { class: 'card soc-card' }, h('div', { class: 'sub', text: App.t('soc.msg.toAlliance') }), bc.el));
}
function drawBlocked() {
if (blocks.err) { listBox.appendChild(X().errorBox(blocks.err, loadBlocks)); return; }
if (!blocks.items) { listBox.appendChild(X().loading()); return; }
listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.block.hint') }));
if (!blocks.items.length) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.block.none') })); return; }
const ul = h('ul', { class: 'soc-list' });
for (const b of blocks.items) {
ul.appendChild(h('li', { class: 'soc-item' }, h('div', { class: 'row-main' }, h('b', { text: b.name }), h('span', { class: 'row-sub', text: App.t('soc.block.since', { t: App.fmt.ago(App.now() - b.createdAt) }) })),
h('button', { class: 'btn small', type: 'button', text: App.t('soc.block.unblock'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
await App.api.del('/messages/blocks/' + b.operatorId);
toast(App.t('soc.block.unblocked', { name: b.name }), 'ok');
await loadBlocks();
}) })));
}
listBox.appendChild(ul);
}
// ------------------------------------------------------------------ thread view
async function openThread(peer) {
thread = { peer, items: [], next: null, loading: true, err: null };
if (!blocked) loadBlocks();
drawThread();
await fetchThread(false);
}
async function fetchThread(more) {
const t = thread;
if (!t) return;
t.loading = true; t.err = null;
try {
const q = { limit: PAGE };
if (more && t.next) q.after = t.next;
const r = await App.api.get('/messages/thread/' + t.peer.operatorId, q);
if (thread !== t) return;
t.items = more ? Soc.mergeMessages(t.items, r.items) : r.items;
t.next = r.next;
const ids = Soc.unreadIds(t.items);
if (ids.length) markRead(ids);
} catch (e) { if (thread === t) t.err = e; } finally {
t.loading = false;
if (thread === t) drawThread(more ? undefined : 'bottom');
}
}
let threadComposer = null, threadFor = 0;
function drawThread(scroll) {
clear(listBox);
if (!thread) return;
tabsEl.hidden = true;
const t = thread;
const isBlocked = blocked && blocked.has(t.peer.operatorId);
const blockBtn = h('button', { class: 'btn small' + (isBlocked ? '' : ' danger'), type: 'button', text: App.t(isBlocked ? 'soc.block.unblock' : 'soc.block.go'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
if (isBlocked) { await App.api.del('/messages/blocks/' + t.peer.operatorId); toast(App.t('soc.block.unblocked', { name: t.peer.name }), 'ok'); } else { await App.api.post('/messages/blocks', { operatorId: t.peer.operatorId }); toast(App.t('soc.block.blocked', { name: t.peer.name }), 'ok'); }
await loadBlocks(); drawThread();
}) });
listBox.appendChild(h('div', { class: 'soc-thread-head' },
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.back'), onclick: closeThread }, icon('back')),
h('h2', { class: 'soc-thread-name', text: t.peer.name }), blockBtn));
if (isBlocked) listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.block.threadHint') }));
if (t.err) listBox.appendChild(X().errorBox(t.err, () => fetchThread(false)));
if (t.loading && !t.items.length) listBox.appendChild(X().loading());
if (t.next !== null) listBox.appendChild(h('button', { class: 'btn small wide', type: 'button', disabled: t.loading, text: App.t('soc.msg.older'), onclick: () => fetchThread(true) }));
if (!t.items.length && !t.loading && !t.err) listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.msg.thread.empty', { name: t.peer.name }) }));
const ul = h('ul', { class: 'soc-thread' });
for (const m of Soc.chronological(t.items)) {
const out = m.direction === 'out';
ul.appendChild(h('li', { class: 'soc-bubble ' + (out ? 'out' : 'in') + (!out && !m.readAt ? ' unread' : '') },
h('p', { class: 'soc-msg-body', text: m.text }),
h('div', { class: 'soc-bubble-meta' }, ago(m.createdAt), h('button', { class: 'soc-del', type: 'button', 'aria-label': App.t('soc.msg.delete'), onclick: (ev) => deleteMessage(m, ev.currentTarget) }, icon('x')))));
}
listBox.appendChild(ul);
if (!threadComposer || threadFor !== t.peer.operatorId) {
if (threadComposer) threadComposer.destroy();
threadFor = t.peer.operatorId;
threadComposer = X().composer({
label: App.t('soc.msg.to', { name: t.peer.name }), placeholder: App.t('soc.msg.reply'), rows: 2,
onSend: async (text) => { await App.api.post('/messages', { text, toOperatorId: t.peer.operatorId }, { retries: 0 }); feeds.sent = blank(); await fetchThread(false); },
});
}
listBox.appendChild(h('div', { class: 'soc-reply' }, threadComposer.el));
if (scroll === 'bottom') requestAnimationFrame(() => { const v = document.getElementById('view'); if (v) v.scrollTop = v.scrollHeight; });
}
function closeThread() {
thread = null;
if (threadComposer) { threadComposer.destroy(); threadComposer = null; }
for (const k of ['inbox', 'sent']) feeds[k] = blank();
drawList(); loadFeed(tab === 'blocked' ? 'inbox' : tab === 'alliance' ? 'alliance' : tab);
}
// ------------------------------------------------------------------ new message sheet
function openNew(prefill) {
const nameIn = h('input', { type: 'text', maxlength: '40', autocomplete: 'off', autocapitalize: 'off', spellcheck: 'false', id: 'soc-to', value: prefill || '' });
const hintEl = h('p', { class: 'field-hint', text: App.t('soc.msg.nameHint') });
const comp = X().composer({
onSend: async (text) => {
const name = Soc.cleanName(nameIn.value);
if (!name) { nameIn.focus(); throw Object.assign(new Error('name'), { code: 'validation_failed' }); }
try { await App.api.post('/messages', { text, toName: name }, { retries: 0 }); } catch (e) {
if (e.code === 'not_found') throw Object.assign(new Error(App.t('soc.msg.unknown', { name })), { code: 'x', message: App.t('soc.msg.unknown', { name }) });
throw e;
}
toast(App.t('soc.msg.sent'), 'ok');
sheet.close();
feeds.sent = blank(); feeds.inbox = blank();
if (tab === 'sent' || tab === 'inbox') loadFeed(tab);
},
});
const sheet = openSheet({ title: App.t('soc.msg.new.title'), icon: 'mail', closeLabel: App.t('common.close'), onClose: comp.destroy,
body: h('div', { class: 'detail' }, h('label', { class: 'field', for: 'soc-to' }, h('span', { class: 'field-lbl', text: App.t('soc.msg.recipient') }), nameIn, hintEl), comp.el) });
setTimeout(() => (prefill ? comp.focus() : nameIn.focus()), 220);
}
// ------------------------------------------------------------------ tabs + shell
function setTab(t) {
if (t === tab && !thread) return;
tab = t; thread = null;
if (threadComposer) { threadComposer.destroy(); threadComposer = null; }
if (t === 'blocked') { if (!blocks.items) loadBlocks(); } else if (!feeds[t].loaded) loadFeed(t); else drawList();
drawList();
}
function startTick() {
if (offTick) offTick();
offTick = App.onTick(() => {
const now = App.now();
for (const el of listBox.querySelectorAll('.when')) { const s = App.fmt.ago(now - Number(el.dataset.at)); if (el.textContent !== s) el.textContent = s; }
});
}
App.registerScreen({
id: 'messages', titleKey: 'screen.messages', navKey: 'nav.messages', icon: 'mail', hud: false, navGroup: 'more',
render(container) {
box = container;
const tabs = [['inbox', 'soc.msg.tab.inbox'], ['sent', 'soc.msg.tab.sent'], ['alliance', 'soc.msg.tab.alliance'], ['blocked', 'soc.msg.tab.blocked']];
tabsEl = h('div', { class: 'seg soc-tabs soc-tabs4', role: 'group', 'aria-label': App.t('soc.tab.label') },
tabs.map(([id, key]) => h('button', { class: 'seg-btn', type: 'button', dataset: { tab: id }, 'aria-pressed': String(tab === id), onclick: () => setTab(id) },
h('span', { class: 'soc-tabt', text: App.t(key) }), id === 'inbox' ? h('span', { class: 'soc-tabn', hidden: true }) : null)));
listBox = h('div', { class: 'soc-listbox' });
box.appendChild(h('div', { class: 'page soc-page' },
h('div', { class: 'card-head page-head' }, h('h1', { id: 'soc-msg-h', text: App.t('screen.messages') }),
h('div', { class: 'soc-head-actions' },
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => { if (thread) fetchThread(false); else if (tab === 'blocked') loadBlocks(); else { feeds[tab] = blank(); loadFeed(tab); } } }, icon('refresh')),
h('button', { class: 'btn small primary', type: 'button', onclick: () => openNew() }, icon('pencil'), App.t('soc.msg.new.go')))),
tabsEl, listBox));
},
onShow(params) {
gen++;
box.querySelector('#soc-msg-h').textContent = App.t('screen.messages');
const labels = { inbox: 'soc.msg.tab.inbox', sent: 'soc.msg.tab.sent', alliance: 'soc.msg.tab.alliance', blocked: 'soc.msg.tab.blocked' };
for (const b of tabsEl.children) b.querySelector('.soc-tabt').textContent = App.t(labels[b.dataset.tab]);
bc = null;
if (!inAlliance() && tab === 'alliance') tab = 'inbox';
if (params && params.to) { tab = 'inbox'; openNew(params.to); }
if (thread) drawThread(); else { drawList(); if (tab === 'blocked') loadBlocks(); else loadFeed(tab); }
startTick();
pollUnread();
},
onHide() { if (offTick) { offTick(); offTick = null; } gen++; },
});
}());

View file

@ -0,0 +1,151 @@
'use strict';
/*
* Movements: what is on the wire right now. Incoming movements of other operators come first and are deliberately loud
* (the server hides their type and units: origin and ETA only); your own outgoing legs and returns follow, with live
* countdowns and a Recall button during the first 90 seconds. Also registers the incoming-warning banner on the POP screen.
* Data comes from App.mil.moves (milstate.js), which push, the poll and the ticker keep current.
*/
(function () {
const { h, clear, icon, toast } = UI;
const Mil = UpstreamMil;
let box, listEl, visible = false, offTick = null, dirty = true;
// ------------------------------------------------------------------ rows
function incomingRow(m) {
const from = m.from || {};
const owner = from.owner;
return h('li', { class: 'mil-row incoming' },
h('span', { class: 'row-ic bad' }, icon('alert')),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: App.t('mov.incoming.title', { town: (m.to && m.to.name) || '?' }) })),
h('span', { class: 'row-sub wrap' }, owner ? App.t('mov.incoming.from', { operator: owner.name }) + ' · ' : '', mil().endLink(from)),
h('span', { class: 'row-sub wrap', text: App.t('mov.incoming.hint') })),
h('span', { class: 'mil-when' }, mil().countdown(m.arriveAt, { cls: 'big' }), h('small', { text: mil().clockTime(m.arriveAt) })));
}
const mil = () => App.mil;
function outgoingRow(m, now) {
const type = m.type;
const sub = [];
if (m.units && Mil.sumUnits(m.units) > 0) sub.push(h('span', { class: 'row-sub wrap', text: mil().unitsText(m.units) }));
if (m.cargo && Object.keys(m.cargo).some((r) => m.cargo[r] > 0)) sub.push(mil().resChips(m.cargo));
if (m.target) sub.push(h('span', { class: 'row-sub wrap', text: App.t('mov.target', { name: App.buildingName(m.target) }) }));
const recallable = m.recallableUntil && m.recallableUntil > now;
const bar = h('i');
const row = h('li', { class: 'mil-row out type-' + type, dataset: { id: m.id } },
h('span', { class: 'row-ic' }, icon(Mil.TYPE_ICON[type] || 'move')),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: mil().typeLabel(type) })),
h('span', { class: 'row-sub wrap' }, mil().endLink(m.from), h('span', { class: 'arrow', 'aria-hidden': 'true' }, icon('move')), mil().endLink(m.to)),
sub,
h('span', { class: 'bar mil-bar', 'aria-hidden': 'true' }, bar),
recallable ? h('button', { class: 'btn small danger mil-recall', type: 'button', dataset: { until: String(m.recallableUntil), id: String(m.id) }, onclick: (ev) => recall(m, ev.currentTarget) },
icon('return'), h('span', { text: App.t('mov.recall') }), mil().countdown(m.recallableUntil)) : null),
h('span', { class: 'mil-when' }, mil().countdown(m.arriveAt), h('small', { text: mil().clockTime(m.arriveAt) })));
row._bar = bar; row._m = m;
return row;
}
async function recall(m, btn) {
btn.disabled = true;
try {
await App.api.post('/movements/' + m.id + '/recall', {}, { intent: 'recall:' + m.id });
toast(App.t('mov.recalled'), 'ok');
} catch (e) {
toast(App.errMsg(e), 'error');
}
App.refreshMovements().catch(() => {});
App.refreshTown().catch(() => {});
}
// ------------------------------------------------------------------ screen
function draw() {
dirty = false;
clear(listEl);
const mv = mil().moves, now = App.now();
const inc = mv.incoming.slice().sort((a, b) => a.arriveAt - b.arriveAt);
const out = mv.outgoing.slice().sort((a, b) => a.arriveAt - b.arriveAt);
if (inc.length) {
listEl.appendChild(h('section', { class: 'card warn-card', role: 'alert' },
h('div', { class: 'card-head' }, h('h2', null, icon('alert'), App.t('mov.incoming.head', { n: inc.length }))),
h('ul', { class: 'mil-list' }, inc.map(incomingRow))));
}
const allied = (mv.alliedIncoming || []).slice().sort((a, b) => a.arriveAt - b.arriveAt);
if (allied.length) {
listEl.appendChild(h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('handshake'), App.t('mov.allied.head'))),
h('ul', { class: 'mil-list' }, allied.map((m) => h('li', { class: 'mil-row' },
h('span', { class: 'row-ic' }, icon('shield')),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: App.t('mov.allied.title', { operator: m.toOperator ? m.toOperator.name : '?', town: (m.to && m.to.name) || '?' }) })),
h('span', { class: 'row-sub wrap' }, m.from && m.from.owner ? App.t('mov.incoming.from', { operator: m.from.owner.name }) + ' · ' : '', mil().endLink(m.from))),
h('span', { class: 'mil-when' }, mil().countdown(m.arriveAt), h('small', { text: mil().clockTime(m.arriveAt) })))))));
}
listEl.appendChild(h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('move'), App.t('mov.outgoing.head')), h('span', { class: 'pill', text: String(out.length) })),
out.length ? h('ul', { class: 'mil-list' }, out.map((m) => outgoingRow(m, now))) : h('p', { class: 'empty', text: mv.loaded ? App.t('mov.empty') : App.t('common.loading') })));
tick(now);
}
function tick(now) {
if (!listEl) return;
for (const row of listEl.querySelectorAll('li.out')) {
if (!row._m) continue;
row._bar.style.setProperty('--p', String(mil().progress(row._m, now)));
}
for (const b of listEl.querySelectorAll('.mil-recall')) if (Number(b.dataset.until) <= now) b.remove();
}
App.registerScreen({
id: 'movements', titleKey: 'screen.movements', navKey: 'nav.movements', icon: 'move', hud: false,
render(container) {
box = container;
listEl = h('div', { class: 'mil-sections' });
box.appendChild(h('div', { class: 'page' },
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.movements') }),
h('div', { class: 'head-actions' },
h('button', { class: 'btn small primary', type: 'button', onclick: () => App.openSend({}) }, icon('target'), App.t('mov.send')),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => App.refreshMovements().catch((e) => toast(App.errMsg(e), 'error')) }, icon('refresh')))),
listEl));
App.on('movements', () => { if (visible) draw(); else dirty = true; });
App.on('lang', () => { if (box) box.querySelector('h1').textContent = App.t('screen.movements'); });
},
onShow() {
visible = true;
box.querySelector('h1').textContent = App.t('screen.movements');
draw();
App.refreshMovements().catch(() => {});
if (offTick) offTick();
offTick = App.onTick(tick);
},
onHide() { visible = false; if (offTick) offTick(); offTick = null; },
});
// ------------------------------------------------------------------ incoming banner on the POP screen
function fillBanner(el) {
clear(el);
const inc = mil().moves.incoming.slice().sort((a, b) => a.arriveAt - b.arriveAt);
el.hidden = !inc.length;
if (!inc.length) return;
const next = inc[0];
el.appendChild(h('div', { class: 'row-ic bad' }, icon('alert')));
el.appendChild(h('div', { class: 'row-main' },
h('b', { text: App.t('mov.banner.title', { n: inc.length }) }),
h('span', { class: 'row-sub wrap' }, App.t('mov.banner.next', { town: (next.to && next.to.name) || '?', operator: next.from && next.from.owner ? next.from.owner.name : '?' }) + ' '),
h('span', { class: 'row-sub wrap' }, App.t('mov.banner.in') + ' ', mil().countdown(next.arriveAt))));
el.appendChild(h('button', { class: 'btn small', type: 'button', onclick: () => App.go('movements') }, App.t('mov.banner.details')));
}
App.popSections.push({
slot: 'top',
render() {
const el = h('section', { class: 'card warn-card mil-banner', role: 'alert', 'aria-live': 'assertive' });
fillBanner(el);
return el;
},
});
App.on('movements', () => { for (const el of document.querySelectorAll('.mil-banner')) fillBanner(el); });
App.on('lang', () => { for (const el of document.querySelectorAll('.mil-banner')) fillBanner(el); });
}());

View file

@ -275,10 +275,7 @@
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 });
const title = h('h1', { class: 'town-name', text: t.name }); // switching POPs lives in the resource bar (main.js)
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'))),
@ -376,8 +373,12 @@
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; }
// other screens add cards here through App.popSections (military: incoming banner on top, expansion below the power card)
const extra = (slot) => (App.popSections || []).filter((s) => s.slot === slot).map((s) => { try { return s.render(t); } catch (e) { console.error(e); return null; } });
const tops = extra('top');
if (tops.some(Boolean)) box.appendChild(h('div', { class: 'pop-top' }, tops));
box.appendChild(h('div', { class: 'cols' },
h('div', { class: 'col' }, header(t), queueCard(t), powerCard()),
h('div', { class: 'col' }, header(t), queueCard(t), powerCard(), extra('main')),
h('div', { class: 'col' }, fieldsCard(t), infraCard(t))));
tick(App.now());
}
@ -482,6 +483,7 @@
App.on('town', onTown);
App.on('session', () => { dirty = true; prevQueue = null; });
App.on('townchange', () => { dirty = true; if (visible) draw(); });
App.on('towns', () => { dirty = true; if (visible) draw(); });
},
onShow() {
visible = true;

View file

@ -0,0 +1,146 @@
'use strict';
/*
* Rankings: operators by footprint, alliances by summed footprint, battle points (attack / defense / total). The server
* returns `you` (your own rank, even when it is not on the loaded page) and a rank-offset cursor (`next`). Rows of your own
* operator or alliance are highlighted. Names are set with textContent only.
*/
(function () {
const { h, clear, icon, openSheet } = UI;
const Soc = UpstreamSocial;
const PAGE = 50;
const X = () => window.SocUI;
let box, listBox, tabsEl, subEl;
let tab = 'operators', by = 'attack';
const sets = {};
let gen = 0;
const keyOf = () => (tab === 'battles' ? 'battles:' + by : tab);
const cur = () => sets[keyOf()] || (sets[keyOf()] = { items: [], next: null, total: 0, you: null, available: true, loaded: false, loading: false, err: null });
const path = () => '/rankings/' + tab;
async function load(more) {
const key = keyOf(), s = cur();
if (s.loading) return;
s.loading = true; s.err = null;
const my = gen;
if (key === keyOf()) draw();
try {
const q = { limit: PAGE };
if (more && s.next !== null) q.after = s.next;
if (tab === 'battles') q.by = by;
const r = await App.api.get(path(), q);
s.items = more ? Soc.mergeRanks(s.items, r.items) : r.items;
s.next = r.next; s.total = r.total; s.you = r.you; s.loaded = true;
if (typeof r.available === 'boolean') s.available = r.available;
} catch (e) { s.err = e; } finally {
s.loading = false;
if (my === gen && key === keyOf()) draw();
}
}
const num = (n) => App.fmt.num(Math.round(n));
// One row: rank, name (+ tag), the value columns. `main` is the metric shown big, `sub` the small line.
function row(r) {
const you = Soc.isYou(tab, r, youRow());
let name, sub, val, tap;
if (tab === 'operators') {
name = r.name; sub = (r.allianceTag ? '[' + r.allianceTag + '] ' : '') + App.t('soc.rank.pops', { n: r.towns }); val = App.fmt.dec(r.footprint);
tap = () => openOperator(r);
} else if (tab === 'alliances') {
name = r.name; sub = '[' + r.tag + '] ' + App.t('soc.rank.members', { n: r.members }) + ' · ' + App.t('soc.rank.pops', { n: r.towns }); val = App.fmt.dec(r.footprint);
tap = () => X().openProfile(r.allianceId, { name: r.name });
} else {
name = r.name; sub = (r.allianceTag ? '[' + r.allianceTag + '] ' : '') + App.t('soc.rank.att', { n: num(r.attackPoints) }) + ' · ' + App.t('soc.rank.def', { n: num(r.defensePoints) });
val = num(Soc.battlePoints(r, by));
tap = () => openOperator(r);
}
return h('li', null, h('button', { class: 'soc-rank' + (you ? ' you' : ''), type: 'button', onclick: tap, 'aria-current': you ? 'true' : null },
h('span', { class: 'soc-rk mono', text: '#' + r.rank }),
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: name }), you ? h('span', { class: 'pill accent', text: App.t('soc.you') }) : null), h('span', { class: 'row-sub', text: sub })),
h('span', { class: 'soc-val mono', text: val })));
}
const youRow = () => cur().you;
function openOperator(r) {
const me = X().myOperatorId();
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v', text: v }));
const body = h('div', { class: 'detail' },
h('div', { class: 'pill-row' }, h('span', { class: 'pill soc-tag mono', text: '#' + r.rank }), r.allianceTag ? X().tagPill(r.allianceTag) : null, r.asNumber ? h('span', { class: 'pill mono', text: UpstreamI18n.fmtAs(r.asNumber) }) : null),
h('div', null,
r.footprint !== undefined ? kv(App.t('soc.footprint'), App.fmt.dec(r.footprint)) : null,
r.towns !== undefined ? kv(App.t('soc.member.pops'), String(r.towns)) : null,
r.attackPoints !== undefined ? kv(App.t('soc.rank.attack'), num(r.attackPoints)) : null,
r.defensePoints !== undefined ? kv(App.t('soc.rank.defense'), num(r.defensePoints)) : null));
const sheet = openSheet({ title: r.name, icon: 'users', closeLabel: App.t('common.close'), body });
if (r.allianceId) body.appendChild(h('button', { class: 'btn wide', type: 'button', onclick: () => { sheet.close(); X().openProfile(r.allianceId, { name: r.allianceTag }); } }, icon('users'), App.t('soc.rank.viewAlliance')));
if (r.operatorId !== me) body.appendChild(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { sheet.close(); X().openCompose({ operator: { operatorId: r.operatorId, name: r.name } }); } }, icon('mail'), App.t('soc.member.message')));
}
function draw() {
if (!listBox) return;
clear(listBox);
for (const b of tabsEl.children) b.setAttribute('aria-pressed', String(b.dataset.tab === tab));
subEl.hidden = tab !== 'battles';
for (const b of subEl.children) b.setAttribute('aria-pressed', String(b.dataset.by === by));
const s = cur();
if (s.err) { listBox.appendChild(X().errorBox(s.err, () => load(false))); return; }
if (!s.loaded) { listBox.appendChild(X().loading()); return; }
if (tab === 'battles' && !s.available) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.rank.unavailable') })); return; }
if (s.you) {
const y = s.you;
const inList = s.items.some((r) => r.rank === y.rank);
listBox.appendChild(h('div', { class: 'card soc-card soc-yourank' },
h('span', { class: 'soc-yr-n mono', text: '#' + y.rank }),
h('span', { class: 'row-main' }, h('b', { text: App.t('soc.rank.yours') }),
h('span', { class: 'row-sub', text: App.t('soc.rank.of', { n: s.total }) + (tab === 'battles' ? ' · ' + num(Soc.battlePoints(y, by)) : ' · ' + App.fmt.dec(y.footprint)) })),
inList ? null : h('span', { class: 'pill dim', text: App.t('soc.rank.notShown') })));
} else if (tab === 'alliances') {
listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.rank.noAlliance') }));
} else if (tab === 'battles') {
listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.rank.noPoints') }));
}
if (!s.items.length) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t(tab === 'battles' ? 'soc.rank.noBattles' : 'soc.rank.empty') })); return; }
const ol = h('ol', { class: 'soc-ranklist' });
for (const r of s.items) ol.appendChild(row(r));
listBox.appendChild(ol);
if (s.next !== null) listBox.appendChild(h('button', { class: 'btn small wide', type: 'button', disabled: s.loading, text: App.t('soc.more') + ' (' + s.items.length + '/' + s.total + ')', onclick: () => load(true) }));
}
function setTab(t) {
tab = t;
draw();
if (!cur().loaded) load(false);
}
App.registerScreen({
id: 'rankings', titleKey: 'screen.rankings', navKey: 'nav.rankings', icon: 'trophy', hud: false, navGroup: 'more',
render(container) {
box = container;
const tabs = [['operators', 'soc.rank.tab.operators'], ['alliances', 'soc.rank.tab.alliances'], ['battles', 'soc.rank.tab.battles']];
tabsEl = h('div', { class: 'seg soc-tabs', role: 'group', 'aria-label': App.t('soc.tab.label') },
tabs.map(([id, key]) => h('button', { class: 'seg-btn', type: 'button', dataset: { tab: id }, 'aria-pressed': String(tab === id), text: App.t(key), onclick: () => setTab(id) })));
subEl = h('div', { class: 'seg soc-subtabs', role: 'group', 'aria-label': App.t('soc.rank.by'), hidden: true },
['attack', 'defense', 'total'].map((k) => h('button', { class: 'chip-btn', type: 'button', dataset: { by: k }, 'aria-pressed': String(by === k), text: App.t('soc.rank.by.' + k), onclick: () => { by = k; draw(); if (!cur().loaded) load(false); } })));
listBox = h('div', { class: 'soc-listbox' });
box.appendChild(h('div', { class: 'page soc-page' },
h('div', { class: 'card-head page-head' }, h('h1', { id: 'soc-rank-h', text: App.t('screen.rankings') }),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => { delete sets[keyOf()]; load(false); } }, icon('refresh'))),
tabsEl, subEl, listBox));
App.on('session', () => { for (const k of Object.keys(sets)) delete sets[k]; });
},
onShow() {
gen++;
box.querySelector('#soc-rank-h').textContent = App.t('screen.rankings');
const labels = { operators: 'soc.rank.tab.operators', alliances: 'soc.rank.tab.alliances', battles: 'soc.rank.tab.battles' };
for (const b of tabsEl.children) b.textContent = App.t(labels[b.dataset.tab]);
for (const b of subEl.children) b.textContent = App.t('soc.rank.by.' + b.dataset.by);
draw();
load(false); // rankings move: always refresh the first page when the screen opens
},
onHide() { gen++; },
});
}());

View file

@ -0,0 +1,316 @@
'use strict';
/*
* Reports: newest first, cursor-paginated (GET /reports?after=<last id>), unread highlighted, a detail sheet per report
* (GET /reports/:id, then POST /reports/:id/read). Detail layouts exist for battle (raid/attack/takeover), scan,
* scan_detected, incumbent, settle, reinforce and movement_failed; coordinates are links that jump to the map.
* `data` differs by report type AND by the recipient's role (attacker / defender / reinforcer / sender / target).
*/
(function () {
const { h, clear, icon, toast, openSheet } = UI;
const D = UpstreamData;
const Mil = UpstreamMil;
const mil = () => App.mil;
const num = (n) => App.fmt.num(n);
const PAGE = 25;
let box, listEl, moreBtn, statusEl, items = [], next = null, loading = false, visible = false, offAgo = null;
// ------------------------------------------------------------------ list rows
const nameOf = (o) => (o && o.name) || '?';
const townOf = (t) => (t ? t.name : '?');
// { icon, title, sub, tone } for the list
function describe(it) {
const s = it.summary || {};
switch (it.type) {
case 'raid': case 'attack': case 'takeover': {
const res = Mil.perspective(it.role, s.outcome);
const mine = it.role === 'attacker';
const title = mil().reportTypeLabel(it.type) + ': ' + townOf(s.target);
const sub = mine ? App.t('rep.sub.you_vs', { name: nameOf(s.defender) }) : App.t('rep.sub.by', { name: nameOf(s.attacker) });
return { icon: Mil.TYPE_ICON[it.type], title, sub: sub + (s.captured ? ' · ' + App.t('rep.captured') : ''), tone: res === 'victory' ? 'good' : 'bad', badge: App.t('rep.' + res) };
}
case 'scan': {
const where = s.target ? townOf(s.target) : (s.site ? s.site.x + ', ' + s.site.y : '?');
return { icon: 'eye', title: App.t('rep.scan.title', { where }), sub: s.success ? App.t('rep.scan.ok') : App.t('rep.scan.failed'), tone: s.success ? 'good' : 'bad' };
}
case 'scan_detected':
return { icon: 'eye', title: App.t('rep.detected.title', { town: townOf(s.target) }), sub: s.identityRevealed && s.by ? App.t('rep.sub.by', { name: nameOf(s.by) }) : App.t('rep.detected.unknown'), tone: 'warn' };
case 'incumbent':
return { icon: 'b-core_router', title: App.t('rep.incumbent.title', { x: s.site ? s.site.x : '?', y: s.site ? s.site.y : '?' }), sub: '', tone: s.outcome === 'attacker_won' ? 'good' : 'bad', badge: s.outcome === 'attacker_won' ? App.t('rep.victory') : App.t('rep.defeat') };
case 'settle':
return { icon: 'flag', title: App.t('rep.settle.title', { name: s.town ? s.town.name : '?' }), sub: '', tone: 'good' };
case 'reinforce':
return { icon: 'shield', title: it.role === 'sender' ? App.t('rep.reinforce.sender', { town: townOf(s.host) }) : App.t('rep.reinforce.target', { town: townOf(s.host) }), sub: mil().unitsText(s.units), tone: 'neutral' };
case 'movement_failed':
return { icon: 'alert', title: App.t('rep.failed.title', { type: mil().typeLabel(s.movementType) }), sub: reasonText(s.reason), tone: 'bad' };
default:
return { icon: 'report', title: mil().reportTypeLabel(it.type), sub: '', tone: 'neutral' };
}
}
function reasonText(code) {
if (!code) return '';
if (UpstreamI18n.strings.en['rep.reason.' + code]) return App.t('rep.reason.' + code);
if (UpstreamI18n.strings.en['err.' + code]) return App.t('err.' + code);
return code;
}
function row(it) {
const d = describe(it);
return h('li', null, h('button', { class: 'alert rep tone-' + d.tone + (it.read ? '' : ' new'), type: 'button', dataset: { id: String(it.id) }, onclick: () => openReport(it.id) },
h('span', { class: 'row-ic' }, icon(d.icon)),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: d.title }), d.badge ? h('span', { class: 'pill ' + (d.tone === 'good' ? 'green' : 'amber'), text: d.badge }) : null, it.read ? null : h('span', { class: 'pill accent', text: App.t('alerts.new') })),
d.sub ? h('span', { class: 'row-sub', text: d.sub }) : null),
h('span', { class: 'when mono', dataset: { at: String(it.createdAt) }, text: App.fmt.ago(App.now() - it.createdAt) })));
}
function draw() {
clear(listEl);
if (!items.length) { listEl.appendChild(h('li', null, h('p', { class: 'empty pad', text: loading ? App.t('common.loading') : App.t('rep.empty') }))); }
for (const it of items) listEl.appendChild(row(it));
moreBtn.hidden = next === null;
}
async function load(more) {
if (loading) return;
loading = true; statusEl.hidden = true;
try {
const r = await App.api.get('/reports', { limit: PAGE, after: more ? next : undefined });
items = more ? items.concat(r.items.filter((x) => !items.some((y) => y.id === x.id))) : r.items;
next = r.next;
mil().reportsUnread = r.unread;
App.setBadge('reports', r.unread, 'info');
} catch (e) {
statusEl.textContent = App.errMsg(e); statusEl.hidden = false;
} finally { loading = false; }
draw();
}
async function markAll() {
try {
await App.api.post('/reports/read-all', {}, { intent: 'reports:read-all' });
for (const it of items) it.read = true;
App.setBadge('reports', 0, 'info');
draw();
} catch (e) { toast(App.errMsg(e), 'error'); }
}
// ------------------------------------------------------------------ detail pieces
const sec = (title, ...kids) => h('section', { class: 'rep-sec' }, h('h3', { class: 'sub', text: title }), kids);
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
function unitsTable(sent, lost, survivors) {
const ids = D.UNIT_ORDER.filter((u) => (sent && sent[u]) || (lost && lost[u]) || (survivors && survivors[u]));
if (!ids.length) return h('p', { class: 'empty', text: App.t('rep.noUnits') });
return h('table', { class: 'mil-table' },
h('thead', null, h('tr', null, h('th', { text: '' }), h('th', { text: App.t('rep.sent') }), h('th', { text: App.t('rep.lost') }), h('th', { text: App.t('rep.left') }))),
h('tbody', null, ids.map((u) => h('tr', null,
h('td', { text: mil().unitName(u) }),
h('td', { class: 'mono', text: num((sent && sent[u]) || 0) }),
h('td', { class: 'mono' + (lost && lost[u] ? ' bad' : ''), text: num((lost && lost[u]) || 0) }),
h('td', { class: 'mono', text: num((survivors && survivors[u]) || 0) })))));
}
const party = (label, operator, town) => kv(label, h('span', { class: 'rep-party' },
h('b', { text: operator ? operator.name : '?' }), operator && operator.asNumber ? h('small', { class: 'dimmer', text: ' ' + UpstreamI18n.fmtAs(operator.asNumber) }) : null,
town ? mil().endLink(town) : null));
function verdict(role, outcome) {
const res = Mil.perspective(role, outcome);
return h('div', { class: 'rep-verdict ' + res }, icon(res === 'victory' ? 'check' : 'alert'), h('b', { text: App.t('rep.' + res) }));
}
function combatBody(r) {
const d = r.data, out = [];
out.push(verdict(r.role, d.outcome));
out.push(h('p', { class: 'row-sub', text: App.t('rep.arrived', { t: mil().dayTime(d.arrivedAt) }) + ' · ' + mil().reportTypeLabel(d.type) }));
out.push(party(App.t('rep.attacker'), d.attacker.operator, d.attacker.town));
out.push(party(App.t('rep.defender'), d.defender.operator, d.defender.town));
const p = d.power || {};
out.push(sec(App.t('rep.power'),
kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(p.attack || 0) })),
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(p.defence || 0) })),
p.firewallLevel !== undefined ? kv(App.t('rep.power.firewall'), h('span', { class: 'mono', text: p.firewallLevel + (p.effectiveFirewall !== undefined && p.effectiveFirewall !== p.firewallLevel ? ' → ' + App.fmt.dec(p.effectiveFirewall) : '') })) : null));
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
const groups = (d.defender.groups || []);
out.push(sec(App.t('rep.defenderUnits'), groups.length ? groups.map((g) => h('div', { class: 'rep-group' },
h('p', { class: 'row-sub wrap' }, g.ownerTownId === (d.defender.town && d.defender.town.id) ? App.t('rep.group.home') : App.t('rep.group.reinf', { town: '#' + g.ownerTownId }), g.offline ? ' · ' + App.t('rep.group.offline') : ''),
unitsTable(g.sent, g.lost, g.survivors))) : h('p', { class: 'empty', text: App.t('rep.noUnits') })));
if (d.loot && D.RESOURCES.some((x) => d.loot[x])) {
out.push(sec(App.t('rep.loot'), mil().resChips(d.loot, true), d.cacheHidden ? h('p', { class: 'row-sub', text: App.t('rep.cache', { p: Math.round(d.cacheHidden * 100) }) }) : null));
}
if (d.siege) out.push(sec(App.t('rep.siege'), h('p', { text: App.t('rep.siege.line', { name: App.buildingName(d.siege.type), a: d.siege.from, b: d.siege.to }) })));
if (d.takeover) {
const t = d.takeover;
const lines = [];
if (t.blocked) lines.push(h('p', { class: 'reason', text: App.t('rep.takeover.blocked.' + t.blocked) }));
else {
lines.push(kv(App.t('rep.takeover.loyalty'), h('b', { class: 'mono', text: num(t.loyaltyBefore) + ' → ' + num(t.loyaltyAfter) + ' (−' + num(t.drop) + ')' })));
if (t.capital) lines.push(h('p', { class: 'row-sub wrap', text: App.t('rep.takeover.capital') }));
}
if (d.capturedTown) lines.push(h('p', { class: 'good', text: App.t('rep.takeover.captured') }));
out.push(sec(App.t('rep.takeover'), lines));
}
return out;
}
function scanBody(r) {
const d = r.data, out = [];
out.push(h('div', { class: 'rep-verdict ' + (d.success ? 'victory' : 'defeat') }, icon(d.success ? 'eye' : 'alert'), h('b', { text: d.success ? App.t('rep.scan.ok') : App.t('rep.scan.failed') })));
if (d.site) out.push(kv(App.t('rep.site'), mil().coordLink(d.site.x, d.site.y)));
if (d.target) out.push(party(App.t('rep.defender'), d.operator, d.target));
if (d.strength) out.push(kv(App.t('rep.scan.strength'), h('span', { class: 'mono', text: App.fmt.dec(d.strength.attacker) + ' vs ' + App.fmt.dec(d.strength.defender) })));
out.push(sec(App.t('rep.scanners'), unitsTable(d.scanners && d.scanners.sent, d.scanners && d.scanners.lost, d.scanners && d.scanners.survivors)));
const intel = d.intel;
if (!intel) { out.push(h('p', { class: 'reason', text: App.t('rep.scan.noIntel') })); return out; }
if (d.site) { // incumbent site
out.push(sec(App.t('rep.intel'),
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(intel.defence) })),
intel.bonusAvailable ? h('p', { class: 'row-sub wrap', text: App.t('rep.incumbent.bonus', { n: num(intel.hardwareBonus) }) }) : h('p', { class: 'row-sub wrap', text: App.t('rep.incumbent.taken') })));
return out;
}
out.push(sec(App.t('rep.intel.resources'), mil().resChips(intel.resources)));
out.push(sec(App.t('rep.intel.units'),
!intel.online ? h('p', { class: 'reason', text: App.t('rep.intel.offline') }) : null,
unitsTable(intel.units.home, {}, intel.units.home),
(intel.units.stationed || []).map((g) => h('div', { class: 'rep-group' }, h('p', { class: 'row-sub wrap', text: App.t('rep.group.reinf', { town: '#' + g.ownerTownId }) }), h('p', { text: mil().unitsText(g.units) })))));
if (intel.buildings) {
out.push(sec(App.t('rep.intel.buildings'),
h('ul', { class: 'rep-buildings' }, intel.buildings.filter((b) => b.level > 0).map((b) => h('li', null, h('span', { text: App.buildingName(b.type) }), h('b', { class: 'mono', text: String(b.level) }))))));
}
if (intel.loyalty !== undefined) out.push(kv(App.t('pop.loyalty'), h('b', { class: 'mono', text: num(intel.loyalty) })));
if (intel.outgoing && intel.outgoing.length) {
out.push(sec(App.t('rep.intel.outgoing'), h('ul', { class: 'rep-buildings' }, intel.outgoing.map((m) => h('li', null, h('span', { text: mil().typeLabel(m.type) }), mil().coordLink(m.to.x, m.to.y), h('small', { class: 'dimmer', text: mil().clockTime(m.arriveAt) }))))));
}
return out;
}
function detectedBody(r) {
const d = r.data, out = [];
out.push(h('div', { class: 'rep-verdict defeat' }, icon('eye'), h('b', { text: App.t('rep.detected.title', { town: townOf(d.target) }) })));
if (d.target) out.push(kv(App.t('rep.target'), mil().endLink(d.target)));
if (d.identityRevealed && d.by) out.push(party(App.t('rep.scannedBy'), d.by.operator, d.by.town));
else out.push(h('p', { class: 'row-sub wrap', text: App.t('rep.detected.unknown') }));
return out;
}
function incumbentBody(r) {
const d = r.data, out = [];
out.push(verdict('attacker', d.outcome));
out.push(kv(App.t('rep.site'), mil().coordLink(d.site.x, d.site.y)));
if (d.origin) out.push(kv(App.t('rep.from'), mil().endLink(d.origin)));
out.push(sec(App.t('rep.power'), kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(d.power.attack) })), kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(d.power.defence) }))));
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
if (d.bonus) out.push(sec(App.t('rep.incumbent.reward'), mil().resChips({ hardware: d.bonus.hardware }, true), d.bonus.researchSpeedBonus ? h('p', { class: 'row-sub', text: App.t('units.research.speed', { p: Math.round(d.bonus.researchSpeedBonus * 100) }) }) : null));
return out;
}
function settleBody(r, ctl) {
const d = r.data, out = [];
out.push(h('div', { class: 'rep-verdict victory' }, icon('flag'), h('b', { text: App.t('rep.settle.title', { name: d.town.name }) })));
out.push(kv(App.t('rep.site'), mil().coordLink(d.town.x, d.town.y)));
out.push(kv(App.t('rep.settle.wild'), h('span', { text: (d.wild || []).map((w) => App.buildingName(w)).join(', ') })));
out.push(h('button', { class: 'btn primary wide', type: 'button', onclick: async () => {
ctl.close();
try { await App.refreshTowns(); } catch (e) { /* the POP list may be stale; setTown below copes */ }
App.setTown(d.town.id); App.go('pop');
} }, icon('pop'), App.t('rep.settle.open')));
out.push(h('p', { class: 'row-sub wrap', text: App.t('rep.settle.hint') }));
return out;
}
function reinforceBody(r) {
const d = r.data, out = [];
out.push(kv(App.t('rep.from'), h('span', null, h('b', { text: nameOf(d.operator) }), mil().endLink(d.from))));
out.push(kv(App.t('rep.host'), h('span', null, h('b', { text: nameOf(d.hostOperator) }), mil().endLink(d.host))));
out.push(sec(App.t('rep.units'), h('p', { text: mil().unitsText(d.units) })));
return out;
}
function failedBody(r) {
const d = r.data, out = [];
out.push(h('div', { class: 'rep-verdict defeat' }, icon('alert'), h('b', { text: App.t('rep.failed.title', { type: mil().typeLabel(d.movementType) }) })));
out.push(h('p', { text: reasonText(d.reason) }));
if (d.to) out.push(kv(App.t('rep.target'), mil().coordLink(d.to.x, d.to.y)));
out.push(sec(App.t('rep.units'), h('p', { text: mil().unitsText(d.units) }), h('p', { class: 'row-sub wrap', text: App.t('rep.failed.home') })));
return out;
}
function genericBody(r) {
return [h('pre', { class: 'rep-raw', text: JSON.stringify(r.summary || {}, null, 1).slice(0, 1500) })];
}
function bodyFor(r, ctl) {
switch (r.type) {
case 'raid': case 'attack': case 'takeover': return combatBody(r);
case 'scan': return scanBody(r);
case 'scan_detected': return detectedBody(r);
case 'incumbent': return incumbentBody(r);
case 'settle': return settleBody(r, ctl);
case 'reinforce': return reinforceBody(r);
case 'movement_failed': return failedBody(r);
default: return genericBody(r);
}
}
// ------------------------------------------------------------------ detail sheet
async function openReport(id) {
const body = h('div', { class: 'detail rep-detail' }, h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' })));
const ctl = openSheet({ title: App.t('screen.reports'), icon: 'report', closeLabel: App.t('common.close'), body });
try {
const res = await App.api.get('/reports/' + id);
const r = res.report;
ctl.setTitle(mil().reportTypeLabel(r.type));
clear(body);
body.appendChild(h('p', { class: 'row-sub', text: mil().dayTime(r.createdAt) + ' · ' + App.t('rep.role.' + r.role) + ' · ' + App.t('rep.expires', { t: mil().dayTime(r.expiresAt) }) }));
let parts;
try { parts = bodyFor(r, ctl); } catch (e) { parts = genericBody(r); }
for (const p of parts.flat(2)) if (p) body.appendChild(p);
if (!r.read) {
App.api.post('/reports/' + id + '/read', {}).then(() => {
const it = items.find((x) => x.id === id); if (it) it.read = true;
if (visible) draw();
App.refreshReportsUnread().catch(() => {});
}).catch(() => {});
}
} catch (e) {
clear(body);
body.appendChild(h('p', { class: 'form-error', text: App.errMsg(e) }));
}
}
// ------------------------------------------------------------------ screen
App.registerScreen({
id: 'reports', titleKey: 'screen.reports', navKey: 'nav.reports', icon: 'report', navGroup: 'more', hud: false,
render(container) {
box = container;
listEl = h('ul', { class: 'alert-list' });
statusEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
moreBtn = h('button', { class: 'btn wide', type: 'button', hidden: true, onclick: () => load(true) }, App.t('rep.older'));
box.appendChild(h('div', { class: 'page' },
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.reports') }),
h('div', { class: 'head-actions' },
h('button', { class: 'btn small', type: 'button', onclick: markAll }, icon('check'), App.t('rep.markAll')),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load(false) }, icon('refresh')))),
statusEl, listEl, moreBtn));
App.on('session', () => { items = []; next = null; });
App.on('report', () => { if (visible) load(false); });
},
onShow(params) {
visible = true;
box.querySelector('h1').textContent = App.t('screen.reports');
moreBtn.textContent = App.t('rep.older');
draw();
load(false);
if (params && params.open) openReport(Number(params.open));
if (offAgo) offAgo();
offAgo = 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() { visible = false; if (offAgo) offAgo(); offAgo = null; },
});
}());

339
public/js/screens/send.js Normal file
View file

@ -0,0 +1,339 @@
'use strict';
/*
* The send dialog: App.openSend({ x, y, fromTownId, type }). Opened from a map tile, the POP screen, the units screen and the
* movements screen. It looks the target up (GET /map/tile), offers the movement types that can work, lets you pick units
* (or cargo, or the wild slots of a new POP), previews latency and arrival from rules.js and sends POST /movements. The
* server re-validates everything; this dialog only avoids obviously doomed sends and explains the greyed-out ones.
* An Idempotency intent is generated per opened dialog (and again after a successful send), so a retried tap cannot send twice.
*/
(function () {
const { h, clear, icon, toast, openSheet } = UI;
const R = UpstreamRules;
const D = UpstreamData;
const Mil = UpstreamMil;
const mil = () => App.mil;
const num = (n) => App.fmt.num(n);
const nonce = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
App.openSend = function openSend(opts) {
opts = opts || {};
const st = {
x: Number.isInteger(opts.x) ? opts.x : null, y: Number.isInteger(opts.y) ? opts.y : null,
tile: null, tileErr: null, fromId: null, from: null, type: null, units: {}, cargo: {}, target: '',
wild: D.START.wild.slice(), endProtection: false, busy: false, nonce: nonce(), loadSeq: 0, tileSeq: 0, options: [],
};
const own = App.state.towns;
st.fromId = own.some((t) => t.id === opts.fromTownId) ? opts.fromTownId : (App.state.townId || (own[0] && own[0].id));
if (!st.fromId) { toast(App.t('pop.noTown'), 'error'); return; }
const body = h('div', { class: 'detail send' });
let offTick = null;
const ctl = openSheet({ title: App.t('send.title'), icon: 'target', closeLabel: App.t('common.close'), body, onClose: () => { if (offTick) offTick(); } });
const secTarget = h('div', { class: 'send-sec' });
const secFrom = h('div', { class: 'send-sec' });
const secType = h('div', { class: 'send-sec' });
const secUnits = h('div', { class: 'send-sec' });
const secPreview = h('div', { class: 'send-sec' });
const secWarn = h('div', { class: 'send-sec' });
const errEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
const submit = h('button', { class: 'btn primary wide', type: 'button', onclick: () => go() }, icon('target'), h('span', { text: App.t('send.go') }));
body.appendChild(secTarget); body.appendChild(secFrom); body.appendChild(secType); body.appendChild(secUnits); body.appendChild(secPreview); body.appendChild(secWarn);
body.appendChild(h('div', { class: 'send-foot' }, errEl, submit));
const fromTown = () => own.find((t) => t.id === st.fromId);
const home = () => (st.from ? st.from.td.military.units.home : {});
const op = () => App.state.operator;
// ------------------------------------------------------------------ data
async function loadFrom() {
const seq = ++st.loadSeq;
let r;
try {
if (st.fromId === App.state.townId && App.state.townData && App.state.townData.military) r = { td: App.state.townData, rt: App.rulesTown(), at: App.fetchedServerTime };
else { const x = await mil().loadTown(st.fromId); r = { td: x.town, rt: App.rulesTownFrom(x.town, x.serverTime), at: x.serverTime }; }
} catch (e) { if (seq === st.loadSeq) showErr(App.errMsg(e)); return; }
if (seq !== st.loadSeq) return;
st.from = r;
afterData();
}
async function loadTile() {
if (st.x === null || st.y === null) { st.tile = null; return; }
const seq = ++st.tileSeq;
st.tile = null; st.tileErr = null;
drawTarget();
try {
const t = await App.api.get('/map/tile', { x: st.x, y: st.y });
if (seq !== st.tileSeq) return;
st.tile = t;
} catch (e) {
if (seq !== st.tileSeq) return;
st.tileErr = e.code === 'not_found' ? App.t('tile.void') : App.errMsg(e);
}
afterData();
}
function afterData() {
drawTarget();
drawFrom();
if (!st.tile || !st.from) { drawTypes(); return; }
computeOptions();
drawTypes();
}
function computeOptions() {
const m = st.from.td.military;
st.options = Mil.moveOptions({ tile: st.tile, home: m.units.home, transport: m.transport, allianceId: op() ? op().allianceId : null, crews: m.units.home[D.EXPANSION.settleUnit] || 0 });
const want = st.type && st.options.some((o) => o.type === st.type) ? st.type : (opts.type && st.options.some((o) => o.type === opts.type && o.ok) ? opts.type : null);
const first = st.options.find((o) => o.ok);
setType(want || (first ? first.type : (st.options[0] ? st.options[0].type : null)), true);
}
function setType(type, keep) {
if (!keep && type === st.type) return;
st.type = type;
st.units = type ? Mil.defaultUnits(type, home()) : {};
st.cargo = {}; st.target = ''; st.endProtection = false;
showErr('');
drawTypes(); drawUnits(); refresh();
}
// ------------------------------------------------------------------ sections
function drawTarget() {
clear(secTarget);
const t = st.tile;
const xin = h('input', { type: 'number', inputmode: 'numeric', value: st.x === null ? '' : String(st.x), class: 'mil-num', 'aria-label': 'x', placeholder: 'x' });
const yin = h('input', { type: 'number', inputmode: 'numeric', value: st.y === null ? '' : String(st.y), class: 'mil-num', 'aria-label': 'y', placeholder: 'y' });
const lookup = () => {
const x = Math.round(Number(xin.value)), y = Math.round(Number(yin.value));
if (xin.value === '' || yin.value === '' || !Number.isFinite(x) || !Number.isFinite(y)) return;
st.x = x; st.y = y; st.type = null; loadTile();
};
secTarget.appendChild(h('h3', { class: 'sub', text: App.t('send.target') }));
secTarget.appendChild(h('div', { class: 'send-coords' }, h('span', { class: 'mono', text: 'x' }), xin, h('span', { class: 'mono', text: 'y' }), yin,
h('button', { class: 'btn small', type: 'button', onclick: lookup }, icon('locate'), App.t('send.lookup'))));
if (!t) {
secTarget.appendChild(h('div', { class: 'chips' }, own.map((o) => h('button', { class: 'chip-btn', type: 'button', onclick: () => { st.x = o.x; st.y = o.y; st.type = null; loadTile(); } }, o.name))));
}
if (st.tileErr) { secTarget.appendChild(h('p', { class: 'reason', text: st.tileErr })); return; }
if (st.x !== null && !t) { secTarget.appendChild(h('p', { class: 'dimmer', text: App.t('common.loading') })); return; }
if (!t) return;
const pills = [h('span', { class: 'pill', text: App.t('tile.' + t.type) })];
if (t.town) {
if (t.town.mine) pills.push(h('span', { class: 'pill accent', text: App.t('map.info.yours') }));
if (t.town.isCapital) pills.push(h('span', { class: 'pill', text: App.t('map.info.capital') }));
if (t.town.owner && t.town.owner.protected) pills.push(h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')));
}
if (t.type === 'rural' && t.bonus) pills.push(h('span', { class: 'pill res-' + t.bonus }, icon(t.bonus), App.resName(t.bonus)));
secTarget.appendChild(h('div', { class: 'send-target' },
h('div', { class: 'row' }, h('b', { text: t.town ? t.town.name : App.t('tile.' + t.type) }), mil().coordLink(t.x, t.y)),
t.town && t.town.owner ? h('p', { class: 'row-sub wrap', text: t.town.owner.name + ' · ' + UpstreamI18n.fmtAs(t.town.owner.asNumber) }) : null,
h('div', { class: 'pill-row' }, pills)));
}
function drawFrom() {
clear(secFrom);
if (own.length < 2) return;
secFrom.appendChild(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.from') }),
h('select', { onchange: (e) => { st.fromId = Number(e.target.value); st.from = null; st.type = null; st.units = {}; drawUnits(); drawTypes(); loadFrom(); } },
own.map((o) => h('option', { value: o.id, selected: o.id === st.fromId, text: o.name })))));
}
function reasonText(o) {
const r = o.reason || '';
if (r.indexOf('settle:') === 0) {
const code = r.slice(7), s = st.tile && st.tile.settle ? st.tile.settle : {};
if (code === 'footprint_too_low') return App.t('send.reason.footprint', { have: num(s.footprint), need: num(s.footprintNeeded) });
if (code === 'out_of_range') return App.t('send.reason.range', { n: s.maxDistance || D.EXPANSION.maxDistance });
return App.t('send.reason.cannotSettle');
}
return App.t('send.reason.' + r);
}
function drawTypes() {
clear(secType);
if (!st.tile || !st.from) return;
if (!st.options.length) { secType.appendChild(h('p', { class: 'empty', text: App.t('send.nothing') })); return; }
secType.appendChild(h('h3', { class: 'sub', text: App.t('send.what') }));
secType.appendChild(h('div', { class: 'seg wrap-seg', role: 'group', 'aria-label': App.t('send.what') }, st.options.map((o) =>
h('button', { class: 'seg-btn', type: 'button', disabled: !o.ok, 'aria-pressed': String(o.type === st.type), onclick: () => setType(o.type) }, icon(Mil.TYPE_ICON[o.type]), h('span', { text: mil().typeLabel(o.type) })))));
const off = st.options.filter((o) => !o.ok);
if (off.length) secType.appendChild(h('ul', { class: 'send-why' }, off.map((o) => h('li', { class: 'row-sub wrap', text: mil().typeLabel(o.type) + ': ' + reasonText(o) }))));
}
function pickRow(label, have, cur, onChange, sub) {
const range = h('input', { type: 'range', min: '0', max: String(have), step: '1', value: String(cur), 'aria-label': label });
const numIn = h('input', { type: 'number', inputmode: 'numeric', min: '0', max: String(have), value: String(cur), class: 'mil-num', 'aria-label': label });
const set = (v) => { v = Math.max(0, Math.min(have, Math.floor(Number(v)) || 0)); range.value = String(v); numIn.value = String(v); onChange(v); };
range.addEventListener('input', () => set(range.value));
numIn.addEventListener('input', () => set(numIn.value));
return h('div', { class: 'mil-pick' },
h('div', { class: 'row' }, h('span', null, h('b', { text: label }), h('span', { class: 'dimmer', text: ' / ' + num(have) })), sub || null),
h('div', { class: 'pick-ctl' },
h('button', { class: 'btn small', type: 'button', 'aria-label': '-1', onclick: () => set(Number(numIn.value) - 1) }, '−'),
range,
h('button', { class: 'btn small', type: 'button', 'aria-label': '+1', onclick: () => set(Number(numIn.value) + 1) }, '+'),
numIn,
h('button', { class: 'btn small', type: 'button', onclick: () => set(have) }, App.t('send.all'))));
}
function drawUnits() {
clear(secUnits);
const type = st.type;
if (!type || !st.from) return;
const opt = st.options.find((o) => o.type === type);
if (!opt || !opt.ok) return; // greyed out: the reason is shown with the type picker
const h0 = home();
if (type === 'settle') {
const s = st.tile.settle || {};
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.settle.title') }));
secUnits.appendChild(h('p', { class: 'preview', text: App.t('send.settle.crews', { n: D.EXPANSION.crews, unit: mil().unitName(D.EXPANSION.settleUnit) }) }));
secUnits.appendChild(h('p', { class: 'row-sub wrap', text: App.t('send.settle.footprint', { have: num(s.footprint), need: num(s.footprintNeeded), n: s.maxDistance || D.EXPANSION.maxDistance }) }));
for (let i = 0; i < D.WILD_SLOTS; i++) {
secUnits.appendChild(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.settle.wild', { n: i + 1 }) }),
h('select', { onchange: (e) => { st.wild[i] = e.target.value; } },
D.FIELD_TYPES.map((ft) => h('option', { value: ft, selected: st.wild[i] === ft, text: App.buildingName(ft) + ' (' + App.resName(D.FIELD_PRODUCES[ft]) + ')' })))));
}
return;
}
if (type === 'transport') {
const m = st.from.td.military;
const cur = R.resourcesAt(st.from.rt, App.now()).amounts;
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.cargo') }));
secUnits.appendChild(h('p', { class: 'row-sub wrap', text: App.t('send.cargo.cap', { n: num(m.transport.capacityPerLink), free: Math.max(0, m.transport.links - m.transport.active), links: m.transport.links }) }));
for (const r of D.RESOURCES) {
const have = Math.floor(cur[r] || 0);
secUnits.appendChild(pickRow(App.resName(r), have, st.cargo[r] || 0, (v) => { if (v > 0) st.cargo[r] = v; else delete st.cargo[r]; refresh(); }));
}
return;
}
const rows = Mil.unitsForType(type, h0);
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.units') }));
if (!rows.length) { secUnits.appendChild(h('p', { class: 'empty', text: App.t('send.reason.no_units') })); return; }
for (const r of rows) {
const def = D.UNITS[r.unit];
secUnits.appendChild(pickRow(mil().unitName(r.unit), r.have, st.units[r.unit] || 0, (v) => { if (v > 0) st.units[r.unit] = v; else delete st.units[r.unit]; refresh(); },
h('span', { class: 'row-sub', text: def.speed + ' ' + App.t('send.tilesPerHour') })));
}
}
// ------------------------------------------------------------------ preview, warnings, button state
function ready() {
if (!st.tile || !st.from || !st.type) return { ok: false, why: '' };
const o = st.options.find((x) => x.type === st.type);
if (!o || !o.ok) return { ok: false, why: '' };
const m = st.from.td.military;
if (!m.units.online) return { ok: false, why: App.t('err.units_offline') };
if (st.type === 'transport') {
const total = Object.keys(st.cargo).reduce((s, k) => s + st.cargo[k], 0);
if (total < 1) return { ok: false, why: '' };
if (total > m.transport.capacityPerLink) return { ok: false, why: App.t('err.capacity_exceeded') };
} else {
const sel = Mil.cleanSelection(st.units, home());
if (Mil.sumUnits(sel) < 1) return { ok: false, why: '' };
if (st.type === 'takeover' && !(sel[D.EXPANSION.conquestUnit] > 0)) return { ok: false, why: App.t('send.reason.needs_ma_team') };
const chk = R.checkUnitsForType(st.type, sel);
if (chk) return { ok: false, why: '' };
}
if (needsProtectionConfirm() && !st.endProtection) return { ok: false, why: App.t('send.protection.need') };
return { ok: true, why: '' };
}
const needsProtectionConfirm = () => Mil.isHostile(st.type) && op() && op().protectionUntil > App.now();
function refresh() {
drawPreview();
drawWarn();
const r = ready();
submit.disabled = !r.ok || st.busy;
}
function drawPreview() {
clear(secPreview);
if (!st.tile || !st.from || !st.type) return;
const from = fromTown();
if (!from) return;
const units = st.type === 'transport' ? {} : Mil.cleanSelection(st.units, home());
const hasSel = st.type === 'transport' ? Object.keys(st.cargo).length > 0 : Mil.sumUnits(units) > 0;
if (!hasSel) { secPreview.appendChild(h('p', { class: 'dimmer', text: App.t('send.pickSome') })); return; }
const p = Mil.preview(st.type, from, { x: st.tile.x, y: st.tile.y }, units, st.cargo, App.state.world.speed);
secPreview.appendChild(h('div', { class: 'send-preview' },
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.distance') }), h('span', { class: 'v mono', text: App.fmt.dec(p.dist) + ' ' + App.t('common.tiles') })),
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.latency') }), h('span', { class: 'v mono', text: App.fmt.dur(p.ms) })),
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.arrives') }), h('span', { class: 'v mono', text: mil().clockTime(App.now() + p.ms) })),
p.slowest ? h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.slowest') }), h('span', { class: 'v mono', text: p.slowest + ' ' + App.t('send.tilesPerHour') })) : null,
(st.type === 'raid' || st.type === 'attack' || st.type === 'takeover') && p.carry > 0 ? h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.carry') }), h('span', { class: 'v mono', text: num(p.carry) })) : null));
}
function drawWarn() {
clear(secWarn);
if (!st.tile || !st.from || !st.type) return;
const type = st.type;
const items = [];
if (needsProtectionConfirm()) {
const cb = h('input', { type: 'checkbox', checked: st.endProtection, onchange: (e) => { st.endProtection = e.target.checked; refresh(); } });
items.push(h('label', { class: 'warn-check' }, cb, h('span', null, h('b', { text: App.t('send.protection.title') }), ' ', App.t('send.protection.body', { t: mil().dayTime(op().protectionUntil) }))));
}
if ((type === 'attack' || type === 'takeover') && (st.units.exploit_kit || 0) > 0) {
items.push(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.siege') }),
h('select', { onchange: (e) => { st.target = e.target.value; } },
h('option', { value: '', text: App.t('send.siege.none') }),
Mil.siegeTargets().map((k) => h('option', { value: k, selected: st.target === k, text: App.buildingName(k) }))),
h('span', { class: 'field-hint', text: App.t('send.siege.hint', { n: D.MILITARY.kitsMin }) })));
}
if (type === 'takeover') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.takeover.hint') }));
if (type === 'raid') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.raid.hint') }));
if (type === 'scan') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.scan.hint') }));
if (type === 'reinforce' && st.tile.town && st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.reinforce.own') }));
if (Mil.isHostile(type) && st.tile.town && !st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.hostile.hint') }));
const r = ready();
if (r.why) items.push(h('p', { class: 'reason', text: r.why }));
secWarn.appendChild(h('div', { class: 'send-warn' }, items));
}
function showErr(msg) { errEl.textContent = msg || ''; errEl.hidden = !msg; }
// ------------------------------------------------------------------ send
async function go() {
const r = ready();
if (!r.ok || st.busy) return;
st.busy = true; submit.disabled = true; showErr('');
const body = { fromTownId: st.fromId, type: st.type };
if (st.tile.town) body.toTownId = st.tile.town.id; else { body.x = st.tile.x; body.y = st.tile.y; }
if (st.type === 'transport') body.cargo = Object.assign({}, st.cargo);
else body.units = Mil.cleanSelection(st.units, home());
if (st.type === 'settle') body.wild = st.wild.slice(0, D.WILD_SLOTS);
if ((st.type === 'attack' || st.type === 'takeover') && st.target && (body.units.exploit_kit || 0) > 0) body.target = st.target;
if (needsProtectionConfirm() && st.endProtection) body.confirmEndProtection = true;
try {
const res = await App.api.post('/movements', body, { intent: 'send:' + st.fromId + ':' + st.nonce });
st.nonce = nonce();
toast(App.t('send.sent', { type: mil().typeLabel(res.type), t: App.fmt.dur(res.arriveAt - res.departAt) }), 'ok');
ctl.close();
App.refreshMovements().catch(() => {});
App.refreshTown().catch(() => {});
if (App.state.operator && res.protectionEnded) App.state.operator.protectionUntil = 0;
} catch (e) {
st.busy = false;
let msg = App.errMsg(e);
const reason = e.details && e.details.reason;
if (e.code === 'invalid_target' && reason && UpstreamI18n.strings.en['send.invalid.' + reason]) msg += ' ' + App.t('send.invalid.' + reason);
showErr(msg);
if (e.code === 'not_enough_units' || e.code === 'units_offline' || e.code === 'conflict') { st.from = null; loadFrom(); }
refresh();
}
}
// keep the arrival clock and affordability honest while the dialog stays open
let lastSlot = 0;
offTick = App.onTick((now) => {
const slot = Math.floor(now / 15000);
if (slot !== lastSlot && !st.busy && st.from && st.tile && st.type) { lastSlot = slot; drawPreview(); }
});
drawTarget(); drawFrom();
loadFrom();
if (st.x !== null) loadTile();
refresh();
};
}());

View file

@ -77,7 +77,7 @@
}
App.registerScreen({
id: 'settings', titleKey: 'screen.settings', navKey: 'nav.settings', icon: 'gear', hud: false,
id: 'settings', titleKey: 'screen.settings', navKey: 'nav.settings', icon: 'gear', hud: false, navGroup: 'more',
render(container) { box = container; App.on('session', () => { tokens = null; }); },
onShow() { draw(); loadTokens(); },
});

View file

@ -0,0 +1,166 @@
'use strict';
/*
* Pieces shared by the social screens (alliance, messages, rankings): window.SocUI. Everything player-controlled (operator
* names, alliance names and tags, notes, message text) goes in through textContent / text nodes only, never innerHTML.
*/
(function () {
const { h, clear, icon, toast, openSheet } = UI;
const Soc = UpstreamSocial;
const D = UpstreamData;
const role = (r) => (D.SOCIAL.roles.includes(r) ? App.t('soc.role.' + r) : String(r));
const state = (s) => (D.SOCIAL.diplomacyStates.includes(s) ? App.t('soc.state.' + s) : String(s));
const kindLabel = (k) => App.t('soc.kind.' + k);
// Error text for a failed call. A 429 from the message limiter carries retryAfter (seconds).
function err(e) {
if (e && e.code === 'rate_limited' && e.retryAfter && (!e.details || !e.details.scope || e.details.scope === 'messages')) return App.t('soc.rate', { t: App.fmt.dur(Soc.retrySeconds(e) * 1000, 2) });
return App.errMsg(e);
}
// /me caches the operator's alliance; after founding, joining, leaving or being kicked refresh just that, without
// App.setSession (which would reset the POP view).
async function refreshOperator() {
const me = await App.api.get('/me');
const mineOp = (me.operators || []).find((o) => App.state.operator && o.id === App.state.operator.id);
if (mineOp && App.state.operator) {
App.state.operator.alliance = mineOp.alliance;
App.state.operator.allianceId = mineOp.allianceId;
App.emit('alliance', mineOp.alliance);
}
return mineOp;
}
const myAlliance = () => (App.state.operator && App.state.operator.alliance) || null;
const myOperatorId = () => (App.state.operator ? App.state.operator.id : 0);
const tagPill = (tag) => h('span', { class: 'pill soc-tag', text: '[' + tag + ']' });
const rolePill = (r) => h('span', { class: 'pill soc-role soc-role-' + r, text: role(r) });
// A busy button: disables itself while the promise runs and reports errors as a toast (or via `onError`).
async function guard(btn, fn, onError) {
if (btn) btn.disabled = true;
try { return await fn(); } catch (e) {
if (onError) onError(e); else toast(err(e), 'error');
return undefined;
} finally { if (btn && btn.isConnected) btn.disabled = false; }
}
// Confirmation sheet. onOk() may throw: the error is shown inside the sheet and it stays open.
function confirmSheet(o) {
const msg = h('p', { class: 'form-error', role: 'alert', hidden: true });
const ok = h('button', { class: 'btn ' + (o.danger ? 'danger' : 'primary'), type: 'button', text: o.ok || App.t('common.confirm') });
const sheet = openSheet({
title: o.title, icon: o.icon || 'alert', closeLabel: App.t('common.close'),
body: h('div', { class: 'detail' }, h('p', { class: 'detail-desc', text: o.text }), msg,
h('div', { class: 'btn-row' }, h('button', { class: 'btn', type: 'button', onclick: () => sheet.close(), text: App.t('common.cancel') }), ok)),
});
ok.addEventListener('click', async () => {
ok.disabled = true; msg.hidden = true;
try { await o.onOk(); sheet.close(); } catch (e) { msg.textContent = err(e); msg.hidden = false; ok.disabled = false; }
});
return sheet;
}
// ------------------------------------------------------------------ composer: textarea + live counter + send
// composer({ onSend(text) -> Promise, placeholder, sendLabel, label }) -> { el, focus(), clear(), input }
// A rate_limited answer disables sending and counts the seconds down; the text is kept.
function composer(o) {
const max = D.SOCIAL.messageMax;
const input = h('textarea', { class: 'soc-text', rows: o.rows || 3, maxlength: String(max * 2), placeholder: o.placeholder || '', 'aria-label': o.label || App.t('soc.msg.text'), enterkeyhint: 'enter' });
const counter = h('span', { class: 'soc-count mono' });
const note = h('p', { class: 'soc-rate', role: 'alert', hidden: true });
const send = h('button', { class: 'btn primary', type: 'button' }, icon('up'), o.sendLabel || App.t('soc.msg.send'));
const el = h('div', { class: 'soc-composer' }, input, h('div', { class: 'soc-composer-bar' }, counter, send), note);
let until = 0, off = null, busy = false;
function refresh() {
const st = Soc.composeState(input.value, max);
counter.textContent = st.n + '/' + max;
counter.classList.toggle('over', st.over);
counter.setAttribute('aria-label', App.t('soc.msg.counter', { n: st.n, max }));
const waiting = until > App.now();
send.disabled = busy || st.empty || st.over || waiting;
}
function tick() {
if (!el.isConnected) { stopTick(); return; }
const left = Math.ceil((until - App.now()) / 1000);
if (left <= 0) { until = 0; note.hidden = true; stopTick(); refresh(); return; }
const s = App.t('soc.rate', { t: App.fmt.dur(left * 1000, 2) });
if (note.textContent !== s) note.textContent = s;
}
function startTick() { if (!off) off = App.onTick(tick); }
function stopTick() { if (off) { off(); off = null; } }
input.addEventListener('input', refresh);
send.addEventListener('click', async () => {
const text = input.value;
if (send.disabled) return;
busy = true; refresh(); note.hidden = true;
try {
await o.onSend(text);
input.value = '';
} catch (e) {
if (e && e.code === 'rate_limited') {
until = App.now() + Soc.retrySeconds(e) * 1000;
note.textContent = App.t('soc.rate', { t: App.fmt.dur(Soc.retrySeconds(e) * 1000, 2) }); note.hidden = false;
startTick();
} else { note.textContent = err(e); note.hidden = false; }
} finally { busy = false; refresh(); }
});
refresh();
return { el, input, focus: () => { try { input.focus({ preventScroll: true }); } catch (e) { /* ignore */ } }, refresh, destroy: stopTick };
}
// Compose sheet. target: { operator: { operatorId, name } } or { alliance: true }.
function openCompose(target, onSent) {
const toAlliance = !!target.alliance;
const to = toAlliance ? '[' + ((myAlliance() || {}).tag || '') + ']' : target.operator.name;
const comp = composer({
onSend: async (text) => {
const body = toAlliance ? { text, toAlliance: true } : { text, toOperatorId: target.operator.operatorId };
await App.api.post('/messages', body, { retries: 0 });
toast(App.t('soc.msg.sent'), 'ok');
sheet.close();
if (onSent) onSent();
},
});
const sheet = openSheet({
title: toAlliance ? App.t('soc.msg.toAlliance') : App.t('soc.msg.to', { name: to }),
icon: 'mail', closeLabel: App.t('common.close'), onClose: comp.destroy,
body: h('div', { class: 'detail' }, toAlliance ? h('p', { class: 'detail-desc', text: App.t('soc.msg.broadcastHint', { tag: to }) }) : null, comp.el),
});
setTimeout(comp.focus, 220);
return sheet;
}
// ------------------------------------------------------------------ alliance profile sheet (public view)
async function openProfile(allianceId, extra) {
const body = h('div', { class: 'detail' }, h('p', { class: 'empty', text: App.t('common.loading') }));
const sheet = openSheet({ title: extra && extra.name ? extra.name : App.t('soc.profile'), icon: 'users', closeLabel: App.t('common.close'), body });
try {
const a = (await App.api.get('/alliances/' + allianceId)).alliance;
sheet.setTitle(a.name);
clear(body);
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
body.appendChild(h('div', { class: 'pill-row' }, tagPill(a.tag),
a.relation ? h('span', { class: 'pill soc-state soc-state-' + a.relation, text: a.relation === 'same' ? App.t('soc.relation.same') : state(a.relation) }) : null,
a.myRole ? rolePill(a.myRole) : null));
body.appendChild(h('div', null,
kv(App.t('soc.members'), App.t('soc.size', { n: a.memberCount, cap: a.sizeCap })),
kv(App.t('soc.leader'), a.leader ? a.leader.name : '-'),
kv(App.t('soc.footprint'), App.fmt.dec(a.footprint || 0)),
kv(App.t('soc.founded'), App.fmt.ago(App.now() - a.createdAt))));
} catch (e) {
clear(body);
body.appendChild(h('p', { class: 'form-error', role: 'alert', text: err(e) }));
}
return sheet;
}
// Loading / error / empty placeholders for a list container.
const loading = () => h('p', { class: 'empty', text: App.t('common.loading') });
const errorBox = (e, retry) => h('div', { class: 'soc-err' }, h('p', { class: 'form-error', role: 'alert', text: err(e) }),
retry ? h('button', { class: 'btn small', type: 'button', onclick: retry }, icon('refresh'), App.t('common.retry')) : null);
window.SocUI = { role, state, kindLabel, err, refreshOperator, myAlliance, myOperatorId, tagPill, rolePill, guard, confirmSheet, composer, openCompose, openProfile, loading, errorBox };
}());

368
public/js/screens/units.js Normal file
View file

@ -0,0 +1,368 @@
'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(); },
});
}());

111
public/js/social.js Normal file
View file

@ -0,0 +1,111 @@
'use strict';
/*
* Pure client logic of the social screens (alliance, messages, rankings): no DOM, no I/O, no clocks. Loads as a browser
* script (window.UpstreamSocial) and as a Node module (test/client-social.test.js). Permissions and diplomacy moves are
* never re-implemented here: they come from rules.js (allianceCan, outranks, diplomacyMove) over the tables in data.js, so
* the buttons the screens show are exactly the ones the server would accept. The server still checks everything.
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory(require('./rules.js'), require('./data.js'));
else root.UpstreamSocial = factory(root.UpstreamRules, root.UpstreamData);
}(typeof self !== 'undefined' ? self : this, function (R, D) {
const S = D.SOCIAL;
// What the viewer may do in their own alliance (role from GET /alliances/mine). `memberCount` decides whether a leader
// can simply leave (alone: the alliance is disbanded) or must hand over leadership first.
function selfActions(role, memberCount) {
const can = (a) => !!role && R.allianceCan(role, a);
return {
invite: can('invite'), viewInvites: can('viewInvites'), cancelInvite: can('cancelInvite'),
editNotes: can('editNotes'), diplomacy: can('diplomacy'), broadcast: can('broadcast'),
disband: can('disband'), transfer: can('transfer'), setRole: can('setRole'),
leave: !!role, leaveNeedsTransfer: role === 'leader' && memberCount > 1,
};
}
// What the viewer may do to one listed member. `kick` needs the permission AND a strictly higher rank; roles are set by the
// leader to diplomat/officer/member only (leadership moves through `transfer`).
function memberActions(myRole, member, myOperatorId) {
const self = member.operatorId === myOperatorId;
const settable = S.roles.filter((r) => r !== 'leader');
return {
self,
message: !self,
kick: !self && !!myRole && R.allianceCan(myRole, 'kick') && R.outranks(myRole, member.role),
roles: !self && !!myRole && R.allianceCan(myRole, 'setRole') && member.role !== 'leader' ? settable.filter((r) => r !== member.role) : [],
transfer: !self && !!myRole && R.allianceCan(myRole, 'transfer'),
};
}
// Relation of the own alliance to another: `relations` is the list of GET /alliances/:id/diplomacy. No row = neutral.
function relationTo(relations, otherId) {
const r = (relations || []).find((x) => x.other && x.other.id === otherId);
return r ? { state: r.state, since: r.since, pending: r.pending || null } : { state: 'neutral', since: null, pending: null };
}
// Moves offered from the current state: [{ state, kind: 'immediate' | 'proposal' | 'delayed' }]. A pair with a scheduled
// change is locked (the server answers diplomacy_pending), so nothing is offered.
function diplomacyOptions(current, pending) {
if (pending) return [];
return S.diplomacyStates.filter((s) => s !== current && R.diplomacyMove(current, s)).map((s) => ({ state: s, kind: R.diplomacyMove(current, s) }));
}
// Milliseconds until a scheduled pact change takes effect (never negative).
const pendingRemaining = (pending, now) => (pending ? Math.max(0, pending.effectiveAt - now) : 0);
// Characters as the server counts them (code points, CRLF folded to LF). The server also strips control characters, so the
// counter can only over-count, never let through something the server then refuses for length.
function charCount(text) { return Array.from(String(text == null ? '' : text).replace(/\r\n?/g, '\n')).length; }
function composeState(text, max) {
max = max || S.messageMax;
const n = charCount(text);
return { n, left: max - n, over: n > max, empty: !String(text == null ? '' : text).trim(), max };
}
// Seconds to show for a rate_limited error (details.retryAfter / Retry-After, already parsed into err.retryAfter).
const retrySeconds = (err) => Math.max(1, Math.ceil((err && err.retryAfter) || 1));
// Messages are listed newest first with `after` = the last id, so the next page holds OLDER ids. Merge without duplicates,
// keep newest first.
function mergeMessages(existing, incoming) {
const seen = new Set(existing.map((m) => m.id));
return existing.concat(incoming.filter((m) => !seen.has(m.id))).sort((a, b) => b.id - a.id);
}
// A conversation reads oldest to newest.
const chronological = (items) => items.slice().sort((a, b) => a.id - b.id);
// The other party of a direct message from the viewer's side.
const peerOf = (m) => (m.direction === 'out' ? m.to : m.from);
// Received, not yet read direct or broadcast messages among `items`.
const unreadIds = (items) => items.filter((m) => m.direction === 'in' && !m.readAt).map((m) => m.id);
// Rankings page by rank offset: the cursor is the number of ranks already seen. Merge by rank so a refetch does not duplicate.
function mergeRanks(existing, incoming) {
const seen = new Set(existing.map((r) => r.rank));
return existing.concat(incoming.filter((r) => !seen.has(r.rank))).sort((a, b) => a.rank - b.rank);
}
// Is this ranking row the viewer's own (kind: 'operators' | 'alliances' | 'battles')?
function isYou(kind, row, you) {
if (!you || !row) return false;
return kind === 'alliances' ? row.allianceId === you.allianceId : row.operatorId === you.operatorId;
}
// Battle ranking value for the tab (attack, defense or total).
const battlePoints = (row, by) => (by === 'defense' ? row.defensePoints : by === 'total' ? row.attackPoints + row.defensePoints : row.attackPoints);
// Where to put a number-or-null "last online": ms since, or null when unknown.
const sinceMs = (at, now) => (at ? Math.max(0, now - at) : null);
// Operator names may be typed or pasted: trim and collapse so " Bob " matches. The server looks names up case-insensitively.
const cleanName = (s) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim();
return {
selfActions, memberActions, relationTo, diplomacyOptions, pendingRemaining,
charCount, composeState, retrySeconds, mergeMessages, chronological, peerOf, unreadIds,
mergeRanks, isYou, battlePoints, sinceMs, cleanName,
};
}));

View file

@ -0,0 +1,13 @@
Per-area string files. Each is a browser script AND a Node module:
```js
'use strict';
(function (root, factory) {
if (typeof module === 'object' && module.exports) factory(require('../i18n.js'));
else factory(root.UpstreamI18n);
}(typeof self !== 'undefined' ? self : this, function (I) {
I.extend({ en: { 'units.title': 'Units' }, nb: { 'units.title': 'Enheter' } });
}));
```
Load it from index.html after i18n.js. test/client-i18n.test.js requires every .js here and enforces en/nb key parity.

View file

@ -0,0 +1,251 @@
'use strict';
/* Strings of the military / expansion screens (units, movements, reports, send dialog, expansion) in en + nb. */
(function (root, factory) {
if (typeof module === 'object' && module.exports) factory(require('../i18n.js'));
else factory(root.UpstreamI18n);
}(typeof self !== 'undefined' ? self : this, function (I) {
I.extend({
en: {
'nav.more': 'More', 'nav.units': 'Units', 'nav.movements': 'Moves', 'nav.reports': 'Reports',
'screen.units': 'Units', 'screen.movements': 'Movements', 'screen.reports': 'Reports',
// ---- unit names and descriptions (ids are generic, names live here)
'unit.port_scanner.name': 'Port scanner', 'unit.port_scanner.desc': 'Quiet little probes. Scout a POP before you commit anything expensive.',
'unit.soc_analyst.name': 'SOC analyst', 'unit.soc_analyst.desc': 'Staring at dashboards so you do not have to. Cheap, steady defence.',
'unit.blue_team.name': 'Blue team', 'unit.blue_team.desc': 'Incident response with proper coffee. Strong defenders.',
'unit.honeypot.name': 'Honeypot', 'unit.honeypot.desc': 'A very attractive, very fake server. Defends in place and never leaves.',
'unit.script_crew.name': 'Script crew', 'unit.script_crew.desc': 'Cheap, fast raiders that carry some loot home.',
'unit.botnet.name': 'Botnet', 'unit.botnet.desc': 'Many small machines with one bad idea. Strong, fast, carries a lot.',
'unit.ddos_rig.name': 'DDoS rig', 'unit.ddos_rig.desc': 'Floods the firewall. Every 10 rigs lower the target firewall by one level.',
'unit.exploit_kit.name': 'Exploit kit', 'unit.exploit_kit.desc': 'Finds the one unpatched thing. Damages a chosen building when you win.',
'unit.rollout_crew.name': 'Rollout crew', 'unit.rollout_crew.desc': 'Trenches, ducts and optimism. Three of them found a new POP.',
'unit.ma_team.name': 'M&A team', 'unit.ma_team.desc': 'Suits with a term sheet. Wears down customer loyalty until the POP changes hands.',
'unit.stats': 'ATK {a} · DEF {d} · {s} tiles/h · carries {c}', 'unit.fixed': 'stays in place', 'unit.draw': 'Power draw {n}/h',
'stat.attack': 'Attack', 'stat.defence': 'Defence',
'move.type.scan': 'Scan', 'move.type.raid': 'Phishing raid', 'move.type.attack': 'Attack', 'move.type.takeover': 'Hostile takeover',
'move.type.reinforce': 'Peering support', 'move.type.settle': 'Found a POP', 'move.type.transport': 'Transport', 'move.type.return': 'Returning home', 'move.type.unknown': 'Unknown',
'report.type.raid': 'Phishing raid', 'report.type.attack': 'Attack', 'report.type.takeover': 'Hostile takeover', 'report.type.scan': 'Scan',
'report.type.scan_detected': 'Scan detected', 'report.type.incumbent': 'Incumbent site', 'report.type.settle': 'New POP', 'report.type.reinforce': 'Reinforcements',
'report.type.movement_failed': 'Movement failed',
'mil.showOnMap': 'Show {x}, {y} on the map',
// ---- units screen
'units.status': 'Status', 'units.online': 'Online', 'units.powerNet': 'Net power {n}/h',
'units.offline.title': 'Units offline', 'units.offline.body': 'The battery is empty, so your units are switched off and cannot be sent. Add power (Substation) or get rid of draw.',
'units.offline.decom': 'Units are decommissioned in',
'units.home': 'At home', 'units.home.empty': 'No units here yet. Train some below.',
'units.hosted': 'Reinforcements here', 'units.away': 'Your units elsewhere',
'units.sendHome': 'Send home', 'units.callBack': 'Call back', 'units.withdrawn': 'On their way home.',
'units.training': 'Training', 'units.training.empty': 'Nothing in training.', 'units.train': 'Train units',
'units.needs': 'Needs', 'units.perUnit': '{t} each', 'units.count': 'Number of units', 'units.max': 'As many as I can afford',
'units.trainBtn': 'Train', 'units.time': 'Training time', 'units.research.time': 'Research time', 'units.readyAt': 'ready {t}', 'units.queued': 'Queued {n} × {unit}.',
'units.research': 'Research', 'units.research.speed': '+{p}% research speed',
'units.research.busy': 'Researching {unit}: {stat} level {level}',
'units.research.hint': 'Each level gives +{p}% attack or defence for this unit type, up to level {max}. One research at a time per POP.',
'units.research.level': 'Level {n} / {max}', 'units.research.effect': 'Per unit: {a} → {b}', 'units.research.start': 'Research level {n}', 'units.research.queued': 'Research started.',
// ---- movements screen + POP banner + push
'mov.send': 'Send', 'mov.empty': 'Nothing on the wire. Pick a target on the map and send something.',
'mov.incoming.head': 'Incoming movements ({n})', 'mov.incoming.title': 'Heading for {town}',
'mov.incoming.from': 'From {operator}', 'mov.incoming.hint': 'Type and size are hidden. Treat it as hostile: raise defence or bring reinforcements.',
'mov.outgoing.head': 'Your movements', 'mov.target': 'Target building: {name}',
'mov.recall': 'Recall', 'mov.recalled': 'Recalled. They are turning around.',
'mov.allied.head': 'Heading for allied POPs', 'mov.allied.title': '{operator}: {town}',
'mov.banner.title': 'Incoming movement ({n})', 'mov.banner.next': 'Next one heads for {town}, from {operator}.', 'mov.banner.in': 'Arrives in', 'mov.banner.details': 'Details',
'push.incoming': 'Incoming movement spotted!',
// ---- send dialog
'send.title': 'Send', 'send.open': 'Send units here', 'send.target': 'Target', 'send.lookup': 'Look up', 'send.from': 'Send from',
'send.what': 'What to do', 'send.nothing': 'There is nothing to send to this tile.', 'send.units': 'Units', 'send.all': 'All',
'send.cargo': 'Cargo', 'send.cargo.cap': 'Up to {n} per transport. {free} of {links} transport links free.',
'send.tilesPerHour': 'tiles/h', 'send.pickSome': 'Pick some units to see latency and arrival.',
'send.distance': 'Distance', 'send.latency': 'Latency', 'send.arrives': 'Arrives about', 'send.slowest': 'Slowest unit', 'send.carry': 'Carries loot',
'send.go': 'Send', 'send.sent': '{type} sent. Latency {t}.',
'send.reason.no_units': 'no suitable units at home', 'send.reason.target_protected': 'target is under beginner protection',
'send.reason.not_allied': 'not in your alliance', 'send.reason.no_link': 'needs an Internet exchange', 'send.reason.links_busy': 'all transport links are busy',
'send.reason.needs_ma_team': 'needs at least one M&A team', 'send.reason.needs_crews': 'needs three Rollout crews at home',
'send.reason.footprint': 'footprint {have} is below the {need} needed', 'send.reason.range': 'must be within {n} tiles of one of your POPs', 'send.reason.cannotSettle': 'only empty land can be settled',
'send.settle.title': 'New POP', 'send.settle.crews': '{n} × {unit} will go and are used up.',
'send.settle.footprint': 'Footprint {have}, {need} needed. Within {n} tiles of one of your POPs.', 'send.settle.wild': 'Wild field {n}',
'send.protection.title': 'This ends your beginner protection.', 'send.protection.body': 'You are protected until {t}. Attacking gives that up for good. Tick to confirm.', 'send.protection.need': 'Confirm that you give up your beginner protection.',
'send.siege': 'Exploit kits: building to damage', 'send.siege.none': 'No preference', 'send.siege.hint': 'Needs at least {n} kits left after the fight to damage anything.',
'send.takeover.hint': 'An M&A team lowers customer loyalty on every win. At zero the POP is yours. Capitals and last POPs cannot be taken.',
'send.raid.hint': 'A raid steals Capital, Fiber and Hardware up to what the survivors carry. Both sides lose fewer units than in an attack.',
'send.scan.hint': 'Scanners come back if they survive. More scanners than the defender gets you more detail.',
'send.reinforce.own': 'Units move into that POP and defend it. Pull them back from the Units screen.',
'send.hostile.hint': 'The target is warned that something is coming, but not what.',
'send.invalid.own_town': 'You cannot target yourself.', 'send.invalid.nothing_there': 'There is nothing there to target.', 'send.invalid.pact': 'A pact prevents that.',
'send.invalid.not_allied': 'Only alliance members and confederates can be reinforced.', 'send.invalid.no_town': 'No POP there.', 'send.invalid.occupied': 'That tile is taken.',
'send.invalid.not_empty_land': 'Only empty land can be settled.', 'send.invalid.outside_map': 'That is off the map.', 'send.invalid.same_town': 'Pick a different POP.',
'send.invalid.incumbent_scan_or_attack_only': 'Incumbent sites can only be scanned or attacked.',
// ---- reports
'rep.empty': 'No reports yet.', 'rep.markAll': 'Mark all read', 'rep.older': 'Older reports',
'rep.victory': 'Victory', 'rep.defeat': 'Defeat', 'rep.captured': 'POP captured',
'rep.sub.you_vs': 'You vs {name}', 'rep.sub.by': 'By {name}',
'rep.scan.title': 'Scan of {where}', 'rep.scan.ok': 'Scan succeeded', 'rep.scan.failed': 'Scan failed', 'rep.scan.noIntel': 'The defender spotted your scanners before they learned anything.',
'rep.scan.strength': 'Scan strength (you vs them)',
'rep.detected.title': 'Scan detected at {town}', 'rep.detected.unknown': 'Somebody scanned this POP. Your scanners could not tell who.',
'rep.incumbent.title': 'Incumbent site {x}, {y}', 'rep.incumbent.bonus': 'First win here pays {n} Hardware.', 'rep.incumbent.taken': 'You already took this site.', 'rep.incumbent.reward': 'Reward',
'rep.settle.title': 'New POP: {name}', 'rep.settle.wild': 'Wild fields', 'rep.settle.open': 'Open the new POP', 'rep.settle.hint': 'It starts with a little Fiber, Hardware and Capital and no infrastructure. Build it up.',
'rep.reinforce.sender': 'Reinforcements arrived at {town}', 'rep.reinforce.target': 'Reinforcements arrived at {town}',
'rep.failed.title': '{type} failed', 'rep.failed.home': 'Units and cargo are on their way home.',
'rep.reason.invalid_target': 'The target is no longer valid.', 'rep.reason.not_allied': 'The target is no longer an ally.', 'rep.reason.own_town': 'The POP changed hands and is yours now.',
'rep.reason.pact': 'A pact with the target now prevents this.', 'rep.reason.protected': 'The target is under beginner protection.', 'rep.reason.target_gone': 'The target is gone.',
'rep.reason.out_of_range': 'The site is out of range.', 'rep.reason.footprint_too_low': 'Your footprint was too low.',
'rep.role.attacker': 'You attacked', 'rep.role.defender': 'You were attacked', 'rep.role.reinforcer': 'Your reinforcements were there', 'rep.role.sender': 'You sent', 'rep.role.target': 'You were the target',
'rep.expires': 'kept until {t}', 'rep.arrived': 'Arrived {t}',
'rep.attacker': 'Attacker', 'rep.defender': 'Defender', 'rep.target': 'Target', 'rep.from': 'From', 'rep.host': 'Host', 'rep.site': 'Site', 'rep.scannedBy': 'Scanned by',
'rep.power': 'Strength', 'rep.power.attack': 'Attack', 'rep.power.defence': 'Defence', 'rep.power.firewall': 'Firewall level',
'rep.attackerUnits': 'Attacking units', 'rep.defenderUnits': 'Defending units', 'rep.units': 'Units', 'rep.scanners': 'Scanners',
'rep.sent': 'Sent', 'rep.lost': 'Lost', 'rep.left': 'Left', 'rep.noUnits': 'No units.',
'rep.group.home': 'Home defence', 'rep.group.reinf': 'Reinforcements from {town}', 'rep.group.offline': 'offline, no defence',
'rep.loot': 'Loot', 'rep.cache': '{p}% of the stock was hidden in the Rack hall.', 'rep.siege': 'Siege', 'rep.siege.line': '{name} damaged: level {a} → {b}',
'rep.takeover': 'Takeover', 'rep.takeover.loyalty': 'Customer loyalty', 'rep.takeover.capital': 'A capital cannot change hands, it can only be drained.', 'rep.takeover.captured': 'The POP is now under new ownership.',
'rep.takeover.blocked.last_pop': 'The target\'s last POP cannot be taken.', 'rep.takeover.blocked.footprint': 'Your footprint is too low to hold another POP.',
'rep.intel': 'Intel', 'rep.intel.resources': 'Resources in stock', 'rep.intel.units': 'Units', 'rep.intel.offline': 'Their units are offline.', 'rep.intel.buildings': 'Buildings', 'rep.intel.outgoing': 'Their movements',
// ---- notification feed
'alerts.incoming': 'Incoming movement', 'alerts.incoming.at': 'Heading for {town}, arrives {time}',
'alerts.report': 'New report: {type}', 'alerts.train_done': '{n} × {unit} trained', 'alerts.research_done': '{unit}: {stat} level {level} researched',
'alerts.movement_returned': 'Units are home', 'alerts.movement_lost': 'A movement lost its way home',
'alerts.transport_arrived': 'Cargo arrived at {town}', 'alerts.transport_delivered': 'Your cargo was delivered',
'alerts.units_offline': 'Units went offline: battery empty', 'alerts.units_decommissioned': 'Units decommissioned after too long without power',
'alerts.town_lost': '{name} was taken over', 'alerts.town_lost.by': 'By {name}', 'alerts.town_gained': '{name} is now yours', 'alerts.reinforcements_home': 'Reinforcements sent home',
// ---- expansion
'exp.title': 'Expansion', 'exp.count': '{n} POPs', 'exp.crews': 'Rollout crews at home', 'exp.footprint': 'Footprint (this POP / needed in total)', 'exp.footprint.v': '{have} / {need}',
'exp.range': 'Range from your POPs', 'exp.hint': 'Three Rollout crews found a POP on empty land. A new POP also needs enough total footprint.',
'exp.found': 'Pick a site on the map', 'exp.pick': 'Tap an empty tile and choose Send units here.', 'exp.train': 'Train Rollout crews', 'exp.needCrews': 'Train {n} more {unit}.',
'exp.needDepot': 'Needs a Rollout depot (Core router level 10).', 'exp.pops': 'Your POPs', 'exp.current': 'Viewing', 'exp.open': 'Switch to',
'map.legend.out': 'Your movement', 'map.legend.in': 'Incoming',
// ---- errors of the military routes
'err.not_enough_units': 'Not enough of those units at home.', 'err.units_offline': 'Your units are offline: the battery is empty.',
'err.invalid_target': 'That target does not work.', 'err.target_protected': 'The target is under beginner protection.',
'err.protection_active': 'You are under beginner protection. Confirm that attacking ends it.', 'err.out_of_range': 'That is too far from your POPs.',
'err.footprint_too_low': 'Your footprint is too low for another POP.', 'err.cannot_takeover': 'That POP cannot be taken over.',
'err.capacity_exceeded': 'That is more than one transport can carry.', 'err.no_transport_link': 'No free transport link: build or wait for an Internet exchange.',
'err.unknown_unit': 'No such unit.', 'err.not_researchable': 'That cannot be researched.', 'err.recall_expired': 'Too late to recall: the first 90 seconds are over.',
},
nb: {
'nav.more': 'Mer', 'nav.units': 'Enheter', 'nav.movements': 'Ferd', 'nav.reports': 'Rapporter',
'screen.units': 'Enheter', 'screen.movements': 'Bevegelser', 'screen.reports': 'Rapporter',
'unit.port_scanner.name': 'Portskanner', 'unit.port_scanner.desc': 'Stille små sonder. Speid en POP før du satser noe dyrt.',
'unit.soc_analyst.name': 'SOC-analytiker', 'unit.soc_analyst.desc': 'Stirrer på dashbord så du slipper. Billig og stødig forsvar.',
'unit.blue_team.name': 'Blått lag', 'unit.blue_team.desc': 'Hendelseshåndtering med skikkelig kaffe. Sterke forsvarere.',
'unit.honeypot.name': 'Honeypot', 'unit.honeypot.desc': 'En svært fristende og svært falsk server. Forsvarer på stedet og går aldri noe sted.',
'unit.script_crew.name': 'Skriptmannskap', 'unit.script_crew.desc': 'Billige, raske raidere som bærer med seg litt bytte hjem.',
'unit.botnet.name': 'Botnett', 'unit.botnet.desc': 'Mange små maskiner med én dårlig idé. Sterkt, raskt og bærer mye.',
'unit.ddos_rig.name': 'DDoS-rigg', 'unit.ddos_rig.desc': 'Flommer brannmuren. Hver 10. rigg senker målets brannmur ett nivå.',
'unit.exploit_kit.name': 'Exploit-sett', 'unit.exploit_kit.desc': 'Finner den ene upatchede tingen. Skader en valgt bygning når du vinner.',
'unit.rollout_crew.name': 'Utrullingslag', 'unit.rollout_crew.desc': 'Grøfter, rør og optimisme. Tre av dem etablerer en ny POP.',
'unit.ma_team.name': 'Oppkjøpsteam', 'unit.ma_team.desc': 'Dress og en intensjonsavtale. Sliter ned kundelojaliteten til POP-en skifter eier.',
'unit.stats': 'ANG {a} · FOR {d} · {s} ruter/t · bærer {c}', 'unit.fixed': 'blir stående', 'unit.draw': 'Strømtrekk {n}/t',
'stat.attack': 'Angrep', 'stat.defence': 'Forsvar',
'move.type.scan': 'Skanning', 'move.type.raid': 'Phishing-raid', 'move.type.attack': 'Angrep', 'move.type.takeover': 'Fiendtlig oppkjøp',
'move.type.reinforce': 'Peering-støtte', 'move.type.settle': 'Etabler POP', 'move.type.transport': 'Transport', 'move.type.return': 'På vei hjem', 'move.type.unknown': 'Ukjent',
'report.type.raid': 'Phishing-raid', 'report.type.attack': 'Angrep', 'report.type.takeover': 'Fiendtlig oppkjøp', 'report.type.scan': 'Skanning',
'report.type.scan_detected': 'Skanning oppdaget', 'report.type.incumbent': 'Gammeloperatørens anlegg', 'report.type.settle': 'Ny POP', 'report.type.reinforce': 'Forsterkninger',
'report.type.movement_failed': 'Bevegelse mislyktes',
'mil.showOnMap': 'Vis {x}, {y} på kartet',
'units.status': 'Status', 'units.online': 'Online', 'units.powerNet': 'Netto strøm {n}/t',
'units.offline.title': 'Enheter offline', 'units.offline.body': 'Batteriet er tomt, så enhetene er slått av og kan ikke sendes. Legg til strøm (Transformatorstasjon) eller kutt trekk.',
'units.offline.decom': 'Enhetene avvikles om',
'units.home': 'Hjemme', 'units.home.empty': 'Ingen enheter her ennå. Tren noen under.',
'units.hosted': 'Forsterkninger her', 'units.away': 'Dine enheter andre steder',
'units.sendHome': 'Send hjem', 'units.callBack': 'Kall tilbake', 'units.withdrawn': 'På vei hjem.',
'units.training': 'Trening', 'units.training.empty': 'Ingenting under trening.', 'units.train': 'Tren enheter',
'units.needs': 'Krever', 'units.perUnit': '{t} per stk.', 'units.count': 'Antall enheter', 'units.max': 'Så mange jeg har råd til',
'units.trainBtn': 'Tren', 'units.time': 'Treningstid', 'units.research.time': 'Forskningstid', 'units.readyAt': 'ferdig {t}', 'units.queued': 'Satt i kø: {n} × {unit}.',
'units.research': 'Forskning', 'units.research.speed': '+{p} % forskningsfart',
'units.research.busy': 'Forsker på {unit}: {stat} nivå {level}',
'units.research.hint': 'Hvert nivå gir +{p} % angrep eller forsvar for denne enhetstypen, opptil nivå {max}. Én forskning om gangen per POP.',
'units.research.level': 'Nivå {n} / {max}', 'units.research.effect': 'Per enhet: {a} → {b}', 'units.research.start': 'Forsk nivå {n}', 'units.research.queued': 'Forskning startet.',
'mov.send': 'Send', 'mov.empty': 'Ingenting på vei. Velg et mål på kartet og send noe.',
'mov.incoming.head': 'Innkommende bevegelser ({n})', 'mov.incoming.title': 'På vei mot {town}',
'mov.incoming.from': 'Fra {operator}', 'mov.incoming.hint': 'Type og størrelse er skjult. Anta at det er fiendtlig: styrk forsvaret eller hent forsterkninger.',
'mov.outgoing.head': 'Dine bevegelser', 'mov.target': 'Målbygning: {name}',
'mov.recall': 'Kall tilbake', 'mov.recalled': 'Kalt tilbake. De snur.',
'mov.allied.head': 'På vei mot allierte POP-er', 'mov.allied.title': '{operator}: {town}',
'mov.banner.title': 'Innkommende bevegelse ({n})', 'mov.banner.next': 'Den neste går mot {town}, fra {operator}.', 'mov.banner.in': 'Ankommer om', 'mov.banner.details': 'Detaljer',
'push.incoming': 'Innkommende bevegelse oppdaget!',
'send.title': 'Send', 'send.open': 'Send enheter hit', 'send.target': 'Mål', 'send.lookup': 'Slå opp', 'send.from': 'Send fra',
'send.what': 'Hva skal skje', 'send.nothing': 'Det er ingenting å sende til denne ruta.', 'send.units': 'Enheter', 'send.all': 'Alle',
'send.cargo': 'Last', 'send.cargo.cap': 'Opptil {n} per transport. {free} av {links} transportlenker er ledige.',
'send.tilesPerHour': 'ruter/t', 'send.pickSome': 'Velg noen enheter for å se latens og ankomst.',
'send.distance': 'Avstand', 'send.latency': 'Latens', 'send.arrives': 'Ankommer ca.', 'send.slowest': 'Tregeste enhet', 'send.carry': 'Bærer bytte',
'send.go': 'Send', 'send.sent': '{type} sendt. Latens {t}.',
'send.reason.no_units': 'ingen egnede enheter hjemme', 'send.reason.target_protected': 'målet har nybegynnerbeskyttelse',
'send.reason.not_allied': 'ikke i din allianse', 'send.reason.no_link': 'krever et Internettknutepunkt', 'send.reason.links_busy': 'alle transportlenker er opptatt',
'send.reason.needs_ma_team': 'krever minst ett oppkjøpsteam', 'send.reason.needs_crews': 'krever tre utrullingslag hjemme',
'send.reason.footprint': 'fotavtrykket {have} er lavere enn de {need} som kreves', 'send.reason.range': 'må ligge innenfor {n} ruter fra en av dine POP-er', 'send.reason.cannotSettle': 'bare tomt land kan bebygges',
'send.settle.title': 'Ny POP', 'send.settle.crews': '{n} × {unit} drar av gårde og brukes opp.',
'send.settle.footprint': 'Fotavtrykk {have}, {need} kreves. Innenfor {n} ruter fra en av dine POP-er.', 'send.settle.wild': 'Fritt felt {n}',
'send.protection.title': 'Dette avslutter nybegynnerbeskyttelsen din.', 'send.protection.body': 'Du er beskyttet til {t}. Et angrep gir den fra seg for godt. Kryss av for å bekrefte.', 'send.protection.need': 'Bekreft at du gir fra deg nybegynnerbeskyttelsen.',
'send.siege': 'Exploit-sett: bygning som skal skades', 'send.siege.none': 'Ingen preferanse', 'send.siege.hint': 'Trenger minst {n} sett igjen etter kampen for å skade noe.',
'send.takeover.hint': 'Et oppkjøpsteam senker kundelojaliteten for hver seier. Ved null er POP-en din. Hovedsteder og siste POP kan ikke tas.',
'send.raid.hint': 'En raid stjeler Kapital, Fiber og Maskinvare opptil det de overlevende bærer. Begge sider mister færre enheter enn i et angrep.',
'send.scan.hint': 'Skannerne kommer tilbake hvis de overlever. Flere skannere enn forsvareren gir flere detaljer.',
'send.reinforce.own': 'Enhetene flytter inn i den POP-en og forsvarer den. Hent dem tilbake fra Enheter-skjermen.',
'send.hostile.hint': 'Målet blir varslet om at noe er på vei, men ikke hva.',
'send.invalid.own_town': 'Du kan ikke velge deg selv.', 'send.invalid.nothing_there': 'Det er ingenting der å angripe.', 'send.invalid.pact': 'En avtale hindrer det.',
'send.invalid.not_allied': 'Bare alliansemedlemmer og konfødererte kan få forsterkninger.', 'send.invalid.no_town': 'Ingen POP der.', 'send.invalid.occupied': 'Den ruta er tatt.',
'send.invalid.not_empty_land': 'Bare tomt land kan bebygges.', 'send.invalid.outside_map': 'Det er utenfor kartet.', 'send.invalid.same_town': 'Velg en annen POP.',
'send.invalid.incumbent_scan_or_attack_only': 'Gammeloperatørens anlegg kan bare skannes eller angripes.',
'rep.empty': 'Ingen rapporter ennå.', 'rep.markAll': 'Merk alle som lest', 'rep.older': 'Eldre rapporter',
'rep.victory': 'Seier', 'rep.defeat': 'Nederlag', 'rep.captured': 'POP overtatt',
'rep.sub.you_vs': 'Du mot {name}', 'rep.sub.by': 'Av {name}',
'rep.scan.title': 'Skanning av {where}', 'rep.scan.ok': 'Skanningen lyktes', 'rep.scan.failed': 'Skanningen mislyktes', 'rep.scan.noIntel': 'Forsvareren oppdaget skannerne dine før de fikk vite noe.',
'rep.scan.strength': 'Skannestyrke (du mot dem)',
'rep.detected.title': 'Skanning oppdaget ved {town}', 'rep.detected.unknown': 'Noen skannet denne POP-en. Skannerne dine kunne ikke si hvem.',
'rep.incumbent.title': 'Gammeloperatørens anlegg {x}, {y}', 'rep.incumbent.bonus': 'Første seier her gir {n} Maskinvare.', 'rep.incumbent.taken': 'Du har allerede tatt dette anlegget.', 'rep.incumbent.reward': 'Belønning',
'rep.settle.title': 'Ny POP: {name}', 'rep.settle.wild': 'Frie felt', 'rep.settle.open': 'Åpne den nye POP-en', 'rep.settle.hint': 'Den starter med litt Fiber, Maskinvare og Kapital og ingen infrastruktur. Bygg den opp.',
'rep.reinforce.sender': 'Forsterkninger kom frem til {town}', 'rep.reinforce.target': 'Forsterkninger kom frem til {town}',
'rep.failed.title': '{type} mislyktes', 'rep.failed.home': 'Enheter og last er på vei hjem.',
'rep.reason.invalid_target': 'Målet er ikke gyldig lenger.', 'rep.reason.not_allied': 'Målet er ikke lenger alliert.', 'rep.reason.own_town': 'POP-en skiftet eier og er din nå.',
'rep.reason.pact': 'En avtale med målet hindrer dette nå.', 'rep.reason.protected': 'Målet har nybegynnerbeskyttelse.', 'rep.reason.target_gone': 'Målet finnes ikke lenger.',
'rep.reason.out_of_range': 'Stedet er utenfor rekkevidde.', 'rep.reason.footprint_too_low': 'Fotavtrykket ditt var for lavt.',
'rep.role.attacker': 'Du angrep', 'rep.role.defender': 'Du ble angrepet', 'rep.role.reinforcer': 'Forsterkningene dine var der', 'rep.role.sender': 'Du sendte', 'rep.role.target': 'Du var målet',
'rep.expires': 'lagres til {t}', 'rep.arrived': 'Ankom {t}',
'rep.attacker': 'Angriper', 'rep.defender': 'Forsvarer', 'rep.target': 'Mål', 'rep.from': 'Fra', 'rep.host': 'Vert', 'rep.site': 'Sted', 'rep.scannedBy': 'Skannet av',
'rep.power': 'Styrke', 'rep.power.attack': 'Angrep', 'rep.power.defence': 'Forsvar', 'rep.power.firewall': 'Brannmurnivå',
'rep.attackerUnits': 'Angripende enheter', 'rep.defenderUnits': 'Forsvarende enheter', 'rep.units': 'Enheter', 'rep.scanners': 'Skannere',
'rep.sent': 'Sendt', 'rep.lost': 'Tapt', 'rep.left': 'Igjen', 'rep.noUnits': 'Ingen enheter.',
'rep.group.home': 'Hjemmeforsvar', 'rep.group.reinf': 'Forsterkninger fra {town}', 'rep.group.offline': 'offline, uten forsvar',
'rep.loot': 'Bytte', 'rep.cache': '{p} % av lageret var skjult i Racksalen.', 'rep.siege': 'Beleiring', 'rep.siege.line': '{name} skadet: nivå {a} → {b}',
'rep.takeover': 'Oppkjøp', 'rep.takeover.loyalty': 'Kundelojalitet', 'rep.takeover.capital': 'En hovedstad kan ikke skifte eier, bare tappes.', 'rep.takeover.captured': 'POP-en har nå ny eier.',
'rep.takeover.blocked.last_pop': 'Målets siste POP kan ikke tas.', 'rep.takeover.blocked.footprint': 'Fotavtrykket ditt er for lavt til å holde enda en POP.',
'rep.intel': 'Etterretning', 'rep.intel.resources': 'Ressurser på lager', 'rep.intel.units': 'Enheter', 'rep.intel.offline': 'Enhetene deres er offline.', 'rep.intel.buildings': 'Bygninger', 'rep.intel.outgoing': 'Bevegelsene deres',
'alerts.incoming': 'Innkommende bevegelse', 'alerts.incoming.at': 'På vei mot {town}, ankommer {time}',
'alerts.report': 'Ny rapport: {type}', 'alerts.train_done': '{n} × {unit} ferdig trent', 'alerts.research_done': '{unit}: {stat} nivå {level} ferdig forsket',
'alerts.movement_returned': 'Enhetene er hjemme', 'alerts.movement_lost': 'En bevegelse fant ikke veien hjem',
'alerts.transport_arrived': 'Last kom frem til {town}', 'alerts.transport_delivered': 'Lasten din er levert',
'alerts.units_offline': 'Enheter gikk offline: tomt batteri', 'alerts.units_decommissioned': 'Enheter avviklet etter for lenge uten strøm',
'alerts.town_lost': '{name} ble overtatt', 'alerts.town_lost.by': 'Av {name}', 'alerts.town_gained': '{name} er nå din', 'alerts.reinforcements_home': 'Forsterkninger sendt hjem',
'exp.title': 'Ekspansjon', 'exp.count': '{n} POP-er', 'exp.crews': 'Utrullingslag hjemme', 'exp.footprint': 'Fotavtrykk (denne POP-en / kreves totalt)', 'exp.footprint.v': '{have} / {need}',
'exp.range': 'Rekkevidde fra dine POP-er', 'exp.hint': 'Tre utrullingslag etablerer en POP på tomt land. En ny POP krever også nok totalt fotavtrykk.',
'exp.found': 'Velg sted på kartet', 'exp.pick': 'Trykk på en tom rute og velg Send enheter hit.', 'exp.train': 'Tren utrullingslag', 'exp.needCrews': 'Tren {n} flere {unit}.',
'exp.needDepot': 'Krever et Utrullingsdepot (Kjerneruter nivå 10).', 'exp.pops': 'Dine POP-er', 'exp.current': 'Vises nå', 'exp.open': 'Bytt til',
'map.legend.out': 'Din bevegelse', 'map.legend.in': 'Innkommende',
'err.not_enough_units': 'Ikke nok av de enhetene hjemme.', 'err.units_offline': 'Enhetene dine er offline: batteriet er tomt.',
'err.invalid_target': 'Det målet fungerer ikke.', 'err.target_protected': 'Målet har nybegynnerbeskyttelse.',
'err.protection_active': 'Du har nybegynnerbeskyttelse. Bekreft at et angrep avslutter den.', 'err.out_of_range': 'Det er for langt fra POP-ene dine.',
'err.footprint_too_low': 'Fotavtrykket ditt er for lavt for enda en POP.', 'err.cannot_takeover': 'Den POP-en kan ikke overtas.',
'err.capacity_exceeded': 'Det er mer enn én transport kan bære.', 'err.no_transport_link': 'Ingen ledig transportlenke: bygg eller vent på et Internettknutepunkt.',
'err.unknown_unit': 'Ingen slik enhet.', 'err.not_researchable': 'Det kan ikke forskes på.', 'err.recall_expired': 'For sent å kalle tilbake: de første 90 sekundene er over.',
},
});
}));

232
public/js/strings/social.js Normal file
View file

@ -0,0 +1,232 @@
'use strict';
/* Strings of the social screens (alliance, messages, rankings). en + nb, key parity enforced by test/client-i18n.test.js. */
(function (root, factory) {
if (typeof module === 'object' && module.exports) factory(require('../i18n.js'));
else factory(root.UpstreamI18n);
}(typeof self !== 'undefined' ? self : this, function (I) {
I.extend({
en: {
'nav.alliance': 'Alliance', 'nav.messages': 'Messages', 'nav.rankings': 'Rankings',
'screen.alliance': 'Alliance', 'screen.messages': 'Messages', 'screen.rankings': 'Rankings',
// errors the social routes can return (existing codes such as forbidden / not_found / rate_limited are translated elsewhere)
'err.peering_office_required': 'You need a Peering office (level 1 or higher) to found or join an alliance.',
'err.already_in_alliance': 'That operator is already in an alliance.',
'err.not_in_alliance': 'You are not in an alliance.',
'err.alliance_name_taken': 'That alliance name is taken.',
'err.alliance_tag_taken': 'That alliance tag is taken.',
'err.alliance_full': 'The alliance has no room for more members.',
'err.invite_expired': 'The invitation has expired.',
'err.leader_must_transfer': 'The leader must hand over leadership before leaving.',
'err.notes_full': 'The pinned-note limit is reached. Remove one first.',
'err.diplomacy_invalid': 'That diplomatic move is not possible from the current state.',
'err.diplomacy_pending': 'A change between these alliances is already scheduled.',
'err.proposal_exists': 'They already proposed this. Accept their proposal instead.',
'err.proposal_expired': 'The proposal has expired.',
'soc.you': 'You', 'soc.more': 'Load more', 'soc.tab.label': 'Sections',
'soc.tab.overview': 'Overview', 'soc.tab.members': 'Members', 'soc.tab.diplomacy': 'Diplomacy',
'soc.role.leader': 'Leader', 'soc.role.diplomat': 'Diplomat', 'soc.role.officer': 'Officer', 'soc.role.member': 'Member',
'soc.state.war': 'War', 'soc.state.neutral': 'Neutral', 'soc.state.nap': 'Non-aggression', 'soc.state.confed': 'Confederation',
'soc.relation.same': 'Your alliance',
'soc.members': 'Members', 'soc.leader': 'Leader', 'soc.footprint': 'Footprint', 'soc.founded': 'Founded', 'soc.profile': 'Alliance',
'soc.size': '{n}/{cap} members', 'soc.leaderIs': 'Leader: {name}',
'soc.rate': 'You are sending too fast. Try again in {t}.',
// not in an alliance
'soc.create.title': 'Found an alliance',
'soc.create.intro': 'Rival operators are easier to outlast with friends. Found an alliance and invite others, or accept an invitation below.',
'soc.create.name': 'Name', 'soc.create.tag': 'Tag',
'soc.create.nameHint': '{a}-{b} characters: letters, digits, spaces, . _ \' -',
'soc.create.tagHint': '{a}-{b} letters or digits, shown in brackets next to names',
'soc.create.go': 'Found alliance', 'soc.create.done': 'Alliance founded.',
'soc.create.needOffice': 'Build a {building} (level {n}) in one of your POPs first.',
'soc.create.invalid': 'Name: {n1}-{n2} characters. Tag: {t1}-{t2} letters or digits.',
'soc.invites.title': 'Invitations', 'soc.invites.none': 'No open invitations.',
'soc.invites.needOffice': 'Accepting needs a {building} too.',
'soc.invites.from': 'from {name}', 'soc.invites.expires': 'expires in {t}',
'soc.invites.accept': 'Accept', 'soc.invites.decline': 'Decline',
'soc.invites.accepted': 'You joined the alliance.', 'soc.invites.declined': 'Invitation declined.',
// overview
'soc.notes.title': 'Pinned notes', 'soc.notes.none': 'No pinned notes yet.', 'soc.notes.add': 'Pin note', 'soc.notes.remove': 'Remove note',
'soc.notes.placeholder': 'Rally points, rules, targets...',
'soc.manage.title': 'Membership',
'soc.leave.go': 'Leave alliance', 'soc.leave.done': 'You left the alliance.',
'soc.leave.confirm': 'Leave {name}? You can be invited again.',
'soc.leave.confirmAlone': 'You are the only member of {name}. Leaving disbands it.',
'soc.leave.mustTransfer': 'You are the leader. Hand over leadership to a member before you can leave.',
'soc.leave.goTransfer': 'Choose a successor',
'soc.disband.go': 'Disband alliance', 'soc.disband.done': 'Alliance disbanded.',
'soc.disband.confirm': 'Disband {name} for everyone? This cannot be undone.',
// members
'soc.member.stats': 'POPs {towns} · footprint {fp}', 'soc.member.online': 'online {t}', 'soc.member.never': 'never online',
'soc.member.pops': 'POPs', 'soc.member.lastOnline': 'Last online', 'soc.member.joined': 'Joined',
'soc.member.message': 'Send message', 'soc.member.setRole': 'Set role',
'soc.member.roleHint': 'Officers invite and remove members, diplomats handle other alliances.',
'soc.member.roleSet': '{name} is now {role}.',
'soc.transfer.go': 'Make leader', 'soc.transfer.confirm': 'Hand leadership to {name}? You become an officer.', 'soc.transfer.done': '{name} is the new leader.',
'soc.kick.go': 'Remove from alliance', 'soc.kick.confirm': 'Remove {name} from the alliance?', 'soc.kick.done': '{name} was removed.',
'soc.invite.title': 'Invite an operator', 'soc.invite.name': 'Operator name', 'soc.invite.go': 'Invite',
'soc.invite.sent': 'Invitation sent to {name}.', 'soc.invite.already': '{name} already has an open invitation.',
'soc.invite.unknown': 'No operator called {name} in this world.',
'soc.invite.pending': 'Open invitations', 'soc.invite.none': 'None pending.', 'soc.invite.cancel': 'Cancel invitation',
// diplomacy
'soc.dip.title': 'Diplomacy', 'soc.dip.new': 'New move', 'soc.dip.relations': 'Relations', 'soc.dip.none': 'Neutral with everyone.',
'soc.dip.readOnly': 'Only leaders and diplomats change diplomatic relations.',
'soc.dip.incoming': 'Proposals to you', 'soc.dip.outgoing': 'Your proposals',
'soc.dip.accept': 'Accept', 'soc.dip.decline': 'Decline', 'soc.dip.withdraw': 'Withdraw', 'soc.dip.revoke': 'Take back',
'soc.dip.revoked': 'Scheduled change cancelled.',
'soc.dip.expires': 'expires in {t}', 'soc.dip.in': 'in {t}', 'soc.dip.applying': 'applying...',
'soc.dip.byUs': 'started by you', 'soc.dip.byThem': 'started by them',
'soc.dip.pick': 'Choose an alliance', 'soc.dip.search': 'Search name or tag', 'soc.dip.noResults': 'No other alliances found.',
'soc.dip.current': 'Now: {state}', 'soc.dip.locked': 'A change is already scheduled for this pair.', 'soc.dip.noMoves': 'No move is possible from here.',
'soc.dip.result.applied': 'Now {state} with {name}.',
'soc.dip.result.proposed': 'Proposal sent: {state} with {name}.',
'soc.dip.result.scheduled': 'Change to {state} with {name} scheduled.',
'soc.kind.immediate': 'Takes effect at once', 'soc.kind.immediate.hint': 'No consent needed.',
'soc.kind.proposal': 'Needs their consent', 'soc.kind.proposal.hint': 'They get a proposal and must accept it.',
'soc.kind.delayed': 'Cancels after a delay', 'soc.kind.delayed.hint': 'Leaving a pact takes {t}, so a partner is never surprised.',
// messages
'soc.msg.tab.inbox': 'Inbox', 'soc.msg.tab.sent': 'Sent', 'soc.msg.tab.alliance': 'Alliance', 'soc.msg.tab.blocked': 'Blocked',
'soc.msg.new.go': 'New', 'soc.msg.new.title': 'New message', 'soc.msg.new': 'New',
'soc.msg.recipient': 'To (operator name)', 'soc.msg.nameHint': 'Names are not case sensitive.',
'soc.msg.text': 'Message', 'soc.msg.send': 'Send', 'soc.msg.sent': 'Message sent.', 'soc.msg.counter': '{n} of {max} characters',
'soc.msg.to': 'Message to {name}', 'soc.msg.toShort': 'To {name}', 'soc.msg.toAlliance': 'Message to your alliance',
'soc.msg.unknown': 'No operator called {name} in this world.',
'soc.msg.reply': 'Write a reply...', 'soc.msg.older': 'Older messages',
'soc.msg.thread.empty': 'No messages with {name} yet.',
'soc.msg.allianceFeed': 'Alliance broadcast',
'soc.msg.broadcast': 'Broadcast', 'soc.msg.broadcastPlaceholder': 'Tell everyone in the alliance...',
'soc.msg.broadcastHint': 'Everyone currently in {tag} gets this message.',
'soc.msg.unreadOnly': 'Unread only', 'soc.msg.markAll': 'Mark all read',
'soc.msg.delete': 'Delete my copy', 'soc.msg.deleted': 'Deleted. The other side keeps their copy.',
'soc.msg.empty.inbox': 'Nothing in your inbox.', 'soc.msg.empty.sent': 'You have not sent anything.', 'soc.msg.empty.alliance': 'No alliance broadcasts yet.',
'soc.block.go': 'Block', 'soc.block.unblock': 'Unblock', 'soc.block.blocked': '{name} is blocked.', 'soc.block.unblocked': '{name} is unblocked.',
'soc.block.hint': 'Blocked operators cannot reach you and are not told.', 'soc.block.none': 'You have not blocked anyone.',
'soc.block.since': 'blocked {t}', 'soc.block.threadHint': 'You blocked this operator. Their messages are not delivered to you.',
// rankings
'soc.rank.tab.operators': 'Operators', 'soc.rank.tab.alliances': 'Alliances', 'soc.rank.tab.battles': 'Battles',
'soc.rank.by': 'Battle ranking by', 'soc.rank.by.attack': 'Attack', 'soc.rank.by.defense': 'Defense', 'soc.rank.by.total': 'Total',
'soc.rank.yours': 'Your rank', 'soc.rank.of': 'of {n}', 'soc.rank.notShown': 'below the loaded list',
'soc.rank.pops': 'POPs {n}', 'soc.rank.members': '{n} members', 'soc.rank.att': 'attack {n}', 'soc.rank.def': 'defense {n}',
'soc.rank.attack': 'Attack points', 'soc.rank.defense': 'Defense points', 'soc.rank.viewAlliance': 'View alliance',
'soc.rank.empty': 'Nobody is ranked yet.', 'soc.rank.noBattles': 'Nobody has battle points yet.',
'soc.rank.unavailable': 'Battle rankings are not recorded yet.',
'soc.rank.noAlliance': 'You are not in an alliance, so you are not ranked here.',
'soc.rank.noPoints': 'You have no battle points yet.',
},
nb: {
'nav.alliance': 'Allianse', 'nav.messages': 'Meldinger', 'nav.rankings': 'Rangering',
'screen.alliance': 'Allianse', 'screen.messages': 'Meldinger', 'screen.rankings': 'Rangering',
'err.peering_office_required': 'Du trenger et peeringkontor (nivå 1 eller høyere) for å stifte eller bli med i en allianse.',
'err.already_in_alliance': 'Den operatøren er allerede i en allianse.',
'err.not_in_alliance': 'Du er ikke i en allianse.',
'err.alliance_name_taken': 'Det alliansenavnet er opptatt.',
'err.alliance_tag_taken': 'Den alliansetaggen er opptatt.',
'err.alliance_full': 'Alliansen har ikke plass til flere medlemmer.',
'err.invite_expired': 'Invitasjonen har utløpt.',
'err.leader_must_transfer': 'Lederen må gi fra seg ledelsen før hen kan forlate alliansen.',
'err.notes_full': 'Grensen for festede notater er nådd. Fjern ett først.',
'err.diplomacy_invalid': 'Det diplomatiske trekket er ikke mulig fra nåværende tilstand.',
'err.diplomacy_pending': 'En endring mellom disse alliansene er allerede planlagt.',
'err.proposal_exists': 'De har allerede foreslått dette. Godta forslaget deres i stedet.',
'err.proposal_expired': 'Forslaget har utløpt.',
'soc.you': 'Du', 'soc.more': 'Last flere', 'soc.tab.label': 'Seksjoner',
'soc.tab.overview': 'Oversikt', 'soc.tab.members': 'Medlemmer', 'soc.tab.diplomacy': 'Diplomati',
'soc.role.leader': 'Leder', 'soc.role.diplomat': 'Diplomat', 'soc.role.officer': 'Offiser', 'soc.role.member': 'Medlem',
'soc.state.war': 'Krig', 'soc.state.neutral': 'Nøytral', 'soc.state.nap': 'Ikke-angrep', 'soc.state.confed': 'Konføderasjon',
'soc.relation.same': 'Din allianse',
'soc.members': 'Medlemmer', 'soc.leader': 'Leder', 'soc.footprint': 'Fotavtrykk', 'soc.founded': 'Stiftet', 'soc.profile': 'Allianse',
'soc.size': '{n}/{cap} medlemmer', 'soc.leaderIs': 'Leder: {name}',
'soc.rate': 'Du sender for fort. Prøv igjen om {t}.',
'soc.create.title': 'Stift en allianse',
'soc.create.intro': 'Rivaliserende operatører er lettere å overleve med venner. Stift en allianse og inviter andre, eller godta en invitasjon under.',
'soc.create.name': 'Navn', 'soc.create.tag': 'Tagg',
'soc.create.nameHint': '{a}-{b} tegn: bokstaver, tall, mellomrom, . _ \' -',
'soc.create.tagHint': '{a}-{b} bokstaver eller tall, vises i klammer ved siden av navn',
'soc.create.go': 'Stift allianse', 'soc.create.done': 'Alliansen er stiftet.',
'soc.create.needOffice': 'Bygg først et {building} (nivå {n}) i en av POP-ene dine.',
'soc.create.invalid': 'Navn: {n1}-{n2} tegn. Tagg: {t1}-{t2} bokstaver eller tall.',
'soc.invites.title': 'Invitasjoner', 'soc.invites.none': 'Ingen åpne invitasjoner.',
'soc.invites.needOffice': 'For å godta trenger du også et {building}.',
'soc.invites.from': 'fra {name}', 'soc.invites.expires': 'utløper om {t}',
'soc.invites.accept': 'Godta', 'soc.invites.decline': 'Avslå',
'soc.invites.accepted': 'Du ble med i alliansen.', 'soc.invites.declined': 'Invitasjonen er avslått.',
'soc.notes.title': 'Festede notater', 'soc.notes.none': 'Ingen festede notater ennå.', 'soc.notes.add': 'Fest notat', 'soc.notes.remove': 'Fjern notat',
'soc.notes.placeholder': 'Samlingspunkter, regler, mål...',
'soc.manage.title': 'Medlemskap',
'soc.leave.go': 'Forlat alliansen', 'soc.leave.done': 'Du forlot alliansen.',
'soc.leave.confirm': 'Forlate {name}? Du kan bli invitert igjen.',
'soc.leave.confirmAlone': 'Du er eneste medlem av {name}. Hvis du forlater den, oppløses den.',
'soc.leave.mustTransfer': 'Du er leder. Gi ledelsen til et medlem før du kan forlate alliansen.',
'soc.leave.goTransfer': 'Velg etterfølger',
'soc.disband.go': 'Oppløs alliansen', 'soc.disband.done': 'Alliansen er oppløst.',
'soc.disband.confirm': 'Oppløse {name} for alle? Dette kan ikke angres.',
'soc.member.stats': 'POP-er {towns} · fotavtrykk {fp}', 'soc.member.online': 'pålogget {t}', 'soc.member.never': 'aldri pålogget',
'soc.member.pops': 'POP-er', 'soc.member.lastOnline': 'Sist pålogget', 'soc.member.joined': 'Ble med',
'soc.member.message': 'Send melding', 'soc.member.setRole': 'Sett rolle',
'soc.member.roleHint': 'Offiserer inviterer og fjerner medlemmer, diplomater tar seg av andre allianser.',
'soc.member.roleSet': '{name} er nå {role}.',
'soc.transfer.go': 'Gjør til leder', 'soc.transfer.confirm': 'Gi ledelsen til {name}? Du blir offiser.', 'soc.transfer.done': '{name} er ny leder.',
'soc.kick.go': 'Fjern fra alliansen', 'soc.kick.confirm': 'Fjerne {name} fra alliansen?', 'soc.kick.done': '{name} ble fjernet.',
'soc.invite.title': 'Inviter en operatør', 'soc.invite.name': 'Operatørnavn', 'soc.invite.go': 'Inviter',
'soc.invite.sent': 'Invitasjon sendt til {name}.', 'soc.invite.already': '{name} har allerede en åpen invitasjon.',
'soc.invite.unknown': 'Ingen operatør heter {name} i denne verdenen.',
'soc.invite.pending': 'Åpne invitasjoner', 'soc.invite.none': 'Ingen ventende.', 'soc.invite.cancel': 'Trekk tilbake invitasjon',
'soc.dip.title': 'Diplomati', 'soc.dip.new': 'Nytt trekk', 'soc.dip.relations': 'Forhold', 'soc.dip.none': 'Nøytral til alle.',
'soc.dip.readOnly': 'Bare ledere og diplomater endrer diplomatiske forhold.',
'soc.dip.incoming': 'Forslag til deg', 'soc.dip.outgoing': 'Dine forslag',
'soc.dip.accept': 'Godta', 'soc.dip.decline': 'Avslå', 'soc.dip.withdraw': 'Trekk tilbake', 'soc.dip.revoke': 'Angre',
'soc.dip.revoked': 'Planlagt endring avbrutt.',
'soc.dip.expires': 'utløper om {t}', 'soc.dip.in': 'om {t}', 'soc.dip.applying': 'trer i kraft...',
'soc.dip.byUs': 'startet av dere', 'soc.dip.byThem': 'startet av dem',
'soc.dip.pick': 'Velg en allianse', 'soc.dip.search': 'Søk etter navn eller tagg', 'soc.dip.noResults': 'Fant ingen andre allianser.',
'soc.dip.current': 'Nå: {state}', 'soc.dip.locked': 'En endring er allerede planlagt for dette paret.', 'soc.dip.noMoves': 'Ingen trekk er mulige herfra.',
'soc.dip.result.applied': 'Nå {state} med {name}.',
'soc.dip.result.proposed': 'Forslag sendt: {state} med {name}.',
'soc.dip.result.scheduled': 'Endring til {state} med {name} er planlagt.',
'soc.kind.immediate': 'Trer i kraft med en gang', 'soc.kind.immediate.hint': 'Trenger ikke samtykke.',
'soc.kind.proposal': 'Trenger deres samtykke', 'soc.kind.proposal.hint': 'De får et forslag og må godta det.',
'soc.kind.delayed': 'Sies opp med frist', 'soc.kind.delayed.hint': 'Å forlate en avtale tar {t}, så en partner aldri overraskes.',
'soc.msg.tab.inbox': 'Innboks', 'soc.msg.tab.sent': 'Sendt', 'soc.msg.tab.alliance': 'Allianse', 'soc.msg.tab.blocked': 'Blokkert',
'soc.msg.new.go': 'Ny', 'soc.msg.new.title': 'Ny melding', 'soc.msg.new': 'Ny',
'soc.msg.recipient': 'Til (operatørnavn)', 'soc.msg.nameHint': 'Store og små bokstaver spiller ingen rolle.',
'soc.msg.text': 'Melding', 'soc.msg.send': 'Send', 'soc.msg.sent': 'Melding sendt.', 'soc.msg.counter': '{n} av {max} tegn',
'soc.msg.to': 'Melding til {name}', 'soc.msg.toShort': 'Til {name}', 'soc.msg.toAlliance': 'Melding til alliansen din',
'soc.msg.unknown': 'Ingen operatør heter {name} i denne verdenen.',
'soc.msg.reply': 'Skriv et svar...', 'soc.msg.older': 'Eldre meldinger',
'soc.msg.thread.empty': 'Ingen meldinger med {name} ennå.',
'soc.msg.allianceFeed': 'Alliansemelding',
'soc.msg.broadcast': 'Send til alle', 'soc.msg.broadcastPlaceholder': 'Si det til alle i alliansen...',
'soc.msg.broadcastHint': 'Alle som er i {tag} nå får denne meldingen.',
'soc.msg.unreadOnly': 'Bare uleste', 'soc.msg.markAll': 'Merk alle som lest',
'soc.msg.delete': 'Slett min kopi', 'soc.msg.deleted': 'Slettet. Den andre siden beholder sin kopi.',
'soc.msg.empty.inbox': 'Ingenting i innboksen.', 'soc.msg.empty.sent': 'Du har ikke sendt noe.', 'soc.msg.empty.alliance': 'Ingen alliansemeldinger ennå.',
'soc.block.go': 'Blokker', 'soc.block.unblock': 'Opphev blokkering', 'soc.block.blocked': '{name} er blokkert.', 'soc.block.unblocked': 'Blokkeringen av {name} er opphevet.',
'soc.block.hint': 'Blokkerte operatører når ikke fram til deg og får ikke beskjed.', 'soc.block.none': 'Du har ikke blokkert noen.',
'soc.block.since': 'blokkert {t}', 'soc.block.threadHint': 'Du har blokkert denne operatøren. Meldingene deres leveres ikke til deg.',
'soc.rank.tab.operators': 'Operatører', 'soc.rank.tab.alliances': 'Allianser', 'soc.rank.tab.battles': 'Kamper',
'soc.rank.by': 'Kamprangering etter', 'soc.rank.by.attack': 'Angrep', 'soc.rank.by.defense': 'Forsvar', 'soc.rank.by.total': 'Totalt',
'soc.rank.yours': 'Din plassering', 'soc.rank.of': 'av {n}', 'soc.rank.notShown': 'under den lastede lista',
'soc.rank.pops': 'POP-er {n}', 'soc.rank.members': '{n} medlemmer', 'soc.rank.att': 'angrep {n}', 'soc.rank.def': 'forsvar {n}',
'soc.rank.attack': 'Angrepspoeng', 'soc.rank.defense': 'Forsvarspoeng', 'soc.rank.viewAlliance': 'Vis allianse',
'soc.rank.empty': 'Ingen er rangert ennå.', 'soc.rank.noBattles': 'Ingen har kamppoeng ennå.',
'soc.rank.unavailable': 'Kamprangering registreres ikke ennå.',
'soc.rank.noAlliance': 'Du er ikke i en allianse og er derfor ikke rangert her.',
'soc.rank.noPoints': 'Du har ingen kamppoeng ennå.',
},
});
}));

174
public/js/ws.js Normal file
View file

@ -0,0 +1,174 @@
'use strict';
/*
* WebSocket push client (docs/PROTOCOL.md). Push is only a HINT: the game is fully playable with the socket down, so
* every failure here is silent (no toasts, no thrown errors) and a slow REST poll runs as the fallback.
*
* connect to ws(s)://<same origin>/ws; first message {"type":"auth","token":"..."}; server answers {"type":"ready","serverTime"}
* server pushes {"type":"town","townId"} {"type":"incoming","townId","arriveAt"} {"type":"notification","id","kind"}
* {"type":"report","id"} {"type":"message","id"}
* client pings {"type":"ping"} every ~25 s and expects {"type":"pong"} within a few seconds, else it reconnects
* reconnect: exponential backoff from 1 s to 60 s with jitter, reset by a successful "ready"
*
* createSocketClient() is pure plumbing with everything injected (WebSocket constructor, timers, token), so
* test/client-ws.test.js can drive it. The browser wiring (bind) feeds pushes into api.emit('push', msg) and refetches
* the affected screens. The token is never logged and never put in the URL.
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory(require('./milcore.js'));
else root.UpstreamWs = factory(root.UpstreamMil);
}(typeof self !== 'undefined' ? self : this, function (Mil) {
function createSocketClient(o) {
const WS = o.WebSocket;
const setT = o.setTimeout || setTimeout, clearT = o.clearTimeout || clearTimeout;
const pingMs = o.pingMs || 25000, pongMs = o.pongTimeoutMs || 8000;
const rnd = o.random || Math.random;
let sock = null, state = 'idle', attempt = 0, wanted = false, hadReady = false;
let retryTimer = null, pingTimer = null, pongTimer = null;
function setState(s) { if (s !== state) { state = s; if (o.onState) o.onState(s); } }
function clearTimers() { clearT(retryTimer); clearT(pingTimer); clearT(pongTimer); retryTimer = pingTimer = pongTimer = null; }
function schedule(minWait) {
if (!wanted || retryTimer) return;
const wait = Math.max(minWait || 0, Mil.backoffMs(attempt, rnd()));
attempt++;
retryTimer = setT(() => { retryTimer = null; connect(); }, wait);
}
function startPing() {
clearT(pingTimer);
pingTimer = setT(() => {
if (!sock || state !== 'open') return;
try { sock.send('{"type":"ping"}'); } catch (e) { drop(); return; }
clearT(pongTimer);
pongTimer = setT(() => drop(), pongMs); // no pong: the connection is dead although nobody told us
startPing();
}, pingMs);
}
function drop(minWait) {
const s = sock;
sock = null;
clearT(pingTimer); clearT(pongTimer); pingTimer = pongTimer = null;
if (s) { try { s.onopen = s.onmessage = s.onclose = s.onerror = null; s.close(); } catch (e) { /* already gone */ } }
setState(wanted ? 'closed' : 'idle');
schedule(minWait);
}
// Close codes of docs/PROTOCOL.md: 4401 (token refused), 4400 and 1009 (a client bug) must not be retried in a loop;
// 4429 (rate limited) waits at least 30 s; everything else is a plain reconnect.
function onClosed(ev) {
const code = ev && ev.code;
if (code === 4401 || code === 4400 || code === 1009) {
wanted = false; clearTimers(); sock = null; setState('idle');
if (o.onFatal) o.onFatal(code);
return;
}
drop(code === 4429 ? 30000 : 0);
}
function connect() {
if (!wanted || sock) return;
const token = o.token();
if (!token || !WS) return;
let s;
try { s = new WS(o.url()); } catch (e) { setState('closed'); schedule(); return; }
sock = s;
setState('connecting');
s.onopen = () => { try { s.send(JSON.stringify({ type: 'auth', token })); } catch (e) { drop(); } };
s.onmessage = (ev) => {
let msg = null;
try { msg = JSON.parse(ev.data); } catch (e) { return; }
if (!msg || typeof msg.type !== 'string') return;
if (msg.type === 'ready') { attempt = 0; const again = hadReady; hadReady = true; setState('open'); startPing(); if (o.onReady) o.onReady(msg, again); return; }
if (msg.type === 'pong') { clearT(pongTimer); pongTimer = null; return; }
if (o.onMessage) o.onMessage(msg);
};
s.onclose = (ev) => { if (sock === s) onClosed(ev); };
s.onerror = () => { /* the close event follows; stay quiet */ };
}
return {
start() { if (wanted) return; wanted = true; attempt = 0; hadReady = false; connect(); },
stop() { wanted = false; clearTimers(); const s = sock; sock = null; if (s) { try { s.onopen = s.onmessage = s.onclose = s.onerror = null; s.close(); } catch (e) { /* ignore */ } } setState('idle'); },
// Try now (back online, tab visible again): skips the backoff wait.
kick() { if (!wanted || sock) return; clearT(retryTimer); retryTimer = null; attempt = 0; connect(); },
get state() { return state; },
get open() { return state === 'open'; },
get attempts() { return attempt; },
};
}
// ------------------------------------------------------------------ browser wiring
function bind(App, UI, windowRef) {
const api = App.api;
const wsUrl = () => (windowRef.location.protocol === 'https:' ? 'wss://' : 'ws://') + windowRef.location.host + '/ws';
const client = createSocketClient({
WebSocket: windowRef.WebSocket,
url: wsUrl,
token: () => api.getToken(),
onMessage: (msg) => api.emit('push', msg),
// after every ready that follows a gap, refetch what is on screen (PROTOCOL.md): hints sent while we were away are lost
onReady: (msg, again) => { poll(true); if (again && App.state.user) { App.refreshTown().catch(() => {}); App.refreshTowns().catch(() => {}); } },
onFatal: () => { /* token refused or a client bug: stay quiet, the REST layer reports a dead token itself */ },
});
App.ws = client;
const timers = {};
function debounce(key, fn, ms) { clearTimeout(timers[key]); timers[key] = setTimeout(fn, ms); }
// ---- what a push means for the screens (everything is a refetch over REST)
api.on('push', (msg) => {
if (!App.state.user) return;
switch (msg.type) {
case 'town':
if (msg.townId === App.state.townId) debounce('town', () => App.refreshTown().catch(() => {}), 250);
break;
case 'incoming':
debounce('moves', () => App.refreshMovements().catch(() => {}), 150);
UI.toast(App.t('push.incoming'), 'error');
break;
case 'report':
App.refreshReportsUnread().catch(() => {});
debounce('towns', () => App.refreshTowns().catch(() => {}), 500); // a settle / takeover report changes the POP list
App.emit('report', msg);
break;
case 'notification':
App.checkAlerts();
if (msg.kind === 'town_gained' || msg.kind === 'town_lost') App.refreshTowns().catch(() => {});
if (/^(train_done|research_done|movement_returned|reinforcements_sent_home|units_offline|units_decommissioned|transport_arrived|town_gained|town_lost)$/.test(msg.kind || '')) {
debounce('town', () => App.refreshTown().catch(() => {}), 400);
debounce('moves', () => App.refreshMovements().catch(() => {}), 400);
}
break;
default: break; // 'message' etc. belong to other screens (api.on('push') there)
}
});
// ---- REST fallback: slow when the socket is open (it only backs the hints up), faster when it is down
let lastPoll = 0;
function poll(force) {
if (!App.state.user || windowRef.document.hidden) return;
const gap = client.open ? 180000 : 45000;
if (!force && Date.now() - lastPoll < gap) return;
lastPoll = Date.now();
App.refreshMovements().catch(() => {});
App.refreshReportsUnread().catch(() => {});
App.refreshTowns().catch(() => {});
App.checkAlerts();
}
setInterval(() => poll(false), 15000);
// ---- lifecycle
App.on('session', (st) => {
if (st && st.user) { client.start(); poll(true); } else client.stop();
});
api.on('unauthorized', () => client.stop());
api.on('online', () => client.kick());
windowRef.document.addEventListener('visibilitychange', () => { if (!windowRef.document.hidden && App.state.user) { client.kick(); poll(false); } });
}
if (typeof window !== 'undefined' && window.App && window.UI) bind(window.App, window.UI, window);
return { createSocketClient, bind };
}));