Phase 3: trade/end-game client, bot simulator, first balance pass

Built:
- Client: trade screen, world/end-game screen (landing sites, shipping, node build, final ranking), report sharing + alliance reports tab, alert describers for all notification types, error-code strings (en+nb) for every server CODE.
- tools/bot.js (+ tools/bot/): 50 headless bots against the real server in-process with a fake clock; resource/unit conservation ledger, exit 1 on broken invariants. docs/BALANCE.md has method and every run behind a number.
- Balance changes (evidence in docs/BALANCE.md): secondQueueCoreLevel 10 -> 3, TRANSPORT.capacityPerLink 500 -> 1000 (end game was shipping-limited in bot runs).
- Server fixes: POST /reports/:id/share 500 without a pending reportCleanup; bounced link shipments were silent about cargo overflow.

Tested: npm test 207/207 (new: bot determinism + invariants, client alerts/world/i18n over CODES, two regression tests that failed before their fix); openapi check up to date. Real-browser scratch runs (not in repo): WebSocket push shows an incoming-attack banner ~214 ms after launch, polling fallback ~52 s, 15 scripted flows, 71 screenshots.

NOT tested: Playwright suite (e2e/ still empty), real devices/Safari, nginx proxy websockets, throttled networks, HTTP-level bot load. NOT claimed: balance. Bots are not humans; open balance items (loot waste, escrow refund clipping, no garrisons at landing sites, end game not scaling with world speed) are listed in docs/BALANCE.md.

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 20:24:41 +02:00
parent d84b0c9d12
commit 931f59e11e
49 changed files with 4750 additions and 59 deletions

View file

