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:
parent
d84b0c9d12
commit
931f59e11e
49 changed files with 4750 additions and 59 deletions
40
public/js/screens/cargo-ui.js
Normal file
40
public/js/screens/cargo-ui.js
Normal 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 };
|
||||
}());
|
||||
|
|
@ -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')));
|
||||
|
|
|
|||
|
|
@ -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; },
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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)),
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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
503
public/js/screens/trade.js
Normal 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
412
public/js/screens/world.js
Normal 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(); },
|
||||
});
|
||||
}());
|
||||
Loading…
Add table
Add a link
Reference in a new issue