Upstream/public/js/screens/social-ui.js
jvanvik b18645dca1 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
2026-10-11 19:05:03 +02:00

166 lines
8.8 KiB
JavaScript

'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 };
}());