Phase 2: client military/social screens, WebSocket push, trade + endgame, review findings pending
Built: units/movements/reports/send/expansion screens, alliance/messages/rankings screens, ws client + server /ws push (docs/PROTOCOL.md), Internet exchange trade, backbone endgame + world end, shared reports, buildDone relative levels. Tested: npm test 175/175. Two adversarial reviews found issues (trade-leg recall exploit, __proto__ via validate.js, rankings DoS, static headers, ...): fixes follow in the next commit. NOT done: bots/balance, e2e suite, real-device checks. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
parent
249818a7aa
commit
b18645dca1
87 changed files with 10201 additions and 71 deletions
|
|
@ -17,6 +17,9 @@
|
|||
if (n.type === 'build_done') {
|
||||
return { icon: 'b-' + p.type, title: App.t('alerts.build_done', { name: App.buildingName(p.type), level: p.level }), detail: App.t('alerts.build_done.in', { town: townName(p.townId) }), go: 'pop' };
|
||||
}
|
||||
// Other screens describe their own notification types: App.alertKinds[type] = (n, p) => ({ icon, title, detail, go, params })
|
||||
const ext = App.alertKinds && App.alertKinds[n.type];
|
||||
if (ext) return ext(n, p);
|
||||
return { icon: 'bell', title: App.t('alerts.unknown', { type: n.type }), detail: '', go: null };
|
||||
}
|
||||
|
||||
|
|
@ -28,7 +31,7 @@
|
|||
const d = describe(n);
|
||||
const isNew = n.id > seenAtOpen;
|
||||
listEl.appendChild(h('li', null,
|
||||
h('button', { class: 'alert' + (isNew ? ' new' : ''), type: 'button', onclick: () => { if (d.go) App.go(d.go); } },
|
||||
h('button', { class: 'alert' + (isNew ? ' new' : ''), type: 'button', onclick: () => { if (d.go) App.go(d.go, d.params); } },
|
||||
h('span', { class: 'row-ic' }, icon(d.icon)),
|
||||
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: d.title }), isNew ? h('span', { class: 'pill accent', text: App.t('alerts.new') }) : null),
|
||||
d.detail ? h('span', { class: 'row-sub', text: d.detail }) : null),
|
||||
|
|
@ -57,7 +60,7 @@
|
|||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'alerts', titleKey: 'screen.alerts', navKey: 'nav.alerts', icon: 'bell', hud: false,
|
||||
id: 'alerts', titleKey: 'screen.alerts', navKey: 'nav.alerts', icon: 'bell', hud: false, navGroup: 'more',
|
||||
render(container) {
|
||||
box = container;
|
||||
listEl = h('ul', { class: 'alert-list' });
|
||||
|
|
|
|||
542
public/js/screens/alliance.js
Normal file
542
public/js/screens/alliance.js
Normal file
|
|
@ -0,0 +1,542 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Alliance screen. Not in an alliance: found one (Peering office needed) and answer invitations. In one: overview with pinned
|
||||
* notes, members (role changes, kick, transfer, invite), diplomacy. What is offered follows data.js SOCIAL.permissions through
|
||||
* rules.js allianceCan/outranks (via UpstreamSocial); the server re-checks everything and its error codes are translated.
|
||||
* Every player-controlled string is set with textContent.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet } = UI;
|
||||
const Soc = UpstreamSocial;
|
||||
const R = UpstreamRules;
|
||||
const D = UpstreamData;
|
||||
const S = D.SOCIAL;
|
||||
const X = () => window.SocUI;
|
||||
|
||||
let box, body, tabsEl, content;
|
||||
let mine = null; // GET /alliances/mine
|
||||
let members = null; // GET /alliances/:id/members items
|
||||
let tab = 'overview';
|
||||
let gen = 0; // bumped on every load: stale async results are dropped
|
||||
let offTick = null;
|
||||
const cache = {}; // per-tab data
|
||||
|
||||
const myRole = () => (mine ? mine.role : null);
|
||||
const acts = () => Soc.selfActions(myRole(), members ? members.length : (mine && mine.alliance ? mine.alliance.memberCount : 0));
|
||||
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
|
||||
|
||||
// ------------------------------------------------------------------ load
|
||||
async function load() {
|
||||
const my = ++gen;
|
||||
const had = !!mine;
|
||||
if (!had) { clear(body); body.appendChild(X().loading()); }
|
||||
try {
|
||||
const m = await App.api.get('/alliances/mine');
|
||||
if (my !== gen) return;
|
||||
mine = m;
|
||||
const al = m.alliance;
|
||||
const cur = X().myAlliance();
|
||||
if ((al && (!cur || cur.id !== al.id)) || (!al && cur)) X().refreshOperator().catch(() => {});
|
||||
if (al) {
|
||||
const r = await App.api.get('/alliances/' + al.id + '/members');
|
||||
if (my !== gen) return;
|
||||
members = r.items;
|
||||
for (const k of Object.keys(cache)) delete cache[k];
|
||||
drawIn();
|
||||
} else {
|
||||
members = null;
|
||||
const inv = await App.api.get('/alliance-invites');
|
||||
if (my !== gen) return;
|
||||
cache.invites = inv.items;
|
||||
drawNone();
|
||||
}
|
||||
} catch (e) {
|
||||
if (my !== gen) return;
|
||||
clear(body);
|
||||
body.appendChild(X().errorBox(e, load));
|
||||
}
|
||||
}
|
||||
|
||||
// Reload after a change of membership (found, join, leave, kick...).
|
||||
function reload() { mine = null; members = null; tab = 'overview'; return load(); }
|
||||
|
||||
// ------------------------------------------------------------------ not in an alliance
|
||||
function drawNone() {
|
||||
clear(body);
|
||||
stopTick();
|
||||
const have = mine.peeringLevel, need = S.minPeeringLevel, ok = have >= need;
|
||||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const nameIn = h('input', { type: 'text', maxlength: String(S.nameLen[1] * 2), autocomplete: 'off', autocapitalize: 'words', spellcheck: 'false', id: 'soc-name' });
|
||||
const tagIn = h('input', { type: 'text', maxlength: String(S.tagLen[1]), autocomplete: 'off', autocapitalize: 'characters', spellcheck: 'false', id: 'soc-tag' });
|
||||
const create = h('button', { class: 'btn primary wide', type: 'button' }, icon('plus'), App.t('soc.create.go'));
|
||||
const valid = () => {
|
||||
const n = Array.from(Soc.cleanName(nameIn.value)).length, t = tagIn.value.trim();
|
||||
return ok && n >= S.nameLen[0] && n <= S.nameLen[1] && /^[A-Za-z0-9]+$/.test(t) && t.length >= S.tagLen[0] && t.length <= S.tagLen[1];
|
||||
};
|
||||
const sync = () => { create.disabled = !valid(); };
|
||||
nameIn.addEventListener('input', sync); tagIn.addEventListener('input', sync);
|
||||
create.addEventListener('click', () => X().guard(create, async () => {
|
||||
err.hidden = true;
|
||||
try {
|
||||
await App.api.post('/alliances', { name: Soc.cleanName(nameIn.value), tag: tagIn.value.trim() }, { intent: 'ally:create' });
|
||||
toast(App.t('soc.create.done'), 'ok');
|
||||
await reload();
|
||||
} catch (e) {
|
||||
err.textContent = e.code === 'validation_failed' ? App.t('soc.create.invalid', { n1: S.nameLen[0], n2: S.nameLen[1], t1: S.tagLen[0], t2: S.tagLen[1] }) : X().err(e);
|
||||
err.hidden = false;
|
||||
}
|
||||
}));
|
||||
sync();
|
||||
|
||||
body.appendChild(h('div', { class: 'card soc-card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('users'), App.t('soc.create.title'))),
|
||||
h('p', { class: 'detail-desc', text: App.t('soc.create.intro') }),
|
||||
h('ul', { class: 'reqs soc-req' }, h('li', { class: ok ? 'ok' : 'miss' }, icon(ok ? 'check' : 'lock'),
|
||||
h('span', { text: App.buildingName('peering_office') + ' ' + App.t('pop.level', { n: need }) }), h('small', { text: App.t('sheet.have', { n: have }) }))),
|
||||
ok ? null : h('p', { class: 'reason', text: App.t('soc.create.needOffice', { building: App.buildingName('peering_office'), n: need }) }),
|
||||
h('label', { class: 'field', for: 'soc-name' }, h('span', { class: 'field-lbl', text: App.t('soc.create.name') }), nameIn,
|
||||
h('span', { class: 'field-hint', text: App.t('soc.create.nameHint', { a: S.nameLen[0], b: S.nameLen[1] }) })),
|
||||
h('label', { class: 'field', for: 'soc-tag' }, h('span', { class: 'field-lbl', text: App.t('soc.create.tag') }), tagIn,
|
||||
h('span', { class: 'field-hint', text: App.t('soc.create.tagHint', { a: S.tagLen[0], b: S.tagLen[1] }) })),
|
||||
err, create));
|
||||
|
||||
const invCard = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('mail'), App.t('soc.invites.title')),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load() }, icon('refresh'))));
|
||||
const items = cache.invites || [];
|
||||
if (!items.length) invCard.appendChild(h('p', { class: 'empty', text: App.t('soc.invites.none') }));
|
||||
else {
|
||||
if (!ok) invCard.appendChild(h('p', { class: 'reason', text: App.t('soc.invites.needOffice', { building: App.buildingName('peering_office') }) }));
|
||||
const list = h('ul', { class: 'soc-list' });
|
||||
const now = App.now();
|
||||
for (const inv of items) {
|
||||
const e2 = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const acc = h('button', { class: 'btn small primary', type: 'button', text: App.t('soc.invites.accept') });
|
||||
const dec = h('button', { class: 'btn small', type: 'button', text: App.t('soc.invites.decline') });
|
||||
const answer = (accept) => X().guard(accept ? acc : dec, async () => {
|
||||
e2.hidden = true;
|
||||
try {
|
||||
await App.api.post('/alliance-invites/' + inv.id + (accept ? '/accept' : '/decline'), {}, { intent: 'ally:invite:' + inv.id });
|
||||
toast(App.t(accept ? 'soc.invites.accepted' : 'soc.invites.declined'), 'ok');
|
||||
await reload();
|
||||
} catch (e) { e2.textContent = X().err(e); e2.hidden = false; }
|
||||
});
|
||||
acc.addEventListener('click', () => answer(true));
|
||||
dec.addEventListener('click', () => answer(false));
|
||||
list.appendChild(h('li', { class: 'soc-item soc-invite' },
|
||||
h('div', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, X().tagPill(inv.alliance.tag), h('b', { text: inv.alliance.name })),
|
||||
h('span', { class: 'row-sub', text: App.t('soc.invites.from', { name: inv.invitedBy.name }) + ' · ' + App.t('soc.invites.expires', { t: App.fmt.dur(Math.max(0, inv.expiresAt - now), 2) }) })),
|
||||
h('div', { class: 'soc-actions' }, dec, acc), e2));
|
||||
}
|
||||
invCard.appendChild(list);
|
||||
}
|
||||
body.appendChild(invCard);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ in an alliance
|
||||
function drawIn() {
|
||||
clear(body);
|
||||
stopTick();
|
||||
const a = mine.alliance;
|
||||
const sizeP = a.sizeCap > 0 ? Math.min(1, a.memberCount / a.sizeCap) : 0;
|
||||
body.appendChild(h('div', { class: 'card soc-card soc-head' },
|
||||
h('div', { class: 'soc-title' }, X().tagPill(a.tag), h('h2', { class: 'soc-name', text: a.name })),
|
||||
h('div', { class: 'pill-row' }, X().rolePill(mine.role),
|
||||
h('span', { class: 'pill', text: App.t('soc.size', { n: a.memberCount, cap: a.sizeCap }) }),
|
||||
h('span', { class: 'pill', text: App.t('soc.leaderIs', { name: a.leader ? a.leader.name : '-' }) })),
|
||||
h('div', { class: 'bar', 'aria-hidden': 'true', style: { '--p': String(sizeP) } }, h('i'))));
|
||||
|
||||
const tabs = [['overview', 'soc.tab.overview'], ['members', 'soc.tab.members'], ['diplomacy', 'soc.tab.diplomacy']];
|
||||
tabsEl = h('div', { class: 'seg soc-tabs', role: 'group', 'aria-label': App.t('soc.tab.label') },
|
||||
tabs.map(([id, key]) => h('button', { class: 'seg-btn', type: 'button', dataset: { tab: id }, 'aria-pressed': String(tab === id), text: App.t(key), onclick: () => setTab(id) })));
|
||||
content = h('div', { class: 'soc-content' });
|
||||
body.appendChild(tabsEl);
|
||||
body.appendChild(content);
|
||||
drawTab();
|
||||
}
|
||||
|
||||
function setTab(id) {
|
||||
tab = id;
|
||||
for (const b of tabsEl.children) b.setAttribute('aria-pressed', String(b.dataset.tab === id));
|
||||
drawTab();
|
||||
}
|
||||
|
||||
function drawTab() {
|
||||
stopTick();
|
||||
clear(content);
|
||||
if (tab === 'members') drawMembers();
|
||||
else if (tab === 'diplomacy') drawDiplomacy();
|
||||
else drawOverview();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- overview: notes, leave / disband
|
||||
const nameOf = (id) => { const m = (members || []).find((x) => x.operatorId === id); return m ? m.name : '#' + id; };
|
||||
|
||||
async function drawOverview() {
|
||||
const my = gen;
|
||||
const A = acts();
|
||||
const notesCard = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('pencil'), App.t('soc.notes.title')),
|
||||
h('span', { class: 'pill dim mono', id: 'soc-notes-count' })));
|
||||
const notesList = h('ul', { class: 'soc-list' });
|
||||
notesCard.appendChild(notesList);
|
||||
content.appendChild(notesCard);
|
||||
|
||||
function drawNotes(items) {
|
||||
clear(notesList);
|
||||
notesCard.querySelector('#soc-notes-count').textContent = items.length + '/' + S.maxNotes;
|
||||
if (!items.length) notesList.appendChild(h('li', { class: 'empty', text: App.t('soc.notes.none') }));
|
||||
for (const n of items) {
|
||||
const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.notes.remove'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
await App.api.del('/alliances/' + mine.alliance.id + '/notes/' + n.id);
|
||||
cache.notes = cache.notes.filter((x) => x.id !== n.id);
|
||||
drawNotes(cache.notes);
|
||||
}) }, icon('x'));
|
||||
notesList.appendChild(h('li', { class: 'soc-item soc-note' },
|
||||
h('div', { class: 'row-main' }, h('p', { class: 'soc-text-out', text: n.text }),
|
||||
h('span', { class: 'row-sub', text: nameOf(n.authorId) + ' · ' + App.fmt.ago(App.now() - n.createdAt) })),
|
||||
A.editNotes ? del : null));
|
||||
}
|
||||
}
|
||||
|
||||
if (A.editNotes) {
|
||||
const ta = h('textarea', { class: 'soc-text', rows: 2, maxlength: String(S.noteMax * 2), 'aria-label': App.t('soc.notes.add'), placeholder: App.t('soc.notes.placeholder') });
|
||||
const cnt = h('span', { class: 'soc-count mono' });
|
||||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const add = h('button', { class: 'btn small primary', type: 'button' }, icon('plus'), App.t('soc.notes.add'));
|
||||
const sync = () => {
|
||||
const st = Soc.composeState(ta.value, S.noteMax);
|
||||
cnt.textContent = st.n + '/' + S.noteMax; cnt.classList.toggle('over', st.over);
|
||||
add.disabled = st.empty || st.over || (cache.notes && cache.notes.length >= S.maxNotes);
|
||||
};
|
||||
ta.addEventListener('input', sync);
|
||||
add.addEventListener('click', () => X().guard(add, async () => {
|
||||
err.hidden = true;
|
||||
try {
|
||||
const r = await App.api.post('/alliances/' + mine.alliance.id + '/notes', { text: ta.value });
|
||||
cache.notes = (cache.notes || []).concat([r.note]);
|
||||
ta.value = '';
|
||||
drawNotes(cache.notes); sync();
|
||||
} catch (e) { err.textContent = X().err(e); err.hidden = false; }
|
||||
}));
|
||||
notesCard.appendChild(h('div', { class: 'soc-addnote' }, ta, h('div', { class: 'soc-composer-bar' }, cnt, add), err));
|
||||
sync();
|
||||
}
|
||||
|
||||
// leave / disband
|
||||
const danger = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('shield'), App.t('soc.manage.title'))));
|
||||
const row = h('div', { class: 'btn-row soc-stack' });
|
||||
if (A.leaveNeedsTransfer) {
|
||||
danger.appendChild(h('p', { class: 'reason', text: App.t('soc.leave.mustTransfer') }));
|
||||
row.appendChild(h('button', { class: 'btn', type: 'button', onclick: () => setTab('members') }, icon('users'), App.t('soc.leave.goTransfer')));
|
||||
} else {
|
||||
row.appendChild(h('button', { class: 'btn danger', type: 'button', onclick: confirmLeave }, icon('logout'), App.t('soc.leave.go')));
|
||||
}
|
||||
if (A.disband) row.appendChild(h('button', { class: 'btn danger', type: 'button', onclick: confirmDisband }, icon('x'), App.t('soc.disband.go')));
|
||||
danger.appendChild(row);
|
||||
content.appendChild(danger);
|
||||
|
||||
if (cache.notes) { drawNotes(cache.notes); return; }
|
||||
notesList.appendChild(X().loading());
|
||||
try {
|
||||
const r = await App.api.get('/alliances/' + mine.alliance.id + '/notes');
|
||||
if (my !== gen) return;
|
||||
cache.notes = r.items;
|
||||
if (tab === 'overview') drawNotes(cache.notes);
|
||||
} catch (e) { if (my === gen && tab === 'overview') { clear(notesList); notesList.appendChild(X().errorBox(e, drawTab)); } }
|
||||
}
|
||||
|
||||
function confirmLeave() {
|
||||
const alone = members && members.length <= 1;
|
||||
X().confirmSheet({
|
||||
title: App.t('soc.leave.go'), icon: 'logout', danger: true, ok: App.t('soc.leave.go'),
|
||||
text: App.t(alone ? 'soc.leave.confirmAlone' : 'soc.leave.confirm', { name: mine.alliance.name }),
|
||||
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/leave', {}, { intent: 'ally:leave' }); toast(App.t('soc.leave.done'), 'ok'); await reload(); },
|
||||
});
|
||||
}
|
||||
|
||||
function confirmDisband() {
|
||||
X().confirmSheet({
|
||||
title: App.t('soc.disband.go'), icon: 'alert', danger: true, ok: App.t('soc.disband.go'),
|
||||
text: App.t('soc.disband.confirm', { name: mine.alliance.name }),
|
||||
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/disband', {}, { intent: 'ally:disband' }); toast(App.t('soc.disband.done'), 'ok'); await reload(); },
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- members
|
||||
function drawMembers() {
|
||||
const A = acts();
|
||||
const now = App.now();
|
||||
const card = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('users'), App.t('soc.members')),
|
||||
h('span', { class: 'pill dim mono', text: App.t('soc.size', { n: members.length, cap: mine.alliance.sizeCap }) })));
|
||||
const list = h('ul', { class: 'soc-list' });
|
||||
for (const m of members) {
|
||||
const you = m.operatorId === X().myOperatorId();
|
||||
list.appendChild(h('li', null, h('button', { class: 'row-btn soc-member', type: 'button', onclick: () => openMember(m) },
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: m.name }), you ? h('span', { class: 'pill accent', text: App.t('soc.you') }) : null, X().rolePill(m.role)),
|
||||
h('span', { class: 'row-sub', text: App.t('soc.member.stats', { towns: m.towns, fp: App.fmt.dec(m.footprint) }) + ' · ' + (m.lastOnline ? App.t('soc.member.online', { t: App.fmt.ago(now - m.lastOnline) }) : App.t('soc.member.never')) })))));
|
||||
}
|
||||
card.appendChild(list);
|
||||
content.appendChild(card);
|
||||
|
||||
if (A.invite) drawInvite();
|
||||
}
|
||||
|
||||
async function drawInvite() {
|
||||
const my = gen;
|
||||
const card = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('mail'), App.t('soc.invite.title'))));
|
||||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const nameIn = h('input', { type: 'text', maxlength: '40', autocomplete: 'off', spellcheck: 'false', 'aria-label': App.t('soc.invite.name'), placeholder: App.t('soc.invite.name'), enterkeyhint: 'send' });
|
||||
const go = h('button', { class: 'btn primary', type: 'button' }, icon('up'), App.t('soc.invite.go'));
|
||||
const pend = h('ul', { class: 'soc-list' });
|
||||
const sync = () => { go.disabled = !Soc.cleanName(nameIn.value); };
|
||||
nameIn.addEventListener('input', sync);
|
||||
nameIn.addEventListener('keydown', (ev) => { if (ev.key === 'Enter' && !go.disabled) go.click(); });
|
||||
go.addEventListener('click', () => X().guard(go, async () => {
|
||||
err.hidden = true;
|
||||
const name = Soc.cleanName(nameIn.value);
|
||||
try {
|
||||
const r = await App.api.post('/alliances/' + mine.alliance.id + '/invite', { name }, { intent: 'ally:invite:' + name.toLowerCase() });
|
||||
toast(App.t(r.changed ? 'soc.invite.sent' : 'soc.invite.already', { name }), 'ok');
|
||||
nameIn.value = ''; sync();
|
||||
loadPending();
|
||||
} catch (e) { err.textContent = e.code === 'not_found' ? App.t('soc.invite.unknown', { name }) : X().err(e); err.hidden = false; }
|
||||
}));
|
||||
sync();
|
||||
card.appendChild(h('div', { class: 'soc-inline' }, nameIn, go));
|
||||
card.appendChild(err);
|
||||
if (acts().viewInvites) { card.appendChild(h('div', { class: 'sub', text: App.t('soc.invite.pending') })); card.appendChild(pend); }
|
||||
content.appendChild(card);
|
||||
|
||||
async function loadPending() {
|
||||
if (!acts().viewInvites) return;
|
||||
try {
|
||||
const r = await App.api.get('/alliances/' + mine.alliance.id + '/invites');
|
||||
if (my !== gen || tab !== 'members') return;
|
||||
clear(pend);
|
||||
if (!r.items.length) pend.appendChild(h('li', { class: 'empty', text: App.t('soc.invite.none') }));
|
||||
const now = App.now();
|
||||
for (const inv of r.items) {
|
||||
const cancel = h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.invite.cancel'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
await App.api.del('/alliances/' + mine.alliance.id + '/invites/' + inv.id);
|
||||
loadPending();
|
||||
}) }, icon('x'));
|
||||
pend.appendChild(h('li', { class: 'soc-item' }, h('div', { class: 'row-main' }, h('b', { text: inv.operator.name }),
|
||||
h('span', { class: 'row-sub', text: App.t('soc.invites.from', { name: inv.invitedBy.name }) + ' · ' + App.t('soc.invites.expires', { t: App.fmt.dur(Math.max(0, inv.expiresAt - now), 2) }) })),
|
||||
acts().cancelInvite ? cancel : null));
|
||||
}
|
||||
} catch (e) { if (my === gen && tab === 'members') { clear(pend); pend.appendChild(X().errorBox(e, loadPending)); } }
|
||||
}
|
||||
loadPending();
|
||||
}
|
||||
|
||||
// Member sheet: message, role (leader), transfer (leader), kick (outranking).
|
||||
function openMember(m) {
|
||||
const act = Soc.memberActions(myRole(), m, X().myOperatorId());
|
||||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const bodyEl = h('div', { class: 'detail' });
|
||||
const sheet = openSheet({ title: m.name, icon: 'users', closeLabel: App.t('common.close'), body: bodyEl });
|
||||
const after = async () => { sheet.close(); await load(); };
|
||||
const run = (btn, fn) => X().guard(btn, async () => { err.hidden = true; try { await fn(); } catch (e) { err.textContent = X().err(e); err.hidden = false; } });
|
||||
|
||||
bodyEl.appendChild(h('div', { class: 'pill-row' }, X().rolePill(m.role), h('span', { class: 'pill mono', text: 'AS' + m.asNumber })));
|
||||
bodyEl.appendChild(h('div', null,
|
||||
kv(App.t('soc.member.pops'), String(m.towns)), kv(App.t('soc.footprint'), App.fmt.dec(m.footprint)),
|
||||
kv(App.t('soc.member.lastOnline'), m.lastOnline ? App.fmt.ago(App.now() - m.lastOnline) : App.t('soc.member.never')),
|
||||
kv(App.t('soc.member.joined'), App.fmt.ago(App.now() - m.joinedAt))));
|
||||
if (act.message) bodyEl.appendChild(h('button', { class: 'btn wide', type: 'button', onclick: () => { sheet.close(); X().openCompose({ operator: { operatorId: m.operatorId, name: m.name } }); } }, icon('mail'), App.t('soc.member.message')));
|
||||
if (act.roles.length) {
|
||||
bodyEl.appendChild(h('div', { class: 'sub', text: App.t('soc.member.setRole') }));
|
||||
bodyEl.appendChild(h('div', { class: 'seg' }, act.roles.map((r) => h('button', { class: 'seg-btn', type: 'button', text: X().role(r), onclick: (ev) => run(ev.currentTarget, async () => {
|
||||
await App.api.post('/alliances/' + mine.alliance.id + '/role', { operatorId: m.operatorId, role: r }, { intent: 'ally:role:' + m.operatorId + ':' + r });
|
||||
toast(App.t('soc.member.roleSet', { name: m.name, role: X().role(r) }), 'ok');
|
||||
await after();
|
||||
}) }))));
|
||||
bodyEl.appendChild(h('p', { class: 'field-hint', text: App.t('soc.member.roleHint') }));
|
||||
}
|
||||
const row = h('div', { class: 'btn-row soc-stack' });
|
||||
if (act.transfer) row.appendChild(h('button', { class: 'btn', type: 'button', onclick: () => {
|
||||
sheet.close();
|
||||
X().confirmSheet({ title: App.t('soc.transfer.go'), icon: 'shield', ok: App.t('soc.transfer.go'), text: App.t('soc.transfer.confirm', { name: m.name }),
|
||||
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/transfer', { operatorId: m.operatorId }, { intent: 'ally:transfer:' + m.operatorId }); toast(App.t('soc.transfer.done', { name: m.name }), 'ok'); await load(); } });
|
||||
} }, icon('shield'), App.t('soc.transfer.go')));
|
||||
if (act.kick) row.appendChild(h('button', { class: 'btn danger', type: 'button', onclick: () => {
|
||||
sheet.close();
|
||||
X().confirmSheet({ title: App.t('soc.kick.go'), icon: 'alert', danger: true, ok: App.t('soc.kick.go'), text: App.t('soc.kick.confirm', { name: m.name }),
|
||||
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/kick', { operatorId: m.operatorId }, { intent: 'ally:kick:' + m.operatorId }); toast(App.t('soc.kick.done', { name: m.name }), 'ok'); await load(); } });
|
||||
} }, icon('x'), App.t('soc.kick.go')));
|
||||
if (row.children.length) bodyEl.appendChild(row);
|
||||
bodyEl.appendChild(err);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- diplomacy
|
||||
async function drawDiplomacy() {
|
||||
const my = gen;
|
||||
const A = acts();
|
||||
const card = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('shield'), App.t('soc.dip.title')),
|
||||
A.diplomacy ? h('button', { class: 'btn small primary', type: 'button', onclick: openPicker }, icon('plus'), App.t('soc.dip.new')) : null));
|
||||
const holder = h('div', { class: 'soc-dip' }, X().loading());
|
||||
card.appendChild(holder);
|
||||
if (!A.diplomacy) card.appendChild(h('p', { class: 'field-hint', text: App.t('soc.dip.readOnly') }));
|
||||
content.appendChild(card);
|
||||
|
||||
const draw = (d) => {
|
||||
cache.dip = d;
|
||||
clear(holder);
|
||||
stopTick();
|
||||
if (d.proposalsIn.length) holder.appendChild(proposalBlock('soc.dip.incoming', d.proposalsIn, 'in'));
|
||||
holder.appendChild(h('div', { class: 'sub', text: App.t('soc.dip.relations') }));
|
||||
if (!d.relations.length) holder.appendChild(h('p', { class: 'empty', text: App.t('soc.dip.none') }));
|
||||
const list = h('ul', { class: 'soc-list' });
|
||||
for (const r of d.relations) list.appendChild(relationRow(r));
|
||||
holder.appendChild(list);
|
||||
if (d.proposalsOut.length) holder.appendChild(proposalBlock('soc.dip.outgoing', d.proposalsOut, 'out'));
|
||||
const cds = holder.querySelectorAll('[data-eff]');
|
||||
if (cds.length) {
|
||||
offTick = App.onTick((now) => {
|
||||
for (const el of cds) {
|
||||
if (!el.isConnected) continue;
|
||||
const left = Math.max(0, Number(el.dataset.eff) - now);
|
||||
const s = left > 0 ? App.t('soc.dip.in', { t: App.fmt.dur(left, 2) }) : App.t('soc.dip.applying');
|
||||
if (el.textContent !== s) el.textContent = s;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const refetch = async () => {
|
||||
try {
|
||||
const d = await App.api.get('/alliances/' + mine.alliance.id + '/diplomacy');
|
||||
if (my !== gen || tab !== 'diplomacy') return;
|
||||
draw(d);
|
||||
} catch (e) { if (my === gen && tab === 'diplomacy') { clear(holder); holder.appendChild(X().errorBox(e, drawTab)); } }
|
||||
};
|
||||
refreshDip = refetch;
|
||||
if (cache.dip) draw(cache.dip);
|
||||
refetch();
|
||||
}
|
||||
let refreshDip = () => {};
|
||||
|
||||
function allianceLabel(other) {
|
||||
return h('span', { class: 'row-title' }, other.tag ? X().tagPill(other.tag) : null, h('b', { text: other.name || '#' + other.id }));
|
||||
}
|
||||
|
||||
function relationRow(r) {
|
||||
const A = acts();
|
||||
const now = App.now();
|
||||
const p = r.pending;
|
||||
const eta = p ? h('span', { class: 'soc-eta mono', dataset: { eff: p.effectiveAt }, text: App.t('soc.dip.in', { t: App.fmt.dur(Math.max(0, p.effectiveAt - now), 2) }) }) : null;
|
||||
const revoke = p && p.byUs && A.diplomacy
|
||||
? h('button', { class: 'btn small', type: 'button', text: App.t('soc.dip.revoke'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
await App.api.del('/alliances/' + mine.alliance.id + '/diplomacy/' + r.other.id + '/pending');
|
||||
toast(App.t('soc.dip.revoked'), 'ok'); refreshDip();
|
||||
}) }) : null;
|
||||
return h('li', { class: 'soc-item soc-rel' },
|
||||
h('div', { class: 'row-main' }, allianceLabel(r.other),
|
||||
h('span', { class: 'row-sub' }, h('span', { class: 'pill soc-state soc-state-' + r.state, text: X().state(r.state) }),
|
||||
p ? h('span', { class: 'soc-pending' }, ' → ', h('b', { text: X().state(p.to) }), ' · ', eta, ' · ', p.byUs ? App.t('soc.dip.byUs') : App.t('soc.dip.byThem')) : null)),
|
||||
revoke);
|
||||
}
|
||||
|
||||
function proposalBlock(titleKey, items, dir) {
|
||||
const A = acts();
|
||||
const wrap = h('div', null, h('div', { class: 'sub', text: App.t(titleKey) }));
|
||||
const list = h('ul', { class: 'soc-list' });
|
||||
const now = App.now();
|
||||
for (const pr of items) {
|
||||
const mk = (label, cls, path, method) => h('button', { class: 'btn small ' + cls, type: 'button', text: label, onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
try {
|
||||
if (method === 'del') await App.api.del(path); else await App.api.post(path, {}, { intent: 'dip:' + path });
|
||||
refreshDip();
|
||||
} catch (e) { toast(X().err(e), 'error'); refreshDip(); }
|
||||
}) });
|
||||
const btns = !A.diplomacy ? [] : dir === 'in'
|
||||
? [mk(App.t('soc.dip.decline'), '', '/diplomacy/proposals/' + pr.id + '/decline'), mk(App.t('soc.dip.accept'), 'primary', '/diplomacy/proposals/' + pr.id + '/accept')]
|
||||
: [mk(App.t('soc.dip.withdraw'), '', '/diplomacy/proposals/' + pr.id, 'del')];
|
||||
list.appendChild(h('li', { class: 'soc-item soc-rel' },
|
||||
h('div', { class: 'row-main' }, allianceLabel(pr.other),
|
||||
h('span', { class: 'row-sub' }, h('span', { class: 'pill soc-state soc-state-' + pr.state, text: X().state(pr.state) }), h('span', { text: App.t('soc.dip.expires', { t: App.fmt.dur(Math.max(0, pr.expiresAt - now), 2) }) }))),
|
||||
h('div', { class: 'soc-actions' }, btns)));
|
||||
}
|
||||
wrap.appendChild(list);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
// Pick another alliance (directory search), then the move.
|
||||
function openPicker() {
|
||||
const results = h('ul', { class: 'soc-list' });
|
||||
const q = h('input', { type: 'text', maxlength: '40', autocomplete: 'off', spellcheck: 'false', placeholder: App.t('soc.dip.search'), 'aria-label': App.t('soc.dip.search'), enterkeyhint: 'search' });
|
||||
const more = h('button', { class: 'btn small wide', type: 'button', hidden: true, text: App.t('soc.more') });
|
||||
let items = [], next = null, seq = 0, timer = null;
|
||||
const sheet = openSheet({ title: App.t('soc.dip.pick'), icon: 'shield', closeLabel: App.t('common.close'), onClose: () => clearTimeout(timer),
|
||||
body: h('div', { class: 'detail' }, q, results, more) });
|
||||
|
||||
function drawResults() {
|
||||
clear(results);
|
||||
const rows = items.filter((x) => x.id !== mine.alliance.id);
|
||||
if (!rows.length) results.appendChild(h('li', { class: 'empty', text: App.t('soc.dip.noResults') }));
|
||||
for (const a of rows) {
|
||||
results.appendChild(h('li', null, h('button', { class: 'row-btn', type: 'button', onclick: () => { sheet.close(); openMove(a); } },
|
||||
h('span', { class: 'row-main' }, allianceLabel(a), h('span', { class: 'row-sub', text: App.t('soc.size', { n: a.memberCount, cap: a.sizeCap }) })))));
|
||||
}
|
||||
more.hidden = next === null;
|
||||
}
|
||||
async function search(append) {
|
||||
const my = ++seq;
|
||||
try {
|
||||
const r = await App.api.get('/alliances', { q: q.value.trim() || undefined, after: append ? next : undefined, limit: 30 });
|
||||
if (my !== seq) return;
|
||||
items = append ? items.concat(r.items) : r.items; next = r.next;
|
||||
drawResults();
|
||||
} catch (e) { if (my === seq) { clear(results); results.appendChild(X().errorBox(e, () => search(false))); } }
|
||||
}
|
||||
q.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(() => search(false), 250); });
|
||||
more.addEventListener('click', () => search(true));
|
||||
search(false);
|
||||
}
|
||||
|
||||
function openMove(other) {
|
||||
const d = cache.dip || { relations: [] };
|
||||
const cur = Soc.relationTo(d.relations, other.id);
|
||||
const opts = Soc.diplomacyOptions(cur.state, cur.pending);
|
||||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const list = h('div', { class: 'soc-moves' });
|
||||
const sheet = openSheet({ title: other.name, icon: 'shield', closeLabel: App.t('common.close'),
|
||||
body: h('div', { class: 'detail' },
|
||||
h('div', { class: 'pill-row' }, X().tagPill(other.tag), h('span', { class: 'pill soc-state soc-state-' + cur.state, text: App.t('soc.dip.current', { state: X().state(cur.state) }) })),
|
||||
cur.pending ? h('p', { class: 'reason', text: App.t('soc.dip.locked') }) : null,
|
||||
!opts.length && !cur.pending ? h('p', { class: 'empty', text: App.t('soc.dip.noMoves') }) : null,
|
||||
list, err) });
|
||||
for (const o of opts) {
|
||||
const hint = o.kind === 'delayed' ? App.t('soc.kind.delayed.hint', { t: App.fmt.dur(R.pactCancelMs(App.state.world ? App.state.world.speed : 1), 2) }) : App.t('soc.kind.' + o.kind + '.hint');
|
||||
list.appendChild(h('button', { class: 'row-btn soc-move', type: 'button', onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
err.hidden = true;
|
||||
try {
|
||||
const r = await App.api.post('/alliances/' + mine.alliance.id + '/diplomacy', { targetId: other.id, state: o.state }, { intent: 'dip:' + other.id + ':' + o.state });
|
||||
toast(App.t('soc.dip.result.' + r.result, { state: X().state(r.state), name: other.name }), 'ok');
|
||||
sheet.close();
|
||||
cache.dip = null;
|
||||
if (tab === 'diplomacy') drawTab();
|
||||
} catch (e) { err.textContent = X().err(e); err.hidden = false; }
|
||||
}) },
|
||||
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('span', { class: 'pill soc-state soc-state-' + o.state, text: X().state(o.state) }), h('b', { text: App.t('soc.kind.' + o.kind) })), h('span', { class: 'row-sub soc-wrap', text: hint }))));
|
||||
}
|
||||
}
|
||||
|
||||
function stopTick() { if (offTick) { offTick(); offTick = null; } }
|
||||
|
||||
App.registerScreen({
|
||||
id: 'alliance', titleKey: 'screen.alliance', navKey: 'nav.alliance', icon: 'users', hud: false, navGroup: 'more',
|
||||
render(container) {
|
||||
box = container;
|
||||
body = h('div', { class: 'soc-body' });
|
||||
box.appendChild(h('div', { class: 'page soc-page' },
|
||||
h('div', { class: 'card-head page-head' }, h('h1', { id: 'soc-alliance-h', text: App.t('screen.alliance') }),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load() }, icon('refresh'))),
|
||||
body));
|
||||
App.on('session', () => { mine = null; members = null; tab = 'overview'; for (const k of Object.keys(cache)) delete cache[k]; });
|
||||
},
|
||||
onShow() { box.querySelector('#soc-alliance-h').textContent = App.t('screen.alliance'); load(); },
|
||||
onHide() { stopTick(); gen++; },
|
||||
});
|
||||
}());
|
||||
50
public/js/screens/expand.js
Normal file
50
public/js/screens/expand.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Expansion on the POP screen (App.popSections, slot 'main'): your POPs (switch between them), and what founding the next
|
||||
* one takes: rollout crews at home, the footprint gate, a shortcut to the map to pick a site (the map tile sheet then offers
|
||||
* "Send" -> Settle with the wild-slot choice, see send.js). The founding itself is a settle movement; the settle report has
|
||||
* an "Open POP" button. The POP switcher in the resource bar lives in main.js.
|
||||
*/
|
||||
(function () {
|
||||
const { h, icon, toast } = UI;
|
||||
const R = UpstreamRules;
|
||||
const D = UpstreamData;
|
||||
const mil = () => App.mil;
|
||||
|
||||
function popsList(t) {
|
||||
const st = App.state;
|
||||
return h('ul', { class: 'mil-list' }, st.towns.map((x) => h('li', { class: 'mil-row' + (x.id === t.id ? ' current' : '') },
|
||||
h('span', { class: 'row-ic' }, icon('pop')),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: x.name }), x.isCapital ? h('span', { class: 'pill accent', text: App.t('pop.capital') }) : null),
|
||||
h('span', { class: 'row-sub' }, mil().coordLink(x.x, x.y))),
|
||||
x.id === t.id ? h('span', { class: 'pill green', text: App.t('exp.current') })
|
||||
: h('button', { class: 'btn small', type: 'button', onclick: () => { App.setTown(x.id); } }, App.t('exp.open')))));
|
||||
}
|
||||
|
||||
function card(t) {
|
||||
const m = t.military;
|
||||
const owned = App.state.towns.length;
|
||||
const need = R.footprintNeeded(owned);
|
||||
const crews = m ? (m.units.home[D.EXPANSION.settleUnit] || 0) : 0;
|
||||
const canTrain = m && m.trainable.some((u) => u.unit === D.EXPANSION.settleUnit && !u.locked);
|
||||
const rows = [
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('exp.crews') }), h('span', { class: 'v mono' + (crews >= D.EXPANSION.crews ? ' good' : ''), text: crews + ' / ' + D.EXPANSION.crews })),
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('exp.footprint') }), h('span', { class: 'v mono', text: App.t('exp.footprint.v', { have: App.fmt.num(t.footprint), need: App.fmt.num(need) }) })),
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('exp.range') }), h('span', { class: 'v mono', text: D.EXPANSION.maxDistance + ' ' + App.t('common.tiles') })),
|
||||
];
|
||||
const actions = [];
|
||||
if (crews >= D.EXPANSION.crews) {
|
||||
actions.push(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { App.go('map', { x: t.x, y: t.y, zoom: 24 }); toast(App.t('exp.pick'), 'ok'); } }, icon('flag'), App.t('exp.found')));
|
||||
} else {
|
||||
actions.push(h('p', { class: 'row-sub wrap', text: canTrain ? App.t('exp.needCrews', { n: D.EXPANSION.crews - crews, unit: mil().unitName(D.EXPANSION.settleUnit) }) : App.t('exp.needDepot') }));
|
||||
if (canTrain) actions.push(h('button', { class: 'btn wide', type: 'button', onclick: () => App.go('units') }, icon('units'), App.t('exp.train')));
|
||||
}
|
||||
return h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('flag'), App.t('exp.title')), h('span', { class: 'pill', text: App.t('exp.count', { n: owned }) })),
|
||||
rows, h('p', { class: 'row-sub wrap', text: App.t('exp.hint') }), actions,
|
||||
owned > 1 ? [h('h3', { class: 'sub', text: App.t('exp.pops') }), popsList(t)] : null);
|
||||
}
|
||||
|
||||
App.popSections.push({ slot: 'main', render: card });
|
||||
}());
|
||||
|
|
@ -77,7 +77,7 @@
|
|||
}
|
||||
|
||||
// ------------------------------------------------------------------ screen
|
||||
let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own';
|
||||
let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own', offMoveTick = null;
|
||||
const store = new Store();
|
||||
let infoSheet = null;
|
||||
|
||||
|
|
@ -113,6 +113,8 @@
|
|||
forEachSpecial: (a, b, c, d, fn) => store.forEachSpecial(a, b, c, d, fn),
|
||||
townsInRect: (a, b, c, d) => store.townsInRect(a, b, c, d),
|
||||
isOwn: (t) => t.owner.id === ownOperatorId(),
|
||||
movements: () => moveLines(),
|
||||
threatened: (t) => App.mil.moves.incoming.some((m) => m.to && m.to.townId === t.id),
|
||||
};
|
||||
view = new MapRender.MapView(canvas, source, {
|
||||
onTap: onTap,
|
||||
|
|
@ -128,6 +130,21 @@
|
|||
drawLegend();
|
||||
}
|
||||
|
||||
// Lines for the movements of the shared cache (App.mil.moves): yours, incoming and allied ones, with progress at draw time.
|
||||
function moveLines() {
|
||||
const mv = App.mil && App.mil.moves;
|
||||
if (!mv) return [];
|
||||
const now = App.now(), out = [];
|
||||
const add = (m, kind) => {
|
||||
if (!m.from || !m.to || m.from.x === undefined || m.to.x === undefined) return;
|
||||
out.push({ from: m.from, to: m.to, kind, p: (now - m.departAt) / Math.max(1, m.arriveAt - m.departAt) });
|
||||
};
|
||||
for (const m of mv.outgoing) add(m, m.type === 'return' ? 'ret' : 'out');
|
||||
for (const m of mv.incoming) add(m, 'in');
|
||||
for (const m of mv.alliedIncoming || []) add(m, 'ally');
|
||||
return out;
|
||||
}
|
||||
|
||||
function drawLegend() {
|
||||
UI.clear(legendEl);
|
||||
const item = (cls, text) => h('li', null, h('span', { class: 'lg ' + cls }), text);
|
||||
|
|
@ -135,6 +152,8 @@
|
|||
legendEl.appendChild(item('rival', App.t('map.legend.rival')));
|
||||
legendEl.appendChild(item('rural', App.t('map.legend.rural')));
|
||||
legendEl.appendChild(item('incumbent', App.t('map.legend.incumbent')));
|
||||
legendEl.appendChild(item('mv-out', App.t('map.legend.out')));
|
||||
legendEl.appendChild(item('mv-in', App.t('map.legend.in')));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tile info
|
||||
|
|
@ -174,6 +193,9 @@
|
|||
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
|
||||
}
|
||||
body.push(row('', App.t('map.info.coords', { x, y })));
|
||||
if (App.openSend && App.state.towns.length && (town || (special && special.type === 'incumbent') || (!special && known))) {
|
||||
body.push(h('button', { class: 'btn wide' + (town && town.owner.id === ownOperatorId() ? '' : ' primary'), type: 'button', onclick: () => App.openSend({ x, y }) }, icon('target'), App.t('send.open')));
|
||||
}
|
||||
if (cap && !(town && town.id === cap.id)) body.push(row('', App.t('map.info.distance', { d: App.fmt.dec(R.distance(cap.x, cap.y, x, y)) })));
|
||||
if (town && town.owner.id === ownOperatorId() && App.state.towns.some((t) => t.id === town.id)) {
|
||||
body.push(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { closeSheet(); App.setTown(town.id); App.go('pop'); } }, icon('pop'), App.t('map.info.open')));
|
||||
|
|
@ -192,10 +214,19 @@
|
|||
render(container) {
|
||||
box = container;
|
||||
App.on('session', () => { store.reset(); pendingFocus = 'own'; });
|
||||
App.on('movements', () => { if (visible && view) view.invalidate(); });
|
||||
App.on('towns', () => { if (view) view.invalidate(); });
|
||||
App.on('town', () => { const t = App.state.townData; if (t) store.patchTown(t.id, { name: t.name }); });
|
||||
},
|
||||
onShow(params) {
|
||||
visible = true;
|
||||
// marker positions move with the clock: redraw about once a second while any movement is on the wire
|
||||
if (offMoveTick) offMoveTick();
|
||||
let lastSec = 0;
|
||||
offMoveTick = App.onTick((now) => {
|
||||
const sec = Math.floor(now / 1000), mv = App.mil.moves;
|
||||
if (sec !== lastSec && view && (mv.outgoing.length || mv.incoming.length || (mv.alliedIncoming || []).length)) { lastSec = sec; view.invalidate(); }
|
||||
});
|
||||
if (!App.state.world) { UI.clear(box); box.appendChild(h('p', { class: 'empty pad', text: App.t('map.noWorld') })); ready = false; return; }
|
||||
setup();
|
||||
view.setWorld(App.state.world.mapRadius);
|
||||
|
|
@ -208,7 +239,7 @@
|
|||
// the container was display:none until now: measure after layout
|
||||
requestAnimationFrame(() => { if (view.resize()) apply(); else setTimeout(() => { view.resize(); apply(); }, 60); });
|
||||
},
|
||||
onHide() { visible = false; closeSheet(); },
|
||||
onHide() { visible = false; if (offMoveTick) offMoveTick(); offMoveTick = null; closeSheet(); },
|
||||
onLang() {
|
||||
if (!ready) return;
|
||||
canvas.setAttribute('aria-label', App.t('map.label'));
|
||||
|
|
|
|||
334
public/js/screens/messages.js
Normal file
334
public/js/screens/messages.js
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Messages: inbox, sent, alliance broadcast feed, blocked operators, one thread per operator, compose. Message text is
|
||||
* plain text and only ever set with textContent (the CSS keeps line breaks). Lists are newest first and paged with
|
||||
* `after` = the last id (the next page holds OLDER ids). The unread count of the inbox is polled in the background and
|
||||
* shown through App.setBadge on the nav entry (or the "More" button).
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet } = UI;
|
||||
const Soc = UpstreamSocial;
|
||||
const D = UpstreamData;
|
||||
const X = () => window.SocUI;
|
||||
const PAGE = 30;
|
||||
|
||||
let box, tabsEl, listBox, tab = 'inbox';
|
||||
let thread = null; // { peer: {operatorId, name}, items, next, loading } while a conversation is open
|
||||
let blocked = null; // Map operatorId -> name (loaded lazily)
|
||||
let unreadOnly = false;
|
||||
let offTick = null, gen = 0;
|
||||
const feeds = { inbox: blank(), sent: blank(), alliance: blank() };
|
||||
let blocks = { items: null, err: null };
|
||||
|
||||
function blank() { return { items: [], next: null, loaded: false, loading: false, err: null }; }
|
||||
const inAlliance = () => !!X().myAlliance();
|
||||
const urls = { inbox: '/messages/inbox', sent: '/messages/outbox', alliance: '/messages/alliance' };
|
||||
|
||||
// ------------------------------------------------------------------ unread badge (works without the screen being open)
|
||||
const badge = { n: 0, polling: false };
|
||||
async function pollUnread() {
|
||||
if (!App.state.user || badge.polling || document.hidden) return;
|
||||
badge.polling = true;
|
||||
try { const r = await App.api.get('/messages/inbox', { limit: 1 }); setUnread(r.unread || 0); } catch (e) { /* a badge is a convenience */ } finally { badge.polling = false; }
|
||||
}
|
||||
// App.setBadge (main.js) shows it on this screen's nav button, or summed on the "More" button when the screen lives there.
|
||||
function setUnread(n) { badge.n = n; App.state.unreadMsgs = n; App.setBadge('messages', n, 'info'); }
|
||||
setInterval(pollUnread, 60000);
|
||||
document.addEventListener('visibilitychange', () => { if (!document.hidden) pollUnread(); });
|
||||
App.on('session', () => { setUnread(0); for (const k of Object.keys(feeds)) feeds[k] = blank(); blocks = { items: null, err: null }; thread = null; setTimeout(pollUnread, 800); });
|
||||
|
||||
// ------------------------------------------------------------------ loading
|
||||
async function loadFeed(kind, more) {
|
||||
const f = feeds[kind];
|
||||
if (f.loading) return;
|
||||
f.loading = true; f.err = null;
|
||||
const my = gen;
|
||||
if (kind === tab && !thread) drawList();
|
||||
try {
|
||||
const q = { limit: PAGE };
|
||||
if (more && f.next) q.after = f.next;
|
||||
if (kind === 'inbox' && unreadOnly) q.unread = true;
|
||||
const r = await App.api.get(urls[kind], q);
|
||||
f.items = more ? Soc.mergeMessages(f.items, r.items) : r.items;
|
||||
f.next = r.next; f.loaded = true;
|
||||
if (kind === 'inbox' && typeof r.unread === 'number') setUnread(r.unread);
|
||||
} catch (e) { f.err = e; if (kind === 'alliance' && e.code === 'not_in_alliance') { f.items = []; f.next = null; f.loaded = true; f.err = null; } } finally {
|
||||
f.loading = false;
|
||||
if (my === gen && kind === tab && !thread) drawList();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBlocks() {
|
||||
blocks.err = null;
|
||||
try { blocks.items = (await App.api.get('/messages/blocks')).items; blocked = new Map(blocks.items.map((b) => [b.operatorId, b.name])); } catch (e) { blocks.err = e; }
|
||||
if (tab === 'blocked' && !thread) drawList();
|
||||
}
|
||||
|
||||
async function markRead(ids) {
|
||||
if (!ids.length) return;
|
||||
try {
|
||||
await App.api.post('/messages/read', { ids: ids.slice(0, 100) });
|
||||
const now = App.now(), set = new Set(ids);
|
||||
for (const k of Object.keys(feeds)) for (const m of feeds[k].items) if (set.has(m.id) && !m.readAt) m.readAt = now;
|
||||
if (thread) for (const m of thread.items) if (set.has(m.id) && !m.readAt) m.readAt = now;
|
||||
pollUnread();
|
||||
} catch (e) { /* unread state only */ }
|
||||
}
|
||||
|
||||
async function deleteMessage(m, btn) {
|
||||
await X().guard(btn, async () => {
|
||||
await App.api.del('/messages/' + m.id);
|
||||
for (const k of Object.keys(feeds)) feeds[k].items = feeds[k].items.filter((x) => x.id !== m.id);
|
||||
if (thread) thread.items = thread.items.filter((x) => x.id !== m.id);
|
||||
toast(App.t('soc.msg.deleted'), 'ok');
|
||||
pollUnread();
|
||||
thread ? drawThread() : drawList();
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ list view
|
||||
const ago = (at) => h('span', { class: 'when mono', dataset: { at }, text: App.fmt.ago(App.now() - at) });
|
||||
|
||||
function msgRow(m) {
|
||||
const out = m.direction === 'out';
|
||||
const unread = !out && !m.readAt;
|
||||
const alliance = m.kind === 'alliance';
|
||||
const who = out ? (alliance ? App.t('soc.msg.allianceFeed') : App.t('soc.msg.toShort', { name: m.to ? m.to.name : '?' })) : m.from.name;
|
||||
const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.msg.delete'), onclick: (ev) => deleteMessage(m, ev.currentTarget) }, icon('x'));
|
||||
return h('li', { class: 'soc-msgrow' },
|
||||
h('button', { class: 'row-btn soc-msg' + (unread ? ' unread' : ''), type: 'button', onclick: () => openMessage(m) },
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: who }), alliance && m.alliance ? X().tagPill(m.alliance.tag) : null, unread ? h('span', { class: 'pill accent', text: App.t('soc.msg.new') }) : null),
|
||||
h('span', { class: 'soc-preview', text: m.text })),
|
||||
ago(m.createdAt)),
|
||||
del);
|
||||
}
|
||||
|
||||
function openMessage(m) {
|
||||
if (m.kind === 'alliance') {
|
||||
if (m.direction === 'in' && !m.readAt) markRead([m.id]);
|
||||
if (tab !== 'alliance') setTab('alliance'); else drawList();
|
||||
return;
|
||||
}
|
||||
const peer = Soc.peerOf(m);
|
||||
openThread({ operatorId: peer.operatorId, name: peer.name });
|
||||
}
|
||||
|
||||
function drawList() {
|
||||
if (!listBox) return;
|
||||
clear(listBox);
|
||||
if (thread) return;
|
||||
tabsEl.hidden = !!thread;
|
||||
for (const b of tabsEl.children) b.setAttribute('aria-pressed', String(b.dataset.tab === tab));
|
||||
const inb = tabsEl.querySelector('[data-tab="inbox"] .soc-tabn');
|
||||
if (inb) { inb.textContent = badge.n ? String(badge.n) : ''; inb.hidden = !badge.n; }
|
||||
const allyBtn = tabsEl.querySelector('[data-tab="alliance"]');
|
||||
if (allyBtn) allyBtn.hidden = !inAlliance();
|
||||
|
||||
if (tab === 'blocked') { drawBlocked(); return; }
|
||||
const f = feeds[tab];
|
||||
|
||||
if (tab === 'inbox') {
|
||||
listBox.appendChild(h('div', { class: 'soc-toolbar' },
|
||||
h('button', { class: 'chip-btn', type: 'button', 'aria-pressed': String(unreadOnly), text: App.t('soc.msg.unreadOnly'), onclick: () => { unreadOnly = !unreadOnly; feeds.inbox = blank(); loadFeed('inbox'); } }),
|
||||
h('button', { class: 'btn small', type: 'button', disabled: !badge.n, text: App.t('soc.msg.markAll'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
await App.api.post('/messages/read', { all: true });
|
||||
const now = App.now();
|
||||
for (const m of feeds.inbox.items) if (!m.readAt) m.readAt = now;
|
||||
setUnread(0); drawList();
|
||||
}) })));
|
||||
}
|
||||
if (tab === 'alliance') drawBroadcast();
|
||||
|
||||
if (f.err) { listBox.appendChild(X().errorBox(f.err, () => loadFeed(tab))); return; }
|
||||
if (!f.loaded && f.loading) { listBox.appendChild(X().loading()); return; }
|
||||
if (!f.items.length) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.msg.empty.' + tab) })); return; }
|
||||
const ul = h('ul', { class: 'soc-list' });
|
||||
for (const m of f.items) ul.appendChild(tab === 'alliance' ? feedItem(m) : msgRow(m));
|
||||
listBox.appendChild(ul);
|
||||
if (f.next !== null) listBox.appendChild(h('button', { class: 'btn small wide', type: 'button', disabled: f.loading, text: App.t('soc.more'), onclick: () => loadFeed(tab, true) }));
|
||||
}
|
||||
|
||||
// One alliance broadcast shown in full.
|
||||
function feedItem(m) {
|
||||
const out = m.direction === 'out';
|
||||
const unread = !out && !m.readAt;
|
||||
return h('li', { class: 'soc-item soc-feed' + (unread ? ' unread' : '') },
|
||||
h('div', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: m.from.name }), unread ? h('span', { class: 'pill accent', text: App.t('soc.msg.new') }) : null, ago(m.createdAt)),
|
||||
h('p', { class: 'soc-msg-body', text: m.text })),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.msg.delete'), onclick: (ev) => deleteMessage(m, ev.currentTarget) }, icon('x')));
|
||||
}
|
||||
|
||||
let bc = null;
|
||||
function drawBroadcast() {
|
||||
if (!bc) {
|
||||
bc = X().composer({
|
||||
label: App.t('soc.msg.toAlliance'), placeholder: App.t('soc.msg.broadcastPlaceholder'), sendLabel: App.t('soc.msg.broadcast'), rows: 2,
|
||||
onSend: async (text) => { await App.api.post('/messages', { text, toAlliance: true }, { retries: 0 }); toast(App.t('soc.msg.sent'), 'ok'); feeds.alliance = blank(); loadFeed('alliance'); },
|
||||
});
|
||||
}
|
||||
listBox.appendChild(h('div', { class: 'card soc-card' }, h('div', { class: 'sub', text: App.t('soc.msg.toAlliance') }), bc.el));
|
||||
}
|
||||
|
||||
function drawBlocked() {
|
||||
if (blocks.err) { listBox.appendChild(X().errorBox(blocks.err, loadBlocks)); return; }
|
||||
if (!blocks.items) { listBox.appendChild(X().loading()); return; }
|
||||
listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.block.hint') }));
|
||||
if (!blocks.items.length) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.block.none') })); return; }
|
||||
const ul = h('ul', { class: 'soc-list' });
|
||||
for (const b of blocks.items) {
|
||||
ul.appendChild(h('li', { class: 'soc-item' }, h('div', { class: 'row-main' }, h('b', { text: b.name }), h('span', { class: 'row-sub', text: App.t('soc.block.since', { t: App.fmt.ago(App.now() - b.createdAt) }) })),
|
||||
h('button', { class: 'btn small', type: 'button', text: App.t('soc.block.unblock'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
await App.api.del('/messages/blocks/' + b.operatorId);
|
||||
toast(App.t('soc.block.unblocked', { name: b.name }), 'ok');
|
||||
await loadBlocks();
|
||||
}) })));
|
||||
}
|
||||
listBox.appendChild(ul);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ thread view
|
||||
async function openThread(peer) {
|
||||
thread = { peer, items: [], next: null, loading: true, err: null };
|
||||
if (!blocked) loadBlocks();
|
||||
drawThread();
|
||||
await fetchThread(false);
|
||||
}
|
||||
|
||||
async function fetchThread(more) {
|
||||
const t = thread;
|
||||
if (!t) return;
|
||||
t.loading = true; t.err = null;
|
||||
try {
|
||||
const q = { limit: PAGE };
|
||||
if (more && t.next) q.after = t.next;
|
||||
const r = await App.api.get('/messages/thread/' + t.peer.operatorId, q);
|
||||
if (thread !== t) return;
|
||||
t.items = more ? Soc.mergeMessages(t.items, r.items) : r.items;
|
||||
t.next = r.next;
|
||||
const ids = Soc.unreadIds(t.items);
|
||||
if (ids.length) markRead(ids);
|
||||
} catch (e) { if (thread === t) t.err = e; } finally {
|
||||
t.loading = false;
|
||||
if (thread === t) drawThread(more ? undefined : 'bottom');
|
||||
}
|
||||
}
|
||||
|
||||
let threadComposer = null, threadFor = 0;
|
||||
function drawThread(scroll) {
|
||||
clear(listBox);
|
||||
if (!thread) return;
|
||||
tabsEl.hidden = true;
|
||||
const t = thread;
|
||||
const isBlocked = blocked && blocked.has(t.peer.operatorId);
|
||||
const blockBtn = h('button', { class: 'btn small' + (isBlocked ? '' : ' danger'), type: 'button', text: App.t(isBlocked ? 'soc.block.unblock' : 'soc.block.go'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
if (isBlocked) { await App.api.del('/messages/blocks/' + t.peer.operatorId); toast(App.t('soc.block.unblocked', { name: t.peer.name }), 'ok'); } else { await App.api.post('/messages/blocks', { operatorId: t.peer.operatorId }); toast(App.t('soc.block.blocked', { name: t.peer.name }), 'ok'); }
|
||||
await loadBlocks(); drawThread();
|
||||
}) });
|
||||
listBox.appendChild(h('div', { class: 'soc-thread-head' },
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.back'), onclick: closeThread }, icon('back')),
|
||||
h('h2', { class: 'soc-thread-name', text: t.peer.name }), blockBtn));
|
||||
if (isBlocked) listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.block.threadHint') }));
|
||||
if (t.err) listBox.appendChild(X().errorBox(t.err, () => fetchThread(false)));
|
||||
if (t.loading && !t.items.length) listBox.appendChild(X().loading());
|
||||
if (t.next !== null) listBox.appendChild(h('button', { class: 'btn small wide', type: 'button', disabled: t.loading, text: App.t('soc.msg.older'), onclick: () => fetchThread(true) }));
|
||||
if (!t.items.length && !t.loading && !t.err) listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.msg.thread.empty', { name: t.peer.name }) }));
|
||||
const ul = h('ul', { class: 'soc-thread' });
|
||||
for (const m of Soc.chronological(t.items)) {
|
||||
const out = m.direction === 'out';
|
||||
ul.appendChild(h('li', { class: 'soc-bubble ' + (out ? 'out' : 'in') + (!out && !m.readAt ? ' unread' : '') },
|
||||
h('p', { class: 'soc-msg-body', text: m.text }),
|
||||
h('div', { class: 'soc-bubble-meta' }, ago(m.createdAt), h('button', { class: 'soc-del', type: 'button', 'aria-label': App.t('soc.msg.delete'), onclick: (ev) => deleteMessage(m, ev.currentTarget) }, icon('x')))));
|
||||
}
|
||||
listBox.appendChild(ul);
|
||||
if (!threadComposer || threadFor !== t.peer.operatorId) {
|
||||
if (threadComposer) threadComposer.destroy();
|
||||
threadFor = t.peer.operatorId;
|
||||
threadComposer = X().composer({
|
||||
label: App.t('soc.msg.to', { name: t.peer.name }), placeholder: App.t('soc.msg.reply'), rows: 2,
|
||||
onSend: async (text) => { await App.api.post('/messages', { text, toOperatorId: t.peer.operatorId }, { retries: 0 }); feeds.sent = blank(); await fetchThread(false); },
|
||||
});
|
||||
}
|
||||
listBox.appendChild(h('div', { class: 'soc-reply' }, threadComposer.el));
|
||||
if (scroll === 'bottom') requestAnimationFrame(() => { const v = document.getElementById('view'); if (v) v.scrollTop = v.scrollHeight; });
|
||||
}
|
||||
|
||||
function closeThread() {
|
||||
thread = null;
|
||||
if (threadComposer) { threadComposer.destroy(); threadComposer = null; }
|
||||
for (const k of ['inbox', 'sent']) feeds[k] = blank();
|
||||
drawList(); loadFeed(tab === 'blocked' ? 'inbox' : tab === 'alliance' ? 'alliance' : tab);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ new message sheet
|
||||
function openNew(prefill) {
|
||||
const nameIn = h('input', { type: 'text', maxlength: '40', autocomplete: 'off', autocapitalize: 'off', spellcheck: 'false', id: 'soc-to', value: prefill || '' });
|
||||
const hintEl = h('p', { class: 'field-hint', text: App.t('soc.msg.nameHint') });
|
||||
const comp = X().composer({
|
||||
onSend: async (text) => {
|
||||
const name = Soc.cleanName(nameIn.value);
|
||||
if (!name) { nameIn.focus(); throw Object.assign(new Error('name'), { code: 'validation_failed' }); }
|
||||
try { await App.api.post('/messages', { text, toName: name }, { retries: 0 }); } catch (e) {
|
||||
if (e.code === 'not_found') throw Object.assign(new Error(App.t('soc.msg.unknown', { name })), { code: 'x', message: App.t('soc.msg.unknown', { name }) });
|
||||
throw e;
|
||||
}
|
||||
toast(App.t('soc.msg.sent'), 'ok');
|
||||
sheet.close();
|
||||
feeds.sent = blank(); feeds.inbox = blank();
|
||||
if (tab === 'sent' || tab === 'inbox') loadFeed(tab);
|
||||
},
|
||||
});
|
||||
const sheet = openSheet({ title: App.t('soc.msg.new.title'), icon: 'mail', closeLabel: App.t('common.close'), onClose: comp.destroy,
|
||||
body: h('div', { class: 'detail' }, h('label', { class: 'field', for: 'soc-to' }, h('span', { class: 'field-lbl', text: App.t('soc.msg.recipient') }), nameIn, hintEl), comp.el) });
|
||||
setTimeout(() => (prefill ? comp.focus() : nameIn.focus()), 220);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tabs + shell
|
||||
function setTab(t) {
|
||||
if (t === tab && !thread) return;
|
||||
tab = t; thread = null;
|
||||
if (threadComposer) { threadComposer.destroy(); threadComposer = null; }
|
||||
if (t === 'blocked') { if (!blocks.items) loadBlocks(); } else if (!feeds[t].loaded) loadFeed(t); else drawList();
|
||||
drawList();
|
||||
}
|
||||
|
||||
function startTick() {
|
||||
if (offTick) offTick();
|
||||
offTick = App.onTick(() => {
|
||||
const now = App.now();
|
||||
for (const el of listBox.querySelectorAll('.when')) { const s = App.fmt.ago(now - Number(el.dataset.at)); if (el.textContent !== s) el.textContent = s; }
|
||||
});
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'messages', titleKey: 'screen.messages', navKey: 'nav.messages', icon: 'mail', hud: false, navGroup: 'more',
|
||||
render(container) {
|
||||
box = container;
|
||||
const tabs = [['inbox', 'soc.msg.tab.inbox'], ['sent', 'soc.msg.tab.sent'], ['alliance', 'soc.msg.tab.alliance'], ['blocked', 'soc.msg.tab.blocked']];
|
||||
tabsEl = h('div', { class: 'seg soc-tabs soc-tabs4', role: 'group', 'aria-label': App.t('soc.tab.label') },
|
||||
tabs.map(([id, key]) => h('button', { class: 'seg-btn', type: 'button', dataset: { tab: id }, 'aria-pressed': String(tab === id), onclick: () => setTab(id) },
|
||||
h('span', { class: 'soc-tabt', text: App.t(key) }), id === 'inbox' ? h('span', { class: 'soc-tabn', hidden: true }) : null)));
|
||||
listBox = h('div', { class: 'soc-listbox' });
|
||||
box.appendChild(h('div', { class: 'page soc-page' },
|
||||
h('div', { class: 'card-head page-head' }, h('h1', { id: 'soc-msg-h', text: App.t('screen.messages') }),
|
||||
h('div', { class: 'soc-head-actions' },
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => { if (thread) fetchThread(false); else if (tab === 'blocked') loadBlocks(); else { feeds[tab] = blank(); loadFeed(tab); } } }, icon('refresh')),
|
||||
h('button', { class: 'btn small primary', type: 'button', onclick: () => openNew() }, icon('pencil'), App.t('soc.msg.new.go')))),
|
||||
tabsEl, listBox));
|
||||
},
|
||||
onShow(params) {
|
||||
gen++;
|
||||
box.querySelector('#soc-msg-h').textContent = App.t('screen.messages');
|
||||
const labels = { inbox: 'soc.msg.tab.inbox', sent: 'soc.msg.tab.sent', alliance: 'soc.msg.tab.alliance', blocked: 'soc.msg.tab.blocked' };
|
||||
for (const b of tabsEl.children) b.querySelector('.soc-tabt').textContent = App.t(labels[b.dataset.tab]);
|
||||
bc = null;
|
||||
if (!inAlliance() && tab === 'alliance') tab = 'inbox';
|
||||
if (params && params.to) { tab = 'inbox'; openNew(params.to); }
|
||||
if (thread) drawThread(); else { drawList(); if (tab === 'blocked') loadBlocks(); else loadFeed(tab); }
|
||||
startTick();
|
||||
pollUnread();
|
||||
},
|
||||
onHide() { if (offTick) { offTick(); offTick = null; } gen++; },
|
||||
});
|
||||
}());
|
||||
151
public/js/screens/movements.js
Normal file
151
public/js/screens/movements.js
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Movements: what is on the wire right now. Incoming movements of other operators come first and are deliberately loud
|
||||
* (the server hides their type and units: origin and ETA only); your own outgoing legs and returns follow, with live
|
||||
* countdowns and a Recall button during the first 90 seconds. Also registers the incoming-warning banner on the POP screen.
|
||||
* Data comes from App.mil.moves (milstate.js), which push, the poll and the ticker keep current.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast } = UI;
|
||||
const Mil = UpstreamMil;
|
||||
|
||||
let box, listEl, visible = false, offTick = null, dirty = true;
|
||||
|
||||
// ------------------------------------------------------------------ rows
|
||||
function incomingRow(m) {
|
||||
const from = m.from || {};
|
||||
const owner = from.owner;
|
||||
return h('li', { class: 'mil-row incoming' },
|
||||
h('span', { class: 'row-ic bad' }, icon('alert')),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: App.t('mov.incoming.title', { town: (m.to && m.to.name) || '?' }) })),
|
||||
h('span', { class: 'row-sub wrap' }, owner ? App.t('mov.incoming.from', { operator: owner.name }) + ' · ' : '', mil().endLink(from)),
|
||||
h('span', { class: 'row-sub wrap', text: App.t('mov.incoming.hint') })),
|
||||
h('span', { class: 'mil-when' }, mil().countdown(m.arriveAt, { cls: 'big' }), h('small', { text: mil().clockTime(m.arriveAt) })));
|
||||
}
|
||||
|
||||
const mil = () => App.mil;
|
||||
|
||||
function outgoingRow(m, now) {
|
||||
const type = m.type;
|
||||
const sub = [];
|
||||
if (m.units && Mil.sumUnits(m.units) > 0) sub.push(h('span', { class: 'row-sub wrap', text: mil().unitsText(m.units) }));
|
||||
if (m.cargo && Object.keys(m.cargo).some((r) => m.cargo[r] > 0)) sub.push(mil().resChips(m.cargo));
|
||||
if (m.target) sub.push(h('span', { class: 'row-sub wrap', text: App.t('mov.target', { name: App.buildingName(m.target) }) }));
|
||||
const recallable = m.recallableUntil && m.recallableUntil > now;
|
||||
const bar = h('i');
|
||||
const row = h('li', { class: 'mil-row out type-' + type, dataset: { id: m.id } },
|
||||
h('span', { class: 'row-ic' }, icon(Mil.TYPE_ICON[type] || 'move')),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: mil().typeLabel(type) })),
|
||||
h('span', { class: 'row-sub wrap' }, mil().endLink(m.from), h('span', { class: 'arrow', 'aria-hidden': 'true' }, icon('move')), mil().endLink(m.to)),
|
||||
sub,
|
||||
h('span', { class: 'bar mil-bar', 'aria-hidden': 'true' }, bar),
|
||||
recallable ? h('button', { class: 'btn small danger mil-recall', type: 'button', dataset: { until: String(m.recallableUntil), id: String(m.id) }, onclick: (ev) => recall(m, ev.currentTarget) },
|
||||
icon('return'), h('span', { text: App.t('mov.recall') }), mil().countdown(m.recallableUntil)) : null),
|
||||
h('span', { class: 'mil-when' }, mil().countdown(m.arriveAt), h('small', { text: mil().clockTime(m.arriveAt) })));
|
||||
row._bar = bar; row._m = m;
|
||||
return row;
|
||||
}
|
||||
|
||||
async function recall(m, btn) {
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await App.api.post('/movements/' + m.id + '/recall', {}, { intent: 'recall:' + m.id });
|
||||
toast(App.t('mov.recalled'), 'ok');
|
||||
} catch (e) {
|
||||
toast(App.errMsg(e), 'error');
|
||||
}
|
||||
App.refreshMovements().catch(() => {});
|
||||
App.refreshTown().catch(() => {});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ screen
|
||||
function draw() {
|
||||
dirty = false;
|
||||
clear(listEl);
|
||||
const mv = mil().moves, now = App.now();
|
||||
const inc = mv.incoming.slice().sort((a, b) => a.arriveAt - b.arriveAt);
|
||||
const out = mv.outgoing.slice().sort((a, b) => a.arriveAt - b.arriveAt);
|
||||
if (inc.length) {
|
||||
listEl.appendChild(h('section', { class: 'card warn-card', role: 'alert' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('alert'), App.t('mov.incoming.head', { n: inc.length }))),
|
||||
h('ul', { class: 'mil-list' }, inc.map(incomingRow))));
|
||||
}
|
||||
const allied = (mv.alliedIncoming || []).slice().sort((a, b) => a.arriveAt - b.arriveAt);
|
||||
if (allied.length) {
|
||||
listEl.appendChild(h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('handshake'), App.t('mov.allied.head'))),
|
||||
h('ul', { class: 'mil-list' }, allied.map((m) => h('li', { class: 'mil-row' },
|
||||
h('span', { class: 'row-ic' }, icon('shield')),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: App.t('mov.allied.title', { operator: m.toOperator ? m.toOperator.name : '?', town: (m.to && m.to.name) || '?' }) })),
|
||||
h('span', { class: 'row-sub wrap' }, m.from && m.from.owner ? App.t('mov.incoming.from', { operator: m.from.owner.name }) + ' · ' : '', mil().endLink(m.from))),
|
||||
h('span', { class: 'mil-when' }, mil().countdown(m.arriveAt), h('small', { text: mil().clockTime(m.arriveAt) })))))));
|
||||
}
|
||||
listEl.appendChild(h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('move'), App.t('mov.outgoing.head')), h('span', { class: 'pill', text: String(out.length) })),
|
||||
out.length ? h('ul', { class: 'mil-list' }, out.map((m) => outgoingRow(m, now))) : h('p', { class: 'empty', text: mv.loaded ? App.t('mov.empty') : App.t('common.loading') })));
|
||||
tick(now);
|
||||
}
|
||||
|
||||
function tick(now) {
|
||||
if (!listEl) return;
|
||||
for (const row of listEl.querySelectorAll('li.out')) {
|
||||
if (!row._m) continue;
|
||||
row._bar.style.setProperty('--p', String(mil().progress(row._m, now)));
|
||||
}
|
||||
for (const b of listEl.querySelectorAll('.mil-recall')) if (Number(b.dataset.until) <= now) b.remove();
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'movements', titleKey: 'screen.movements', navKey: 'nav.movements', icon: 'move', hud: false,
|
||||
render(container) {
|
||||
box = container;
|
||||
listEl = h('div', { class: 'mil-sections' });
|
||||
box.appendChild(h('div', { class: 'page' },
|
||||
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.movements') }),
|
||||
h('div', { class: 'head-actions' },
|
||||
h('button', { class: 'btn small primary', type: 'button', onclick: () => App.openSend({}) }, icon('target'), App.t('mov.send')),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => App.refreshMovements().catch((e) => toast(App.errMsg(e), 'error')) }, icon('refresh')))),
|
||||
listEl));
|
||||
App.on('movements', () => { if (visible) draw(); else dirty = true; });
|
||||
App.on('lang', () => { if (box) box.querySelector('h1').textContent = App.t('screen.movements'); });
|
||||
},
|
||||
onShow() {
|
||||
visible = true;
|
||||
box.querySelector('h1').textContent = App.t('screen.movements');
|
||||
draw();
|
||||
App.refreshMovements().catch(() => {});
|
||||
if (offTick) offTick();
|
||||
offTick = App.onTick(tick);
|
||||
},
|
||||
onHide() { visible = false; if (offTick) offTick(); offTick = null; },
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ incoming banner on the POP screen
|
||||
function fillBanner(el) {
|
||||
clear(el);
|
||||
const inc = mil().moves.incoming.slice().sort((a, b) => a.arriveAt - b.arriveAt);
|
||||
el.hidden = !inc.length;
|
||||
if (!inc.length) return;
|
||||
const next = inc[0];
|
||||
el.appendChild(h('div', { class: 'row-ic bad' }, icon('alert')));
|
||||
el.appendChild(h('div', { class: 'row-main' },
|
||||
h('b', { text: App.t('mov.banner.title', { n: inc.length }) }),
|
||||
h('span', { class: 'row-sub wrap' }, App.t('mov.banner.next', { town: (next.to && next.to.name) || '?', operator: next.from && next.from.owner ? next.from.owner.name : '?' }) + ' '),
|
||||
h('span', { class: 'row-sub wrap' }, App.t('mov.banner.in') + ' ', mil().countdown(next.arriveAt))));
|
||||
el.appendChild(h('button', { class: 'btn small', type: 'button', onclick: () => App.go('movements') }, App.t('mov.banner.details')));
|
||||
}
|
||||
|
||||
App.popSections.push({
|
||||
slot: 'top',
|
||||
render() {
|
||||
const el = h('section', { class: 'card warn-card mil-banner', role: 'alert', 'aria-live': 'assertive' });
|
||||
fillBanner(el);
|
||||
return el;
|
||||
},
|
||||
});
|
||||
App.on('movements', () => { for (const el of document.querySelectorAll('.mil-banner')) fillBanner(el); });
|
||||
App.on('lang', () => { for (const el of document.querySelectorAll('.mil-banner')) fillBanner(el); });
|
||||
}());
|
||||
|
|
@ -275,10 +275,7 @@
|
|||
function header(t) {
|
||||
const st = App.state;
|
||||
const bonus = D.RESOURCES.filter((r) => (t.bonus && t.bonus[r] > 0)).map((r) => h('span', { class: 'pill res-' + r }, icon(r), '+' + Math.round(t.bonus[r] * 100) + '% ' + App.resName(r)));
|
||||
const title = st.towns.length > 1
|
||||
? h('select', { class: 'town-select', 'aria-label': App.t('screen.pop'), onchange: (e) => App.setTown(Number(e.target.value)) },
|
||||
st.towns.map((x) => h('option', { value: x.id, selected: x.id === t.id, text: x.name })))
|
||||
: h('h1', { class: 'town-name', text: t.name });
|
||||
const title = h('h1', { class: 'town-name', text: t.name }); // switching POPs lives in the resource bar (main.js)
|
||||
return h('section', { class: 'card pop-head' },
|
||||
h('div', { class: 'pop-title' }, title,
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('pop.rename'), onclick: openRename }, icon('pencil'))),
|
||||
|
|
@ -376,8 +373,12 @@
|
|||
const t = td();
|
||||
if (!App.state.townId) { box.appendChild(h('p', { class: 'empty pad', text: App.t('pop.noTown') })); return; }
|
||||
if (!t) { box.appendChild(h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') }))); return; }
|
||||
// other screens add cards here through App.popSections (military: incoming banner on top, expansion below the power card)
|
||||
const extra = (slot) => (App.popSections || []).filter((s) => s.slot === slot).map((s) => { try { return s.render(t); } catch (e) { console.error(e); return null; } });
|
||||
const tops = extra('top');
|
||||
if (tops.some(Boolean)) box.appendChild(h('div', { class: 'pop-top' }, tops));
|
||||
box.appendChild(h('div', { class: 'cols' },
|
||||
h('div', { class: 'col' }, header(t), queueCard(t), powerCard()),
|
||||
h('div', { class: 'col' }, header(t), queueCard(t), powerCard(), extra('main')),
|
||||
h('div', { class: 'col' }, fieldsCard(t), infraCard(t))));
|
||||
tick(App.now());
|
||||
}
|
||||
|
|
@ -482,6 +483,7 @@
|
|||
App.on('town', onTown);
|
||||
App.on('session', () => { dirty = true; prevQueue = null; });
|
||||
App.on('townchange', () => { dirty = true; if (visible) draw(); });
|
||||
App.on('towns', () => { dirty = true; if (visible) draw(); });
|
||||
},
|
||||
onShow() {
|
||||
visible = true;
|
||||
|
|
|
|||
146
public/js/screens/rankings.js
Normal file
146
public/js/screens/rankings.js
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Rankings: operators by footprint, alliances by summed footprint, battle points (attack / defense / total). The server
|
||||
* returns `you` (your own rank, even when it is not on the loaded page) and a rank-offset cursor (`next`). Rows of your own
|
||||
* operator or alliance are highlighted. Names are set with textContent only.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, openSheet } = UI;
|
||||
const Soc = UpstreamSocial;
|
||||
const PAGE = 50;
|
||||
const X = () => window.SocUI;
|
||||
|
||||
let box, listBox, tabsEl, subEl;
|
||||
let tab = 'operators', by = 'attack';
|
||||
const sets = {};
|
||||
let gen = 0;
|
||||
|
||||
const keyOf = () => (tab === 'battles' ? 'battles:' + by : tab);
|
||||
const cur = () => sets[keyOf()] || (sets[keyOf()] = { items: [], next: null, total: 0, you: null, available: true, loaded: false, loading: false, err: null });
|
||||
const path = () => '/rankings/' + tab;
|
||||
|
||||
async function load(more) {
|
||||
const key = keyOf(), s = cur();
|
||||
if (s.loading) return;
|
||||
s.loading = true; s.err = null;
|
||||
const my = gen;
|
||||
if (key === keyOf()) draw();
|
||||
try {
|
||||
const q = { limit: PAGE };
|
||||
if (more && s.next !== null) q.after = s.next;
|
||||
if (tab === 'battles') q.by = by;
|
||||
const r = await App.api.get(path(), q);
|
||||
s.items = more ? Soc.mergeRanks(s.items, r.items) : r.items;
|
||||
s.next = r.next; s.total = r.total; s.you = r.you; s.loaded = true;
|
||||
if (typeof r.available === 'boolean') s.available = r.available;
|
||||
} catch (e) { s.err = e; } finally {
|
||||
s.loading = false;
|
||||
if (my === gen && key === keyOf()) draw();
|
||||
}
|
||||
}
|
||||
|
||||
const num = (n) => App.fmt.num(Math.round(n));
|
||||
|
||||
// One row: rank, name (+ tag), the value columns. `main` is the metric shown big, `sub` the small line.
|
||||
function row(r) {
|
||||
const you = Soc.isYou(tab, r, youRow());
|
||||
let name, sub, val, tap;
|
||||
if (tab === 'operators') {
|
||||
name = r.name; sub = (r.allianceTag ? '[' + r.allianceTag + '] ' : '') + App.t('soc.rank.pops', { n: r.towns }); val = App.fmt.dec(r.footprint);
|
||||
tap = () => openOperator(r);
|
||||
} else if (tab === 'alliances') {
|
||||
name = r.name; sub = '[' + r.tag + '] ' + App.t('soc.rank.members', { n: r.members }) + ' · ' + App.t('soc.rank.pops', { n: r.towns }); val = App.fmt.dec(r.footprint);
|
||||
tap = () => X().openProfile(r.allianceId, { name: r.name });
|
||||
} else {
|
||||
name = r.name; sub = (r.allianceTag ? '[' + r.allianceTag + '] ' : '') + App.t('soc.rank.att', { n: num(r.attackPoints) }) + ' · ' + App.t('soc.rank.def', { n: num(r.defensePoints) });
|
||||
val = num(Soc.battlePoints(r, by));
|
||||
tap = () => openOperator(r);
|
||||
}
|
||||
return h('li', null, h('button', { class: 'soc-rank' + (you ? ' you' : ''), type: 'button', onclick: tap, 'aria-current': you ? 'true' : null },
|
||||
h('span', { class: 'soc-rk mono', text: '#' + r.rank }),
|
||||
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: name }), you ? h('span', { class: 'pill accent', text: App.t('soc.you') }) : null), h('span', { class: 'row-sub', text: sub })),
|
||||
h('span', { class: 'soc-val mono', text: val })));
|
||||
}
|
||||
|
||||
const youRow = () => cur().you;
|
||||
|
||||
function openOperator(r) {
|
||||
const me = X().myOperatorId();
|
||||
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v', text: v }));
|
||||
const body = h('div', { class: 'detail' },
|
||||
h('div', { class: 'pill-row' }, h('span', { class: 'pill soc-tag mono', text: '#' + r.rank }), r.allianceTag ? X().tagPill(r.allianceTag) : null, r.asNumber ? h('span', { class: 'pill mono', text: UpstreamI18n.fmtAs(r.asNumber) }) : null),
|
||||
h('div', null,
|
||||
r.footprint !== undefined ? kv(App.t('soc.footprint'), App.fmt.dec(r.footprint)) : null,
|
||||
r.towns !== undefined ? kv(App.t('soc.member.pops'), String(r.towns)) : null,
|
||||
r.attackPoints !== undefined ? kv(App.t('soc.rank.attack'), num(r.attackPoints)) : null,
|
||||
r.defensePoints !== undefined ? kv(App.t('soc.rank.defense'), num(r.defensePoints)) : null));
|
||||
const sheet = openSheet({ title: r.name, icon: 'users', closeLabel: App.t('common.close'), body });
|
||||
if (r.allianceId) body.appendChild(h('button', { class: 'btn wide', type: 'button', onclick: () => { sheet.close(); X().openProfile(r.allianceId, { name: r.allianceTag }); } }, icon('users'), App.t('soc.rank.viewAlliance')));
|
||||
if (r.operatorId !== me) body.appendChild(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { sheet.close(); X().openCompose({ operator: { operatorId: r.operatorId, name: r.name } }); } }, icon('mail'), App.t('soc.member.message')));
|
||||
}
|
||||
|
||||
function draw() {
|
||||
if (!listBox) return;
|
||||
clear(listBox);
|
||||
for (const b of tabsEl.children) b.setAttribute('aria-pressed', String(b.dataset.tab === tab));
|
||||
subEl.hidden = tab !== 'battles';
|
||||
for (const b of subEl.children) b.setAttribute('aria-pressed', String(b.dataset.by === by));
|
||||
const s = cur();
|
||||
if (s.err) { listBox.appendChild(X().errorBox(s.err, () => load(false))); return; }
|
||||
if (!s.loaded) { listBox.appendChild(X().loading()); return; }
|
||||
if (tab === 'battles' && !s.available) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.rank.unavailable') })); return; }
|
||||
|
||||
if (s.you) {
|
||||
const y = s.you;
|
||||
const inList = s.items.some((r) => r.rank === y.rank);
|
||||
listBox.appendChild(h('div', { class: 'card soc-card soc-yourank' },
|
||||
h('span', { class: 'soc-yr-n mono', text: '#' + y.rank }),
|
||||
h('span', { class: 'row-main' }, h('b', { text: App.t('soc.rank.yours') }),
|
||||
h('span', { class: 'row-sub', text: App.t('soc.rank.of', { n: s.total }) + (tab === 'battles' ? ' · ' + num(Soc.battlePoints(y, by)) : ' · ' + App.fmt.dec(y.footprint)) })),
|
||||
inList ? null : h('span', { class: 'pill dim', text: App.t('soc.rank.notShown') })));
|
||||
} else if (tab === 'alliances') {
|
||||
listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.rank.noAlliance') }));
|
||||
} else if (tab === 'battles') {
|
||||
listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.rank.noPoints') }));
|
||||
}
|
||||
if (!s.items.length) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t(tab === 'battles' ? 'soc.rank.noBattles' : 'soc.rank.empty') })); return; }
|
||||
const ol = h('ol', { class: 'soc-ranklist' });
|
||||
for (const r of s.items) ol.appendChild(row(r));
|
||||
listBox.appendChild(ol);
|
||||
if (s.next !== null) listBox.appendChild(h('button', { class: 'btn small wide', type: 'button', disabled: s.loading, text: App.t('soc.more') + ' (' + s.items.length + '/' + s.total + ')', onclick: () => load(true) }));
|
||||
}
|
||||
|
||||
function setTab(t) {
|
||||
tab = t;
|
||||
draw();
|
||||
if (!cur().loaded) load(false);
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'rankings', titleKey: 'screen.rankings', navKey: 'nav.rankings', icon: 'trophy', hud: false, navGroup: 'more',
|
||||
render(container) {
|
||||
box = container;
|
||||
const tabs = [['operators', 'soc.rank.tab.operators'], ['alliances', 'soc.rank.tab.alliances'], ['battles', 'soc.rank.tab.battles']];
|
||||
tabsEl = h('div', { class: 'seg soc-tabs', role: 'group', 'aria-label': App.t('soc.tab.label') },
|
||||
tabs.map(([id, key]) => h('button', { class: 'seg-btn', type: 'button', dataset: { tab: id }, 'aria-pressed': String(tab === id), text: App.t(key), onclick: () => setTab(id) })));
|
||||
subEl = h('div', { class: 'seg soc-subtabs', role: 'group', 'aria-label': App.t('soc.rank.by'), hidden: true },
|
||||
['attack', 'defense', 'total'].map((k) => h('button', { class: 'chip-btn', type: 'button', dataset: { by: k }, 'aria-pressed': String(by === k), text: App.t('soc.rank.by.' + k), onclick: () => { by = k; draw(); if (!cur().loaded) load(false); } })));
|
||||
listBox = h('div', { class: 'soc-listbox' });
|
||||
box.appendChild(h('div', { class: 'page soc-page' },
|
||||
h('div', { class: 'card-head page-head' }, h('h1', { id: 'soc-rank-h', text: App.t('screen.rankings') }),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => { delete sets[keyOf()]; load(false); } }, icon('refresh'))),
|
||||
tabsEl, subEl, listBox));
|
||||
App.on('session', () => { for (const k of Object.keys(sets)) delete sets[k]; });
|
||||
},
|
||||
onShow() {
|
||||
gen++;
|
||||
box.querySelector('#soc-rank-h').textContent = App.t('screen.rankings');
|
||||
const labels = { operators: 'soc.rank.tab.operators', alliances: 'soc.rank.tab.alliances', battles: 'soc.rank.tab.battles' };
|
||||
for (const b of tabsEl.children) b.textContent = App.t(labels[b.dataset.tab]);
|
||||
for (const b of subEl.children) b.textContent = App.t('soc.rank.by.' + b.dataset.by);
|
||||
draw();
|
||||
load(false); // rankings move: always refresh the first page when the screen opens
|
||||
},
|
||||
onHide() { gen++; },
|
||||
});
|
||||
}());
|
||||
316
public/js/screens/reports.js
Normal file
316
public/js/screens/reports.js
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Reports: newest first, cursor-paginated (GET /reports?after=<last id>), unread highlighted, a detail sheet per report
|
||||
* (GET /reports/:id, then POST /reports/:id/read). Detail layouts exist for battle (raid/attack/takeover), scan,
|
||||
* scan_detected, incumbent, settle, reinforce and movement_failed; coordinates are links that jump to the map.
|
||||
* `data` differs by report type AND by the recipient's role (attacker / defender / reinforcer / sender / target).
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet } = UI;
|
||||
const D = UpstreamData;
|
||||
const Mil = UpstreamMil;
|
||||
const mil = () => App.mil;
|
||||
const num = (n) => App.fmt.num(n);
|
||||
const PAGE = 25;
|
||||
|
||||
let box, listEl, moreBtn, statusEl, items = [], next = null, loading = false, visible = false, offAgo = null;
|
||||
|
||||
// ------------------------------------------------------------------ list rows
|
||||
const nameOf = (o) => (o && o.name) || '?';
|
||||
const townOf = (t) => (t ? t.name : '?');
|
||||
|
||||
// { icon, title, sub, tone } for the list
|
||||
function describe(it) {
|
||||
const s = it.summary || {};
|
||||
switch (it.type) {
|
||||
case 'raid': case 'attack': case 'takeover': {
|
||||
const res = Mil.perspective(it.role, s.outcome);
|
||||
const mine = it.role === 'attacker';
|
||||
const title = mil().reportTypeLabel(it.type) + ': ' + townOf(s.target);
|
||||
const sub = mine ? App.t('rep.sub.you_vs', { name: nameOf(s.defender) }) : App.t('rep.sub.by', { name: nameOf(s.attacker) });
|
||||
return { icon: Mil.TYPE_ICON[it.type], title, sub: sub + (s.captured ? ' · ' + App.t('rep.captured') : ''), tone: res === 'victory' ? 'good' : 'bad', badge: App.t('rep.' + res) };
|
||||
}
|
||||
case 'scan': {
|
||||
const where = s.target ? townOf(s.target) : (s.site ? s.site.x + ', ' + s.site.y : '?');
|
||||
return { icon: 'eye', title: App.t('rep.scan.title', { where }), sub: s.success ? App.t('rep.scan.ok') : App.t('rep.scan.failed'), tone: s.success ? 'good' : 'bad' };
|
||||
}
|
||||
case 'scan_detected':
|
||||
return { icon: 'eye', title: App.t('rep.detected.title', { town: townOf(s.target) }), sub: s.identityRevealed && s.by ? App.t('rep.sub.by', { name: nameOf(s.by) }) : App.t('rep.detected.unknown'), tone: 'warn' };
|
||||
case 'incumbent':
|
||||
return { icon: 'b-core_router', title: App.t('rep.incumbent.title', { x: s.site ? s.site.x : '?', y: s.site ? s.site.y : '?' }), sub: '', tone: s.outcome === 'attacker_won' ? 'good' : 'bad', badge: s.outcome === 'attacker_won' ? App.t('rep.victory') : App.t('rep.defeat') };
|
||||
case 'settle':
|
||||
return { icon: 'flag', title: App.t('rep.settle.title', { name: s.town ? s.town.name : '?' }), sub: '', tone: 'good' };
|
||||
case 'reinforce':
|
||||
return { icon: 'shield', title: it.role === 'sender' ? App.t('rep.reinforce.sender', { town: townOf(s.host) }) : App.t('rep.reinforce.target', { town: townOf(s.host) }), sub: mil().unitsText(s.units), tone: 'neutral' };
|
||||
case 'movement_failed':
|
||||
return { icon: 'alert', title: App.t('rep.failed.title', { type: mil().typeLabel(s.movementType) }), sub: reasonText(s.reason), tone: 'bad' };
|
||||
default:
|
||||
return { icon: 'report', title: mil().reportTypeLabel(it.type), sub: '', tone: 'neutral' };
|
||||
}
|
||||
}
|
||||
|
||||
function reasonText(code) {
|
||||
if (!code) return '';
|
||||
if (UpstreamI18n.strings.en['rep.reason.' + code]) return App.t('rep.reason.' + code);
|
||||
if (UpstreamI18n.strings.en['err.' + code]) return App.t('err.' + code);
|
||||
return code;
|
||||
}
|
||||
|
||||
function row(it) {
|
||||
const d = describe(it);
|
||||
return h('li', null, h('button', { class: 'alert rep tone-' + d.tone + (it.read ? '' : ' new'), type: 'button', dataset: { id: String(it.id) }, onclick: () => openReport(it.id) },
|
||||
h('span', { class: 'row-ic' }, icon(d.icon)),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: d.title }), d.badge ? h('span', { class: 'pill ' + (d.tone === 'good' ? 'green' : 'amber'), text: d.badge }) : null, it.read ? null : h('span', { class: 'pill accent', text: App.t('alerts.new') })),
|
||||
d.sub ? h('span', { class: 'row-sub', text: d.sub }) : null),
|
||||
h('span', { class: 'when mono', dataset: { at: String(it.createdAt) }, text: App.fmt.ago(App.now() - it.createdAt) })));
|
||||
}
|
||||
|
||||
function draw() {
|
||||
clear(listEl);
|
||||
if (!items.length) { listEl.appendChild(h('li', null, h('p', { class: 'empty pad', text: loading ? App.t('common.loading') : App.t('rep.empty') }))); }
|
||||
for (const it of items) listEl.appendChild(row(it));
|
||||
moreBtn.hidden = next === null;
|
||||
}
|
||||
|
||||
async function load(more) {
|
||||
if (loading) return;
|
||||
loading = true; statusEl.hidden = true;
|
||||
try {
|
||||
const r = await App.api.get('/reports', { limit: PAGE, after: more ? next : undefined });
|
||||
items = more ? items.concat(r.items.filter((x) => !items.some((y) => y.id === x.id))) : r.items;
|
||||
next = r.next;
|
||||
mil().reportsUnread = r.unread;
|
||||
App.setBadge('reports', r.unread, 'info');
|
||||
} catch (e) {
|
||||
statusEl.textContent = App.errMsg(e); statusEl.hidden = false;
|
||||
} finally { loading = false; }
|
||||
draw();
|
||||
}
|
||||
|
||||
async function markAll() {
|
||||
try {
|
||||
await App.api.post('/reports/read-all', {}, { intent: 'reports:read-all' });
|
||||
for (const it of items) it.read = true;
|
||||
App.setBadge('reports', 0, 'info');
|
||||
draw();
|
||||
} catch (e) { toast(App.errMsg(e), 'error'); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ detail pieces
|
||||
const sec = (title, ...kids) => h('section', { class: 'rep-sec' }, h('h3', { class: 'sub', text: title }), kids);
|
||||
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
|
||||
|
||||
function unitsTable(sent, lost, survivors) {
|
||||
const ids = D.UNIT_ORDER.filter((u) => (sent && sent[u]) || (lost && lost[u]) || (survivors && survivors[u]));
|
||||
if (!ids.length) return h('p', { class: 'empty', text: App.t('rep.noUnits') });
|
||||
return h('table', { class: 'mil-table' },
|
||||
h('thead', null, h('tr', null, h('th', { text: '' }), h('th', { text: App.t('rep.sent') }), h('th', { text: App.t('rep.lost') }), h('th', { text: App.t('rep.left') }))),
|
||||
h('tbody', null, ids.map((u) => h('tr', null,
|
||||
h('td', { text: mil().unitName(u) }),
|
||||
h('td', { class: 'mono', text: num((sent && sent[u]) || 0) }),
|
||||
h('td', { class: 'mono' + (lost && lost[u] ? ' bad' : ''), text: num((lost && lost[u]) || 0) }),
|
||||
h('td', { class: 'mono', text: num((survivors && survivors[u]) || 0) })))));
|
||||
}
|
||||
|
||||
const party = (label, operator, town) => kv(label, h('span', { class: 'rep-party' },
|
||||
h('b', { text: operator ? operator.name : '?' }), operator && operator.asNumber ? h('small', { class: 'dimmer', text: ' ' + UpstreamI18n.fmtAs(operator.asNumber) }) : null,
|
||||
town ? mil().endLink(town) : null));
|
||||
|
||||
function verdict(role, outcome) {
|
||||
const res = Mil.perspective(role, outcome);
|
||||
return h('div', { class: 'rep-verdict ' + res }, icon(res === 'victory' ? 'check' : 'alert'), h('b', { text: App.t('rep.' + res) }));
|
||||
}
|
||||
|
||||
function combatBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(verdict(r.role, d.outcome));
|
||||
out.push(h('p', { class: 'row-sub', text: App.t('rep.arrived', { t: mil().dayTime(d.arrivedAt) }) + ' · ' + mil().reportTypeLabel(d.type) }));
|
||||
out.push(party(App.t('rep.attacker'), d.attacker.operator, d.attacker.town));
|
||||
out.push(party(App.t('rep.defender'), d.defender.operator, d.defender.town));
|
||||
const p = d.power || {};
|
||||
out.push(sec(App.t('rep.power'),
|
||||
kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(p.attack || 0) })),
|
||||
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(p.defence || 0) })),
|
||||
p.firewallLevel !== undefined ? kv(App.t('rep.power.firewall'), h('span', { class: 'mono', text: p.firewallLevel + (p.effectiveFirewall !== undefined && p.effectiveFirewall !== p.firewallLevel ? ' → ' + App.fmt.dec(p.effectiveFirewall) : '') })) : null));
|
||||
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
|
||||
const groups = (d.defender.groups || []);
|
||||
out.push(sec(App.t('rep.defenderUnits'), groups.length ? groups.map((g) => h('div', { class: 'rep-group' },
|
||||
h('p', { class: 'row-sub wrap' }, g.ownerTownId === (d.defender.town && d.defender.town.id) ? App.t('rep.group.home') : App.t('rep.group.reinf', { town: '#' + g.ownerTownId }), g.offline ? ' · ' + App.t('rep.group.offline') : ''),
|
||||
unitsTable(g.sent, g.lost, g.survivors))) : h('p', { class: 'empty', text: App.t('rep.noUnits') })));
|
||||
if (d.loot && D.RESOURCES.some((x) => d.loot[x])) {
|
||||
out.push(sec(App.t('rep.loot'), mil().resChips(d.loot, true), d.cacheHidden ? h('p', { class: 'row-sub', text: App.t('rep.cache', { p: Math.round(d.cacheHidden * 100) }) }) : null));
|
||||
}
|
||||
if (d.siege) out.push(sec(App.t('rep.siege'), h('p', { text: App.t('rep.siege.line', { name: App.buildingName(d.siege.type), a: d.siege.from, b: d.siege.to }) })));
|
||||
if (d.takeover) {
|
||||
const t = d.takeover;
|
||||
const lines = [];
|
||||
if (t.blocked) lines.push(h('p', { class: 'reason', text: App.t('rep.takeover.blocked.' + t.blocked) }));
|
||||
else {
|
||||
lines.push(kv(App.t('rep.takeover.loyalty'), h('b', { class: 'mono', text: num(t.loyaltyBefore) + ' → ' + num(t.loyaltyAfter) + ' (−' + num(t.drop) + ')' })));
|
||||
if (t.capital) lines.push(h('p', { class: 'row-sub wrap', text: App.t('rep.takeover.capital') }));
|
||||
}
|
||||
if (d.capturedTown) lines.push(h('p', { class: 'good', text: App.t('rep.takeover.captured') }));
|
||||
out.push(sec(App.t('rep.takeover'), lines));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function scanBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(h('div', { class: 'rep-verdict ' + (d.success ? 'victory' : 'defeat') }, icon(d.success ? 'eye' : 'alert'), h('b', { text: d.success ? App.t('rep.scan.ok') : App.t('rep.scan.failed') })));
|
||||
if (d.site) out.push(kv(App.t('rep.site'), mil().coordLink(d.site.x, d.site.y)));
|
||||
if (d.target) out.push(party(App.t('rep.defender'), d.operator, d.target));
|
||||
if (d.strength) out.push(kv(App.t('rep.scan.strength'), h('span', { class: 'mono', text: App.fmt.dec(d.strength.attacker) + ' vs ' + App.fmt.dec(d.strength.defender) })));
|
||||
out.push(sec(App.t('rep.scanners'), unitsTable(d.scanners && d.scanners.sent, d.scanners && d.scanners.lost, d.scanners && d.scanners.survivors)));
|
||||
const intel = d.intel;
|
||||
if (!intel) { out.push(h('p', { class: 'reason', text: App.t('rep.scan.noIntel') })); return out; }
|
||||
if (d.site) { // incumbent site
|
||||
out.push(sec(App.t('rep.intel'),
|
||||
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(intel.defence) })),
|
||||
intel.bonusAvailable ? h('p', { class: 'row-sub wrap', text: App.t('rep.incumbent.bonus', { n: num(intel.hardwareBonus) }) }) : h('p', { class: 'row-sub wrap', text: App.t('rep.incumbent.taken') })));
|
||||
return out;
|
||||
}
|
||||
out.push(sec(App.t('rep.intel.resources'), mil().resChips(intel.resources)));
|
||||
out.push(sec(App.t('rep.intel.units'),
|
||||
!intel.online ? h('p', { class: 'reason', text: App.t('rep.intel.offline') }) : null,
|
||||
unitsTable(intel.units.home, {}, intel.units.home),
|
||||
(intel.units.stationed || []).map((g) => h('div', { class: 'rep-group' }, h('p', { class: 'row-sub wrap', text: App.t('rep.group.reinf', { town: '#' + g.ownerTownId }) }), h('p', { text: mil().unitsText(g.units) })))));
|
||||
if (intel.buildings) {
|
||||
out.push(sec(App.t('rep.intel.buildings'),
|
||||
h('ul', { class: 'rep-buildings' }, intel.buildings.filter((b) => b.level > 0).map((b) => h('li', null, h('span', { text: App.buildingName(b.type) }), h('b', { class: 'mono', text: String(b.level) }))))));
|
||||
}
|
||||
if (intel.loyalty !== undefined) out.push(kv(App.t('pop.loyalty'), h('b', { class: 'mono', text: num(intel.loyalty) })));
|
||||
if (intel.outgoing && intel.outgoing.length) {
|
||||
out.push(sec(App.t('rep.intel.outgoing'), h('ul', { class: 'rep-buildings' }, intel.outgoing.map((m) => h('li', null, h('span', { text: mil().typeLabel(m.type) }), mil().coordLink(m.to.x, m.to.y), h('small', { class: 'dimmer', text: mil().clockTime(m.arriveAt) }))))));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function detectedBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(h('div', { class: 'rep-verdict defeat' }, icon('eye'), h('b', { text: App.t('rep.detected.title', { town: townOf(d.target) }) })));
|
||||
if (d.target) out.push(kv(App.t('rep.target'), mil().endLink(d.target)));
|
||||
if (d.identityRevealed && d.by) out.push(party(App.t('rep.scannedBy'), d.by.operator, d.by.town));
|
||||
else out.push(h('p', { class: 'row-sub wrap', text: App.t('rep.detected.unknown') }));
|
||||
return out;
|
||||
}
|
||||
|
||||
function incumbentBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(verdict('attacker', d.outcome));
|
||||
out.push(kv(App.t('rep.site'), mil().coordLink(d.site.x, d.site.y)));
|
||||
if (d.origin) out.push(kv(App.t('rep.from'), mil().endLink(d.origin)));
|
||||
out.push(sec(App.t('rep.power'), kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(d.power.attack) })), kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(d.power.defence) }))));
|
||||
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
|
||||
if (d.bonus) out.push(sec(App.t('rep.incumbent.reward'), mil().resChips({ hardware: d.bonus.hardware }, true), d.bonus.researchSpeedBonus ? h('p', { class: 'row-sub', text: App.t('units.research.speed', { p: Math.round(d.bonus.researchSpeedBonus * 100) }) }) : null));
|
||||
return out;
|
||||
}
|
||||
|
||||
function settleBody(r, ctl) {
|
||||
const d = r.data, out = [];
|
||||
out.push(h('div', { class: 'rep-verdict victory' }, icon('flag'), h('b', { text: App.t('rep.settle.title', { name: d.town.name }) })));
|
||||
out.push(kv(App.t('rep.site'), mil().coordLink(d.town.x, d.town.y)));
|
||||
out.push(kv(App.t('rep.settle.wild'), h('span', { text: (d.wild || []).map((w) => App.buildingName(w)).join(', ') })));
|
||||
out.push(h('button', { class: 'btn primary wide', type: 'button', onclick: async () => {
|
||||
ctl.close();
|
||||
try { await App.refreshTowns(); } catch (e) { /* the POP list may be stale; setTown below copes */ }
|
||||
App.setTown(d.town.id); App.go('pop');
|
||||
} }, icon('pop'), App.t('rep.settle.open')));
|
||||
out.push(h('p', { class: 'row-sub wrap', text: App.t('rep.settle.hint') }));
|
||||
return out;
|
||||
}
|
||||
|
||||
function reinforceBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(kv(App.t('rep.from'), h('span', null, h('b', { text: nameOf(d.operator) }), mil().endLink(d.from))));
|
||||
out.push(kv(App.t('rep.host'), h('span', null, h('b', { text: nameOf(d.hostOperator) }), mil().endLink(d.host))));
|
||||
out.push(sec(App.t('rep.units'), h('p', { text: mil().unitsText(d.units) })));
|
||||
return out;
|
||||
}
|
||||
|
||||
function failedBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(h('div', { class: 'rep-verdict defeat' }, icon('alert'), h('b', { text: App.t('rep.failed.title', { type: mil().typeLabel(d.movementType) }) })));
|
||||
out.push(h('p', { text: reasonText(d.reason) }));
|
||||
if (d.to) out.push(kv(App.t('rep.target'), mil().coordLink(d.to.x, d.to.y)));
|
||||
out.push(sec(App.t('rep.units'), h('p', { text: mil().unitsText(d.units) }), h('p', { class: 'row-sub wrap', text: App.t('rep.failed.home') })));
|
||||
return out;
|
||||
}
|
||||
|
||||
function genericBody(r) {
|
||||
return [h('pre', { class: 'rep-raw', text: JSON.stringify(r.summary || {}, null, 1).slice(0, 1500) })];
|
||||
}
|
||||
|
||||
function bodyFor(r, ctl) {
|
||||
switch (r.type) {
|
||||
case 'raid': case 'attack': case 'takeover': return combatBody(r);
|
||||
case 'scan': return scanBody(r);
|
||||
case 'scan_detected': return detectedBody(r);
|
||||
case 'incumbent': return incumbentBody(r);
|
||||
case 'settle': return settleBody(r, ctl);
|
||||
case 'reinforce': return reinforceBody(r);
|
||||
case 'movement_failed': return failedBody(r);
|
||||
default: return genericBody(r);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ detail sheet
|
||||
async function openReport(id) {
|
||||
const body = h('div', { class: 'detail rep-detail' }, h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' })));
|
||||
const ctl = openSheet({ title: App.t('screen.reports'), icon: 'report', closeLabel: App.t('common.close'), body });
|
||||
try {
|
||||
const res = await App.api.get('/reports/' + id);
|
||||
const r = res.report;
|
||||
ctl.setTitle(mil().reportTypeLabel(r.type));
|
||||
clear(body);
|
||||
body.appendChild(h('p', { class: 'row-sub', text: mil().dayTime(r.createdAt) + ' · ' + App.t('rep.role.' + r.role) + ' · ' + App.t('rep.expires', { t: mil().dayTime(r.expiresAt) }) }));
|
||||
let parts;
|
||||
try { parts = bodyFor(r, ctl); } catch (e) { parts = genericBody(r); }
|
||||
for (const p of parts.flat(2)) if (p) body.appendChild(p);
|
||||
if (!r.read) {
|
||||
App.api.post('/reports/' + id + '/read', {}).then(() => {
|
||||
const it = items.find((x) => x.id === id); if (it) it.read = true;
|
||||
if (visible) draw();
|
||||
App.refreshReportsUnread().catch(() => {});
|
||||
}).catch(() => {});
|
||||
}
|
||||
} catch (e) {
|
||||
clear(body);
|
||||
body.appendChild(h('p', { class: 'form-error', text: App.errMsg(e) }));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ screen
|
||||
App.registerScreen({
|
||||
id: 'reports', titleKey: 'screen.reports', navKey: 'nav.reports', icon: 'report', navGroup: 'more', hud: false,
|
||||
render(container) {
|
||||
box = container;
|
||||
listEl = h('ul', { class: 'alert-list' });
|
||||
statusEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
moreBtn = h('button', { class: 'btn wide', type: 'button', hidden: true, onclick: () => load(true) }, App.t('rep.older'));
|
||||
box.appendChild(h('div', { class: 'page' },
|
||||
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.reports') }),
|
||||
h('div', { class: 'head-actions' },
|
||||
h('button', { class: 'btn small', type: 'button', onclick: markAll }, icon('check'), App.t('rep.markAll')),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load(false) }, icon('refresh')))),
|
||||
statusEl, listEl, moreBtn));
|
||||
App.on('session', () => { items = []; next = null; });
|
||||
App.on('report', () => { if (visible) load(false); });
|
||||
},
|
||||
onShow(params) {
|
||||
visible = true;
|
||||
box.querySelector('h1').textContent = App.t('screen.reports');
|
||||
moreBtn.textContent = App.t('rep.older');
|
||||
draw();
|
||||
load(false);
|
||||
if (params && params.open) openReport(Number(params.open));
|
||||
if (offAgo) offAgo();
|
||||
offAgo = App.onTick(() => {
|
||||
const now = App.now();
|
||||
for (const el of listEl.querySelectorAll('.when')) { const s = App.fmt.ago(now - Number(el.dataset.at)); if (el.textContent !== s) el.textContent = s; }
|
||||
});
|
||||
},
|
||||
onHide() { visible = false; if (offAgo) offAgo(); offAgo = null; },
|
||||
});
|
||||
}());
|
||||
339
public/js/screens/send.js
Normal file
339
public/js/screens/send.js
Normal file
|
|
@ -0,0 +1,339 @@
|
|||
'use strict';
|
||||
/*
|
||||
* The send dialog: App.openSend({ x, y, fromTownId, type }). Opened from a map tile, the POP screen, the units screen and the
|
||||
* movements screen. It looks the target up (GET /map/tile), offers the movement types that can work, lets you pick units
|
||||
* (or cargo, or the wild slots of a new POP), previews latency and arrival from rules.js and sends POST /movements. The
|
||||
* server re-validates everything; this dialog only avoids obviously doomed sends and explains the greyed-out ones.
|
||||
* An Idempotency intent is generated per opened dialog (and again after a successful send), so a retried tap cannot send twice.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet } = UI;
|
||||
const R = UpstreamRules;
|
||||
const D = UpstreamData;
|
||||
const Mil = UpstreamMil;
|
||||
const mil = () => App.mil;
|
||||
const num = (n) => App.fmt.num(n);
|
||||
const nonce = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
|
||||
|
||||
App.openSend = function openSend(opts) {
|
||||
opts = opts || {};
|
||||
const st = {
|
||||
x: Number.isInteger(opts.x) ? opts.x : null, y: Number.isInteger(opts.y) ? opts.y : null,
|
||||
tile: null, tileErr: null, fromId: null, from: null, type: null, units: {}, cargo: {}, target: '',
|
||||
wild: D.START.wild.slice(), endProtection: false, busy: false, nonce: nonce(), loadSeq: 0, tileSeq: 0, options: [],
|
||||
};
|
||||
const own = App.state.towns;
|
||||
st.fromId = own.some((t) => t.id === opts.fromTownId) ? opts.fromTownId : (App.state.townId || (own[0] && own[0].id));
|
||||
if (!st.fromId) { toast(App.t('pop.noTown'), 'error'); return; }
|
||||
|
||||
const body = h('div', { class: 'detail send' });
|
||||
let offTick = null;
|
||||
const ctl = openSheet({ title: App.t('send.title'), icon: 'target', closeLabel: App.t('common.close'), body, onClose: () => { if (offTick) offTick(); } });
|
||||
|
||||
const secTarget = h('div', { class: 'send-sec' });
|
||||
const secFrom = h('div', { class: 'send-sec' });
|
||||
const secType = h('div', { class: 'send-sec' });
|
||||
const secUnits = h('div', { class: 'send-sec' });
|
||||
const secPreview = h('div', { class: 'send-sec' });
|
||||
const secWarn = h('div', { class: 'send-sec' });
|
||||
const errEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const submit = h('button', { class: 'btn primary wide', type: 'button', onclick: () => go() }, icon('target'), h('span', { text: App.t('send.go') }));
|
||||
body.appendChild(secTarget); body.appendChild(secFrom); body.appendChild(secType); body.appendChild(secUnits); body.appendChild(secPreview); body.appendChild(secWarn);
|
||||
body.appendChild(h('div', { class: 'send-foot' }, errEl, submit));
|
||||
|
||||
const fromTown = () => own.find((t) => t.id === st.fromId);
|
||||
const home = () => (st.from ? st.from.td.military.units.home : {});
|
||||
const op = () => App.state.operator;
|
||||
|
||||
// ------------------------------------------------------------------ data
|
||||
async function loadFrom() {
|
||||
const seq = ++st.loadSeq;
|
||||
let r;
|
||||
try {
|
||||
if (st.fromId === App.state.townId && App.state.townData && App.state.townData.military) r = { td: App.state.townData, rt: App.rulesTown(), at: App.fetchedServerTime };
|
||||
else { const x = await mil().loadTown(st.fromId); r = { td: x.town, rt: App.rulesTownFrom(x.town, x.serverTime), at: x.serverTime }; }
|
||||
} catch (e) { if (seq === st.loadSeq) showErr(App.errMsg(e)); return; }
|
||||
if (seq !== st.loadSeq) return;
|
||||
st.from = r;
|
||||
afterData();
|
||||
}
|
||||
|
||||
async function loadTile() {
|
||||
if (st.x === null || st.y === null) { st.tile = null; return; }
|
||||
const seq = ++st.tileSeq;
|
||||
st.tile = null; st.tileErr = null;
|
||||
drawTarget();
|
||||
try {
|
||||
const t = await App.api.get('/map/tile', { x: st.x, y: st.y });
|
||||
if (seq !== st.tileSeq) return;
|
||||
st.tile = t;
|
||||
} catch (e) {
|
||||
if (seq !== st.tileSeq) return;
|
||||
st.tileErr = e.code === 'not_found' ? App.t('tile.void') : App.errMsg(e);
|
||||
}
|
||||
afterData();
|
||||
}
|
||||
|
||||
function afterData() {
|
||||
drawTarget();
|
||||
drawFrom();
|
||||
if (!st.tile || !st.from) { drawTypes(); return; }
|
||||
computeOptions();
|
||||
drawTypes();
|
||||
}
|
||||
|
||||
function computeOptions() {
|
||||
const m = st.from.td.military;
|
||||
st.options = Mil.moveOptions({ tile: st.tile, home: m.units.home, transport: m.transport, allianceId: op() ? op().allianceId : null, crews: m.units.home[D.EXPANSION.settleUnit] || 0 });
|
||||
const want = st.type && st.options.some((o) => o.type === st.type) ? st.type : (opts.type && st.options.some((o) => o.type === opts.type && o.ok) ? opts.type : null);
|
||||
const first = st.options.find((o) => o.ok);
|
||||
setType(want || (first ? first.type : (st.options[0] ? st.options[0].type : null)), true);
|
||||
}
|
||||
|
||||
function setType(type, keep) {
|
||||
if (!keep && type === st.type) return;
|
||||
st.type = type;
|
||||
st.units = type ? Mil.defaultUnits(type, home()) : {};
|
||||
st.cargo = {}; st.target = ''; st.endProtection = false;
|
||||
showErr('');
|
||||
drawTypes(); drawUnits(); refresh();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ sections
|
||||
function drawTarget() {
|
||||
clear(secTarget);
|
||||
const t = st.tile;
|
||||
const xin = h('input', { type: 'number', inputmode: 'numeric', value: st.x === null ? '' : String(st.x), class: 'mil-num', 'aria-label': 'x', placeholder: 'x' });
|
||||
const yin = h('input', { type: 'number', inputmode: 'numeric', value: st.y === null ? '' : String(st.y), class: 'mil-num', 'aria-label': 'y', placeholder: 'y' });
|
||||
const lookup = () => {
|
||||
const x = Math.round(Number(xin.value)), y = Math.round(Number(yin.value));
|
||||
if (xin.value === '' || yin.value === '' || !Number.isFinite(x) || !Number.isFinite(y)) return;
|
||||
st.x = x; st.y = y; st.type = null; loadTile();
|
||||
};
|
||||
secTarget.appendChild(h('h3', { class: 'sub', text: App.t('send.target') }));
|
||||
secTarget.appendChild(h('div', { class: 'send-coords' }, h('span', { class: 'mono', text: 'x' }), xin, h('span', { class: 'mono', text: 'y' }), yin,
|
||||
h('button', { class: 'btn small', type: 'button', onclick: lookup }, icon('locate'), App.t('send.lookup'))));
|
||||
if (!t) {
|
||||
secTarget.appendChild(h('div', { class: 'chips' }, own.map((o) => h('button', { class: 'chip-btn', type: 'button', onclick: () => { st.x = o.x; st.y = o.y; st.type = null; loadTile(); } }, o.name))));
|
||||
}
|
||||
if (st.tileErr) { secTarget.appendChild(h('p', { class: 'reason', text: st.tileErr })); return; }
|
||||
if (st.x !== null && !t) { secTarget.appendChild(h('p', { class: 'dimmer', text: App.t('common.loading') })); return; }
|
||||
if (!t) return;
|
||||
const pills = [h('span', { class: 'pill', text: App.t('tile.' + t.type) })];
|
||||
if (t.town) {
|
||||
if (t.town.mine) pills.push(h('span', { class: 'pill accent', text: App.t('map.info.yours') }));
|
||||
if (t.town.isCapital) pills.push(h('span', { class: 'pill', text: App.t('map.info.capital') }));
|
||||
if (t.town.owner && t.town.owner.protected) pills.push(h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')));
|
||||
}
|
||||
if (t.type === 'rural' && t.bonus) pills.push(h('span', { class: 'pill res-' + t.bonus }, icon(t.bonus), App.resName(t.bonus)));
|
||||
secTarget.appendChild(h('div', { class: 'send-target' },
|
||||
h('div', { class: 'row' }, h('b', { text: t.town ? t.town.name : App.t('tile.' + t.type) }), mil().coordLink(t.x, t.y)),
|
||||
t.town && t.town.owner ? h('p', { class: 'row-sub wrap', text: t.town.owner.name + ' · ' + UpstreamI18n.fmtAs(t.town.owner.asNumber) }) : null,
|
||||
h('div', { class: 'pill-row' }, pills)));
|
||||
}
|
||||
|
||||
function drawFrom() {
|
||||
clear(secFrom);
|
||||
if (own.length < 2) return;
|
||||
secFrom.appendChild(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.from') }),
|
||||
h('select', { onchange: (e) => { st.fromId = Number(e.target.value); st.from = null; st.type = null; st.units = {}; drawUnits(); drawTypes(); loadFrom(); } },
|
||||
own.map((o) => h('option', { value: o.id, selected: o.id === st.fromId, text: o.name })))));
|
||||
}
|
||||
|
||||
function reasonText(o) {
|
||||
const r = o.reason || '';
|
||||
if (r.indexOf('settle:') === 0) {
|
||||
const code = r.slice(7), s = st.tile && st.tile.settle ? st.tile.settle : {};
|
||||
if (code === 'footprint_too_low') return App.t('send.reason.footprint', { have: num(s.footprint), need: num(s.footprintNeeded) });
|
||||
if (code === 'out_of_range') return App.t('send.reason.range', { n: s.maxDistance || D.EXPANSION.maxDistance });
|
||||
return App.t('send.reason.cannotSettle');
|
||||
}
|
||||
return App.t('send.reason.' + r);
|
||||
}
|
||||
|
||||
function drawTypes() {
|
||||
clear(secType);
|
||||
if (!st.tile || !st.from) return;
|
||||
if (!st.options.length) { secType.appendChild(h('p', { class: 'empty', text: App.t('send.nothing') })); return; }
|
||||
secType.appendChild(h('h3', { class: 'sub', text: App.t('send.what') }));
|
||||
secType.appendChild(h('div', { class: 'seg wrap-seg', role: 'group', 'aria-label': App.t('send.what') }, st.options.map((o) =>
|
||||
h('button', { class: 'seg-btn', type: 'button', disabled: !o.ok, 'aria-pressed': String(o.type === st.type), onclick: () => setType(o.type) }, icon(Mil.TYPE_ICON[o.type]), h('span', { text: mil().typeLabel(o.type) })))));
|
||||
const off = st.options.filter((o) => !o.ok);
|
||||
if (off.length) secType.appendChild(h('ul', { class: 'send-why' }, off.map((o) => h('li', { class: 'row-sub wrap', text: mil().typeLabel(o.type) + ': ' + reasonText(o) }))));
|
||||
}
|
||||
|
||||
function pickRow(label, have, cur, onChange, sub) {
|
||||
const range = h('input', { type: 'range', min: '0', max: String(have), step: '1', value: String(cur), 'aria-label': label });
|
||||
const numIn = h('input', { type: 'number', inputmode: 'numeric', min: '0', max: String(have), value: String(cur), class: 'mil-num', 'aria-label': label });
|
||||
const set = (v) => { v = Math.max(0, Math.min(have, Math.floor(Number(v)) || 0)); range.value = String(v); numIn.value = String(v); onChange(v); };
|
||||
range.addEventListener('input', () => set(range.value));
|
||||
numIn.addEventListener('input', () => set(numIn.value));
|
||||
return h('div', { class: 'mil-pick' },
|
||||
h('div', { class: 'row' }, h('span', null, h('b', { text: label }), h('span', { class: 'dimmer', text: ' / ' + num(have) })), sub || null),
|
||||
h('div', { class: 'pick-ctl' },
|
||||
h('button', { class: 'btn small', type: 'button', 'aria-label': '-1', onclick: () => set(Number(numIn.value) - 1) }, '−'),
|
||||
range,
|
||||
h('button', { class: 'btn small', type: 'button', 'aria-label': '+1', onclick: () => set(Number(numIn.value) + 1) }, '+'),
|
||||
numIn,
|
||||
h('button', { class: 'btn small', type: 'button', onclick: () => set(have) }, App.t('send.all'))));
|
||||
}
|
||||
|
||||
function drawUnits() {
|
||||
clear(secUnits);
|
||||
const type = st.type;
|
||||
if (!type || !st.from) return;
|
||||
const opt = st.options.find((o) => o.type === type);
|
||||
if (!opt || !opt.ok) return; // greyed out: the reason is shown with the type picker
|
||||
const h0 = home();
|
||||
if (type === 'settle') {
|
||||
const s = st.tile.settle || {};
|
||||
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.settle.title') }));
|
||||
secUnits.appendChild(h('p', { class: 'preview', text: App.t('send.settle.crews', { n: D.EXPANSION.crews, unit: mil().unitName(D.EXPANSION.settleUnit) }) }));
|
||||
secUnits.appendChild(h('p', { class: 'row-sub wrap', text: App.t('send.settle.footprint', { have: num(s.footprint), need: num(s.footprintNeeded), n: s.maxDistance || D.EXPANSION.maxDistance }) }));
|
||||
for (let i = 0; i < D.WILD_SLOTS; i++) {
|
||||
secUnits.appendChild(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.settle.wild', { n: i + 1 }) }),
|
||||
h('select', { onchange: (e) => { st.wild[i] = e.target.value; } },
|
||||
D.FIELD_TYPES.map((ft) => h('option', { value: ft, selected: st.wild[i] === ft, text: App.buildingName(ft) + ' (' + App.resName(D.FIELD_PRODUCES[ft]) + ')' })))));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (type === 'transport') {
|
||||
const m = st.from.td.military;
|
||||
const cur = R.resourcesAt(st.from.rt, App.now()).amounts;
|
||||
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.cargo') }));
|
||||
secUnits.appendChild(h('p', { class: 'row-sub wrap', text: App.t('send.cargo.cap', { n: num(m.transport.capacityPerLink), free: Math.max(0, m.transport.links - m.transport.active), links: m.transport.links }) }));
|
||||
for (const r of D.RESOURCES) {
|
||||
const have = Math.floor(cur[r] || 0);
|
||||
secUnits.appendChild(pickRow(App.resName(r), have, st.cargo[r] || 0, (v) => { if (v > 0) st.cargo[r] = v; else delete st.cargo[r]; refresh(); }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const rows = Mil.unitsForType(type, h0);
|
||||
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.units') }));
|
||||
if (!rows.length) { secUnits.appendChild(h('p', { class: 'empty', text: App.t('send.reason.no_units') })); return; }
|
||||
for (const r of rows) {
|
||||
const def = D.UNITS[r.unit];
|
||||
secUnits.appendChild(pickRow(mil().unitName(r.unit), r.have, st.units[r.unit] || 0, (v) => { if (v > 0) st.units[r.unit] = v; else delete st.units[r.unit]; refresh(); },
|
||||
h('span', { class: 'row-sub', text: def.speed + ' ' + App.t('send.tilesPerHour') })));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ preview, warnings, button state
|
||||
function ready() {
|
||||
if (!st.tile || !st.from || !st.type) return { ok: false, why: '' };
|
||||
const o = st.options.find((x) => x.type === st.type);
|
||||
if (!o || !o.ok) return { ok: false, why: '' };
|
||||
const m = st.from.td.military;
|
||||
if (!m.units.online) return { ok: false, why: App.t('err.units_offline') };
|
||||
if (st.type === 'transport') {
|
||||
const total = Object.keys(st.cargo).reduce((s, k) => s + st.cargo[k], 0);
|
||||
if (total < 1) return { ok: false, why: '' };
|
||||
if (total > m.transport.capacityPerLink) return { ok: false, why: App.t('err.capacity_exceeded') };
|
||||
} else {
|
||||
const sel = Mil.cleanSelection(st.units, home());
|
||||
if (Mil.sumUnits(sel) < 1) return { ok: false, why: '' };
|
||||
if (st.type === 'takeover' && !(sel[D.EXPANSION.conquestUnit] > 0)) return { ok: false, why: App.t('send.reason.needs_ma_team') };
|
||||
const chk = R.checkUnitsForType(st.type, sel);
|
||||
if (chk) return { ok: false, why: '' };
|
||||
}
|
||||
if (needsProtectionConfirm() && !st.endProtection) return { ok: false, why: App.t('send.protection.need') };
|
||||
return { ok: true, why: '' };
|
||||
}
|
||||
|
||||
const needsProtectionConfirm = () => Mil.isHostile(st.type) && op() && op().protectionUntil > App.now();
|
||||
|
||||
function refresh() {
|
||||
drawPreview();
|
||||
drawWarn();
|
||||
const r = ready();
|
||||
submit.disabled = !r.ok || st.busy;
|
||||
}
|
||||
|
||||
function drawPreview() {
|
||||
clear(secPreview);
|
||||
if (!st.tile || !st.from || !st.type) return;
|
||||
const from = fromTown();
|
||||
if (!from) return;
|
||||
const units = st.type === 'transport' ? {} : Mil.cleanSelection(st.units, home());
|
||||
const hasSel = st.type === 'transport' ? Object.keys(st.cargo).length > 0 : Mil.sumUnits(units) > 0;
|
||||
if (!hasSel) { secPreview.appendChild(h('p', { class: 'dimmer', text: App.t('send.pickSome') })); return; }
|
||||
const p = Mil.preview(st.type, from, { x: st.tile.x, y: st.tile.y }, units, st.cargo, App.state.world.speed);
|
||||
secPreview.appendChild(h('div', { class: 'send-preview' },
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.distance') }), h('span', { class: 'v mono', text: App.fmt.dec(p.dist) + ' ' + App.t('common.tiles') })),
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.latency') }), h('span', { class: 'v mono', text: App.fmt.dur(p.ms) })),
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.arrives') }), h('span', { class: 'v mono', text: mil().clockTime(App.now() + p.ms) })),
|
||||
p.slowest ? h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.slowest') }), h('span', { class: 'v mono', text: p.slowest + ' ' + App.t('send.tilesPerHour') })) : null,
|
||||
(st.type === 'raid' || st.type === 'attack' || st.type === 'takeover') && p.carry > 0 ? h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.carry') }), h('span', { class: 'v mono', text: num(p.carry) })) : null));
|
||||
}
|
||||
|
||||
function drawWarn() {
|
||||
clear(secWarn);
|
||||
if (!st.tile || !st.from || !st.type) return;
|
||||
const type = st.type;
|
||||
const items = [];
|
||||
if (needsProtectionConfirm()) {
|
||||
const cb = h('input', { type: 'checkbox', checked: st.endProtection, onchange: (e) => { st.endProtection = e.target.checked; refresh(); } });
|
||||
items.push(h('label', { class: 'warn-check' }, cb, h('span', null, h('b', { text: App.t('send.protection.title') }), ' ', App.t('send.protection.body', { t: mil().dayTime(op().protectionUntil) }))));
|
||||
}
|
||||
if ((type === 'attack' || type === 'takeover') && (st.units.exploit_kit || 0) > 0) {
|
||||
items.push(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.siege') }),
|
||||
h('select', { onchange: (e) => { st.target = e.target.value; } },
|
||||
h('option', { value: '', text: App.t('send.siege.none') }),
|
||||
Mil.siegeTargets().map((k) => h('option', { value: k, selected: st.target === k, text: App.buildingName(k) }))),
|
||||
h('span', { class: 'field-hint', text: App.t('send.siege.hint', { n: D.MILITARY.kitsMin }) })));
|
||||
}
|
||||
if (type === 'takeover') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.takeover.hint') }));
|
||||
if (type === 'raid') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.raid.hint') }));
|
||||
if (type === 'scan') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.scan.hint') }));
|
||||
if (type === 'reinforce' && st.tile.town && st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.reinforce.own') }));
|
||||
if (Mil.isHostile(type) && st.tile.town && !st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.hostile.hint') }));
|
||||
const r = ready();
|
||||
if (r.why) items.push(h('p', { class: 'reason', text: r.why }));
|
||||
secWarn.appendChild(h('div', { class: 'send-warn' }, items));
|
||||
}
|
||||
|
||||
function showErr(msg) { errEl.textContent = msg || ''; errEl.hidden = !msg; }
|
||||
|
||||
// ------------------------------------------------------------------ send
|
||||
async function go() {
|
||||
const r = ready();
|
||||
if (!r.ok || st.busy) return;
|
||||
st.busy = true; submit.disabled = true; showErr('');
|
||||
const body = { fromTownId: st.fromId, type: st.type };
|
||||
if (st.tile.town) body.toTownId = st.tile.town.id; else { body.x = st.tile.x; body.y = st.tile.y; }
|
||||
if (st.type === 'transport') body.cargo = Object.assign({}, st.cargo);
|
||||
else body.units = Mil.cleanSelection(st.units, home());
|
||||
if (st.type === 'settle') body.wild = st.wild.slice(0, D.WILD_SLOTS);
|
||||
if ((st.type === 'attack' || st.type === 'takeover') && st.target && (body.units.exploit_kit || 0) > 0) body.target = st.target;
|
||||
if (needsProtectionConfirm() && st.endProtection) body.confirmEndProtection = true;
|
||||
try {
|
||||
const res = await App.api.post('/movements', body, { intent: 'send:' + st.fromId + ':' + st.nonce });
|
||||
st.nonce = nonce();
|
||||
toast(App.t('send.sent', { type: mil().typeLabel(res.type), t: App.fmt.dur(res.arriveAt - res.departAt) }), 'ok');
|
||||
ctl.close();
|
||||
App.refreshMovements().catch(() => {});
|
||||
App.refreshTown().catch(() => {});
|
||||
if (App.state.operator && res.protectionEnded) App.state.operator.protectionUntil = 0;
|
||||
} catch (e) {
|
||||
st.busy = false;
|
||||
let msg = App.errMsg(e);
|
||||
const reason = e.details && e.details.reason;
|
||||
if (e.code === 'invalid_target' && reason && UpstreamI18n.strings.en['send.invalid.' + reason]) msg += ' ' + App.t('send.invalid.' + reason);
|
||||
showErr(msg);
|
||||
if (e.code === 'not_enough_units' || e.code === 'units_offline' || e.code === 'conflict') { st.from = null; loadFrom(); }
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
|
||||
// keep the arrival clock and affordability honest while the dialog stays open
|
||||
let lastSlot = 0;
|
||||
offTick = App.onTick((now) => {
|
||||
const slot = Math.floor(now / 15000);
|
||||
if (slot !== lastSlot && !st.busy && st.from && st.tile && st.type) { lastSlot = slot; drawPreview(); }
|
||||
});
|
||||
drawTarget(); drawFrom();
|
||||
loadFrom();
|
||||
if (st.x !== null) loadTile();
|
||||
refresh();
|
||||
};
|
||||
}());
|
||||
|
|
@ -77,7 +77,7 @@
|
|||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'settings', titleKey: 'screen.settings', navKey: 'nav.settings', icon: 'gear', hud: false,
|
||||
id: 'settings', titleKey: 'screen.settings', navKey: 'nav.settings', icon: 'gear', hud: false, navGroup: 'more',
|
||||
render(container) { box = container; App.on('session', () => { tokens = null; }); },
|
||||
onShow() { draw(); loadTokens(); },
|
||||
});
|
||||
|
|
|
|||
166
public/js/screens/social-ui.js
Normal file
166
public/js/screens/social-ui.js
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Pieces shared by the social screens (alliance, messages, rankings): window.SocUI. Everything player-controlled (operator
|
||||
* names, alliance names and tags, notes, message text) goes in through textContent / text nodes only, never innerHTML.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet } = UI;
|
||||
const Soc = UpstreamSocial;
|
||||
const D = UpstreamData;
|
||||
|
||||
const role = (r) => (D.SOCIAL.roles.includes(r) ? App.t('soc.role.' + r) : String(r));
|
||||
const state = (s) => (D.SOCIAL.diplomacyStates.includes(s) ? App.t('soc.state.' + s) : String(s));
|
||||
const kindLabel = (k) => App.t('soc.kind.' + k);
|
||||
|
||||
// Error text for a failed call. A 429 from the message limiter carries retryAfter (seconds).
|
||||
function err(e) {
|
||||
if (e && e.code === 'rate_limited' && e.retryAfter && (!e.details || !e.details.scope || e.details.scope === 'messages')) return App.t('soc.rate', { t: App.fmt.dur(Soc.retrySeconds(e) * 1000, 2) });
|
||||
return App.errMsg(e);
|
||||
}
|
||||
|
||||
// /me caches the operator's alliance; after founding, joining, leaving or being kicked refresh just that, without
|
||||
// App.setSession (which would reset the POP view).
|
||||
async function refreshOperator() {
|
||||
const me = await App.api.get('/me');
|
||||
const mineOp = (me.operators || []).find((o) => App.state.operator && o.id === App.state.operator.id);
|
||||
if (mineOp && App.state.operator) {
|
||||
App.state.operator.alliance = mineOp.alliance;
|
||||
App.state.operator.allianceId = mineOp.allianceId;
|
||||
App.emit('alliance', mineOp.alliance);
|
||||
}
|
||||
return mineOp;
|
||||
}
|
||||
const myAlliance = () => (App.state.operator && App.state.operator.alliance) || null;
|
||||
const myOperatorId = () => (App.state.operator ? App.state.operator.id : 0);
|
||||
|
||||
const tagPill = (tag) => h('span', { class: 'pill soc-tag', text: '[' + tag + ']' });
|
||||
const rolePill = (r) => h('span', { class: 'pill soc-role soc-role-' + r, text: role(r) });
|
||||
|
||||
// A busy button: disables itself while the promise runs and reports errors as a toast (or via `onError`).
|
||||
async function guard(btn, fn, onError) {
|
||||
if (btn) btn.disabled = true;
|
||||
try { return await fn(); } catch (e) {
|
||||
if (onError) onError(e); else toast(err(e), 'error');
|
||||
return undefined;
|
||||
} finally { if (btn && btn.isConnected) btn.disabled = false; }
|
||||
}
|
||||
|
||||
// Confirmation sheet. onOk() may throw: the error is shown inside the sheet and it stays open.
|
||||
function confirmSheet(o) {
|
||||
const msg = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const ok = h('button', { class: 'btn ' + (o.danger ? 'danger' : 'primary'), type: 'button', text: o.ok || App.t('common.confirm') });
|
||||
const sheet = openSheet({
|
||||
title: o.title, icon: o.icon || 'alert', closeLabel: App.t('common.close'),
|
||||
body: h('div', { class: 'detail' }, h('p', { class: 'detail-desc', text: o.text }), msg,
|
||||
h('div', { class: 'btn-row' }, h('button', { class: 'btn', type: 'button', onclick: () => sheet.close(), text: App.t('common.cancel') }), ok)),
|
||||
});
|
||||
ok.addEventListener('click', async () => {
|
||||
ok.disabled = true; msg.hidden = true;
|
||||
try { await o.onOk(); sheet.close(); } catch (e) { msg.textContent = err(e); msg.hidden = false; ok.disabled = false; }
|
||||
});
|
||||
return sheet;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ composer: textarea + live counter + send
|
||||
// composer({ onSend(text) -> Promise, placeholder, sendLabel, label }) -> { el, focus(), clear(), input }
|
||||
// A rate_limited answer disables sending and counts the seconds down; the text is kept.
|
||||
function composer(o) {
|
||||
const max = D.SOCIAL.messageMax;
|
||||
const input = h('textarea', { class: 'soc-text', rows: o.rows || 3, maxlength: String(max * 2), placeholder: o.placeholder || '', 'aria-label': o.label || App.t('soc.msg.text'), enterkeyhint: 'enter' });
|
||||
const counter = h('span', { class: 'soc-count mono' });
|
||||
const note = h('p', { class: 'soc-rate', role: 'alert', hidden: true });
|
||||
const send = h('button', { class: 'btn primary', type: 'button' }, icon('up'), o.sendLabel || App.t('soc.msg.send'));
|
||||
const el = h('div', { class: 'soc-composer' }, input, h('div', { class: 'soc-composer-bar' }, counter, send), note);
|
||||
let until = 0, off = null, busy = false;
|
||||
|
||||
function refresh() {
|
||||
const st = Soc.composeState(input.value, max);
|
||||
counter.textContent = st.n + '/' + max;
|
||||
counter.classList.toggle('over', st.over);
|
||||
counter.setAttribute('aria-label', App.t('soc.msg.counter', { n: st.n, max }));
|
||||
const waiting = until > App.now();
|
||||
send.disabled = busy || st.empty || st.over || waiting;
|
||||
}
|
||||
function tick() {
|
||||
if (!el.isConnected) { stopTick(); return; }
|
||||
const left = Math.ceil((until - App.now()) / 1000);
|
||||
if (left <= 0) { until = 0; note.hidden = true; stopTick(); refresh(); return; }
|
||||
const s = App.t('soc.rate', { t: App.fmt.dur(left * 1000, 2) });
|
||||
if (note.textContent !== s) note.textContent = s;
|
||||
}
|
||||
function startTick() { if (!off) off = App.onTick(tick); }
|
||||
function stopTick() { if (off) { off(); off = null; } }
|
||||
|
||||
input.addEventListener('input', refresh);
|
||||
send.addEventListener('click', async () => {
|
||||
const text = input.value;
|
||||
if (send.disabled) return;
|
||||
busy = true; refresh(); note.hidden = true;
|
||||
try {
|
||||
await o.onSend(text);
|
||||
input.value = '';
|
||||
} catch (e) {
|
||||
if (e && e.code === 'rate_limited') {
|
||||
until = App.now() + Soc.retrySeconds(e) * 1000;
|
||||
note.textContent = App.t('soc.rate', { t: App.fmt.dur(Soc.retrySeconds(e) * 1000, 2) }); note.hidden = false;
|
||||
startTick();
|
||||
} else { note.textContent = err(e); note.hidden = false; }
|
||||
} finally { busy = false; refresh(); }
|
||||
});
|
||||
refresh();
|
||||
return { el, input, focus: () => { try { input.focus({ preventScroll: true }); } catch (e) { /* ignore */ } }, refresh, destroy: stopTick };
|
||||
}
|
||||
|
||||
// Compose sheet. target: { operator: { operatorId, name } } or { alliance: true }.
|
||||
function openCompose(target, onSent) {
|
||||
const toAlliance = !!target.alliance;
|
||||
const to = toAlliance ? '[' + ((myAlliance() || {}).tag || '') + ']' : target.operator.name;
|
||||
const comp = composer({
|
||||
onSend: async (text) => {
|
||||
const body = toAlliance ? { text, toAlliance: true } : { text, toOperatorId: target.operator.operatorId };
|
||||
await App.api.post('/messages', body, { retries: 0 });
|
||||
toast(App.t('soc.msg.sent'), 'ok');
|
||||
sheet.close();
|
||||
if (onSent) onSent();
|
||||
},
|
||||
});
|
||||
const sheet = openSheet({
|
||||
title: toAlliance ? App.t('soc.msg.toAlliance') : App.t('soc.msg.to', { name: to }),
|
||||
icon: 'mail', closeLabel: App.t('common.close'), onClose: comp.destroy,
|
||||
body: h('div', { class: 'detail' }, toAlliance ? h('p', { class: 'detail-desc', text: App.t('soc.msg.broadcastHint', { tag: to }) }) : null, comp.el),
|
||||
});
|
||||
setTimeout(comp.focus, 220);
|
||||
return sheet;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ alliance profile sheet (public view)
|
||||
async function openProfile(allianceId, extra) {
|
||||
const body = h('div', { class: 'detail' }, h('p', { class: 'empty', text: App.t('common.loading') }));
|
||||
const sheet = openSheet({ title: extra && extra.name ? extra.name : App.t('soc.profile'), icon: 'users', closeLabel: App.t('common.close'), body });
|
||||
try {
|
||||
const a = (await App.api.get('/alliances/' + allianceId)).alliance;
|
||||
sheet.setTitle(a.name);
|
||||
clear(body);
|
||||
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
|
||||
body.appendChild(h('div', { class: 'pill-row' }, tagPill(a.tag),
|
||||
a.relation ? h('span', { class: 'pill soc-state soc-state-' + a.relation, text: a.relation === 'same' ? App.t('soc.relation.same') : state(a.relation) }) : null,
|
||||
a.myRole ? rolePill(a.myRole) : null));
|
||||
body.appendChild(h('div', null,
|
||||
kv(App.t('soc.members'), App.t('soc.size', { n: a.memberCount, cap: a.sizeCap })),
|
||||
kv(App.t('soc.leader'), a.leader ? a.leader.name : '-'),
|
||||
kv(App.t('soc.footprint'), App.fmt.dec(a.footprint || 0)),
|
||||
kv(App.t('soc.founded'), App.fmt.ago(App.now() - a.createdAt))));
|
||||
} catch (e) {
|
||||
clear(body);
|
||||
body.appendChild(h('p', { class: 'form-error', role: 'alert', text: err(e) }));
|
||||
}
|
||||
return sheet;
|
||||
}
|
||||
|
||||
// Loading / error / empty placeholders for a list container.
|
||||
const loading = () => h('p', { class: 'empty', text: App.t('common.loading') });
|
||||
const errorBox = (e, retry) => h('div', { class: 'soc-err' }, h('p', { class: 'form-error', role: 'alert', text: err(e) }),
|
||||
retry ? h('button', { class: 'btn small', type: 'button', onclick: retry }, icon('refresh'), App.t('common.retry')) : null);
|
||||
|
||||
window.SocUI = { role, state, kindLabel, err, refreshOperator, myAlliance, myOperatorId, tagPill, rolePill, guard, confirmSheet, composer, openCompose, openProfile, loading, errorBox };
|
||||
}());
|
||||
368
public/js/screens/units.js
Normal file
368
public/js/screens/units.js
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Units: what stands in this POP (home, reinforcements from others, your units standing elsewhere), the training queue
|
||||
* with a train form, research, and the power/offline status. Everything comes from GET /towns/:id (town.military); the
|
||||
* client previews cost/time with rules.trainPlan / researchPlan (same functions the server runs) and the server decides.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet, closeSheet } = UI;
|
||||
const R = UpstreamRules;
|
||||
const D = UpstreamData;
|
||||
const Mil = UpstreamMil;
|
||||
|
||||
const td = () => App.state.townData;
|
||||
const mi = () => (td() ? td().military : null);
|
||||
const mil = () => App.mil;
|
||||
|
||||
let box, bodyEl, visible = false, dirty = true, offTick = null;
|
||||
const refetch = new Map(); // training/research event id -> { n, at }
|
||||
|
||||
const num = (n) => App.fmt.num(n);
|
||||
const val = (x) => (Number.isInteger(x) ? num(x) : App.fmt.dec(x));
|
||||
|
||||
// ------------------------------------------------------------------ pieces
|
||||
function statLine(unit, levels) {
|
||||
const def = D.UNITS[unit];
|
||||
const a = R.unitStat(unit, 'attack', levels), d = R.unitStat(unit, 'defence', levels);
|
||||
return App.t('unit.stats', { a: val(a), d: val(d), s: def.speed || 0, c: def.carry || 0 }) + (def.fixed ? ' · ' + App.t('unit.fixed') : '');
|
||||
}
|
||||
|
||||
function unitRow(unit, count, levels, right) {
|
||||
return h('li', { class: 'mil-row unit' },
|
||||
h('span', { class: 'row-ic' }, mil().unitIcon(unit)),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: mil().unitName(unit) }), count !== null ? h('span', { class: 'lv mono', text: '× ' + num(count) }) : null),
|
||||
h('span', { class: 'row-sub wrap', text: statLine(unit, levels) })),
|
||||
right || null);
|
||||
}
|
||||
|
||||
function unitList(units, levels) {
|
||||
const rows = D.UNIT_ORDER.filter((u) => units && units[u] > 0).map((u) => unitRow(u, units[u], levels));
|
||||
return rows.length ? h('ul', { class: 'mil-list' }, rows) : null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ status
|
||||
function statusCard(m) {
|
||||
const t = td();
|
||||
if (!m.units.online) {
|
||||
const until = Mil.decommissionAt(m.units.offlineSince || App.now(), App.state.world.speed);
|
||||
return h('section', { class: 'card warn-card', role: 'alert' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('power'), App.t('units.offline.title'))),
|
||||
h('p', { class: 'detail-desc', text: App.t('units.offline.body') }),
|
||||
h('p', { class: 'row-sub wrap' }, App.t('units.offline.decom') + ' ', mil().countdown(until)));
|
||||
}
|
||||
return h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('units'), App.t('units.status')),
|
||||
h('span', { class: 'pill green', text: App.t('units.online') })),
|
||||
h('p', { class: 'row-sub wrap', text: App.t('units.powerNet', { n: App.fmt.dec(t.power.net, true) }) }));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ home / stationed
|
||||
function homeCard(m) {
|
||||
const levels = m.research.levels;
|
||||
const list = unitList(m.units.home, levels);
|
||||
return h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('units'), App.t('units.home')),
|
||||
h('button', { class: 'btn small primary', type: 'button', disabled: !list, onclick: () => App.openSend({ fromTownId: td().id }) }, icon('target'), App.t('mov.send'))),
|
||||
list || h('p', { class: 'empty', text: App.t('units.home.empty') }));
|
||||
}
|
||||
|
||||
async function withdraw(hostTownId, ownerTownId, btn) {
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await App.api.post('/towns/' + hostTownId + '/withdraw', { ownerTownId }, { intent: 'withdraw:' + hostTownId + ':' + ownerTownId });
|
||||
toast(App.t('units.withdrawn'), 'ok');
|
||||
} catch (e) { toast(App.errMsg(e), 'error'); }
|
||||
App.refreshMovements().catch(() => {});
|
||||
App.refreshTown().catch(() => {});
|
||||
}
|
||||
|
||||
function stationedCards(m) {
|
||||
const out = [];
|
||||
if (m.units.stationedHere.length) {
|
||||
out.push(h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('shield'), App.t('units.hosted'))),
|
||||
h('ul', { class: 'mil-list' }, m.units.stationedHere.map((g) => h('li', { class: 'mil-group' },
|
||||
h('div', { class: 'row' },
|
||||
h('span', null, h('b', { text: g.ownerTownName || '#' + g.ownerTownId }), g.owner ? h('span', { class: 'dimmer', text: ' · ' + g.owner.name }) : null),
|
||||
h('button', { class: 'btn small', type: 'button', onclick: (ev) => withdraw(td().id, g.ownerTownId, ev.currentTarget) }, icon('return'), App.t('units.sendHome'))),
|
||||
h('p', { class: 'row-sub wrap', text: mil().unitsText(g.units) }))))));
|
||||
}
|
||||
if (m.units.stationedAway.length) {
|
||||
out.push(h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('flag'), App.t('units.away'))),
|
||||
h('ul', { class: 'mil-list' }, m.units.stationedAway.map((g) => h('li', { class: 'mil-group' },
|
||||
h('div', { class: 'row' },
|
||||
h('span', null, h('b', { text: g.hostTownName || '#' + g.hostTownId })),
|
||||
h('button', { class: 'btn small', type: 'button', onclick: (ev) => withdraw(g.hostTownId, td().id, ev.currentTarget) }, icon('return'), App.t('units.callBack'))),
|
||||
h('p', { class: 'row-sub wrap', text: mil().unitsText(g.units) }))))));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ training
|
||||
const tailFor = (m, building) => m.training.filter((b) => b.building === building).reduce((t, b) => Math.max(t, b.dueAt), 0);
|
||||
|
||||
function trainingCard(m) {
|
||||
const queue = h('ul', { class: 'mil-list queue' });
|
||||
for (const b of m.training) {
|
||||
const bar = h('i');
|
||||
const li = h('li', { class: 'mil-row batch' },
|
||||
h('span', { class: 'row-ic' }, mil().unitIcon(b.unit)),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: mil().unitName(b.unit) }), h('span', { class: 'lv mono', text: '× ' + num(b.count) }), h('span', { class: 'lv', text: App.buildingName(b.building) })),
|
||||
h('span', { class: 'bar mil-bar', 'aria-hidden': 'true' }, bar)),
|
||||
h('span', { class: 'mil-when' }, mil().countdown(b.dueAt)));
|
||||
li._bar = bar; li._b = b;
|
||||
queue.appendChild(li);
|
||||
}
|
||||
const trainable = h('ul', { class: 'mil-list' }, m.trainable.map((u) => {
|
||||
const def = D.UNITS[u.unit];
|
||||
const row = h('button', { class: 'row-btn mil-train' + (u.locked ? ' locked' : ''), type: 'button', dataset: { unit: u.unit }, onclick: () => openTrain(u.unit) },
|
||||
h('span', { class: 'row-ic' }, mil().unitIcon(u.unit)),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: mil().unitName(u.unit) }), h('span', { class: 'lv', text: App.buildingName(def.building) })),
|
||||
u.locked
|
||||
? h('span', { class: 'row-sub wrap', text: App.t('units.needs') + ' ' + u.missing.map((x) => App.buildingName(x.type) + ' ' + App.t('pop.level', { n: x.level })).join(', ') })
|
||||
: h('span', { class: 'row-sub wrap', text: App.t('units.perUnit', { t: App.fmt.dur(u.timeMs) }) })),
|
||||
u.locked ? h('span', { class: 'pill dim' }, icon('lock')) : mil().resChips(u.cost));
|
||||
return h('li', null, row);
|
||||
}));
|
||||
return h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('clock'), App.t('units.training')), h('span', { class: 'pill', text: String(m.training.length) })),
|
||||
m.training.length ? queue : h('p', { class: 'empty', text: App.t('units.training.empty') }),
|
||||
h('h3', { class: 'sub', text: App.t('units.train') }), trainable);
|
||||
}
|
||||
|
||||
function openTrain(unit) {
|
||||
const body = h('div', { class: 'detail' });
|
||||
let off = null;
|
||||
const ctl = openSheet({ title: mil().unitName(unit), icon: 'units', closeLabel: App.t('common.close'), body, onClose: () => { if (off) off(); } });
|
||||
const els = {};
|
||||
let count = 1, busy = false;
|
||||
const def = D.UNITS[unit];
|
||||
|
||||
function plan() {
|
||||
const t = td(), m = mi();
|
||||
const rt = App.rulesTown();
|
||||
if (!t || !rt) return null;
|
||||
const p = R.trainPlan(rt, unit, count, App.now(), tailFor(m, def.building));
|
||||
if (p.ok && m.training.filter((b) => b.building === def.building).length >= D.MILITARY.maxTrainQueue) return Object.assign(p, { ok: false, code: 'queue_full' });
|
||||
return p;
|
||||
}
|
||||
function maxAffordable() {
|
||||
const cur = App.resourcesNow();
|
||||
if (!cur) return 1;
|
||||
let n = D.MILITARY.maxBatch;
|
||||
for (const r of D.RESOURCES) if (def.cost[r] > 0) n = Math.min(n, Math.floor(cur.amounts[r] / def.cost[r] + 1e-6));
|
||||
return Math.max(0, n);
|
||||
}
|
||||
|
||||
body.appendChild(h('p', { class: 'detail-desc', text: mil().unitDesc(unit) }));
|
||||
body.appendChild(h('p', { class: 'preview', text: statLine(unit, mi().research.levels) + ' · ' + App.t('unit.draw', { n: def.draw }) }));
|
||||
els.input = h('input', { type: 'number', inputmode: 'numeric', min: '1', max: String(D.MILITARY.maxBatch), value: '1', class: 'mil-num', 'aria-label': App.t('units.count') });
|
||||
const step = (d) => { count = Math.max(1, Math.min(D.MILITARY.maxBatch, count + d)); els.input.value = String(count); live(); };
|
||||
els.input.addEventListener('input', () => { const v = Math.floor(Number(els.input.value)); count = Number.isFinite(v) && v >= 1 ? Math.min(v, D.MILITARY.maxBatch) : 1; live(); });
|
||||
body.appendChild(h('div', { class: 'stepper' },
|
||||
h('button', { class: 'btn', type: 'button', 'aria-label': '-10', onclick: () => step(-10) }, '−10'),
|
||||
h('button', { class: 'btn', type: 'button', 'aria-label': '-1', onclick: () => step(-1) }, '−'),
|
||||
els.input,
|
||||
h('button', { class: 'btn', type: 'button', 'aria-label': '+1', onclick: () => step(1) }, '+'),
|
||||
h('button', { class: 'btn', type: 'button', 'aria-label': '+10', onclick: () => step(10) }, '+10')));
|
||||
body.appendChild(h('button', { class: 'btn small wide', type: 'button', onclick: () => { count = Math.max(1, maxAffordable()); els.input.value = String(count); live(); } }, App.t('units.max')));
|
||||
els.costs = h('div', { class: 'costs' });
|
||||
els.time = h('b');
|
||||
els.done = h('span', { class: 'dimmer' });
|
||||
body.appendChild(h('h3', { class: 'sub', text: App.t('sheet.cost') }));
|
||||
body.appendChild(els.costs);
|
||||
body.appendChild(h('div', { class: 'row meta' }, icon('clock'), h('span', { text: App.t('units.time') + ': ' }), els.time, els.done));
|
||||
els.reason = h('p', { class: 'reason', 'aria-live': 'polite' });
|
||||
els.btn = h('button', { class: 'btn primary wide', type: 'button', onclick: go }, icon('units'), h('span', { text: App.t('units.trainBtn') }));
|
||||
body.appendChild(els.reason); body.appendChild(els.btn);
|
||||
|
||||
function live() {
|
||||
const p = plan();
|
||||
if (!p) return;
|
||||
const cur = App.resourcesNow();
|
||||
clear(els.costs);
|
||||
for (const r of D.RESOURCES) {
|
||||
const short = cur && cur.amounts[r] + 1e-6 < p.cost[r];
|
||||
els.costs.appendChild(h('span', { class: 'cost ' + r + (short ? ' short' : '') }, icon(r), h('b', { text: num(p.cost[r]) }), cur ? h('small', { text: App.t('sheet.have', { n: num(cur.amounts[r]) }) }) : null));
|
||||
}
|
||||
els.time.textContent = App.fmt.dur(p.durationMs);
|
||||
els.done.textContent = ' · ' + App.t('units.readyAt', { t: mil().clockTime(p.dueAt) });
|
||||
let reason = '';
|
||||
if (!p.ok) {
|
||||
reason = App.t('err.' + p.code);
|
||||
if (p.code === 'requirements_not_met' && p.missing && p.missing.length) reason += ' ' + p.missing.map((x) => App.buildingName(x.type) + ' ' + App.t('pop.level', { n: x.level })).join(', ');
|
||||
}
|
||||
els.reason.textContent = reason; els.reason.hidden = !reason;
|
||||
els.btn.disabled = !p.ok || busy;
|
||||
}
|
||||
async function go() {
|
||||
if (busy) return;
|
||||
busy = true; els.btn.disabled = true;
|
||||
const t = td();
|
||||
try {
|
||||
await App.api.post('/towns/' + t.id + '/train', { unit, count }, { intent: 'train:' + t.id + ':' + unit + ':' + count });
|
||||
toast(App.t('units.queued', { n: num(count), unit: mil().unitName(unit) }), 'ok');
|
||||
ctl.close();
|
||||
await App.refreshTown();
|
||||
} catch (e) {
|
||||
toast(App.errMsg(e), 'error');
|
||||
busy = false;
|
||||
App.refreshTown().catch(() => {});
|
||||
live();
|
||||
}
|
||||
}
|
||||
off = App.onTick(() => { if (!busy) live(); });
|
||||
live();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ research
|
||||
function researchCard(m) {
|
||||
const levels = m.research.levels;
|
||||
const q = m.research.queue;
|
||||
const head = h('div', { class: 'card-head' }, h('h2', null, icon('flask'), App.t('units.research')),
|
||||
m.research.speedBonus > 0 ? h('span', { class: 'pill green', text: App.t('units.research.speed', { p: Math.round(m.research.speedBonus * 100) }) }) : null);
|
||||
const busy = q ? h('div', { class: 'detail-queue' },
|
||||
h('div', { class: 'row' }, h('span', { text: App.t('units.research.busy', { unit: mil().unitName(q.unit), stat: App.t('stat.' + q.stat), level: q.toLevel }) }), mil().countdown(q.dueAt)),
|
||||
h('div', { class: 'bar' }, h('i', { dataset: { rs: '1' } }))) : null;
|
||||
const rows = D.UNIT_ORDER.filter((u) => D.UNITS[u].attack > 0 || D.UNITS[u].defence > 0).map((u) => {
|
||||
const a = levels[R.researchKey(u, 'attack')] || 0, d = levels[R.researchKey(u, 'defence')] || 0;
|
||||
return h('li', null, h('button', { class: 'row-btn', type: 'button', onclick: () => openResearch(u) },
|
||||
h('span', { class: 'row-ic' }, mil().unitIcon(u)),
|
||||
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: mil().unitName(u) })),
|
||||
h('span', { class: 'row-sub wrap', text: App.t('stat.attack') + ' ' + a + ' · ' + App.t('stat.defence') + ' ' + d })),
|
||||
h('span', { class: 'pill', text: '+' + Math.round((a + d) * D.MILITARY.researchPerLevel * 100) + '%' })));
|
||||
});
|
||||
return h('section', { class: 'card' }, head, busy, h('ul', { class: 'mil-list' }, rows));
|
||||
}
|
||||
|
||||
function openResearch(unit) {
|
||||
const body = h('div', { class: 'detail' });
|
||||
let off = null;
|
||||
const ctl = openSheet({ title: mil().unitName(unit), icon: 'flask', closeLabel: App.t('common.close'), body, onClose: () => { if (off) off(); } });
|
||||
let busy = false;
|
||||
const def = D.UNITS[unit];
|
||||
const parts = {};
|
||||
|
||||
function build() {
|
||||
clear(body);
|
||||
const m = mi();
|
||||
body.appendChild(h('p', { class: 'detail-desc', text: App.t('units.research.hint', { p: Math.round(D.MILITARY.researchPerLevel * 100), max: D.RESEARCH.maxLevel }) }));
|
||||
for (const stat of D.RESEARCH.stats) {
|
||||
if (!(def[stat] > 0)) continue;
|
||||
const level = m.research.levels[R.researchKey(unit, stat)] || 0;
|
||||
const sec = h('section', { class: 'card inner' });
|
||||
sec.appendChild(h('div', { class: 'card-head' }, h('h2', { text: App.t('stat.' + stat) }),
|
||||
h('span', { class: 'pill', text: App.t('units.research.level', { n: level, max: D.RESEARCH.maxLevel }) })));
|
||||
if (level >= D.RESEARCH.maxLevel) { sec.appendChild(h('p', { class: 'empty', text: App.t('sheet.maxed') })); body.appendChild(sec); continue; }
|
||||
const costs = h('div', { class: 'costs' }), reason = h('p', { class: 'reason', 'aria-live': 'polite' }), time = h('b');
|
||||
const btn = h('button', { class: 'btn primary wide', type: 'button', onclick: () => go(stat, btn) }, icon('flask'), h('span', { text: App.t('units.research.start', { n: level + 1 }) }));
|
||||
sec.appendChild(h('p', { class: 'preview', text: App.t('units.research.effect', { a: val(def[stat] * R.researchMult(level)), b: val(def[stat] * R.researchMult(level + 1)) }) }));
|
||||
sec.appendChild(costs);
|
||||
sec.appendChild(h('div', { class: 'row meta' }, icon('clock'), h('span', { text: App.t('units.research.time') + ': ' }), time));
|
||||
sec.appendChild(reason); sec.appendChild(btn);
|
||||
parts[stat] = { level, costs, reason, time, btn };
|
||||
body.appendChild(sec);
|
||||
}
|
||||
live();
|
||||
}
|
||||
function live() {
|
||||
const m = mi(), rt = App.rulesTown();
|
||||
if (!m || !rt) return;
|
||||
const cur = App.resourcesNow();
|
||||
for (const stat of Object.keys(parts)) {
|
||||
const p = parts[stat];
|
||||
const plan = R.researchPlan(rt, unit, stat, p.level, !!m.research.queue, App.now(), m.research.speedBonus);
|
||||
clear(p.costs);
|
||||
for (const r of D.RESOURCES) p.costs.appendChild(h('span', { class: 'cost ' + r + (cur && cur.amounts[r] + 1e-6 < plan.cost[r] ? ' short' : '') }, icon(r), h('b', { text: num(plan.cost[r]) })));
|
||||
p.time.textContent = App.fmt.dur(plan.durationMs);
|
||||
let reason = '';
|
||||
if (!plan.ok) {
|
||||
reason = App.t('err.' + plan.code);
|
||||
if (plan.code === 'requirements_not_met' && plan.missing && plan.missing.length) reason += ' ' + plan.missing.map((x) => App.buildingName(x.type) + ' ' + App.t('pop.level', { n: x.level })).join(', ');
|
||||
}
|
||||
p.reason.textContent = reason; p.reason.hidden = !reason;
|
||||
p.btn.disabled = !plan.ok || busy;
|
||||
}
|
||||
}
|
||||
async function go(stat, btn) {
|
||||
if (busy) return;
|
||||
busy = true; btn.disabled = true;
|
||||
const t = td();
|
||||
try {
|
||||
await App.api.post('/towns/' + t.id + '/research', { unit, stat }, { intent: 'research:' + t.id + ':' + unit + ':' + stat });
|
||||
toast(App.t('units.research.queued'), 'ok');
|
||||
ctl.close();
|
||||
await App.refreshTown();
|
||||
} catch (e) {
|
||||
toast(App.errMsg(e), 'error');
|
||||
busy = false;
|
||||
App.refreshTown().then(() => build()).catch(() => {});
|
||||
}
|
||||
}
|
||||
build();
|
||||
off = App.onTick(live);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ screen
|
||||
function head() {
|
||||
return h('div', { class: 'card-head page-head units-head' }, h('h1', { text: App.t('screen.units') }),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => App.refreshTown().catch((e) => toast(App.errMsg(e), 'error')) }, icon('refresh')));
|
||||
}
|
||||
|
||||
function draw() {
|
||||
dirty = false;
|
||||
clear(bodyEl);
|
||||
const t = td(), m = mi();
|
||||
if (!App.state.townId) { bodyEl.appendChild(h('p', { class: 'empty pad', text: App.t('pop.noTown') })); return; }
|
||||
if (!t || !m) { bodyEl.appendChild(h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') }))); return; }
|
||||
bodyEl.appendChild(head());
|
||||
bodyEl.appendChild(h('div', { class: 'cols' },
|
||||
h('div', { class: 'col' }, statusCard(m), homeCard(m), stationedCards(m)),
|
||||
h('div', { class: 'col' }, trainingCard(m), researchCard(m))));
|
||||
tick(App.now());
|
||||
}
|
||||
|
||||
function tick(now) {
|
||||
const m = mi();
|
||||
if (!m || !bodyEl) return;
|
||||
for (const li of bodyEl.querySelectorAll('li.batch')) {
|
||||
const b = li._b;
|
||||
if (!b) continue;
|
||||
li._bar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - b.startAt) / Math.max(1, b.dueAt - b.startAt)))));
|
||||
}
|
||||
const rs = bodyEl.querySelector('[data-rs]');
|
||||
if (rs && m.research.queue) rs.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - m.research.queue.startedAt) / Math.max(1, m.research.queue.dueAt - m.research.queue.startedAt)))));
|
||||
// something came due: refetch (with a gentle retry, like the build queue)
|
||||
const items = m.training.map((b) => ({ id: 't' + b.id, due: b.dueAt })).concat(m.research.queue ? [{ id: 'r' + m.research.queue.id, due: m.research.queue.dueAt }] : []);
|
||||
for (const it of items) {
|
||||
if (now - it.due < 300) continue;
|
||||
const tries = refetch.get(it.id) || { n: 0, at: 0 };
|
||||
if (Date.now() >= tries.at) { refetch.set(it.id, { n: tries.n + 1, at: Date.now() + Math.min(10000, 1500 * (tries.n + 1)) }); App.refreshTown().catch(() => {}); }
|
||||
}
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'units', titleKey: 'screen.units', navKey: 'nav.units', icon: 'units', hud: true,
|
||||
render(container) {
|
||||
box = container;
|
||||
bodyEl = h('div', { class: 'units-body' });
|
||||
box.appendChild(bodyEl);
|
||||
App.on('town', () => { if (visible) draw(); else dirty = true; });
|
||||
App.on('townchange', () => { dirty = true; if (visible) draw(); });
|
||||
App.on('session', () => { dirty = true; refetch.clear(); });
|
||||
App.on('towns', () => { if (visible) draw(); else dirty = true; });
|
||||
},
|
||||
onShow() {
|
||||
visible = true;
|
||||
draw();
|
||||
if (offTick) offTick();
|
||||
offTick = App.onTick(tick);
|
||||
if (td() && Date.now() - App.state.townFetchedAt > 15000) App.refreshTown().catch(() => {});
|
||||
},
|
||||
onHide() { visible = false; if (offTick) offTick(); offTick = null; closeSheet(); },
|
||||
});
|
||||
}());
|
||||
Loading…
Add table
Add a link
Reference in a new issue