@ -511,3 +511,95 @@ select { width: 100%; }
.mil-train .cost { padding: 3px 8px; }
.mil-train .cost svg.ic { width: 15px; height: 15px; }
.mil-train .pill { max-width: none; }
/* ---------------------------------------------------------------- Internet exchange (trd-), end game (wld-), ended world */
.trd-page, .wld-page { gap: 10px; }
.trd-tabs .seg-btn { min-width: 0; padding: 0 4px; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.trd-body { display: grid; gap: 12px; align-content: start; min-width: 0; }
.trd-filters { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 10px; }
.trd-filters .field:nth-child(3) { grid-column: 1 / -1; }
.trd-reach { margin: 0 0 10px; }
.trd-list { gap: 8px; }
.trd-offer { display: grid; grid-template-columns: 38px minmax(0, 1fr); gap: 8px 10px; align-items: start; }
.trd-offer .row-main { gap: 6px; }
.trd-offer .row-sub { white-space: normal; overflow-wrap: anywhere; }
.trd-offer > .btn { grid-column: 1 / -1; min-height: 44px; }
.trd-terms { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px 10px; }
.trd-term { display: grid; gap: 3px; min-width: 0; align-content: start; }
.trd-lbl { font-size: 11px; color: var(--dimmer); text-transform: uppercase; letter-spacing: .08em; }
.trd-terms .cost { width: max-content; max-width: 100%; }
.trd-chips { margin-bottom: 2px; }
.trd-need { display: grid; gap: 10px; }
.trd-need .card-head { margin-bottom: 0; }
.trd-pops { display: grid; gap: 8px; }
.trd-pop { display: flex; align-items: flex-start; gap: 10px; background: var(--panel2); border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; min-height: 56px; }
.trd-pop:has(input:checked) { border-color: var(--cyan); background: #0c1f33; }
.trd-pop.off { opacity: .65; }
.trd-pop input { width: 22px; height: 22px; flex: none; margin-top: 2px; accent-color: var(--cyan); }
.trd-form .field { margin-bottom: 8px; }
.trd-form .sub { margin-top: 10px; }
.trd-form .field-hint, .trd-form > .dimmer { display: block; margin-top: 2px; }
.trd-page .card .detail-desc { margin-bottom: 8px; }
.trd-pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 8px; align-items: center; }
.trd-pair select, .trd-pair input.mil-num { min-height: 46px; }
.trd-pair .btn.small { min-height: 46px; }
.trd-msgs { display: grid; gap: 4px; margin-top: 8px; }
.trd-msgs:empty { display: none; }
.trd-note { display: grid; gap: 4px; margin-top: 4px; }
.trd-links .mil-row { align-items: flex-start; }
.trd-links .bar { margin-top: 6px; --c: var(--cyan); }
.trd-empty { display: grid; gap: 8px; }
.wld-banner { display: flex; gap: 14px; align-items: center; border-color: var(--line2); }
.wld-banner .row-main { gap: 6px; }
.wld-banner h2 { font-size: 18px; line-height: 1.25; text-transform: none; letter-spacing: 0; color: var(--text); overflow-wrap: anywhere; }
.wld-trophy { width: 52px; height: 52px; flex: none; display: grid; place-items: center; border-radius: 16px; background: var(--panel3); color: var(--cyan); }
.wld-trophy svg.ic { width: 30px; height: 30px; }
.wld-banner.open { border-color: color-mix(in srgb, var(--cyan) 55%, var(--line2)); }
.wld-banner.won, .wld-banner.ended { border-color: #6b5a1f; background: rgba(43, 34, 8, .55); }
.wld-banner.won .wld-trophy, .wld-banner.ended .wld-trophy { color: var(--amber); background: #3a2d08; }
.wld-count { font-size: 26px; color: var(--cyan); line-height: 1.1; }
.wld-cd { font-variant-numeric: tabular-nums; }
.wld-bar { height: 8px; margin-top: 4px; --c: var(--dim); }
.wld-bar.mine { --c: var(--cyan); } .wld-bar.rival { --c: var(--amber); } .wld-bar.incumbent { --c: var(--violet); } .wld-bar.build { --c: var(--amber); height: 6px; }
.wld-sub { margin-top: 4px; }
.wld-sites { display: grid; gap: 10px; grid-template-columns: minmax(0, 1fr); }
@media (min-width: 900px) { .wld-sites { grid-template-columns: repeat(2, minmax(0, 1fr)); } .wld-page { max-width: 980px; } }
.wld-site { display: grid; gap: 8px; align-content: start; }
.wld-site.mine { border-color: color-mix(in srgb, var(--cyan) 65%, var(--line)); background: rgba(10, 30, 50, .85); }
.wld-site.rival { border-color: #6b5a1f; }
.wld-site.flash { animation: wld-flash 1.6s ease-out 1; }
@keyframes wld-flash { 0% { box-shadow: 0 0 0 3px var(--amber); } 100% { box-shadow: 0 0 0 0 transparent; } }
.wld-site-head { display: flex; align-items: center; gap: 10px; }
.wld-site-head .row-main { min-width: 0; }
.wld-site .row-sub { white-space: normal; }
.wld-holder { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.wld-level { display: grid; gap: 2px; }
.wld-building { display: grid; gap: 2px; }
.wld-acts { display: flex; flex-wrap: wrap; gap: 8px; }
.wld-how { padding-left: 20px; display: grid; gap: 6px; color: var(--dim); font-size: 14px; }
.wld-sec { display: grid; gap: 8px; margin-top: 6px; }
.wld-manage .costs { margin: 2px 0; }
.wld-results { display: grid; gap: 8px; }
.wld-results .card-head { margin-bottom: 0; }
.wld-ranks { display: grid; gap: 6px; }
.wld-rank { display: flex; align-items: center; gap: 10px; background: var(--panel2); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; min-height: 52px; }
.wld-rank .row-main { min-width: 0; }
.wld-rank .row-sub { white-space: normal; overflow-wrap: anywhere; }
.wld-rank.you { border-color: var(--cyan); background: #0c1f33; }
.wld-rank.win { border-color: #6b5a1f; background: rgba(43, 34, 8, .55); }
.wld-rank.win svg.ic { color: var(--amber); }
.wld-ended-card { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; border-color: #6b5a1f; background: rgba(43, 34, 8, .6); }
.wld-ended-card .row-main { flex: 1 1 200px; min-width: 0; }
.wld-ended-card > .btn { flex: none; }
.wld-ended-card .row-ic { color: var(--amber); }
.lg.backbone { background: #2b2208; border: 2px solid #f5c542; transform: rotate(45deg) scale(.85); }
.ended-pill { margin-left: auto; background: #2b2208; color: var(--amber); border: 1px solid #6b5a1f; cursor: pointer; min-height: 30px; }
html[data-ended] #app { box-shadow: inset 0 3px 0 #6b5a1f; }
button[data-ended-lock] { cursor: not-allowed; }
.rep-tabs { margin-bottom: 0; }
.rep-tabs .seg-btn { min-height: 42px; font-size: 14px; }
.rep-verdict.neutral { background: var(--panel2); color: var(--dim); border: 1px solid var(--line2); }
.rep-share { display: grid; gap: 8px; border-top: 1px solid var(--line); padding-top: 12px; margin-top: 4px; }

View file

@ -21,6 +21,7 @@
<header id="topbar">
<div class="brand"><span class="brand-mark" aria-hidden="true"></span><span id="title">UPSTREAM</span></div>
<span id="netstate" class="netstate" role="status" aria-live="polite" hidden></span>
<button id="world-pill" class="netstate ended-pill" type="button" data-keep hidden></button>
</header>
<section id="hud" class="hud" aria-label="Resources" hidden></section>
<main id="view"></main>
@ -35,13 +36,18 @@
<script src="js/i18n.js" defer></script>
<script src="js/strings/military.js" defer></script>
<script src="js/strings/social.js" defer></script>
<script src="js/strings/alerts.js" defer></script>
<script src="js/strings/trade.js" defer></script>
<script src="js/strings/world.js" defer></script>
<script src="js/api.js" defer></script>
<script src="js/ui.js" defer></script>
<script src="js/social.js" defer></script>
<script src="js/render.js" defer></script>
<script src="js/milcore.js" defer></script>
<script src="js/endcore.js" defer></script>
<script src="js/main.js" defer></script>
<script src="js/milstate.js" defer></script>
<script src="js/alertkinds.js" defer></script>
<script src="js/ws.js" defer></script>
<script src="js/screens/auth.js" defer></script>
<script src="js/screens/pop.js" defer></script>
@ -57,5 +63,8 @@
<script src="js/screens/alliance.js" defer></script>
<script src="js/screens/messages.js" defer></script>
<script src="js/screens/rankings.js" defer></script>
<script src="js/screens/cargo-ui.js" defer></script>
<script src="js/screens/trade.js" defer></script>
<script src="js/screens/world.js" defer></script>
</body>
</html>

77
public/js/alertkinds.js Normal file
View file

@ -0,0 +1,77 @@
'use strict';
/*
* What the Alerts feed shows for the notification types of trade, the end game, the world and the social screens
* (alliances, diplomacy, messages). Pure: no DOM, no App. make(ctx) returns { type: (notification, payload) -> { icon, title,
* detail, go, params } } and test/client-alerts.test.js feeds it payloads in the shapes the server writes. In the browser the
* bottom of this file registers the describers in App.alertKinds (the military ones live in milstate.js, build_done in
* screens/alerts.js). Unknown payload fields never throw: a describer falls back to something readable.
*
* ctx = { t(key, vars), num(n), resName(res), townName(id) -> string | null, clockTime(ms), dayTime(ms) }
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = { make: factory };
else {
root.UpstreamAlertKinds = { make: factory };
if (root.App && root.UpstreamI18n) {
const App = root.App, mil = () => App.mil;
const kinds = factory({
t: (k, v) => App.t(k, v), num: (n) => App.fmt.num(n), resName: (r) => App.resName(r),
townName: (id) => (mil() ? mil().townName(id) : null), clockTime: (ms) => mil().clockTime(ms), dayTime: (ms) => mil().dayTime(ms),
});
for (const k of Object.keys(kinds)) if (!App.alertKinds[k]) App.alertKinds[k] = kinds[k];
}
}
}(typeof self !== 'undefined' ? self : this, function make(c) {
const t = c.t;
const RES = ['fiber', 'hardware', 'capital'];
const amt = (a) => (a && a.resource ? c.num(a.amount) + ' ' + c.resName(a.resource) : '');
const cargoText = (cargo) => RES.filter((r) => cargo && cargo[r] > 0).map((r) => c.num(cargo[r]) + ' ' + c.resName(r)).join(', ');
const town = (id) => c.townName(id) || '#' + id;
const tag = (o) => (o ? (o.tag ? '[' + o.tag + ']' : (o.name || '')) : '');
const site = (p) => (Number.isInteger(p.index) ? p.index + 1 : '?');
const known = (prefix, key) => { const k = prefix + key; const s = t(k); return s === k ? String(key) : s; };
const there = (p) => (p.x !== undefined ? t('alerts.at', { x: p.x, y: p.y }) : '');
const worldGo = (p) => ({ go: 'world', params: p && Number.isInteger(p.index) ? { site: p.index } : null });
return {
// ---- trade
trade_accepted: (n, p) => ({ icon: 'swap', title: t('alerts.trade_accepted', { give: amt(p.give), want: amt(p.want) }), detail: t('alerts.build_done.in', { town: town(p.townId) }), go: 'trade', params: { tab: 'mine' } }),
trade_completed: (n, p) => ({ icon: 'swap', title: t('alerts.trade_completed', { give: amt(p.give), want: amt(p.want) }), detail: '', go: 'trade', params: { tab: 'mine' } }),
trade_expired: (n, p) => ({ icon: 'clock', title: t('alerts.trade_expired'), detail: t('alerts.trade_expired.back', { what: amt(p.returned), town: town(p.townId) }), go: 'trade', params: { tab: 'mine' } }),
trade_void: (n, p) => ({ icon: 'alert', title: t('alerts.trade_void'), detail: t('alerts.build_done.in', { town: town(p.townId) }), go: 'trade', params: { tab: 'mine' } }),
// ---- end game
backbone_open: (n, p) => Object.assign({ icon: 'b-backbone_node', title: t('alerts.backbone_open'), detail: t('alerts.backbone_open.n', { n: (p.sites || []).length || 7 }) }, worldGo(null)),
backbone_taken: (n, p) => Object.assign({ icon: 'flag', title: t('alerts.backbone_taken', { n: site(p) }), detail: [t('alerts.level', { n: p.level || 0 }), p.from ? t('alerts.backbone_taken.from', { tag: tag(p.from) }) : t('alerts.backbone_taken.incumbent'), there(p)].filter(Boolean).join(' · ') }, worldGo(p)),
backbone_lost: (n, p) => Object.assign({ icon: 'alert', title: t('alerts.backbone_lost', { n: site(p), tag: tag(p.by) }), detail: [t('alerts.level', { n: p.level || 0 }), there(p)].filter(Boolean).join(' · ') }, worldGo(p)),
backbone_level: (n, p) => Object.assign({ icon: 'b-backbone_node', title: t('alerts.backbone_level', { n: site(p), level: p.level }), detail: '' }, worldGo(p)),
backbone_delivered: (n, p) => ({ icon: 'box', title: t('alerts.backbone_delivered'), detail: cargoText(p.cargo), go: 'world', params: null }),
backbone_ship_bounced: (n, p) => ({ icon: 'alert', title: t('alerts.backbone_ship_bounced'), detail: cargoText(p.cargo), go: 'movements', params: null }),
backbone_won: (n, p) => ({ icon: 'trophy', title: t('alerts.backbone_won', { name: p.name || tag(p) }), detail: p.endsAt ? t('alerts.backbone_won.ends', { time: c.dayTime(p.endsAt) }) : '', go: 'world', params: null }),
world_ended: (n, p) => ({ icon: 'trophy', title: t('alerts.world_ended'), detail: p.winner && p.winner.name ? t('alerts.world_ended.winner', { name: p.winner.name }) : t('alerts.world_ended.nowinner'), go: 'world', params: null }),
// ---- alliance
alliance_invite: (n, p) => ({ icon: 'users', title: t('alerts.alliance_invite', { name: p.name || tag(p) }), detail: t('alerts.alliance_invite.by', { name: p.by || '?' }), go: 'alliance', params: null }),
alliance_invite_declined: (n, p) => ({ icon: 'users', title: t('alerts.alliance_invite_declined', { name: p.by || '?' }), detail: '', go: 'alliance', params: null }),
alliance_member_joined: (n, p) => ({ icon: 'users', title: t('alerts.alliance_member_joined', { name: p.name || '?' }), detail: '', go: 'alliance', params: null }),
alliance_member_left: (n, p) => ({ icon: 'users', title: t(p.kicked ? 'alerts.alliance_member_kicked' : 'alerts.alliance_member_left', { name: p.name || '?' }), detail: '', go: 'alliance', params: null }),
alliance_kicked: (n, p) => ({ icon: 'alert', title: t('alerts.alliance_kicked', { name: p.name || tag(p) }), detail: '', go: 'alliance', params: null }),
alliance_role: (n, p) => ({ icon: 'users', title: t('alerts.alliance_role', { role: known('soc.role.', p.role) }), detail: p.from ? t('alerts.alliance_role.was', { role: known('soc.role.', p.from) }) : '', go: 'alliance', params: null }),
alliance_leader: (n, p) => ({ icon: 'users', title: t('alerts.alliance_leader', { name: p.name || '?' }), detail: p.from ? t('alerts.alliance_leader.from', { name: p.from }) : '', go: 'alliance', params: null }),
alliance_disbanded: (n, p) => ({ icon: 'alert', title: t('alerts.alliance_disbanded', { name: p.name || tag(p) }), detail: '', go: 'alliance', params: null }),
// ---- diplomacy (diplomacy_changed has two payload shapes: { other: {tag,..} } and, when an alliance was disbanded, { otherTag, reason })
diplomacy_proposal: (n, p) => ({ icon: 'handshake', title: t('alerts.diplomacy_proposal', { tag: tag(p.from), state: known('soc.state.', p.state) }), detail: p.expiresAt ? t('alerts.diplomacy_proposal.until', { time: c.dayTime(p.expiresAt) }) : '', go: 'alliance', params: null }),
diplomacy_declined: (n, p) => ({ icon: 'handshake', title: t('alerts.diplomacy_declined', { tag: tag(p.by), state: known('soc.state.', p.state) }), detail: '', go: 'alliance', params: null }),
diplomacy_changed: (n, p) => ({
icon: 'handshake', title: t('alerts.diplomacy_changed', { tag: p.other ? tag(p.other) : (p.otherTag ? '[' + p.otherTag + ']' : '?'), to: known('soc.state.', p.to) }),
detail: [p.from ? t('alerts.diplomacy_changed.was', { state: known('soc.state.', p.from) }) : '', p.reason === 'disbanded' ? t('alerts.diplomacy_changed.disbanded') : ''].filter(Boolean).join(' · '), go: 'alliance', params: null,
}),
diplomacy_cancel_pending: (n, p) => ({ icon: 'clock', title: t('alerts.diplomacy_cancel_pending', { tag: tag(p.other), state: known('soc.state.', p.from) }), detail: p.effectiveAt ? t('alerts.diplomacy_cancel_pending.at', { time: c.dayTime(p.effectiveAt) }) : '', go: 'alliance', params: null }),
diplomacy_cancel_revoked: (n, p) => ({ icon: 'handshake', title: t('alerts.diplomacy_cancel_revoked', { tag: tag(p.other), state: known('soc.state.', p.state) }), detail: '', go: 'alliance', params: null }),
// ---- messages
message: (n, p) => ({ icon: 'mail', title: t('alerts.message', { name: p.from && p.from.name ? p.from.name : '?' }), detail: '', go: 'messages', params: null }),
alliance_message: (n, p) => ({ icon: 'mail', title: t('alerts.alliance_message', { name: typeof p.from === 'string' ? p.from : '?' }), detail: p.tag ? '[' + p.tag + ']' : '', go: 'messages', params: null }),
};
}));

View file

@ -36,7 +36,8 @@
footprintNeedExp: 1.8,
loyaltyRegenPerHour: 1,
loyaltyMax: 100,
secondQueueCoreLevel: 10, // Core router level that opens the second build slot
secondQueueCoreLevel: 3, // Core router level that opens the second build slot (was 10; docs/BALANCE.md B1)
extraQueueCores: [], // Core router levels that each open one more build slot (after the second)
minBuildMs: 5000,
};
@ -215,7 +216,8 @@
};
// Resource transport between POPs (trade is built on it): `links` concurrent transports = Internet exchange level.
const TRANSPORT = { building: 'internet_exchange', speed: 12, capacityPerLink: 500 };
// capacityPerLink was 500; 1000 since docs/BALANCE.md B2 (the end game was shipping-limited: 21.6 M units in 500-unit trips).
const TRANSPORT = { building: 'internet_exchange', speed: 12, capacityPerLink: 1000 };
// Which unit roles may go on which movement type.
const MOVE_ROLES = {

87
public/js/endcore.js Normal file
View file

@ -0,0 +1,87 @@
'use strict';
/*
* Pure helpers of the end game screen (no DOM, no storage, no clock): who leads the race, how far a node build is, what a build
* still lacks, what a holder may do. Loads as a browser script (window.UpstreamEnd) and as a Node module (test/client-world.test.js).
* The SERVER decides everything (GET /worlds/:id/status, GET /backbone/:id); this only avoids doomed taps and explains the greyed-out ones.
*
* A site is the `LandingSite` of docs/openapi.json: { id | null, index, x, y, holder: { allianceId, tag, name } | null, takenBy, takenAt,
* level, maxLevel, progress, pool: { fiber, hardware, capital }, build: { toLevel, startedAt, dueAt } | null, next: { toLevel, cost, durationMs } | null }.
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory(require('./data.js'));
else root.UpstreamEnd = factory(root.UpstreamData);
}(typeof self !== 'undefined' ? self : this, function (D) {
const RES = D.RESOURCES;
// The alliance furthest in the race: highest node level on any of its sites; ties by more sites held, then the earlier takeover.
// -> { allianceId, tag, name, level, sites, siteIndex } | null (nobody holds a site)
function leading(sites) {
const by = new Map();
for (const s of sites || []) {
if (!s.holder) continue;
const k = s.holder.allianceId;
const c = by.get(k) || { allianceId: k, tag: s.holder.tag, name: s.holder.name, level: -1, sites: 0, siteIndex: null, at: Infinity };
c.sites++;
if (s.level > c.level) { c.level = s.level; c.siteIndex = s.index; }
c.at = Math.min(c.at, s.takenAt || Infinity);
by.set(k, c);
}
const all = Array.from(by.values());
if (!all.length) return null;
all.sort((a, b) => b.level - a.level || b.sites - a.sites || a.at - b.at || a.allianceId - b.allianceId);
const w = all[0];
return { allianceId: w.allianceId, tag: w.tag, name: w.name, level: w.level, sites: w.sites, siteIndex: w.siteIndex };
}
// Progress 0..1 of the node level being built, or null when nothing is being built.
function buildProgress(site, now) {
const b = site && site.build;
if (!b) return null;
return Math.max(0, Math.min(1, (now - b.startedAt) / Math.max(1, b.dueAt - b.startedAt)));
}
// What the stockpile lacks for `cost`: { res: missing } (empty object = enough).
function missing(cost, pool) {
const out = {};
for (const r of RES) {
const lack = ((cost && cost[r]) || 0) - ((pool && pool[r]) || 0);
if (lack > 0) out[r] = lack;
}
return out;
}
// Who holds the site, seen from `allianceId`: 'mine' | 'rival' | 'incumbent'.
function holderKind(site, allianceId) {
if (!site.holder) return 'incumbent';
return allianceId && site.holder.allianceId === allianceId ? 'mine' : 'rival';
}
// May the node be built now? -> { ok, reason } with reason in: ended, forbidden, max_level, already_queued, not_enough_resources.
// `you` = the `you` block of GET /backbone/:id.
function buildCheck(site, you, ended) {
if (ended) return { ok: false, reason: 'ended' };
if (!you || !you.holder || !you.canBuild) return { ok: false, reason: 'forbidden' };
if (!site.next) return { ok: false, reason: 'max_level' };
if (site.build) return { ok: false, reason: 'already_queued' };
if (Object.keys(missing(site.next.cost, site.pool)).length) return { ok: false, reason: 'not_enough_resources' };
return { ok: true, reason: null };
}
// The phase as the clock sees it: the status says 'running' until it is refetched, but the sites open at opensAt.
function phaseNow(status, now) {
if (!status) return 'running';
if (status.phase === 'ended') return 'ended';
if (status.phase === 'running' && now >= status.opensAt) return 'backbone_open';
return status.phase;
}
// Share of the way to the opening day, 0..1.
const openProgress = (status) => (status && status.openDay ? Math.max(0, Math.min(1, status.ageDays / status.openDay)) : 0);
const sumCargo = (c) => Object.keys(c || {}).reduce((s, k) => s + (c[k] || 0), 0);
// Rows of a final ranking list for display: the first `n` (a snapshot holds the top 100).
const topRows = (list, n) => (list || []).slice(0, n);
return { leading, buildProgress, missing, holderKind, buildCheck, phaseNow, openProgress, sumCargo, topRows };
}));

View file

@ -59,6 +59,7 @@
};
App.errMsg = (err) => {
const code = err && err.code;
if (code === 'world_ended' && App.markWorldEnded) App.markWorldEnded(); // every screen shows its errors through here
if (code && Object.prototype.hasOwnProperty.call(I.strings.en, 'err.' + code)) return App.t('err.' + code);
return (err && err.message) || App.t('err.unknown');
};

View file

@ -31,7 +31,8 @@
* 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
* allianceId: my alliance id or null, crews: number of rollout crews at home,
* transportOnly: the dialog was opened for a transport (trade screen): a POP, anybody's, offers only the transport
* } -> [{ 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.
@ -42,6 +43,14 @@
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 });
const linksFree = () => {
const links = (c.transport && c.transport.links) || 0, active = (c.transport && c.transport.active) || 0;
return { ok: links > active, reason: links === 0 ? 'no_link' : 'links_busy' };
};
if (c.transportOnly) { // resources may go to any POP, a rival's too (the server warns its owner of the arrival)
if (t.town) { const l = linksFree(); add('transport', l.ok, l.reason); }
return out;
}
if (t.town) {
if (t.town.mine) {
add('reinforce', has('reinforce'), 'no_units');
@ -60,6 +69,14 @@
} else if (t.type === 'incumbent') {
add('scan', has('scan'), 'no_units');
add('attack', has('attack'), 'no_units');
} else if (t.type === 'backbone') {
// End game landing site: scan or attack, nothing else. Attacking needs an alliance and a site that is not your own
// alliance's (pacts are the server's call: its answer is shown by the dialog).
const b = t.backbone || {};
add('scan', has('scan'), 'no_units');
if (!c.allianceId) add('attack', false, 'no_alliance');
else if (b.mine) add('attack', false, 'own_site');
else 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'));

View file

@ -125,6 +125,7 @@
if (!op) return;
const before = townSig(st.towns);
st.operators = me.operators; st.operator = op; st.world = op.world; st.towns = op.towns;
if (App.checkWorld) App.checkWorld(); // the world may have ended while we were away
let gone = false;
if (!st.towns.some((t) => t.id === st.townId)) {
const pick = st.towns.find((t) => t.isCapital) || st.towns[0] || null;

View file

@ -8,6 +8,7 @@
* 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)
* source.myAllianceId() -> id | null optional: colours the end game landing sites (specials of type 'backbone')
* 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 }
*
@ -19,6 +20,7 @@
const COLORS = {
void: '#04070e', land: '#0d1626', land2: '#0f192b', grid: 'rgba(120,160,220,0.10)', grid10: 'rgba(120,160,220,0.22)', border: 'rgba(77,227,255,0.55)',
fiber: '#4de3ff', hardware: '#ff9f5a', capital: '#5be08f', incumbent: '#b06cff', incumbentFill: '#241338',
backbone: '#f5c542', backboneFill: '#2b2208', rivalSite: '#ff6bd6',
own: '#4de3ff', ownFill: '#0f4b63', select: '#ffd24d', text: '#e4f0ff', halo: 'rgba(4,7,14,0.9)', reach: 'rgba(77,227,255,0.35)',
};
@ -278,6 +280,7 @@
this.src.forEachSpecial(v.x0, v.y0, v.x1, v.y1, (sp) => {
const s = this.toScreen(sp.x, sp.y);
if (sp.type === 'rural') this._rural(s.x, s.y, sp.bonus);
else if (sp.type === 'backbone') this._backbone(s.x, s.y, sp);
else this._incumbent(s.x, s.y);
});
@ -336,6 +339,41 @@
}
}
// End game landing site: a diamond with a ring that fills with the node level; gold = nobody's (the incumbent's), cyan = your
// alliance, a rival hue = another alliance. Clearly not an incumbent square and not a POP hexagon.
_backbone(x, y, sp) {
const { ctx, zoom: z } = this;
if (x < -40 || y < -40 || x > this.w + 40 || y > this.h + 40) return;
const site = sp.site || {};
const mine = !!(this.src.myAllianceId && site.holder && site.holder.allianceId === this.src.myAllianceId());
const col = !site.holder ? COLORS.backbone : mine ? COLORS.own : COLORS.rivalSite;
const r = Math.max(4, z * 0.46);
ctx.save();
ctx.shadowColor = col; ctx.shadowBlur = Math.min(18, 4 + z * 0.3);
ctx.beginPath(); ctx.moveTo(x, y - r); ctx.lineTo(x + r, y); ctx.lineTo(x, y + r); ctx.lineTo(x - r, y); ctx.closePath();
ctx.fillStyle = COLORS.backboneFill; ctx.fill();
ctx.restore();
ctx.beginPath(); ctx.moveTo(x, y - r); ctx.lineTo(x + r, y); ctx.lineTo(x, y + r); ctx.lineTo(x - r, y); ctx.closePath();
ctx.strokeStyle = col; ctx.lineWidth = Math.max(1.5, z * 0.09); ctx.stroke();
if (z >= 7) {
const rr = r * 1.45, frac = site.maxLevel ? Math.max(0, Math.min(1, (site.level || 0) / site.maxLevel)) : 0;
ctx.lineWidth = Math.max(2, z * 0.1); ctx.lineCap = 'round';
ctx.strokeStyle = 'rgba(160,180,220,0.22)'; ctx.beginPath(); ctx.arc(x, y, rr, 0, Math.PI * 2); ctx.stroke();
if (frac > 0) { ctx.strokeStyle = col; ctx.beginPath(); ctx.arc(x, y, rr, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * frac); ctx.stroke(); }
}
if (z >= 14) { // a lightning bolt: the backbone
ctx.fillStyle = col; ctx.beginPath();
ctx.moveTo(x + r * 0.12, y - r * 0.55); ctx.lineTo(x - r * 0.3, y + r * 0.08); ctx.lineTo(x - r * 0.02, y + r * 0.08);
ctx.lineTo(x - r * 0.14, y + r * 0.55); ctx.lineTo(x + r * 0.3, y - r * 0.1); ctx.lineTo(x + r * 0.02, y - r * 0.1); ctx.closePath(); ctx.fill();
}
if (z >= 18) {
ctx.font = '700 ' + Math.round(clamp(z * 0.3, 10, 13)) + 'px system-ui, sans-serif';
ctx.textAlign = 'center'; ctx.textBaseline = 'top'; ctx.lineWidth = 3; ctx.lineJoin = 'round'; ctx.strokeStyle = COLORS.halo;
const label = (site.index !== undefined ? 'S' + (site.index + 1) : '') + (site.holder ? ' [' + site.holder.tag + ']' : '') + ' L' + (site.level || 0);
ctx.strokeText(label, x, y + r * 1.45 + 4); ctx.fillStyle = col; ctx.fillText(label, x, y + r * 1.45 + 4);
}
}
_hex(x, y, rad) {
const { ctx } = this;
ctx.beginPath();

View file

@ -204,7 +204,14 @@
return Math.max(F.minBuildMs, Math.round(secs * 1000));
}
function queueSlots(town) { return coreLevel(town) >= F.secondQueueCoreLevel ? 2 : 1; }
// Build slots (builds running at once): 1, one more from Core router F.secondQueueCoreLevel, and one more at each level listed
// in F.extraQueueCores (data, default none).
function queueSlots(town) {
const core = coreLevel(town);
let n = core >= F.secondQueueCoreLevel ? 2 : 1;
for (const lv of F.extraQueueCores || []) if (core >= lv) n += 1;
return n;
}
function storageCap(town) {
const r = town.buildings.rack_hall;

View file

@ -0,0 +1,40 @@
'use strict';
/*
* Cargo pickers shared by the trade and end game screens (window.CargoUI): one slider + stepper + number box per resource.
* The server decides everything (capacity per link, stock, links); this only keeps the numbers inside what the POP holds.
*/
(function () {
const { h } = UI;
const D = UpstreamData;
const num = (n) => App.fmt.num(n);
// One row: label, "/ have", slider, -/+ buttons, number box, "all". onChange(v) gets the clamped integer.
function pickRow(label, have, cur, onChange, sub) {
have = Math.max(0, Math.floor(have));
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'))));
}
// Pickers for fiber / hardware / capital writing into `cargo` ({res: n}, zero entries removed). have = { fiber, hardware, capital }.
function cargoPickers(cargo, have, onChange) {
return D.RESOURCES.map((r) => pickRow(App.resName(r), Math.floor(have[r] || 0), cargo[r] || 0, (v) => {
if (v > 0) cargo[r] = v; else delete cargo[r];
if (onChange) onChange();
}));
}
const cargoTotal = (cargo) => Object.keys(cargo).reduce((s, k) => s + (cargo[k] || 0), 0);
window.CargoUI = { pickRow, cargoPickers, cargoTotal };
}());

View file

@ -35,7 +35,7 @@
];
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')));
actions.push(h('button', { class: 'btn primary wide', type: 'button', 'data-keep': '', 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')));

View file

@ -115,6 +115,7 @@
isOwn: (t) => t.owner.id === ownOperatorId(),
movements: () => moveLines(),
threatened: (t) => App.mil.moves.incoming.some((m) => m.to && m.to.townId === t.id),
myAllianceId: () => (App.state.operator ? App.state.operator.allianceId : null),
};
view = new MapRender.MapView(canvas, source, {
onTap: onTap,
@ -152,6 +153,7 @@
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('backbone', App.t('map.legend.backbone')));
legendEl.appendChild(item('mv-out', App.t('map.legend.out')));
legendEl.appendChild(item('mv-in', App.t('map.legend.in')));
}
@ -187,22 +189,31 @@
body.push(h('div', { class: 'pill-row' }, h('span', { class: 'pill res-' + special.bonus }, icon(special.bonus), '+' + Math.round(F.ruralBonus * 100) + '% ' + App.resName(special.bonus))));
} else if (special && special.type === 'incumbent') {
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.incumbent') }));
} else if (special && special.type === 'backbone') {
const site = special.site || {};
const mine = !!(site.holder && site.holder.allianceId && site.holder.allianceId === (App.state.operator && App.state.operator.allianceId));
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.backbone', { max: site.maxLevel || UpstreamData.ENDGAME.maxLevel }) }));
body.push(h('div', { class: 'pill-row' },
site.holder ? h('span', { class: 'pill' + (mine ? ' accent' : '') }, '[' + site.holder.tag + '] ' + site.holder.name) : h('span', { class: 'pill dim', text: App.t('wld.incumbent') }),
h('span', { class: 'pill', text: App.t('wld.level', { n: site.level || 0, max: site.maxLevel || UpstreamData.ENDGAME.maxLevel }) })));
body.push(h('div', { class: 'bar wld-bar ' + (mine ? 'mine' : site.holder ? 'rival' : 'incumbent'), 'aria-hidden': 'true' }, (() => { const i = h('i'); i.style.setProperty('--p', String(site.maxLevel ? (site.level || 0) / site.maxLevel : 0)); return i; })()));
body.push(h('button', { class: 'btn wide', type: 'button', 'data-keep': '', onclick: () => { closeSheet(); App.go('world', { site: site.index }); } }, icon('b-backbone_node'), App.t('map.info.openWorld')));
} else if (!known) {
body.push(h('p', { class: 'detail-desc dimmer', text: App.t('map.scanning') }));
} else {
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
}
body.push(row('', App.t('map.info.coords', { x, y })));
if (App.openSend && App.state.towns.length && (town || (special && special.type === 'incumbent') || (!special && known))) {
if (App.openSend && App.state.towns.length && (town || (special && (special.type === 'incumbent' || (special.type === 'backbone' && !(special.site && special.site.holder && special.site.holder.allianceId === (App.state.operator && App.state.operator.allianceId))))) || (!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')));
body.push(h('button', { class: 'btn primary wide', type: 'button', 'data-keep': '', onclick: () => { closeSheet(); App.setTown(town.id); App.go('pop'); } }, icon('pop'), App.t('map.info.open')));
}
const title = town ? town.name : App.t('tile.' + type);
const title = town ? town.name : (type === 'backbone' && special.site && Number.isInteger(special.site.index) ? App.t('wld.site', { n: special.site.index + 1 }) : App.t('tile.' + type));
infoSheet = openSheet({
title, icon: town ? 'pop' : type === 'rural' ? 'fiber' : type === 'incumbent' ? 'b-core_router' : 'map', iconClass: special && special.type === 'rural' ? 'res-' + special.bonus : (town && town.owner.id === ownOperatorId() ? 'own' : ''),
title, icon: town ? 'pop' : type === 'rural' ? 'fiber' : type === 'incumbent' ? 'b-core_router' : type === 'backbone' ? 'b-backbone_node' : 'map', iconClass: special && special.type === 'rural' ? 'res-' + special.bonus : (town && town.owner.id === ownOperatorId() ? 'own' : ''),
closeLabel: App.t('common.close'), body: h('div', { class: 'detail' }, body),
onClose: () => { if (view) view.setSelected(null); infoSheet = null; },
});

View file

@ -32,10 +32,11 @@
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) }) }));
if (m.siteId) sub.push(h('span', { class: 'row-sub wrap', text: App.t('mov.siteShipment') })); // a shipment to a backbone landing site (POST /backbone/:id/ship)
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-ic' }, icon(m.siteId ? 'b-backbone_node' : (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)),

View file

@ -1,9 +1,11 @@
'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).
* (GET /reports/:id, then POST /reports/:id/read). Detail layouts exist for battle (raid/attack/takeover), landing (an attack on a backbone
* landing site), scan (also of a landing site), 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).
* Alliance folder: a report can be shared with your alliance (POST /reports/:id/share) and the "Alliance" tab lists the folder
* (GET /alliances/:id/reports). Shared reports have no recipient role and no read flag: they are told from nobody's side ("attacker won").
*/
(function () {
const { h, clear, icon, toast, openSheet } = UI;
@ -14,6 +16,11 @@
const PAGE = 25;
let box, listEl, moreBtn, statusEl, items = [], next = null, loading = false, visible = false, offAgo = null;
let tabsEl, markBtn, mode = 'mine'; // 'mine' | 'alliance' (the shared folder)
const folder = { items: [], next: null, loaded: false };
const allianceId = () => (App.state.operator ? App.state.operator.allianceId : null);
const curItems = () => (mode === 'alliance' ? folder.items : items);
const curNext = () => (mode === 'alliance' ? folder.next : next);
// ------------------------------------------------------------------ list rows
const nameOf = (o) => (o && o.name) || '?';
@ -22,16 +29,26 @@
// { icon, title, sub, tone } for the list
function describe(it) {
const s = it.summary || {};
const sharedItem = !it.role; // alliance folder: nobody's side
switch (it.type) {
case 'raid': case 'attack': case 'takeover': {
if (sharedItem) {
return { icon: Mil.TYPE_ICON[it.type], title: mil().reportTypeLabel(it.type) + ': ' + townOf(s.target), sub: App.t('rep.vs', { a: nameOf(s.attacker), d: nameOf(s.defender) }) + (s.captured ? ' · ' + App.t('rep.captured') : ''), tone: 'neutral', badge: App.t(s.outcome === 'attacker_won' ? 'rep.attackerWon' : 'rep.defenderWon') };
}
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 'landing': {
const site = s.site || {};
const taken = !!s.taken;
const res = sharedItem ? null : Mil.perspective(it.role, s.outcome);
return { icon: 'b-backbone_node', title: App.t('rep.landing.title', { n: Number.isInteger(site.index) ? site.index + 1 : '?' }), sub: sharedItem ? App.t('rep.by', { name: nameOf(s.attacker) }) + ' · ' + (taken ? App.t('rep.landing.taken') : App.t('rep.landing.held')) : (taken ? App.t('rep.landing.taken') : App.t('rep.landing.held')), tone: res === null ? 'neutral' : (res === 'victory' ? 'good' : 'bad'), badge: res === null ? null : App.t('rep.' + res) };
}
case 'scan': {
const where = s.target ? townOf(s.target) : (s.site ? s.site.x + ', ' + s.site.y : '?');
const where = s.target ? townOf(s.target) : (s.site ? (s.site.type === 'backbone' ? App.t('wld.site', { n: s.site.index + 1 }) : 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':
@ -58,23 +75,49 @@
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) },
const unread = it.read === false; // shared items have no read flag
const shared = mode === 'alliance';
return h('li', null, h('button', { class: 'alert rep tone-' + d.tone + (unread ? ' new' : ''), type: 'button', dataset: { id: String(it.id) }, onclick: () => openReport(it.id, shared) },
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: 'row-title' }, h('b', { text: d.title }), d.badge ? h('span', { class: 'pill ' + (d.tone === 'good' ? 'green' : 'amber'), text: d.badge }) : null, unread ? h('span', { class: 'pill accent', text: App.t('alerts.new') }) : null),
d.sub ? h('span', { class: 'row-sub', text: d.sub }) : null,
shared && it.sharedBy ? h('span', { class: 'row-sub', text: App.t('rep.sharedBy', { name: it.sharedBy.name }) }) : 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;
const list = curItems();
if (mode === 'alliance' && !allianceId()) { listEl.appendChild(h('li', null, h('p', { class: 'empty pad', text: App.t('rep.folder.none') }))); moreBtn.hidden = true; return; }
if (!list.length) { listEl.appendChild(h('li', null, h('p', { class: 'empty pad', text: loading || (mode === 'alliance' && !folder.loaded) ? App.t('common.loading') : App.t(mode === 'alliance' ? 'rep.folder.empty' : 'rep.empty') }))); }
for (const it of list) listEl.appendChild(row(it));
moreBtn.hidden = curNext() === null;
if (markBtn) markBtn.hidden = mode === 'alliance';
drawTabs();
}
function drawTabs() {
if (!tabsEl) return;
tabsEl.hidden = !allianceId();
clear(tabsEl);
for (const k of ['mine', 'alliance']) tabsEl.appendChild(h('button', { class: 'seg-btn', type: 'button', dataset: { tab: k }, 'aria-pressed': String(mode === k), onclick: () => { mode = k; draw(); load(false); } }, App.t(k === 'mine' ? 'rep.tab.mine' : 'rep.tab.alliance')));
}
async function load(more) {
if (loading) return;
if (mode === 'alliance') {
if (!allianceId()) { draw(); return; }
loading = true; statusEl.hidden = true;
try {
const r = await App.api.get('/alliances/' + allianceId() + '/reports', { limit: PAGE, after: more ? folder.next : undefined });
folder.items = more ? folder.items.concat(r.items.filter((x) => !folder.items.some((y) => y.id === x.id))) : r.items;
folder.next = r.next; folder.loaded = true;
} catch (e) { statusEl.textContent = e.code === 'forbidden' ? App.t('rep.folder.forbidden') : App.errMsg(e); statusEl.hidden = false; folder.loaded = true; }
finally { loading = false; }
draw();
return;
}
loading = true; statusEl.hidden = true;
try {
const r = await App.api.get('/reports', { limit: PAGE, after: more ? next : undefined });
@ -118,6 +161,7 @@
town ? mil().endLink(town) : null));
function verdict(role, outcome) {
if (!role) return h('div', { class: 'rep-verdict neutral' }, icon('report'), h('b', { text: App.t(outcome === 'attacker_won' ? 'rep.attackerWon' : 'rep.defenderWon') })); // shared: nobody's side
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) }));
}
@ -165,6 +209,14 @@
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 && d.site.type === 'backbone') { // end game landing site: the static defence is the number to beat
out.push(sec(App.t('rep.intel'),
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(intel.defence) })),
kv(App.t('wld.levelShort'), h('b', { class: 'mono', text: App.t('wld.level', { n: intel.level || 0, max: D.ENDGAME.maxLevel }) })),
kv(App.t('rep.landing.holder'), h('span', { text: intel.holder ? '[' + intel.holder.tag + '] ' + intel.holder.name : App.t('wld.incumbent') })),
intel.build ? kv(App.t('wld.building', { n: intel.build.toLevel }), h('span', { text: mil().dayTime(intel.build.dueAt) })) : null));
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) })),
@ -198,7 +250,7 @@
function incumbentBody(r) {
const d = r.data, out = [];
out.push(verdict('attacker', d.outcome));
out.push(verdict(r.role ? 'attacker' : null, 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) }))));
@ -207,12 +259,30 @@
return out;
}
function landingBody(r) {
const d = r.data, out = [];
const site = d.site || {};
out.push(verdict(r.role, d.outcome));
out.push(h('p', { class: 'row-sub', text: App.t('rep.arrived', { t: mil().dayTime(d.arrivedAt) }) }));
out.push(kv(App.t('rep.site'), h('span', { class: 'rep-party' }, h('b', { text: Number.isInteger(site.index) ? App.t('wld.site', { n: site.index + 1 }) : '?' }), mil().coordLink(site.x, site.y))));
out.push(kv(App.t('rep.landing.holder'), h('span', { text: site.holder ? '[' + site.holder.tag + '] ' + site.holder.name : App.t('wld.incumbent') })));
out.push(kv(App.t('wld.levelShort'), h('b', { class: 'mono', text: App.t('wld.level', { n: site.level || 0, max: D.ENDGAME.maxLevel }) })));
out.push(d.taken ? h('p', { class: 'good', text: App.t('rep.landing.takenLine', { tag: d.attacker && d.attacker.alliance ? '[' + d.attacker.alliance.tag + '] ' + d.attacker.alliance.name : '?' }) }) : h('p', { class: 'row-sub wrap', text: App.t('rep.landing.heldLine') }));
out.push(party(App.t('rep.attacker'), d.attacker.operator, d.origin));
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) }))));
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
out.push(h('button', { class: 'btn wide', type: 'button', 'data-keep': '', onclick: () => { UI.closeSheet(); App.go('world', Number.isInteger(site.index) ? { site: site.index } : null); } }, icon('b-backbone_node'), App.t('map.info.openWorld')));
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 () => {
if (r.shared) return out;
out.push(h('button', { class: 'btn primary wide', type: 'button', 'data-keep': '', 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');
@ -245,6 +315,7 @@
function bodyFor(r, ctl) {
switch (r.type) {
case 'raid': case 'attack': case 'takeover': return combatBody(r);
case 'landing': return landingBody(r);
case 'scan': return scanBody(r);
case 'scan_detected': return detectedBody(r);
case 'incumbent': return incumbentBody(r);
@ -256,19 +327,53 @@
}
// ------------------------------------------------------------------ detail sheet
async function openReport(id) {
function shareRow(r) {
const msg = h('p', { class: 'form-error', role: 'alert', hidden: true });
const btn = h('button', { class: 'btn', type: 'button', 'data-act': '' }, icon('users'), App.t('rep.share'));
btn.addEventListener('click', async () => {
btn.disabled = true; msg.hidden = true;
try {
const res = await App.api.post('/reports/' + r.id + '/share', {}, { intent: 'report-share:' + r.id });
toast(App.t(res.changed === false ? 'rep.share.already' : 'rep.share.done'), 'ok');
folder.loaded = false;
} catch (e) {
msg.textContent = e.code === 'forbidden' ? App.t('rep.share.forbidden') : App.errMsg(e); msg.hidden = false; btn.disabled = false;
}
});
return h('div', { class: 'rep-share' }, h('p', { class: 'row-sub wrap', text: App.t('rep.share.hint') }), btn, msg);
}
function unshareRow(r, ctl) {
const msg = h('p', { class: 'form-error', role: 'alert', hidden: true });
const btn = h('button', { class: 'btn danger', type: 'button' }, icon('x'), App.t('rep.unshare'));
btn.addEventListener('click', async () => {
btn.disabled = true; msg.hidden = true;
try {
await App.api.del('/reports/' + r.id + '/share');
toast(App.t('rep.unshare.done'), 'ok');
folder.items = folder.items.filter((x) => x.id !== r.id);
ctl.close(); if (visible) draw();
} catch (e) { msg.textContent = e.code === 'forbidden' ? App.t('rep.unshare.forbidden') : App.errMsg(e); msg.hidden = false; btn.disabled = false; }
});
return h('div', { class: 'rep-share' }, btn, msg);
}
async function openReport(id, shared) {
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 res = await App.api.get(shared ? '/alliances/' + allianceId() + '/reports/' + id : '/reports/' + id);
const r = res.report;
r.shared = !!shared;
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) }) }));
body.appendChild(h('p', { class: 'row-sub', text: mil().dayTime(r.createdAt) + ' · ' + (shared ? App.t('rep.sharedBy', { name: r.sharedBy ? r.sharedBy.name : '?' }) : 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) {
if (shared) body.appendChild(unshareRow(r, ctl));
else if (allianceId()) body.appendChild(shareRow(r));
if (!shared && !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();
@ -289,22 +394,26 @@
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'));
tabsEl = h('div', { class: 'seg rep-tabs', role: 'group', hidden: true });
markBtn = h('button', { class: 'btn small', type: 'button', onclick: markAll }, icon('check'), App.t('rep.markAll'));
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('div', { class: 'head-actions' }, markBtn,
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; });
tabsEl, statusEl, listEl, moreBtn));
App.on('session', () => { items = []; next = null; folder.items = []; folder.next = null; folder.loaded = false; mode = 'mine'; });
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');
markBtn.lastChild.textContent = App.t('rep.markAll');
if (params && params.tab === 'alliance' && allianceId()) mode = 'alliance';
if (mode === 'alliance' && !allianceId()) mode = 'mine';
draw();
load(false);
if (params && params.open) openReport(Number(params.open));
if (params && params.open) openReport(Number(params.open), false);
if (offAgo) offAgo();
offAgo = App.onTick(() => {
const now = App.now();

View file

@ -84,7 +84,7 @@
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 });
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, transportOnly: opts.type === 'transport' });
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);
@ -126,8 +126,14 @@
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)));
const bb = t.type === 'backbone' ? (t.backbone || {}) : null; // end game landing site
if (bb) {
if (bb.holder) pills.push(h('span', { class: 'pill' + (bb.mine ? ' accent' : '') }, '[' + bb.holder.tag + '] ' + bb.holder.name));
else pills.push(h('span', { class: 'pill dim', text: App.t('wld.incumbent') }));
pills.push(h('span', { class: 'pill', text: App.t('wld.level', { n: bb.level || 0, max: bb.maxLevel || D.ENDGAME.maxLevel }) }));
}
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)),
h('div', { class: 'row' }, h('b', { text: t.town ? t.town.name : (bb && Number.isInteger(bb.index) ? App.t('wld.site', { n: bb.index + 1 }) : 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)));
}
@ -283,6 +289,8 @@
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 (st.tile.type === 'backbone' && (type === 'attack' || type === 'scan')) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.landing.hint', { mult: D.ENDGAME.defenceMult }) }));
if (type === 'transport' && st.tile.town && !st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.transport.rival') }));
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') }));

503
public/js/screens/trade.js Normal file
View file

@ -0,0 +1,503 @@
'use strict';
/*
* Internet exchange: trade offers and direct transports (More > Exchange). Four tabs:
* offers open offers of other operators that one of your exchanges can reach (GET /trade/offers), filters for what they give / want,
* "Take" opens a sheet with the POPs that may accept (acceptableFrom) and what each one would pay
* new post an offer (POST /trade/offers): terms checked live with rules.tradeTermsCheck (1:2 band, per-link capacity, distance)
* mine offers you posted or took (GET /trade/offers/mine), cancel (DELETE), expiry countdowns
* send direct transport to one of your POPs or to any POP by coordinates (the send dialog in transport mode) + the links in use
* Needs an Internet exchange (level 1+). Without one every tab but "mine" shows what is required. The server re-validates everything and
* its error codes are translated; player-controlled strings (operator and POP names) are set with textContent only.
*/
(function () {
const { h, clear, icon, toast, openSheet } = UI;
const R = UpstreamRules;
const D = UpstreamData;
const T = D.TRADE;
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);
const EXCH = D.TRANSPORT.building;
const TABS = ['offers', 'new', 'mine', 'send'];
const PAGE = 25;
let box, tabsEl, bodyEl, visible = false, offTick = null;
let tab = 'offers', gen = 0;
const S = {
levels: null, // [{ townId, level, reach }] of my POPs with an exchange, from GET /trade/offers
filter: { give: '', want: '', townId: 0 },
offers: { items: [], next: null, loaded: false, loading: false, err: null },
mine: { items: [], next: null, loaded: false, loading: false, err: null, status: '' },
form: null, // the "new offer" draft, kept while you switch tabs
send: { fromId: 0, x: '', y: '' },
};
const townName = (id) => mil().townName(id) || '#' + id;
const speed = () => (App.state.world ? App.state.world.speed : 1);
const hasExchange = () => !!(S.levels && S.levels.length);
const levelOf = (townId) => { const l = (S.levels || []).find((x) => x.townId === townId); return l ? l.level : 0; };
const chip = (res, amount, signed) => h('span', { class: 'cost ' + res }, icon(res), h('b', { text: (signed || '') + num(amount) }), h('small', { text: App.resName(res) }));
const amountChip = (a, signed) => chip(a.resource, a.amount, signed);
const sel = (opts, value, onchange, label) => h('select', { 'aria-label': label, onchange: (e) => onchange(e.target.value) }, opts.map((o) => h('option', { value: o.value, selected: String(o.value) === String(value), text: o.text })));
const resOptions = (any) => (any ? [{ value: '', text: App.t('trd.any') }] : []).concat(D.RESOURCES.map((r) => ({ value: r, text: App.resName(r) })));
function errText(e) {
const d = e.details || {};
if (e.code === 'trade_out_of_range') return App.t('trd.err.range', { d: App.fmt.dec(d.distance || 0), max: d.maxDistance || 0, reach: d.reach || 0 });
if (e.code === 'trade_ratio') return App.t('trd.err.ratio', { n: T.ratioMax });
if (e.code === 'capacity_exceeded') return App.t('trd.err.cap', { n: D.TRANSPORT.capacityPerLink });
return App.errMsg(e);
}
// ------------------------------------------------------------------ POP info (stock + links), cached for a few seconds
const infos = new Map();
async function townInfo(id, force) {
const c = infos.get(id);
if (!force && c && Date.now() - c.at < 8000) return c;
const x = await mil().loadTown(id);
const rec = { at: Date.now(), id, td: x.town, rt: App.rulesTownFrom(x.town, x.serverTime) };
infos.set(id, rec);
return rec;
}
const stock = (rec) => R.resourcesAt(rec.rt, App.now()).amounts;
const linkState = (rec) => { const t = rec.td.military.transport; return { links: t.links, active: t.active, free: Math.max(0, t.links - t.active) }; };
// ------------------------------------------------------------------ loading
async function loadLevels() {
const r = await App.api.get('/trade/offers', { limit: 1 });
S.levels = r.exchangeLevels || [];
if (S.filter.townId && !levelOf(S.filter.townId)) S.filter.townId = 0;
}
async function loadOffers(more) {
const o = S.offers;
if (o.loading) return;
o.loading = true; o.err = null;
try {
const q = { limit: PAGE };
if (S.filter.give) q.give = S.filter.give;
if (S.filter.want) q.want = S.filter.want;
if (S.filter.townId) q.townId = S.filter.townId;
if (more && o.next) q.after = o.next;
const r = await App.api.get('/trade/offers', q);
o.items = more ? o.items.concat(r.items.filter((x) => !o.items.some((y) => y.id === x.id))) : r.items;
o.next = r.next; o.loaded = true;
if (!S.filter.townId) S.levels = r.exchangeLevels || [];
} catch (e) { o.err = e; } finally {
o.loading = false;
if (visible && tab === 'offers') drawBody();
}
}
async function loadMine(more) {
const m = S.mine;
if (m.loading) return;
m.loading = true; m.err = null;
try {
const q = { limit: PAGE };
if (m.status) q.status = m.status;
if (more && m.next) q.after = m.next;
const r = await App.api.get('/trade/offers/mine', q);
m.items = more ? m.items.concat(r.items.filter((x) => !m.items.some((y) => y.id === x.id))) : r.items;
m.next = r.next; m.loaded = true;
} catch (e) { m.err = e; } finally {
m.loading = false;
if (visible && tab === 'mine') drawBody();
}
}
function reloadAll() {
infos.clear();
loadLevels().catch(() => {}).then(() => { if (visible) drawBody(); });
loadOffers(false); loadMine(false);
}
// ------------------------------------------------------------------ pieces
function needExchange() {
const req = (D.BUILDINGS[EXCH].requires || []).map((r) => App.t('trd.need.req', { building: App.buildingName(r.type), level: r.level })).join(' ');
return h('section', { class: 'card trd-need' },
h('div', { class: 'card-head' }, h('h2', null, icon('b-' + EXCH), App.t('trd.need.title'))),
h('p', { class: 'detail-desc', text: App.t('trd.need.body', { n: T.reachPerLevel, cap: D.TRANSPORT.capacityPerLink }) }),
h('p', { class: 'row-sub wrap', text: req }),
h('button', { class: 'btn primary wide', type: 'button', onclick: () => App.go('pop') }, icon('pop'), App.t('trd.need.go')));
}
function reachPills() {
return h('div', { class: 'pill-row trd-reach' }, (S.levels || []).map((l) => h('span', { class: 'pill', title: App.t('trd.reach.title') },
icon('b-' + EXCH), townName(l.townId) + ' · ' + App.t('trd.reach', { lv: l.level, n: l.reach }))));
}
function statusPill(status) {
const cls = { open: 'accent', accepted: 'amber', completed: 'green' }[status] || 'dim';
return h('span', { class: 'pill ' + cls, text: App.t('trd.status.' + status) });
}
// ------------------------------------------------------------------ tab: offers
function drawOffers(into) {
const o = S.offers;
if (!hasExchange()) { into.appendChild(needExchange()); return; }
const filters = h('div', { class: 'trd-filters' },
h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('trd.f.give') }), sel(resOptions(true), S.filter.give, (v) => { S.filter.give = v; loadOffers(false); }, App.t('trd.f.give'))),
h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('trd.f.want') }), sel(resOptions(true), S.filter.want, (v) => { S.filter.want = v; loadOffers(false); }, App.t('trd.f.want'))),
S.levels.length > 1 ? h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('trd.f.from') }),
sel([{ value: 0, text: App.t('trd.f.allPops') }].concat(S.levels.map((l) => ({ value: l.townId, text: townName(l.townId) }))), S.filter.townId, (v) => { S.filter.townId = Number(v); loadOffers(false); }, App.t('trd.f.from'))) : null);
into.appendChild(h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', null, icon('swap'), App.t('trd.offers.head'))), reachPills(), filters));
if (o.err) into.appendChild(h('div', { class: 'soc-err' }, h('p', { class: 'form-error', role: 'alert', text: errText(o.err) }), h('button', { class: 'btn small', type: 'button', onclick: () => loadOffers(false) }, icon('refresh'), App.t('common.retry'))));
if (!o.loaded) { into.appendChild(h('p', { class: 'empty', text: App.t('common.loading') })); return; }
if (!o.items.length) {
into.appendChild(h('div', { class: 'card trd-empty' }, h('p', { class: 'empty', text: S.filter.give || S.filter.want ? App.t('trd.offers.emptyFiltered') : App.t('trd.offers.empty') }),
h('button', { class: 'btn wide', type: 'button', onclick: () => setTab('new') }, icon('plus'), App.t('trd.offers.post'))));
return;
}
into.appendChild(h('ul', { class: 'mil-list trd-list' }, o.items.map(openRow)));
if (o.next) into.appendChild(h('button', { class: 'btn wide', type: 'button', disabled: o.loading, onclick: () => loadOffers(true) }, App.t('trd.more')));
}
function terms(get, pay) {
return h('div', { class: 'trd-terms' },
h('div', { class: 'trd-term' }, h('span', { class: 'trd-lbl', text: App.t('trd.get') }), amountChip(get)),
h('div', { class: 'trd-term' }, h('span', { class: 'trd-lbl', text: App.t('trd.pay') }), amountChip(pay)));
}
function openRow(o) {
const near = o.acceptableFrom && o.acceptableFrom.length ? Math.min.apply(null, o.acceptableFrom.map((a) => a.distance)) : null;
return h('li', { class: 'mil-row trd-offer', dataset: { id: String(o.id) } },
h('span', { class: 'row-ic' }, icon('swap')),
h('span', { class: 'row-main' },
terms(o.give, o.want),
h('span', { class: 'row-sub wrap' }, h('span', { text: o.operator.name + (o.townName ? ' · ' + o.townName : '') + ' ' }), o.x !== null && o.x !== undefined ? mil().coordLink(o.x, o.y) : null,
near !== null ? h('span', { text: ' · ' + App.t('trd.away', { d: App.fmt.dec(near) }) }) : null),
h('span', { class: 'row-sub wrap' }, App.t('trd.maxDist', { n: o.maxDistance }) + ' · ' + App.t('trd.expiresIn') + ' ', mil().countdown(o.expiresAt))),
h('button', { class: 'btn small primary', type: 'button', onclick: () => openAccept(o) }, App.t('trd.take')));
}
// The accept sheet: which of my POPs takes the offer.
async function openAccept(o) {
const body = h('div', { class: 'detail trd-accept' });
const sheet = openSheet({ title: App.t('trd.accept.title'), icon: 'swap', closeLabel: App.t('common.close'), body });
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
const list = h('div', { class: 'trd-pops' }, h('p', { class: 'empty', text: App.t('common.loading') }));
const errEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
const go = h('button', { class: 'btn primary wide', type: 'button', disabled: true }, icon('check'), App.t('trd.accept.go'));
body.appendChild(h('div', null, kv(App.t('trd.get'), amountChip(o.give)), kv(App.t('trd.pay'), amountChip(o.want)),
kv(App.t('trd.from'), h('span', null, o.operator.name + (o.townName ? ' · ' + o.townName : ''))), kv(App.t('trd.expiresIn'), mil().countdown(o.expiresAt))));
body.appendChild(h('h3', { class: 'sub', text: App.t('trd.accept.with') }));
body.appendChild(list); body.appendChild(errEl); body.appendChild(h('div', { class: 'send-foot' }, go));
let chosen = 0, busy = false, intent = 'trade-accept:' + o.id + ':' + nonce();
try {
const cands = (o.acceptableFrom || []).slice().sort((a, b) => a.distance - b.distance);
const recs = await Promise.all(cands.map((c) => townInfo(c.townId, true).catch(() => null)));
clear(list);
if (!cands.length) list.appendChild(h('p', { class: 'reason', text: App.t('trd.accept.nopop') }));
cands.forEach((c, i) => {
const rec = recs[i];
let why = '';
if (!rec) why = App.t('err.unknown');
else {
const have = stock(rec)[o.want.resource], ls = linkState(rec);
if (have + 1e-6 < o.want.amount) why = App.t('trd.accept.short', { res: App.resName(o.want.resource), have: num(have) });
else if (!ls.free) why = App.t('trd.accept.nolink');
}
const radio = h('input', { type: 'radio', name: 'trd-pop', value: String(c.townId), disabled: !!why, onchange: () => { chosen = c.townId; go.disabled = busy; } });
list.appendChild(h('label', { class: 'trd-pop' + (why ? ' off' : '') }, radio,
h('span', { class: 'row-main' },
h('b', { text: townName(c.townId) }),
h('span', { class: 'row-sub wrap', text: App.t('trd.away', { d: App.fmt.dec(c.distance) }) + ' · ' + App.t('trd.latency', { t: App.fmt.dur(R.transportMs(c.distance, speed())) }) + (rec ? ' · ' + App.t('trd.have', { n: num(stock(rec)[o.want.resource]), res: App.resName(o.want.resource) }) : '') }),
why ? h('span', { class: 'reason', text: why }) : null)));
if (!why && !chosen) { radio.checked = true; chosen = c.townId; go.disabled = false; }
});
} catch (e) { clear(list); list.appendChild(h('p', { class: 'form-error', text: errText(e) })); }
go.addEventListener('click', async () => {
if (!chosen || busy) return;
busy = true; go.disabled = true; errEl.hidden = true;
try {
const r = await App.api.post('/trade/offers/' + o.id + '/accept', { townId: chosen }, { intent: intent });
toast(App.t('trd.accept.done', { t: App.fmt.dur(r.arriveAt - App.now()) }), 'ok');
sheet.close();
infos.clear();
App.refreshTown().catch(() => {}); App.refreshMovements().catch(() => {});
loadOffers(false); loadMine(false);
} catch (e) {
busy = false; go.disabled = false;
errEl.textContent = errText(e); errEl.hidden = false;
if (e.code === 'offer_closed' || e.code === 'not_found') { loadOffers(false); go.disabled = true; }
intent = 'trade-accept:' + o.id + ':' + nonce();
}
});
}
// ------------------------------------------------------------------ tab: new offer
function newForm() {
if (S.form) return S.form;
const first = (S.levels || [])[0];
S.form = { townId: first ? first.townId : 0, giveRes: 'fiber', giveAmount: 100, wantRes: 'hardware', wantAmount: 100, maxDistance: null, touchedDist: false, nonce: nonce() };
return S.form;
}
function drawNew(into) {
if (!hasExchange()) { into.appendChild(needExchange()); return; }
const F = newForm();
if (!levelOf(F.townId)) F.townId = S.levels[0].townId;
const defaultDist = () => Math.min(T.maxDistance, Math.max(1, (S.levels.find((l) => l.townId === F.townId) || { reach: 10 }).reach));
if (F.maxDistance === null) F.maxDistance = defaultDist();
let rec = null;
const msgs = h('div', { class: 'trd-msgs', role: 'status' });
const note = h('div', { class: 'trd-note' });
const bandEl = h('p', { class: 'field-hint' });
const stockEl = h('span', { class: 'dimmer' });
const submit = h('button', { class: 'btn primary wide', type: 'button', onclick: () => post() }, icon('swap'), App.t('trd.new.go'));
const errEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
const numField = (key, label, min, max) => {
const input = h('input', { type: 'number', inputmode: 'numeric', class: 'mil-num', min: String(min), max: String(max), value: F[key] === null ? '' : String(F[key]), 'aria-label': label });
input.addEventListener('input', () => { F[key] = input.value === '' ? 0 : Math.floor(Number(input.value)) || 0; if (key === 'maxDistance') F.touchedDist = true; refresh(); });
return input;
};
const giveIn = numField('giveAmount', App.t('trd.new.giveAmount'), 1, D.TRANSPORT.capacityPerLink);
const wantIn = numField('wantAmount', App.t('trd.new.wantAmount'), 1, D.TRANSPORT.capacityPerLink);
const distIn = numField('maxDistance', App.t('trd.new.maxDist'), 1, T.maxDistance);
const maxBtn = h('button', { class: 'btn small', type: 'button', onclick: () => { const have = rec ? Math.floor(stock(rec)[F.giveRes]) : 0; F.giveAmount = Math.max(1, Math.min(D.TRANSPORT.capacityPerLink, have)); giveIn.value = String(F.giveAmount); refresh(); } }, App.t('send.all'));
const matchBtn = h('button', { class: 'btn small', type: 'button', onclick: () => { F.wantAmount = F.giveAmount; wantIn.value = String(F.wantAmount); refresh(); } }, App.t('trd.new.match'));
function validate() {
const out = [];
const chk = R.tradeTermsCheck({ giveRes: F.giveRes, giveAmount: F.giveAmount, wantRes: F.wantRes, wantAmount: F.wantAmount, maxDistance: F.maxDistance });
if (!chk.ok) {
if (chk.code === 'trade_ratio') out.push(App.t('trd.err.ratio', { n: T.ratioMax }));
else if (chk.code === 'capacity_exceeded') out.push(App.t('trd.err.cap', { n: D.TRANSPORT.capacityPerLink }));
else out.push(App.t('trd.v.' + ((chk.errors && chk.errors[0] && chk.errors[0].path) || 'terms')));
}
if (rec) {
const have = stock(rec)[F.giveRes];
if (have + 1e-6 < F.giveAmount) out.push(App.t('trd.v.have', { res: App.resName(F.giveRes), have: num(have) }));
if (!linkState(rec).free) out.push(App.t('trd.v.links'));
}
return out;
}
function refresh() {
const lv = levelOf(F.townId), reach = (S.levels.find((l) => l.townId === F.townId) || {}).reach || 0;
const problems = validate();
clear(msgs);
for (const p of problems) msgs.appendChild(h('p', { class: 'reason', text: p }));
submit.disabled = problems.length > 0 || !rec;
if (F.giveAmount >= 1) {
const lo = Math.max(1, Math.ceil(F.giveAmount / T.ratioMax)), hi = Math.min(D.TRANSPORT.capacityPerLink, F.giveAmount * T.ratioMax);
bandEl.textContent = App.t('trd.new.band', { lo: num(lo), hi: num(hi) });
} else bandEl.textContent = '';
stockEl.textContent = rec ? App.t('trd.have', { n: num(stock(rec)[F.giveRes]), res: App.resName(F.giveRes) }) : '';
clear(note);
const need = Math.max(1, Math.ceil((F.maxDistance || 1) / T.reachPerLevel));
note.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.new.level', { lv, reach, need, d: F.maxDistance || 0 }) }));
note.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.new.rules', { cap: D.TRANSPORT.capacityPerLink, n: T.ratioMax, ttl: App.fmt.dur(T.ttlHours * D.HOUR_MS / speed()) }) }));
if (rec) { const ls = linkState(rec); note.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.new.links', { free: ls.free, links: ls.links }) })); }
}
async function loadRec() {
rec = null; refresh();
try { rec = await townInfo(F.townId); } catch (e) { rec = null; }
refresh();
}
async function post() {
if (submit.disabled) return;
submit.disabled = true; errEl.hidden = true;
try {
await App.api.post('/trade/offers', { townId: F.townId, giveRes: F.giveRes, giveAmount: F.giveAmount, wantRes: F.wantRes, wantAmount: F.wantAmount, maxDistance: F.maxDistance }, { intent: 'trade-offer:' + F.nonce });
F.nonce = nonce();
toast(App.t('trd.new.done'), 'ok');
infos.clear();
App.refreshTown().catch(() => {});
S.mine.status = ''; loadMine(false);
setTab('mine');
} catch (e) {
errEl.textContent = errText(e); errEl.hidden = false;
if (e.code !== 'network_error') F.nonce = nonce();
loadRec();
}
}
const otherRes = (r) => D.RESOURCES.find((x) => x !== r);
const giveResSel = sel(resOptions(false), F.giveRes, (v) => { F.giveRes = v; if (F.wantRes === v) { F.wantRes = otherRes(v); wantResSel.value = F.wantRes; } refresh(); }, App.t('trd.new.giveRes'));
const wantResSel = sel(resOptions(false), F.wantRes, (v) => { F.wantRes = v; if (F.giveRes === v) { F.giveRes = otherRes(v); giveResSel.value = F.giveRes; } refresh(); }, App.t('trd.new.wantRes'));
const popField = S.levels.length > 1
? h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('trd.new.pop') }),
sel(S.levels.map((l) => ({ value: l.townId, text: townName(l.townId) + ' · ' + App.t('trd.reach', { lv: l.level, n: l.reach }) })), F.townId, (v) => { F.townId = Number(v); if (!F.touchedDist) { F.maxDistance = defaultDist(); distIn.value = String(F.maxDistance); } loadRec(); }, App.t('trd.new.pop')))
: h('p', { class: 'row-sub wrap', text: townName(F.townId) });
into.appendChild(h('section', { class: 'card trd-form' },
h('div', { class: 'card-head' }, h('h2', null, icon('plus'), App.t('trd.new.head'))),
popField,
h('h3', { class: 'sub', text: App.t('trd.new.give') }),
h('div', { class: 'trd-pair' }, giveResSel, giveIn, maxBtn),
stockEl,
h('h3', { class: 'sub', text: App.t('trd.new.want') }),
h('div', { class: 'trd-pair' }, wantResSel, wantIn, matchBtn),
bandEl,
h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('trd.new.maxDist') }), distIn, h('span', { class: 'field-hint', text: App.t('trd.new.maxDistHint', { max: T.maxDistance }) })),
note, msgs, errEl, h('div', { class: 'send-foot' }, submit)));
loadRec();
}
// ------------------------------------------------------------------ tab: mine
function mineRow(o) {
const poster = o.role === 'poster';
const get = poster ? o.want : o.give, pay = poster ? o.give : o.want;
const open = o.status === 'open';
const cancel = open && poster ? h('button', { class: 'btn small danger', type: 'button', onclick: (ev) => cancelOffer(o, ev.currentTarget) }, icon('x'), App.t('trd.cancel')) : null;
return h('li', { class: 'mil-row trd-offer', dataset: { id: String(o.id), status: o.status } },
h('span', { class: 'row-ic' }, icon('swap')),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: App.t('trd.role.' + o.role) }), statusPill(o.status)),
terms(get, pay),
h('span', { class: 'row-sub wrap' }, o.townName ? h('span', { text: o.townName + ' ' }) : null, o.x !== null && o.x !== undefined ? mil().coordLink(o.x, o.y) : null, h('span', { text: ' · ' + App.t('trd.maxDist', { n: o.maxDistance }) })),
open ? h('span', { class: 'row-sub wrap' }, App.t('trd.expiresIn') + ' ', mil().countdown(o.expiresAt)) : null,
o.status === 'accepted' ? h('span', { class: 'row-sub wrap', text: App.t('trd.settles') }) : null,
o.status === 'void' ? h('span', { class: 'row-sub wrap', text: App.t('trd.voidHint') }) : null,
h('span', { class: 'row-sub', text: App.fmt.ago(App.now() - (o.closedAt || o.acceptedAt || o.createdAt)) })),
cancel);
}
async function cancelOffer(o, btn) {
btn.disabled = true;
try {
const r = await App.api.del('/trade/offers/' + o.id, { intent: 'trade-cancel:' + o.id });
toast(App.t('trd.cancelled', { what: r.returned ? num(r.returned.amount) + ' ' + App.resName(r.returned.resource) : '' }), 'ok');
infos.clear();
App.refreshTown().catch(() => {});
loadMine(false); loadOffers(false);
} catch (e) {
toast(errText(e), 'error');
if (e.code === 'offer_closed') loadMine(false);
btn.disabled = false;
}
}
function drawMine(into) {
const m = S.mine;
const chips = ['', 'open', 'accepted', 'completed'].map((s) => h('button', { class: 'chip-btn', type: 'button', 'aria-pressed': String(m.status === s), onclick: () => { m.status = s; m.loaded = false; drawBody(); loadMine(false); } }, App.t(s ? 'trd.status.' + s : 'trd.status.all')));
into.appendChild(h('div', { class: 'soc-subtabs trd-chips' }, chips));
if (m.err) into.appendChild(h('p', { class: 'form-error', role: 'alert', text: errText(m.err) }));
if (!m.loaded) { into.appendChild(h('p', { class: 'empty', text: App.t('common.loading') })); return; }
if (!m.items.length) { into.appendChild(h('p', { class: 'empty pad', text: App.t('trd.mine.empty') })); return; }
into.appendChild(h('ul', { class: 'mil-list trd-list' }, m.items.map(mineRow)));
if (m.next) into.appendChild(h('button', { class: 'btn wide', type: 'button', disabled: m.loading, onclick: () => loadMine(true) }, App.t('trd.more')));
}
// ------------------------------------------------------------------ tab: direct transport + links in use
function drawSend(into) {
if (!hasExchange()) { into.appendChild(needExchange()); return; }
const sd = S.send;
if (!levelOf(sd.fromId)) sd.fromId = S.levels[0].townId;
const own = App.state.towns;
const xin = h('input', { type: 'number', inputmode: 'numeric', class: 'mil-num', 'aria-label': 'x', placeholder: 'x', value: String(sd.x) });
const yin = h('input', { type: 'number', inputmode: 'numeric', class: 'mil-num', 'aria-label': 'y', placeholder: 'y', value: String(sd.y) });
xin.addEventListener('input', () => { sd.x = xin.value; }); yin.addEventListener('input', () => { sd.y = yin.value; });
const open = (x, y) => { if (App.openSend) App.openSend({ x, y, fromTownId: sd.fromId, type: 'transport' }); };
const lookup = () => { if (xin.value === '' || yin.value === '') return; open(Math.round(Number(xin.value)), Math.round(Number(yin.value))); };
into.appendChild(h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('box'), App.t('trd.send.head'))),
h('p', { class: 'detail-desc', text: App.t('trd.send.body', { n: D.TRANSPORT.capacityPerLink }) }),
S.levels.length > 1 ? h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.from') }),
sel(S.levels.map((l) => ({ value: l.townId, text: townName(l.townId) })), sd.fromId, (v) => { sd.fromId = Number(v); }, App.t('send.from'))) : h('p', { class: 'row-sub', text: App.t('send.from') + ': ' + townName(sd.fromId) }),
h('h3', { class: 'sub', text: App.t('trd.send.own') }),
own.filter((t) => t.id !== sd.fromId).length ? h('div', { class: 'chips' }, own.filter((t) => t.id !== sd.fromId).map((t) => h('button', { class: 'chip-btn', type: 'button', onclick: () => open(t.x, t.y) }, t.name))) : h('p', { class: 'row-sub', text: App.t('trd.send.noOwn') }),
h('h3', { class: 'sub', text: App.t('trd.send.coords') }),
h('div', { class: 'send-coords' }, h('span', { class: 'mono', text: 'x' }), xin, h('span', { class: 'mono', text: 'y' }), yin, h('button', { class: 'btn small primary', type: 'button', onclick: lookup }, icon('locate'), App.t('send.lookup'))),
h('p', { class: 'row-sub wrap', text: App.t('trd.send.warn') })));
// links in use
const wrap = h('section', { class: 'card trd-links' }, h('div', { class: 'card-head' }, h('h2', null, icon('b-' + EXCH), App.t('trd.links.head'))), h('p', { class: 'empty', text: App.t('common.loading') }));
into.appendChild(wrap);
const my = gen;
Promise.all(S.levels.map((l) => townInfo(l.townId, true).catch(() => null))).then((recs) => {
if (my !== gen || tab !== 'send' || !wrap.isConnected) return;
clear(wrap);
wrap.appendChild(h('div', { class: 'card-head' }, h('h2', null, icon('b-' + EXCH), App.t('trd.links.head'))));
const rows = h('ul', { class: 'mil-list' });
S.levels.forEach((l, i) => {
const rec = recs[i]; if (!rec) return;
const ls = linkState(rec);
const bar = h('span', { class: 'bar', 'aria-hidden': 'true' }, h('i'));
bar.firstChild.style.setProperty('--p', String(ls.links ? ls.active / ls.links : 0));
rows.appendChild(h('li', { class: 'mil-row' }, h('span', { class: 'row-ic' }, icon('swap')),
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: townName(l.townId) })),
h('span', { class: 'row-sub wrap', text: App.t('trd.links.used', { a: ls.active, n: ls.links, free: ls.free, cap: num(rec.td.military.transport.capacityPerLink) }) }), bar)));
});
wrap.appendChild(rows);
wrap.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.links.hint') }));
const tx = (mil().moves.outgoing || []).filter((m) => m.type === 'transport');
if (tx.length) {
wrap.appendChild(h('h3', { class: 'sub', text: App.t('trd.links.active') }));
wrap.appendChild(h('ul', { class: 'mil-list' }, tx.map((m) => h('li', { class: 'mil-row' }, h('span', { class: 'row-ic' }, icon('box')),
h('span', { class: 'row-main' }, h('span', { class: 'row-sub wrap' }, mil().endLink(m.from), h('span', { class: 'arrow', 'aria-hidden': 'true' }, icon('move')), mil().endLink(m.to)), mil().resChips(m.cargo)),
h('span', { class: 'mil-when' }, mil().countdown(m.arriveAt))))));
}
});
}
// ------------------------------------------------------------------ screen
function drawTabs() {
clear(tabsEl);
for (const k of TABS) {
tabsEl.appendChild(h('button', { class: 'seg-btn', type: 'button', dataset: { tab: k }, 'aria-pressed': String(tab === k), onclick: () => setTab(k) }, App.t('trd.tab.' + k)));
}
}
function drawBody() {
if (!bodyEl) return;
const top = box.scrollTop;
clear(bodyEl);
if (tab === 'offers') drawOffers(bodyEl);
else if (tab === 'new') drawNew(bodyEl);
else if (tab === 'mine') drawMine(bodyEl);
else drawSend(bodyEl);
box.scrollTop = top;
}
function setTab(k) {
if (!TABS.includes(k)) k = 'offers';
tab = k; gen++;
drawTabs(); drawBody();
if (k === 'offers' && !S.offers.loaded) loadOffers(false);
if (k === 'mine') loadMine(false);
}
App.registerScreen({
id: 'trade', titleKey: 'screen.trade', navKey: 'nav.trade', icon: 'swap', hud: false, navGroup: 'more',
render(container) {
box = container;
tabsEl = h('div', { class: 'seg trd-tabs', role: 'group', 'aria-label': App.t('screen.trade') });
bodyEl = h('div', { class: 'trd-body' });
box.appendChild(h('div', { class: 'page trd-page' },
h('div', { class: 'card-head page-head' }, h('h1', { id: 'trd-h', text: App.t('screen.trade') }),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => reloadAll() }, icon('refresh'))),
tabsEl, bodyEl));
App.on('session', () => { S.levels = null; S.offers = { items: [], next: null, loaded: false, loading: false, err: null }; S.mine = { items: [], next: null, loaded: false, loading: false, err: null, status: '' }; S.form = null; infos.clear(); });
App.on('movements', () => { if (visible && tab === 'send') drawBody(); });
App.api.on('push', (msg) => {
if (!visible || !msg || msg.type !== 'notification' || !/^trade_/.test(msg.kind || '')) return;
infos.clear(); loadMine(false); loadOffers(false);
});
},
onShow(params) {
visible = true;
document.getElementById('trd-h').textContent = App.t('screen.trade');
const want = params && params.tab && TABS.includes(params.tab) ? params.tab : tab;
S.form = S.form && S.form.townId && !levelOf(S.form.townId) && S.levels ? null : S.form;
tab = want; gen++;
drawTabs(); drawBody();
loadLevels().catch(() => {}).then(() => { if (visible) { drawBody(); } });
loadOffers(false); loadMine(false);
if (offTick) offTick();
let last = 0;
offTick = App.onTick((now) => {
if (now - last < 4000) return;
last = now;
const stale = (list) => list.some((o) => o.status === 'open' && o.expiresAt < now - 1500);
if ((tab === 'offers' && stale(S.offers.items.map((o) => Object.assign({ status: 'open' }, o)))) && !S.offers.loading) loadOffers(false);
if (tab === 'mine' && stale(S.mine.items) && !S.mine.loading) loadMine(false);
});
},
onHide() { visible = false; gen++; if (offTick) offTick(); offTick = null; },
onLang() { drawTabs(); document.getElementById('trd-h').textContent = App.t('screen.trade'); drawBody(); },
});
}());

