'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: R.transportCapacity(speed()) }); 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: R.transportCapacity(speed()) }) }), 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, R.transportCapacity(speed())); const wantIn = numField('wantAmount', App.t('trd.new.wantAmount'), 1, R.transportCapacity(speed())); 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(R.transportCapacity(speed()), 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 }, speed()); 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: R.transportCapacity(speed()) })); 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(R.transportCapacity(speed()), 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: R.transportCapacity(speed()), 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: R.transportCapacity(speed()) }) }), 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(); }, }); }());