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
334 lines
18 KiB
JavaScript
334 lines
18 KiB
JavaScript
'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++; },
|
|
});
|
|
}());
|