412
public/js/screens/world.js Normal file
View file

@ -0,0 +1,412 @@
'use strict';
/*
* The end game: the Backbone race (More > Backbone) and the read-only state of an ended world.
*
* Screen: GET /worlds/:id/status -> phase (running | backbone_open | ended), a countdown to the day the 7 landing sites appear, the sites with
* holder / node level / build progress, the leading alliance, the winner banner; when the world has ended GET /worlds/:id/results -> final ranking.
* Sites your alliance holds open a "manage" sheet (GET /backbone/:id): the stockpile, build the next node level (POST /backbone/:id/build), ship
* resources from a POP (POST /backbone/:id/ship, a transport) and the contribution ledger. Other sites: scan or attack through the send dialog.
*
* Also here (loaded at start-up, whether or not the screen is ever opened): the ended-world mode of the whole client. Once the world has ended
* (`/me` says so, the `world_ended` notification arrives, or any command answers `world_ended`) the page gets `data-ended`, a pill in the top bar,
* a card on the POP screen, and every action button (primary / danger buttons, `[data-act]`) is disabled with an explanation. Reading, messages and
* navigation keep working; the server refuses everything else with `world_ended` anyway, so this only makes that graceful.
*/
(function () {
const { h, clear, icon, toast, openSheet } = UI;
const R = UpstreamRules;
const D = UpstreamData;
const E = UpstreamEnd;
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);
const worldId = () => (App.state.world ? App.state.world.id : 0);
const myAllianceId = () => (App.state.operator ? App.state.operator.allianceId : null);
const speed = () => (App.state.world ? App.state.world.speed : 1);
// ================================================================== ended-world mode (whole client)
let lockObserver = null, lockQueued = false;
const LOCK_SEL = 'button.btn.primary, button.btn.danger, button[data-act]';
const LOCK_SKIP = '.screen-auth, .screen-settings, .screen-messages, .screen-rankings, .soc-composer, .boot, [data-keep]';
function lockButtons() {
lockQueued = false;
if (!App.worldEnded()) return;
const msg = App.t('ended.locked');
for (const b of document.querySelectorAll(LOCK_SEL)) {
if (b.disabled || b.closest(LOCK_SKIP) || b.hasAttribute('data-keep')) continue;
b.disabled = true; b.dataset.endedLock = '1'; b.title = msg;
}
}
function unlockButtons() {
for (const b of document.querySelectorAll('[data-ended-lock]')) { b.disabled = false; delete b.dataset.endedLock; b.removeAttribute('title'); }
}
function applyEnded() {
const on = App.worldEnded() && !!App.state.user;
document.documentElement.toggleAttribute('data-ended', on);
const pill = document.getElementById('world-pill');
if (pill) { pill.hidden = !on; pill.textContent = App.t('ended.pill'); pill.title = App.t('ended.body'); }
if (on && !lockObserver) {
lockObserver = new MutationObserver(() => { if (!lockQueued) { lockQueued = true; requestAnimationFrame(lockButtons); } });
lockObserver.observe(document.body, { childList: true, subtree: true });
} else if (!on && lockObserver) { lockObserver.disconnect(); lockObserver = null; unlockButtons(); }
if (on) lockButtons();
for (const el of document.querySelectorAll('.wld-ended-card')) fillEndedCard(el);
}
App.worldEnded = () => !!(App.state.world && App.state.world.status === 'ended');
// Something told us the world has ended (a refused command, the notification, the status fetch).
App.markWorldEnded = () => {
if (!App.state.world) return;
const was = App.worldEnded();
App.state.world.status = 'ended';
applyEnded();
if (!was) App.emit('worldended', App.state.world);
};
App.checkWorld = () => applyEnded();
App.on('session', () => applyEnded());
App.on('lang', () => applyEnded());
App.on('towns', () => applyEnded());
document.addEventListener('DOMContentLoaded', () => {
const pill = document.getElementById('world-pill');
if (pill) pill.addEventListener('click', () => App.go('world'));
});
function fillEndedCard(el) {
clear(el);
el.hidden = !App.worldEnded();
if (el.hidden) return;
el.appendChild(h('div', { class: 'row-ic' }, icon('trophy')));
el.appendChild(h('div', { class: 'row-main' }, h('b', { text: App.t('ended.title') }), h('span', { class: 'row-sub wrap', text: App.t('ended.body') })));
el.appendChild(h('button', { class: 'btn small', type: 'button', 'data-keep': '', onclick: () => App.go('world') }, App.t('ended.see')));
}
App.popSections.push({
slot: 'top',
render() { const el = h('section', { class: 'card wld-ended-card', role: 'status' }); fillEndedCard(el); return el; },
});
// ================================================================== the screen
let box, bodyEl, visible = false, offTick = null, gen = 0, focusSite = null;
const W = { status: null, results: null, err: null, loading: false, at: 0, rankTab: 'operators', rankN: 20, resErr: null };
const siteTitle = (s) => App.t('wld.site', { n: s.index + 1 });
const tagPill = (hd) => h('span', { class: 'pill wld-holder', title: hd.name }, '[' + hd.tag + '] ' + hd.name);
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
const costChips = (cost, pool) => h('div', { class: 'costs' }, D.RESOURCES.map((r) => {
const short = pool && (pool[r] || 0) < (cost[r] || 0);
return h('span', { class: 'cost ' + r + (short ? ' short' : '') }, icon(r), h('b', { text: num(cost[r] || 0) }));
}));
const bar = (p, cls) => { const i = h('i'); i.style.setProperty('--p', String(Math.max(0, Math.min(1, p)))); return h('span', { class: 'bar wld-bar ' + (cls || ''), 'aria-hidden': 'true' }, i); };
const cd = (ms) => h('b', { class: 'mono wld-cd', dataset: { until: String(ms) }, text: App.fmt.dur(ms - App.now(), 3) });
async function loadStatus() {
if (W.loading || !worldId()) return;
W.loading = true;
const my = gen;
try {
const st = await App.api.get('/worlds/' + worldId() + '/status');
W.status = st; W.err = null; W.at = Date.now();
if (st.phase === 'ended' || st.status === 'ended') {
App.markWorldEnded();
try { const r = await App.api.get('/worlds/' + worldId() + '/results'); W.results = r.available ? r : null; W.resErr = null; } catch (e) { W.resErr = e; }
}
} catch (e) { W.err = e; } finally {
W.loading = false;
if (my === gen && visible) draw();
}
}
function phaseCard() {
const st = W.status;
const now = App.now();
const phase = E.phaseNow(st, now);
const lead = E.leading(st.sites);
if (phase === 'ended') {
const w = st.winner;
return h('section', { class: 'card wld-banner ended' },
h('div', { class: 'wld-trophy' }, icon('trophy')),
h('div', { class: 'row-main' },
h('h2', { text: w && w.name ? App.t('wld.won', { name: w.name }) : App.t('wld.endedNoWinner') }),
w && w.tag ? h('p', { class: 'row-sub wrap', text: '[' + w.tag + ']' + (w.wonAt ? ' · ' + App.t('wld.wonAt', { t: mil().dayTime(w.wonAt) }) : '') }) : null,
h('p', { class: 'row-sub wrap', text: App.t('wld.endedAt', { t: st.endedAt ? mil().dayTime(st.endedAt) : '' }) + ' ' + App.t('ended.body') })));
}
if (st.winner) {
return h('section', { class: 'card wld-banner won' },
h('div', { class: 'wld-trophy' }, icon('trophy')),
h('div', { class: 'row-main' },
h('h2', { text: App.t('wld.won', { name: st.winner.name }) }),
h('p', { class: 'row-sub wrap' }, App.t('wld.endsIn') + ' ', st.endsAt ? cd(st.endsAt) : null),
h('p', { class: 'row-sub wrap', text: App.t('wld.winnerKeep') })));
}
if (phase === 'backbone_open') {
return h('section', { class: 'card wld-banner open' },
h('div', { class: 'wld-trophy' }, icon('b-backbone_node')),
h('div', { class: 'row-main' },
h('h2', { text: App.t('wld.open') }),
lead ? h('p', { class: 'row-sub wrap', text: App.t('wld.leading', { tag: lead.tag, name: lead.name, n: lead.siteIndex + 1, level: lead.level, max: D.ENDGAME.maxLevel }) })
: h('p', { class: 'row-sub wrap', text: App.t('wld.noLeader') }),
h('p', { class: 'row-sub wrap', text: App.t('wld.goal', { max: D.ENDGAME.maxLevel }) })));
}
return h('section', { class: 'card wld-banner' },
h('div', { class: 'wld-trophy' }, icon('b-backbone_node')),
h('div', { class: 'row-main' },
h('h2', { text: App.t('wld.opensIn') }),
h('p', { class: 'wld-count' }, cd(st.opensAt)),
bar(E.openProgress(st)),
h('p', { class: 'row-sub wrap', text: App.t('wld.day', { day: App.fmt.dec(st.ageDays), open: st.openDay }) })));
}
function howCard() {
return h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('flag'), App.t('wld.how.head'))),
h('ol', { class: 'wld-how' },
h('li', { text: App.t('wld.how.1', { n: D.ENDGAME.sites, day: D.ENDGAME.openDay }) }),
h('li', { text: App.t('wld.how.2') }),
h('li', { text: App.t('wld.how.3', { max: D.ENDGAME.maxLevel }) }),
h('li', { text: App.t('wld.how.4', { d: D.ENDGAME.graceDays }) })));
}
function siteCard(s) {
const kind = E.holderKind(s, myAllianceId());
const ended = App.worldEnded();
const now = App.now();
const prog = E.buildProgress(s, now);
const kids = [
h('div', { class: 'wld-site-head' },
h('span', { class: 'row-ic' }, icon(kind === 'mine' ? 'flag' : 'b-backbone_node')),
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: siteTitle(s) }), mil().coordLink(s.x, s.y)),
h('span', { class: 'row-sub wrap' }, s.holder ? [tagPill(s.holder), kind === 'mine' ? h('span', { class: 'pill accent', text: App.t('wld.yours') }) : null] : h('span', { class: 'pill dim', text: App.t('wld.incumbent') }),
s.takenBy ? h('span', { text: ' ' + App.t('wld.takenBy', { name: s.takenBy.name }) }) : null))),
h('div', { class: 'wld-level' }, h('b', { class: 'mono', text: App.t('wld.level', { n: s.level, max: s.maxLevel }) }), bar(s.progress, kind)),
];
if (s.build && !ended) { // a running build is frozen when the world ends: do not show a countdown that never finishes
const b = bar(prog || 0, 'build'); b.dataset.build = String(s.index);
kids.push(h('div', { class: 'wld-building' }, h('span', { class: 'row-sub wrap' }, App.t('wld.building', { n: s.build.toLevel }) + ' ', cd(s.build.dueAt)), b));
}
if (s.holder && s.id) kids.push(h('div', { class: 'row-sub wrap' }, App.t('wld.stock') + ' ', mil().resChips(s.pool)));
const acts = [];
if (kind === 'mine' && s.id) acts.push(h('button', { class: 'btn small primary', type: 'button', disabled: ended, onclick: () => openManage(s) }, icon('up'), App.t('wld.manage')));
if (kind !== 'mine' && App.openSend && App.state.towns.length) acts.push(h('button', { class: 'btn small primary', type: 'button', disabled: ended, onclick: () => App.openSend({ x: s.x, y: s.y }) }, icon('target'), App.t('wld.attack')));
acts.push(h('button', { class: 'btn small', type: 'button', onclick: () => App.go('map', { x: s.x, y: s.y, zoom: 40 }) }, icon('map'), App.t('wld.onMap')));
kids.push(h('div', { class: 'wld-acts' }, acts));
return h('li', { class: 'card wld-site ' + kind, dataset: { index: String(s.index) } }, kids);
}
function resultsCard() {
const r = W.results;
if (W.resErr) return h('p', { class: 'form-error', role: 'alert', text: App.errMsg(W.resErr) });
if (!r || !r.results) return null;
const res = r.results;
const tabs = ['operators', 'alliances', 'attackers', 'defenders'];
const list = res[W.rankTab] || [];
const me = App.state.operator ? App.state.operator.id : 0;
const row = (x) => {
let name, sub, val;
if (W.rankTab === 'alliances') { name = x.name; sub = '[' + x.tag + '] ' + App.t('soc.rank.members', { n: x.members }) + ' · ' + App.t('soc.rank.pops', { n: x.towns }); val = App.fmt.dec(x.footprint); }
else if (W.rankTab === 'operators') { name = x.name; sub = (x.allianceTag ? '[' + x.allianceTag + '] ' : '') + App.t('soc.rank.pops', { n: x.towns }); val = App.fmt.dec(x.footprint); }
else { name = x.name; sub = x.allianceTag ? '[' + x.allianceTag + ']' : ''; val = num(W.rankTab === 'attackers' ? x.attackPoints : x.defensePoints); }
const you = (W.rankTab !== 'alliances' && x.operatorId === me) || (W.rankTab === 'alliances' && x.allianceId === myAllianceId());
const win = W.rankTab === 'alliances' && r.winner && x.allianceId === r.winner.allianceId;
return h('li', { class: 'wld-rank' + (you ? ' you' : '') + (win ? ' win' : '') },
h('span', { class: 'soc-rk mono', text: '#' + x.rank }),
h('span', { class: 'row-main' }, h('b', { text: name }), sub ? h('span', { class: 'row-sub', text: sub }) : null),
win ? icon('trophy') : null,
h('b', { class: 'mono', text: val }));
};
const shown = E.topRows(list, W.rankN);
return h('section', { class: 'card wld-results' },
h('div', { class: 'card-head' }, h('h2', null, icon('trophy'), App.t('wld.results'))),
h('div', { class: 'soc-subtabs' }, tabs.map((k) => h('button', { class: 'chip-btn', type: 'button', 'data-keep': '', 'aria-pressed': String(W.rankTab === k), onclick: () => { W.rankTab = k; W.rankN = 20; draw(); } }, App.t('wld.rank.' + k)))),
shown.length ? h('ul', { class: 'wld-ranks' }, shown.map(row)) : h('p', { class: 'empty', text: App.t('wld.rank.empty') }),
list.length > shown.length ? h('button', { class: 'btn wide', type: 'button', 'data-keep': '', onclick: () => { W.rankN += 20; draw(); } }, App.t('trd.more')) : null,
res.totals ? h('p', { class: 'row-sub', text: App.t('wld.rank.totals', { o: res.totals.operators, a: res.totals.alliances }) }) : null);
}
function draw() {
if (!bodyEl) return;
const top = box.scrollTop;
clear(bodyEl);
if (W.err && !W.status) {
bodyEl.appendChild(h('div', { class: 'soc-err' }, h('p', { class: 'form-error', role: 'alert', text: App.errMsg(W.err) }), h('button', { class: 'btn small', type: 'button', onclick: () => loadStatus() }, icon('refresh'), App.t('common.retry'))));
return;
}
if (!W.status) { bodyEl.appendChild(h('p', { class: 'empty', text: App.t('common.loading') })); return; }
const st = W.status;
bodyEl.appendChild(phaseCard());
const phase = E.phaseNow(st, App.now());
if (phase === 'running') bodyEl.appendChild(howCard());
if (st.sites.length) {
bodyEl.appendChild(h('h3', { class: 'sub wld-sub', text: App.t('wld.sites') }));
bodyEl.appendChild(h('ul', { class: 'wld-sites' }, st.sites.map(siteCard)));
} else if (phase === 'backbone_open') {
bodyEl.appendChild(h('p', { class: 'empty', text: App.t('wld.noSites') }));
}
if (phase === 'ended') { const rc = resultsCard(); if (rc) bodyEl.appendChild(rc); }
box.scrollTop = top;
if (focusSite !== null) {
const el = bodyEl.querySelector('[data-index="' + focusSite + '"]');
focusSite = null;
if (el) { el.scrollIntoView({ block: 'center' }); el.classList.add('flash'); }
}
}
// ---- the manage sheet of a site your alliance holds
async function openManage(site0) {
const body = h('div', { class: 'detail wld-manage' }, h('p', { class: 'empty', text: App.t('common.loading') }));
const sheet = openSheet({ title: siteTitle(site0), icon: 'b-backbone_node', closeLabel: App.t('common.close'), body });
let data = null, pops = null;
const sh = { fromId: 0, cargo: {}, nonce: nonce() };
async function load() {
try {
const [d, p] = await Promise.all([
App.api.get('/backbone/' + site0.id),
pops ? Promise.resolve(pops) : Promise.all(App.state.towns.map((t) => mil().loadTown(t.id).then((x) => ({ id: t.id, name: t.name, x: t.x, y: t.y, td: x.town, rt: App.rulesTownFrom(x.town, x.serverTime) })).catch(() => null))),
]);
data = d; pops = p.filter(Boolean);
if (!pops.some((q) => q.id === sh.fromId)) { sh.fromId = (pops.find((q) => q.td.military.transport.links > 0) || pops[0] || { id: 0 }).id; sh.cargo = {}; }
drawManage();
} catch (e) {
clear(body);
body.appendChild(h('p', { class: 'form-error', role: 'alert', text: App.errMsg(e) }));
}
}
function drawManage() {
clear(body);
const s = data.site, you = data.you;
sheet.setTitle(siteTitle(s));
if (!you.holder) { body.appendChild(h('p', { class: 'reason', text: App.t('wld.lost') })); }
body.appendChild(h('div', null, kv(App.t('wld.levelShort'), h('b', { class: 'mono', text: App.t('wld.level', { n: s.level, max: s.maxLevel }) }))));
body.appendChild(bar(s.progress, 'mine'));
body.appendChild(h('div', null,
kv(App.t('wld.stock'), mil().resChips(s.pool)),
kv(App.t('wld.coords'), mil().coordLink(s.x, s.y))));
// ---- build the next node level
const chk = E.buildCheck(s, you, App.worldEnded());
const buildErr = h('p', { class: 'form-error', role: 'alert', hidden: true });
const sec = h('section', { class: 'wld-sec' }, h('h3', { class: 'sub', text: App.t('wld.build.head') }));
if (s.build) sec.appendChild(h('div', { class: 'detail-queue' }, h('b', { text: App.t('wld.building', { n: s.build.toLevel }) }), h('span', null, cd(s.build.dueAt)), bar(E.buildProgress(s, App.now()) || 0, 'build')));
if (s.next && !s.build) {
sec.appendChild(h('p', { class: 'row-sub wrap', text: App.t('wld.build.next', { n: s.next.toLevel, t: App.fmt.dur(s.next.durationMs) }) }));
sec.appendChild(costChips(s.next.cost, s.pool));
const lack = E.missing(s.next.cost, s.pool);
if (Object.keys(lack).length) sec.appendChild(h('p', { class: 'reason', text: App.t('wld.build.lack', { what: D.RESOURCES.filter((r) => lack[r]).map((r) => num(lack[r]) + ' ' + App.resName(r)).join(', ') }) }));
} else if (!s.next) sec.appendChild(h('p', { class: 'good', text: App.t('wld.build.max') }));
const btn = h('button', { class: 'btn primary wide', type: 'button', disabled: !chk.ok, onclick: async () => {
btn.disabled = true; buildErr.hidden = true;
try {
const r = await App.api.post('/backbone/' + s.id + '/build', {}, { intent: 'bb-build:' + s.id + ':' + (s.next ? s.next.toLevel : 0) });
toast(App.t('wld.build.started', { n: r.toLevel, t: App.fmt.dur(r.dueAt - App.now()) }), 'ok');
await Promise.all([load(), loadStatus()]);
} catch (e) { buildErr.textContent = App.errMsg(e); buildErr.hidden = false; btn.disabled = false; load(); }
} }, icon('up'), s.next ? App.t('wld.build.go', { n: s.build ? s.build.toLevel : s.next.toLevel }) : App.t('wld.build.max'));
sec.appendChild(buildErr);
if (chk.reason && chk.reason !== 'not_enough_resources' && chk.reason !== 'max_level' && chk.reason !== 'already_queued') sec.appendChild(h('p', { class: 'reason', text: App.t('wld.build.why.' + chk.reason) }));
sec.appendChild(btn);
body.appendChild(sec);
// ---- ship resources
const ship = h('section', { class: 'wld-sec' }, h('h3', { class: 'sub', text: App.t('wld.ship.head') }));
const cur = pops.find((q) => q.id === sh.fromId);
if (!you.canShip) ship.appendChild(h('p', { class: 'reason', text: App.t('wld.ship.no') }));
else if (!cur) ship.appendChild(h('p', { class: 'empty', text: App.t('pop.noTown') }));
else {
const tr = cur.td.military.transport, free = Math.max(0, tr.links - tr.active), cap = tr.capacityPerLink;
const prev = h('div', { class: 'send-preview' });
const shipErr = h('p', { class: 'form-error', role: 'alert', hidden: true });
const go = h('button', { class: 'btn primary wide', type: 'button' }, icon('box'), App.t('wld.ship.go'));
const refresh = () => {
const total = CargoUI.cargoTotal(sh.cargo);
clear(prev);
const dist = R.distance(cur.x, cur.y, s.x, s.y);
prev.appendChild(kv(App.t('wld.ship.cargo'), h('b', { class: 'mono' + (total > cap ? ' bad' : ''), text: num(total) + ' / ' + num(cap) })));
prev.appendChild(kv(App.t('send.distance'), h('span', { class: 'mono', text: App.fmt.dec(dist) + ' ' + App.t('common.tiles') })));
prev.appendChild(kv(App.t('send.latency'), h('span', { class: 'mono', text: App.fmt.dur(R.transportMs(dist, speed())) })));
prev.appendChild(kv(App.t('trd.links.head'), h('span', { class: 'mono', text: free + ' / ' + tr.links })));
go.disabled = total < 1 || total > cap || !free;
};
if (pops.length > 1) ship.appendChild(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.from') }),
h('select', { onchange: (e) => { sh.fromId = Number(e.target.value); sh.cargo = {}; drawManage(); } }, pops.map((q) => h('option', { value: q.id, selected: q.id === sh.fromId, text: q.name })))));
ship.appendChild(h('p', { class: 'row-sub wrap', text: App.t('wld.ship.hint', { n: num(cap) }) }));
if (!tr.links) ship.appendChild(h('p', { class: 'reason', text: App.t('err.no_transport_link') }));
const have = R.resourcesAt(cur.rt, App.now()).amounts;
for (const row of CargoUI.cargoPickers(sh.cargo, have, refresh)) ship.appendChild(row);
ship.appendChild(prev); ship.appendChild(shipErr); ship.appendChild(go);
go.addEventListener('click', async () => {
go.disabled = true; shipErr.hidden = true;
try {
await App.api.post('/backbone/' + s.id + '/ship', { fromTownId: sh.fromId, cargo: Object.assign({}, sh.cargo) }, { intent: 'bb-ship:' + sh.nonce });
sh.nonce = nonce(); sh.cargo = {}; pops = null;
toast(App.t('wld.ship.done'), 'ok');
App.refreshTown().catch(() => {}); App.refreshMovements().catch(() => {});
await load();
} catch (e) { shipErr.textContent = App.errMsg(e); shipErr.hidden = false; if (e.code !== 'network_error') sh.nonce = nonce(); refresh(); }
});
refresh();
}
body.appendChild(ship);
// ---- ledger
const ledger = (data.contributions || []).filter((c) => c.fiber || c.hardware || c.capital);
if (ledger.length) {
body.appendChild(h('section', { class: 'wld-sec' }, h('h3', { class: 'sub', text: App.t('wld.ledger') }),
h('ul', { class: 'mil-list' }, ledger.slice(0, 15).map((c) => h('li', { class: 'mil-row' },
h('span', { class: 'row-main' }, h('b', { text: c.name }), mil().resChips({ fiber: c.fiber, hardware: c.hardware, capital: c.capital }))))),
));
}
}
load();
}
// ---- ticks: countdown texts, build bars, phase flips
function tick(now) {
if (!box) return;
for (const el of bodyEl.querySelectorAll('.wld-cd')) {
const s = App.fmt.dur(Number(el.dataset.until) - now, 3);
if (el.textContent !== s) el.textContent = s;
}
for (const el of bodyEl.querySelectorAll('[data-build]')) {
const site = W.status && W.status.sites.find((x) => String(x.index) === el.dataset.build);
const p = site ? E.buildProgress(site, now) : null;
if (p !== null) el.firstChild.style.setProperty('--p', String(p));
}
if (W.status && !W.loading) {
const flip = W.status.phase === 'running' && now >= W.status.opensAt + 800;
const due = W.status.sites.some((s) => s.build && s.build.dueAt < now - 1500) || (W.status.winner && W.status.endsAt && W.status.phase !== 'ended' && now > W.status.endsAt + 1500);
if ((flip || due) && Date.now() - W.at > 4000) loadStatus();
else if (Date.now() - W.at > 60000) loadStatus();
}
}
App.registerScreen({
id: 'world', titleKey: 'screen.world', navKey: 'nav.world', icon: 'b-backbone_node', hud: false, navGroup: 'more',
render(container) {
box = container;
bodyEl = h('div', { class: 'wld-body' });
box.appendChild(h('div', { class: 'page wld-page' },
h('div', { class: 'card-head page-head' }, h('h1', { id: 'wld-h', text: App.t('screen.world') }),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), 'data-keep': '', onclick: () => loadStatus() }, icon('refresh'))),
bodyEl));
App.on('session', () => { W.status = null; W.results = null; W.err = null; });
App.api.on('push', (msg) => {
if (!msg || msg.type !== 'notification' || !App.state.user) return;
if (msg.kind === 'world_ended') { App.markWorldEnded(); App.refreshTowns().catch(() => {}); }
if (/^(backbone_|world_ended)/.test(msg.kind || '')) { if (visible) loadStatus(); else W.at = 0; }
});
},
onShow(params) {
visible = true; gen++;
document.getElementById('wld-h').textContent = App.t('screen.world');
if (params && Number.isInteger(params.site)) focusSite = params.site;
draw();
loadStatus();
if (offTick) offTick();
offTick = App.onTick(tick);
},
onHide() { visible = false; gen++; if (offTick) offTick(); offTick = null; },
onLang() { document.getElementById('wld-h').textContent = App.t('screen.world'); draw(); },
});
}());

View file

@ -0,0 +1,82 @@
'use strict';
/* Strings of the Alerts feed for the notification types of trade, the end game, alliances, diplomacy and messages (js/alertkinds.js), 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: {
'alerts.level': 'level {n}', 'alerts.at': 'at {x}, {y}',
// trade
'alerts.trade_accepted': 'Your offer was taken: {give} for {want}',
'alerts.trade_completed': 'Trade settled: {give} for {want}',
'alerts.trade_expired': 'An offer of yours expired',
'alerts.trade_expired.back': '{what} is back in {town}',
'alerts.trade_void': 'An offer was voided: the POP changed hands',
// end game
'alerts.backbone_open': 'The backbone landing sites are open',
'alerts.backbone_open.n': '{n} landing sites are up for grabs. Scan one, then take it.',
'alerts.backbone_taken': 'Your alliance took landing site {n}',
'alerts.backbone_taken.from': 'from {tag}', 'alerts.backbone_taken.incumbent': 'from the incumbent',
'alerts.backbone_lost': 'Landing site {n} was taken by {tag}',
'alerts.backbone_level': 'Backbone node on site {n} reached level {level}',
'alerts.backbone_delivered': 'Your shipment reached the landing site',
'alerts.backbone_ship_bounced': 'A shipment was turned back: the site changed hands',
'alerts.backbone_won': '{name} completed the Backbone',
'alerts.backbone_won.ends': 'The world ends {time}',
'alerts.world_ended': 'The world has ended',
'alerts.world_ended.winner': 'Winner: {name}', 'alerts.world_ended.nowinner': 'It can still be read, nothing can be changed.',
// alliance
'alerts.alliance_invite': 'You were invited to {name}', 'alerts.alliance_invite.by': 'by {name}',
'alerts.alliance_invite_declined': '{name} declined your invitation',
'alerts.alliance_member_joined': '{name} joined the alliance',
'alerts.alliance_member_left': '{name} left the alliance', 'alerts.alliance_member_kicked': '{name} was removed from the alliance',
'alerts.alliance_kicked': 'You were removed from {name}',
'alerts.alliance_role': 'Your role is now {role}', 'alerts.alliance_role.was': 'was {role}',
'alerts.alliance_leader': '{name} is the new leader', 'alerts.alliance_leader.from': 'handed over by {name}',
'alerts.alliance_disbanded': '{name} was disbanded',
// diplomacy
'alerts.diplomacy_proposal': '{tag} proposes: {state}', 'alerts.diplomacy_proposal.until': 'answer by {time}',
'alerts.diplomacy_declined': '{tag} declined: {state}',
'alerts.diplomacy_changed': 'Relation with {tag} is now {to}', 'alerts.diplomacy_changed.was': 'was {state}', 'alerts.diplomacy_changed.disbanded': 'their alliance was disbanded',
'alerts.diplomacy_cancel_pending': 'The {state} with {tag} is ending', 'alerts.diplomacy_cancel_pending.at': 'effective {time}',
'alerts.diplomacy_cancel_revoked': 'Ending the {state} with {tag} was called off',
// messages
'alerts.message': 'Message from {name}', 'alerts.alliance_message': 'Alliance message from {name}',
},
nb: {
'alerts.level': 'nivå {n}', 'alerts.at': 'ved {x}, {y}',
'alerts.trade_accepted': 'Tilbudet ditt ble tatt: {give} for {want}',
'alerts.trade_completed': 'Handel gjennomført: {give} for {want}',
'alerts.trade_expired': 'Et tilbud fra deg gikk ut',
'alerts.trade_expired.back': '{what} er tilbake i {town}',
'alerts.trade_void': 'Et tilbud ble ugyldig: POP-en skiftet eier',
'alerts.backbone_open': 'Ryggradens landingspunkter er åpne',
'alerts.backbone_open.n': '{n} landingspunkter kan tas. Skann ett, og ta det.',
'alerts.backbone_taken': 'Alliansen din tok landingspunkt {n}',
'alerts.backbone_taken.from': 'fra {tag}', 'alerts.backbone_taken.incumbent': 'fra inkumbenten',
'alerts.backbone_lost': 'Landingspunkt {n} ble tatt av {tag}',
'alerts.backbone_level': 'Ryggradsnoden på punkt {n} nådde nivå {level}',
'alerts.backbone_delivered': 'Forsendelsen din nådde landingspunktet',
'alerts.backbone_ship_bounced': 'En forsendelse ble snudd: punktet skiftet eier',
'alerts.backbone_won': '{name} fullførte Ryggraden',
'alerts.backbone_won.ends': 'Verdenen slutter {time}',
'alerts.world_ended': 'Verdenen er slutt',
'alerts.world_ended.winner': 'Vinner: {name}', 'alerts.world_ended.nowinner': 'Den kan fortsatt leses, men ingenting kan endres.',
'alerts.alliance_invite': 'Du ble invitert til {name}', 'alerts.alliance_invite.by': 'av {name}',
'alerts.alliance_invite_declined': '{name} avslo invitasjonen din',
'alerts.alliance_member_joined': '{name} ble med i alliansen',
'alerts.alliance_member_left': '{name} forlot alliansen', 'alerts.alliance_member_kicked': '{name} ble fjernet fra alliansen',
'alerts.alliance_kicked': 'Du ble fjernet fra {name}',
'alerts.alliance_role': 'Rollen din er nå {role}', 'alerts.alliance_role.was': 'var {role}',
'alerts.alliance_leader': '{name} er ny leder', 'alerts.alliance_leader.from': 'overlatt av {name}',
'alerts.alliance_disbanded': '{name} ble oppløst',
'alerts.diplomacy_proposal': '{tag} foreslår: {state}', 'alerts.diplomacy_proposal.until': 'svar innen {time}',
'alerts.diplomacy_declined': '{tag} avslo: {state}',
'alerts.diplomacy_changed': 'Forholdet til {tag} er nå {to}', 'alerts.diplomacy_changed.was': 'var {state}', 'alerts.diplomacy_changed.disbanded': 'alliansen deres ble oppløst',
'alerts.diplomacy_cancel_pending': '{state} med {tag} avsluttes', 'alerts.diplomacy_cancel_pending.at': 'gjelder fra {time}',
'alerts.diplomacy_cancel_revoked': 'Avslutningen av {state} med {tag} ble avlyst',
'alerts.message': 'Melding fra {name}', 'alerts.alliance_message': 'Alliansemelding fra {name}',
},
});
}));

105
public/js/strings/trade.js Normal file
View file

@ -0,0 +1,105 @@
'use strict';
/* Strings of the Internet exchange screen (offers, new offer, mine, direct transport, links) and its error codes, 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.trade': 'Trade', 'screen.trade': 'Internet exchange',
'trd.tab.offers': 'Offers', 'trd.tab.new': 'New', 'trd.tab.mine': 'Mine', 'trd.tab.send': 'Send',
'trd.any': 'Any', 'trd.more': 'Load more',
'trd.status.all': 'All', 'trd.status.open': 'Open', 'trd.status.accepted': 'Taken', 'trd.status.completed': 'Settled',
'trd.status.cancelled': 'Cancelled', 'trd.status.expired': 'Expired', 'trd.status.void': 'Void',
'trd.role.poster': 'You posted', 'trd.role.acceptor': 'You took',
'trd.need.title': 'You need an Internet exchange',
'trd.need.body': 'Trading runs over the Internet exchange. Its level is the number of transports that can run at once, each level reaches {n} tiles, and one link carries up to {cap}.',
'trd.need.req': 'You can build it once {building} is level {level}.', 'trd.need.go': 'Open POP',
'trd.reach': 'level {lv} · reach {n} tiles', 'trd.reach.title': 'How far this exchange sees and trades',
'trd.offers.head': 'Open offers in reach', 'trd.offers.empty': 'No open offers in reach. Post one of your own: somebody nearby has a surplus.',
'trd.offers.emptyFiltered': 'No offers match that filter.', 'trd.offers.post': 'Post an offer',
'trd.f.give': 'They give', 'trd.f.want': 'They want', 'trd.f.from': 'Trade from', 'trd.f.allPops': 'All my POPs',
'trd.get': 'You get', 'trd.pay': 'You pay', 'trd.from': 'From', 'trd.away': '{d} tiles away', 'trd.maxDist': 'max {n} tiles',
'trd.expiresIn': 'expires in', 'trd.take': 'Take', 'trd.have': 'In stock: {n} {res}', 'trd.latency': 'transport takes {t}',
'trd.accept.title': 'Take this offer', 'trd.accept.go': 'Take offer', 'trd.accept.with': 'Pay from which POP?',
'trd.accept.nopop': 'None of your POPs can take this offer any more.', 'trd.accept.short': 'Only {have} {res} here', 'trd.accept.nolink': 'No free transport link',
'trd.accept.done': 'Deal. Both transports are on their way and land in {t}.',
'trd.new.head': 'Post an offer', 'trd.new.pop': 'From POP', 'trd.new.give': 'You give', 'trd.new.want': 'You want in return',
'trd.new.giveRes': 'Resource you give', 'trd.new.wantRes': 'Resource you want', 'trd.new.giveAmount': 'Amount you give', 'trd.new.wantAmount': 'Amount you want',
'trd.new.match': 'Match', 'trd.new.band': 'Fair range for what you ask: {lo} to {hi}.',
'trd.new.maxDist': 'Max distance (tiles)', 'trd.new.maxDistHint': 'Only POPs this close can take it. 1 to {max}.',
'trd.new.level': 'Posting needs an Internet exchange of level 1 or higher: this POP has level {lv} (reach {reach} tiles). A taker needs level {need} to trade across {d} tiles.',
'trd.new.rules': 'Each side fits one transport link, at most {cap}, and the two amounts may differ by at most 1:{n}. What you give is held in escrow and one link is reserved until somebody takes the offer, you cancel it, or it expires after {ttl}.',
'trd.new.links': 'Free transport links here: {free} of {links}.', 'trd.new.go': 'Post offer', 'trd.new.done': 'Offer posted. The goods wait in escrow.',
'trd.v.giveRes': 'Pick a resource to give.', 'trd.v.wantRes': 'Give and want must be different resources.', 'trd.v.giveAmount': 'Give at least 1.',
'trd.v.wantAmount': 'Ask for at least 1.', 'trd.v.maxDistance': 'Max distance must be a whole number of tiles.', 'trd.v.terms': 'Check the terms.',
'trd.v.have': 'You only have {have} {res} here.', 'trd.v.links': 'No free transport link at this POP: all are busy or reserved by open offers.',
'trd.cancel': 'Cancel', 'trd.cancelled': 'Offer cancelled. {what} is back in the POP.', 'trd.settles': 'Settles when both transports have landed.',
'trd.voidHint': 'The POP changed hands, the goods went with it.', 'trd.mine.empty': 'No offers yet.',
'trd.send.head': 'Send resources', 'trd.send.body': 'A direct transport carries up to {n} per link, no strings attached. Pick one of your POPs, or type the coordinates of any POP.',
'trd.send.own': 'To one of your POPs', 'trd.send.noOwn': 'You have no other POP yet.', 'trd.send.coords': 'To any POP by coordinates',
'trd.send.warn': 'The owner of a POP that is not yours sees an incoming movement (type hidden) until the cargo lands.',
'trd.links.head': 'Transport links', 'trd.links.used': '{a} of {n} links in use, {free} free · {cap} per link',
'trd.links.hint': 'An open offer holds one link. A transport holds one until it lands and the empty carriers are back.', 'trd.links.active': 'On the road',
'trd.err.range': 'That POP is {d} tiles away. The offer reaches {max} tiles and your exchange reaches {reach}.',
'trd.err.ratio': 'The two amounts may differ by at most 1:{n}.', 'trd.err.cap': 'Each side must fit one transport link: at most {n}.',
'err.trade_ratio': 'The two amounts may differ by at most 1:2.', 'err.offer_closed': 'That offer is not open any more.', 'err.own_offer': 'You cannot take your own offer.',
'err.trade_out_of_range': 'That POP is too far from the offer: its max distance or your exchange reach is exceeded.',
},
nb: {
'nav.trade': 'Handel', 'screen.trade': 'Internettknutepunkt',
'trd.tab.offers': 'Tilbud', 'trd.tab.new': 'Nytt', 'trd.tab.mine': 'Mine', 'trd.tab.send': 'Send',
'trd.any': 'Alle', 'trd.more': 'Last flere',
'trd.status.all': 'Alle', 'trd.status.open': 'Åpne', 'trd.status.accepted': 'Tatt', 'trd.status.completed': 'Gjort opp',
'trd.status.cancelled': 'Trukket', 'trd.status.expired': 'Utløpt', 'trd.status.void': 'Ugyldig',
'trd.role.poster': 'Du la ut', 'trd.role.acceptor': 'Du tok',
'trd.need.title': 'Du trenger et Internettknutepunkt',
'trd.need.body': 'Handel går over Internettknutepunktet. Nivået er antall transporter som kan gå samtidig, hvert nivå rekker {n} felt, og én lenke bærer opptil {cap}.',
'trd.need.req': 'Du kan bygge det når {building} er på nivå {level}.', 'trd.need.go': 'Åpne POP',
'trd.reach': 'nivå {lv} · rekkevidde {n} felt', 'trd.reach.title': 'Hvor langt dette knutepunktet ser og handler',
'trd.offers.head': 'Åpne tilbud innen rekkevidde', 'trd.offers.empty': 'Ingen åpne tilbud innen rekkevidde. Legg ut ett selv: noen i nærheten har overskudd.',
'trd.offers.emptyFiltered': 'Ingen tilbud passer det filteret.', 'trd.offers.post': 'Legg ut et tilbud',
'trd.f.give': 'De gir', 'trd.f.want': 'De vil ha', 'trd.f.from': 'Handle fra', 'trd.f.allPops': 'Alle POP-ene mine',
'trd.get': 'Du får', 'trd.pay': 'Du betaler', 'trd.from': 'Fra', 'trd.away': '{d} felt unna', 'trd.maxDist': 'maks {n} felt',
'trd.expiresIn': 'utløper om', 'trd.take': 'Ta', 'trd.have': 'På lager: {n} {res}', 'trd.latency': 'transporten tar {t}',
'trd.accept.title': 'Ta dette tilbudet', 'trd.accept.go': 'Ta tilbudet', 'trd.accept.with': 'Betale fra hvilken POP?',
'trd.accept.nopop': 'Ingen av POP-ene dine kan ta dette tilbudet lenger.', 'trd.accept.short': 'Bare {have} {res} her', 'trd.accept.nolink': 'Ingen ledig transportlenke',
'trd.accept.done': 'Avtale. Begge transportene er på vei og lander om {t}.',
'trd.new.head': 'Legg ut et tilbud', 'trd.new.pop': 'Fra POP', 'trd.new.give': 'Du gir', 'trd.new.want': 'Du vil ha til gjengjeld',
'trd.new.giveRes': 'Ressurs du gir', 'trd.new.wantRes': 'Ressurs du vil ha', 'trd.new.giveAmount': 'Mengde du gir', 'trd.new.wantAmount': 'Mengde du vil ha',
'trd.new.match': 'Likt', 'trd.new.band': 'Rimelig område for det du ber om: {lo} til {hi}.',
'trd.new.maxDist': 'Maks avstand (felt)', 'trd.new.maxDistHint': 'Bare POP-er så nær kan ta det. 1 til {max}.',
'trd.new.level': 'Å legge ut krever et Internettknutepunkt på nivå 1 eller høyere: denne POP-en har nivå {lv} (rekkevidde {reach} felt). Den som tar det trenger nivå {need} for å handle over {d} felt.',
'trd.new.rules': 'Hver side må rommes av én transportlenke, maks {cap}, og de to mengdene kan avvike med høyst 1:{n}. Det du gir holdes i depot og én lenke reserveres til noen tar tilbudet, du trekker det, eller det utløper etter {ttl}.',
'trd.new.links': 'Ledige transportlenker her: {free} av {links}.', 'trd.new.go': 'Legg ut tilbud', 'trd.new.done': 'Tilbudet er lagt ut. Varene venter i depot.',
'trd.v.giveRes': 'Velg en ressurs å gi.', 'trd.v.wantRes': 'Du må gi og ønske ulike ressurser.', 'trd.v.giveAmount': 'Gi minst 1.',
'trd.v.wantAmount': 'Be om minst 1.', 'trd.v.maxDistance': 'Maks avstand må være et helt antall felt.', 'trd.v.terms': 'Sjekk vilkårene.',
'trd.v.have': 'Du har bare {have} {res} her.', 'trd.v.links': 'Ingen ledig transportlenke i denne POP-en: alle er opptatt eller reservert av åpne tilbud.',
'trd.cancel': 'Trekk', 'trd.cancelled': 'Tilbudet er trukket. {what} er tilbake i POP-en.', 'trd.settles': 'Gjøres opp når begge transportene har landet.',
'trd.voidHint': 'POP-en skiftet eier, og varene fulgte med.', 'trd.mine.empty': 'Ingen tilbud ennå.',
'trd.send.head': 'Send ressurser', 'trd.send.body': 'En direkte transport bærer opptil {n} per lenke, uten betingelser. Velg en av POP-ene dine, eller skriv koordinatene til en hvilken som helst POP.',
'trd.send.own': 'Til en av POP-ene dine', 'trd.send.noOwn': 'Du har ingen annen POP ennå.', 'trd.send.coords': 'Til en hvilken som helst POP med koordinater',
'trd.send.warn': 'Eieren av en POP som ikke er din ser en innkommende bevegelse (type skjult) til lasten lander.',
'trd.links.head': 'Transportlenker', 'trd.links.used': '{a} av {n} lenker i bruk, {free} ledige · {cap} per lenke',
'trd.links.hint': 'Et åpent tilbud holder én lenke. En transport holder én til den har landet og de tomme bærerne er tilbake.', 'trd.links.active': 'På veien',
'trd.err.range': 'Den POP-en er {d} felt unna. Tilbudet rekker {max} felt og knutepunktet ditt rekker {reach}.',
'trd.err.ratio': 'De to mengdene kan avvike med høyst 1:{n}.', 'trd.err.cap': 'Hver side må rommes av én transportlenke: høyst {n}.',
'err.trade_ratio': 'De to mengdene kan avvike med høyst 1:2.', 'err.offer_closed': 'Det tilbudet er ikke åpent lenger.', 'err.own_offer': 'Du kan ikke ta ditt eget tilbud.',
'err.trade_out_of_range': 'Den POP-en er for langt unna tilbudet: maks avstand eller knutepunktets rekkevidde er overskredet.',
},
});
}));

116
public/js/strings/world.js Normal file
View file

@ -0,0 +1,116 @@
'use strict';
/* Strings of the end game: the Backbone race screen, the ended-world mode, landing sites on the map / send dialog / reports,
* the shared report folder, and the world_ended / backbone_closed error codes, 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.world': 'Backbone', 'screen.world': 'The Backbone race',
'ended.locked': 'This world has ended. Everything is read-only now.', 'ended.pill': 'World ended', 'ended.title': 'This world has ended',
'ended.body': 'You can still read everything and message people, but nothing can be built, sent or traded any more.', 'ended.see': 'Final standings',
'wld.site': 'Landing site {n}', 'wld.yours': 'Your alliance', 'wld.incumbent': 'Incumbent', 'wld.takenBy': 'taken by {name}',
'wld.level': 'Level {n} / {max}', 'wld.levelShort': 'Node level', 'wld.building': 'Building level {n}', 'wld.stock': 'Stockpile', 'wld.coords': 'Position',
'wld.manage': 'Manage', 'wld.attack': 'Scan or attack', 'wld.onMap': 'On map', 'wld.sites': 'Landing sites',
'wld.noSites': 'The sites are open but none is listed yet. Refresh in a moment.',
'wld.won': '{name} won the world', 'wld.endedNoWinner': 'The world has ended', 'wld.wonAt': 'finished {t}', 'wld.endedAt': 'Ended {t}.',
'wld.endsIn': 'The world ends in', 'wld.winnerKeep': 'The race is decided. Until the end you can still fight for the ranking.',
'wld.open': 'The landing sites are open', 'wld.leading': 'Leading: [{tag}] {name}, site {n}, node level {level} of {max}',
'wld.noLeader': 'Nobody holds a landing site yet. The first alliance to scan one and take it starts the race.',
'wld.goal': 'Build the Backbone node to level {max} first and your alliance wins the world.',
'wld.opensIn': 'The landing sites appear in', 'wld.day': 'World day {day} of {open}',
'wld.how.head': 'How the world ends',
'wld.how.1': '{n} backbone landing sites appear on the map on world day {day}.',
'wld.how.2': 'An alliance takes a site by beating its static defence: scan it first, then attack. Holders cannot garrison a site, they can only grow the node, which also makes it harder to take.',
'wld.how.3': 'The holders ship Fiber, Hardware and Capital to their site and build the Backbone node level by level up to {max}. The first node at level {max} wins.',
'wld.how.4': 'The world closes {d} world days after the winning level lands. After that it is read-only.',
'wld.lost': 'Your alliance no longer holds this site.',
'wld.build.head': 'Backbone node', 'wld.build.next': 'Next: level {n}, takes {t}', 'wld.build.lack': 'The stockpile lacks {what}.', 'wld.build.max': 'Fully built',
'wld.build.started': 'Level {n} is building, done in {t}.', 'wld.build.go': 'Build level {n}',
'wld.build.why.ended': 'The world has ended.', 'wld.build.why.forbidden': 'Your role may not build the node.',
'wld.ship.head': 'Ship resources', 'wld.ship.no': 'Only members of the holding alliance can ship.', 'wld.ship.go': 'Ship', 'wld.ship.cargo': 'Cargo',
'wld.ship.hint': 'A shipment is a transport: up to {n} per link. It lands in the stockpile, or rides home if the site has changed hands on the way.',
'wld.ship.done': 'Shipment on its way.', 'wld.ledger': 'Who shipped what',
'wld.results': 'Final standings', 'wld.rank.operators': 'Operators', 'wld.rank.alliances': 'Alliances', 'wld.rank.attackers': 'Attackers', 'wld.rank.defenders': 'Defenders',
'wld.rank.empty': 'Nobody on this list.', 'wld.rank.totals': '{o} operators in {a} alliances',
'tile.backbone': 'Backbone landing site', 'map.legend.backbone': 'Landing site', 'map.info.openWorld': 'Backbone race',
'map.info.backbone': 'A backbone landing site. The first alliance to build the node here to level {max} wins the world.',
'send.landing.hint': 'A landing site has no garrison: only its static defence counts (a scan shows the number, about {mult} times an incumbent site). Winning makes your alliance the holder.',
'send.transport.rival': 'This is a POP you do not own: the cargo is a gift, and its owner sees an incoming movement until it lands. For a trade use the Internet exchange.',
'send.reason.no_alliance': 'only alliance members can attack a landing site', 'send.reason.own_site': 'your alliance already holds this site',
'send.invalid.no_alliance': 'Join an alliance first.', 'send.invalid.own_site': 'Your alliance holds that site.',
'send.invalid.landing_scan_or_attack_only': 'Landing sites can only be scanned or attacked.', 'send.invalid.backbone_site': 'A landing site cannot be settled.',
'mov.siteShipment': 'Shipment to a landing site',
'report.type.landing': 'Landing site attack',
'rep.vs': '{a} vs {d}', 'rep.by': 'By {name}', 'rep.attackerWon': 'Attacker won', 'rep.defenderWon': 'Defender won',
'rep.landing.title': 'Landing site {n}', 'rep.landing.taken': 'Site taken', 'rep.landing.held': 'Site held', 'rep.landing.holder': 'Holder',
'rep.landing.takenLine': '{tag} took the site.', 'rep.landing.heldLine': 'The defence held. The site did not change hands.',
'rep.tab.mine': 'My reports', 'rep.tab.alliance': 'Alliance', 'rep.sharedBy': 'shared by {name}',
'rep.folder.none': 'Join an alliance to use the shared folder.', 'rep.folder.empty': 'Nothing shared yet. Open a report and share it with the alliance.',
'rep.folder.forbidden': 'Your role may not read the shared folder.',
'rep.share': 'Share with alliance', 'rep.share.hint': 'Put this report in the alliance folder. It is kept for another 14 days from now.',
'rep.share.done': 'Shared with the alliance.', 'rep.share.already': 'Already in the alliance folder.', 'rep.share.forbidden': 'Your role may not share reports.',
'rep.unshare': 'Remove from folder', 'rep.unshare.done': 'Removed from the folder.', 'rep.unshare.forbidden': 'Only the person who shared it, or a leader or officer, may remove it.',
'err.world_ended': 'This world has ended. It can still be read, but nothing can be changed.',
'err.backbone_closed': 'The backbone landing sites have not appeared yet.',
},
nb: {
'nav.world': 'Ryggrad', 'screen.world': 'Ryggradskappløpet',
'ended.locked': 'Denne verdenen er slutt. Alt er skrivebeskyttet nå.', 'ended.pill': 'Verdenen er slutt', 'ended.title': 'Denne verdenen er slutt',
'ended.body': 'Du kan fortsatt lese alt og sende meldinger, men ingenting kan bygges, sendes eller handles lenger.', 'ended.see': 'Sluttresultat',
'wld.site': 'Landingspunkt {n}', 'wld.yours': 'Din allianse', 'wld.incumbent': 'Inkumbent', 'wld.takenBy': 'tatt av {name}',
'wld.level': 'Nivå {n} / {max}', 'wld.levelShort': 'Nodenivå', 'wld.building': 'Bygger nivå {n}', 'wld.stock': 'Lager', 'wld.coords': 'Posisjon',
'wld.manage': 'Styr', 'wld.attack': 'Skann eller angrip', 'wld.onMap': 'På kartet', 'wld.sites': 'Landingspunkter',
'wld.noSites': 'Punktene er åpne, men ingen er listet ennå. Oppdater om et øyeblikk.',
'wld.won': '{name} vant verdenen', 'wld.endedNoWinner': 'Verdenen er slutt', 'wld.wonAt': 'ferdig {t}', 'wld.endedAt': 'Sluttet {t}.',
'wld.endsIn': 'Verdenen slutter om', 'wld.winnerKeep': 'Kappløpet er avgjort. Fram til slutten kan du fortsatt kjempe om rangeringen.',
'wld.open': 'Landingspunktene er åpne', 'wld.leading': 'Leder: [{tag}] {name}, punkt {n}, nodenivå {level} av {max}',
'wld.noLeader': 'Ingen holder et landingspunkt ennå. Første allianse som skanner ett og tar det starter kappløpet.',
'wld.goal': 'Bygg Ryggradsnoden til nivå {max} først, så vinner alliansen din verdenen.',
'wld.opensIn': 'Landingspunktene dukker opp om', 'wld.day': 'Verdensdag {day} av {open}',
'wld.how.head': 'Slik slutter verdenen',
'wld.how.1': '{n} landingspunkter for ryggraden dukker opp på kartet på verdensdag {day}.',
'wld.how.2': 'En allianse tar et punkt ved å slå det statiske forsvaret: skann det først, så angrip. Eierne kan ikke stasjonere enheter der, bare bygge noden, som også gjør det vanskeligere å ta.',
'wld.how.3': 'Eierne sender Fiber, Maskinvare og Kapital til punktet sitt og bygger Ryggradsnoden nivå for nivå opp til {max}. Første node på nivå {max} vinner.',
'wld.how.4': 'Verdenen stenger {d} verdensdager etter at vinnernivået er bygget. Etter det er den skrivebeskyttet.',
'wld.lost': 'Alliansen din holder ikke dette punktet lenger.',
'wld.build.head': 'Ryggradsnode', 'wld.build.next': 'Neste: nivå {n}, tar {t}', 'wld.build.lack': 'Lageret mangler {what}.', 'wld.build.max': 'Ferdigbygd',
'wld.build.started': 'Nivå {n} bygges, ferdig om {t}.', 'wld.build.go': 'Bygg nivå {n}',
'wld.build.why.ended': 'Verdenen er slutt.', 'wld.build.why.forbidden': 'Rollen din kan ikke bygge noden.',
'wld.ship.head': 'Send ressurser', 'wld.ship.no': 'Bare medlemmer av eieralliansen kan sende.', 'wld.ship.go': 'Send', 'wld.ship.cargo': 'Last',
'wld.ship.hint': 'En forsendelse er en transport: opptil {n} per lenke. Den lander på lageret, eller drar hjem hvis punktet har skiftet eier underveis.',
'wld.ship.done': 'Forsendelsen er på vei.', 'wld.ledger': 'Hvem sendte hva',
'wld.results': 'Sluttresultat', 'wld.rank.operators': 'Operatører', 'wld.rank.alliances': 'Allianser', 'wld.rank.attackers': 'Angripere', 'wld.rank.defenders': 'Forsvarere',
'wld.rank.empty': 'Ingen på denne listen.', 'wld.rank.totals': '{o} operatører i {a} allianser',
'tile.backbone': 'Landingspunkt for ryggraden', 'map.legend.backbone': 'Landingspunkt', 'map.info.openWorld': 'Ryggradskappløpet',
'map.info.backbone': 'Et landingspunkt for ryggraden. Første allianse som bygger noden her til nivå {max} vinner verdenen.',
'send.landing.hint': 'Et landingspunkt har ingen garnison: bare det statiske forsvaret teller (en skanning viser tallet, omtrent {mult} ganger et inkumbentpunkt). Seier gjør alliansen din til eier.',
'send.transport.rival': 'Dette er en POP du ikke eier: lasten er en gave, og eieren ser en innkommende bevegelse til den lander. For handel, bruk Internettknutepunktet.',
'send.reason.no_alliance': 'bare alliansemedlemmer kan angripe et landingspunkt', 'send.reason.own_site': 'alliansen din holder allerede dette punktet',
'send.invalid.no_alliance': 'Bli med i en allianse først.', 'send.invalid.own_site': 'Alliansen din holder det punktet.',
'send.invalid.landing_scan_or_attack_only': 'Landingspunkter kan bare skannes eller angripes.', 'send.invalid.backbone_site': 'Et landingspunkt kan ikke bosettes.',
'mov.siteShipment': 'Forsendelse til et landingspunkt',
'report.type.landing': 'Angrep på landingspunkt',
'rep.vs': '{a} mot {d}', 'rep.by': 'Av {name}', 'rep.attackerWon': 'Angriper vant', 'rep.defenderWon': 'Forsvarer vant',
'rep.landing.title': 'Landingspunkt {n}', 'rep.landing.taken': 'Punktet ble tatt', 'rep.landing.held': 'Punktet holdt', 'rep.landing.holder': 'Eier',
'rep.landing.takenLine': '{tag} tok punktet.', 'rep.landing.heldLine': 'Forsvaret holdt. Punktet skiftet ikke eier.',
'rep.tab.mine': 'Mine rapporter', 'rep.tab.alliance': 'Allianse', 'rep.sharedBy': 'delt av {name}',
'rep.folder.none': 'Bli med i en allianse for å bruke den delte mappen.', 'rep.folder.empty': 'Ingenting delt ennå. Åpne en rapport og del den med alliansen.',
'rep.folder.forbidden': 'Rollen din kan ikke lese den delte mappen.',
'rep.share': 'Del med alliansen', 'rep.share.hint': 'Legg denne rapporten i alliansemappen. Den lagres i 14 dager til fra nå.',
'rep.share.done': 'Delt med alliansen.', 'rep.share.already': 'Ligger allerede i alliansemappen.', 'rep.share.forbidden': 'Rollen din kan ikke dele rapporter.',
'rep.unshare': 'Fjern fra mappen', 'rep.unshare.done': 'Fjernet fra mappen.', 'rep.unshare.forbidden': 'Bare den som delte den, eller en leder eller offiser, kan fjerne den.',
'err.world_ended': 'Denne verdenen er slutt. Den kan fortsatt leses, men ingenting kan endres.',
'err.backbone_closed': 'Landingspunktene for ryggraden har ikke dukket opp ennå.',
},
});
}));

View file

@ -131,6 +131,7 @@
case 'report':
App.refreshReportsUnread().catch(() => {});
debounce('towns', () => App.refreshTowns().catch(() => {}), 500); // a settle / takeover report changes the POP list
debounce('moves', () => App.refreshMovements().catch(() => {}), 300); // the movement that made the report is over: the incoming banner must go
App.emit('report', msg);
break;
case 'notification':